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,402 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The live-session registry — host state, shared by the adapters that need it.
|
|
3
|
+
*
|
|
4
|
+
* **Why it exists.** Measured 2026-09-04 on the live host: Claude Code registers
|
|
5
|
+
* an MCP server from a STATIC configuration (command, args, env), so
|
|
6
|
+
* `mcp/bin/serve.ts` never receives `--session`. Every `session_end` call was
|
|
7
|
+
* therefore refused `no-bound-session` and no session's dump ever landed — the
|
|
8
|
+
* authored front door was shut for the whole run while the ask kept going out.
|
|
9
|
+
* The hooks DO know the session id (the host hands it to every hook); the server
|
|
10
|
+
* does not. This file is the note the hooks leave where the server can read it.
|
|
11
|
+
*
|
|
12
|
+
* **It is host state, never memory** (constitution 5). It carries no content: an
|
|
13
|
+
* id, a scope, three timestamps, and a few marks about what this session's hooks
|
|
14
|
+
* have already done — which configuration they read, whether the first-launch
|
|
15
|
+
* question went out, the wake's sentinel of counts and whether its arrival has
|
|
16
|
+
* been checked. Losing the whole directory costs a lazy bind and nothing else,
|
|
17
|
+
* which is why `store/paths.ts` classifies it `backup: false`.
|
|
18
|
+
*
|
|
19
|
+
* **Where it lives.** `<dataDir>/sessions/<id>.json`, because the data dir is the
|
|
20
|
+
* one path both sides already agree on — the hooks resolve it in
|
|
21
|
+
* `claude-code/bin/hook.ts`, the server in `Counterpart.open`.
|
|
22
|
+
*
|
|
23
|
+
* **Neither adapter imports the other.** `mcp/INTERFACE-GAPS.md` §7 keeps
|
|
24
|
+
* adapters as leaves; a sibling module both may import is the shape that rule
|
|
25
|
+
* allows, and it is the reason this file sits beside them rather than inside
|
|
26
|
+
* `claude-code/`.
|
|
27
|
+
*
|
|
28
|
+
* Three rules the code below mechanizes:
|
|
29
|
+
*
|
|
30
|
+
* 1. **Nothing here ever throws at a caller.** A hook may not fail the host
|
|
31
|
+
* (`claude-code/CONTRACT.md` §5 G2) and a tool may not fail on host trivia.
|
|
32
|
+
* Every entry point returns `null` on any failure.
|
|
33
|
+
* 2. **A session id is a FILENAME, and the MCP path takes it from a model.**
|
|
34
|
+
* `isSessionId` is the whole gate: one path segment of `[A-Za-z0-9._-]`,
|
|
35
|
+
* never `.` or `..`. An id that fails it is not looked up at all.
|
|
36
|
+
* 3. **Writes are atomic** — a temp file beside the target, then `rename`,
|
|
37
|
+
* so a reader never sees half a record. Same directory, so same
|
|
38
|
+
* filesystem, so the rename is a rename.
|
|
39
|
+
*/
|
|
40
|
+
import {
|
|
41
|
+
mkdirSync,
|
|
42
|
+
readFileSync,
|
|
43
|
+
readdirSync,
|
|
44
|
+
realpathSync,
|
|
45
|
+
renameSync,
|
|
46
|
+
rmSync,
|
|
47
|
+
statSync,
|
|
48
|
+
writeFileSync,
|
|
49
|
+
} from "node:fs";
|
|
50
|
+
import { join, resolve } from "node:path";
|
|
51
|
+
|
|
52
|
+
/** The one directory name. Classified in `store/paths.ts` LAYOUT. */
|
|
53
|
+
export const SESSIONS_DIR = "sessions";
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* **CAL.** How long after its last boundary a session may still be claimed.
|
|
57
|
+
*
|
|
58
|
+
* Every Stop refreshes `lastBoundaryAt`, and the Stop ask is delivered AT
|
|
59
|
+
* a Stop — so this window never has to cover an ordinary session's length, only
|
|
60
|
+
* the gap between an ask and the answer. Four hours is well past any plausible
|
|
61
|
+
* think-time (a session left open over lunch still binds) and comfortably short
|
|
62
|
+
* of a day, so a session that died last night cannot be claimed into today's
|
|
63
|
+
* memory by a server that outlived it.
|
|
64
|
+
*/
|
|
65
|
+
export const SESSION_TTL_MS = 4 * 60 * 60 * 1000;
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* **CAL.** How long a record survives at all. Pruned on SessionStart, which is
|
|
69
|
+
* once per session rather than once per turn. A week keeps the run's own
|
|
70
|
+
* forensics readable (constitution 16) while bounding the directory: the files
|
|
71
|
+
* are ~150 bytes and a busy week is a few hundred of them.
|
|
72
|
+
*/
|
|
73
|
+
export const SESSION_PRUNE_MS = 7 * 24 * 60 * 60 * 1000;
|
|
74
|
+
|
|
75
|
+
export type SessionPhase = "start" | "boundary" | "end";
|
|
76
|
+
|
|
77
|
+
export interface SessionRecord {
|
|
78
|
+
readonly sessionId: string;
|
|
79
|
+
/** The project directory the session runs in — the hook's own cwd, resolved. */
|
|
80
|
+
readonly scope: string;
|
|
81
|
+
readonly startedAt: number;
|
|
82
|
+
/** Refreshed at every boundary. Liveness is measured from HERE, not from start. */
|
|
83
|
+
readonly lastBoundaryAt: number;
|
|
84
|
+
/** Set once, by SessionEnd. A record with an end is never live again. */
|
|
85
|
+
readonly endedAt: number | null;
|
|
86
|
+
/**
|
|
87
|
+
* The `claude-code.json` the HOOK that wrote this record read — absolute, and
|
|
88
|
+
* present only when the hook was told (`claude-code/bin/hook.ts` resolves it
|
|
89
|
+
* through `adapters/config-path.ts` and passes it in).
|
|
90
|
+
*
|
|
91
|
+
* It is here because a hook has no way to TELL anyone: its stdout is the
|
|
92
|
+
* model's context and its stderr is a host log nobody reads. "Which config did
|
|
93
|
+
* that hook use" was, until 2026-09-05, unanswerable after the fact — and it
|
|
94
|
+
* is the question behind every "why is my memory empty" on a machine with more
|
|
95
|
+
* than one configuration. Still host state, still no content: a path, beside
|
|
96
|
+
* the id, the scope and the three timestamps.
|
|
97
|
+
*/
|
|
98
|
+
readonly config?: string;
|
|
99
|
+
/**
|
|
100
|
+
* TRUE once this session has been asked the first-launch scope question
|
|
101
|
+
* (G41). Set by the SessionStart hook at the moment it puts the block into
|
|
102
|
+
* the model's context, and carried forward like `config`.
|
|
103
|
+
*
|
|
104
|
+
* It is here rather than in the scope registry because it is a fact about ONE
|
|
105
|
+
* SESSION, not about the directory: the registry stays `unset` until somebody
|
|
106
|
+
* answers, and asking twice in a session that resumed or compacted is the
|
|
107
|
+
* thing this flag exists to stop. Still host state, still no content.
|
|
108
|
+
*/
|
|
109
|
+
readonly askedScope?: boolean;
|
|
110
|
+
/**
|
|
111
|
+
* THE TAIL SENTINEL THE WAKE WAS PRINTED WITH — the expectation the delivery
|
|
112
|
+
* check compares what arrived against, written by SessionStart at the moment
|
|
113
|
+
* it hands the bundle to the host.
|
|
114
|
+
*
|
|
115
|
+
* It is here because the check runs in a DIFFERENT PROCESS. Every hook is its
|
|
116
|
+
* own process; the expectation used to live in a `Map` on the adapter
|
|
117
|
+
* instance, so the hook that was meant to test it always met an empty one and
|
|
118
|
+
* `adapter.wake.delivered` never wrote a row in two weeks of running.
|
|
119
|
+
*
|
|
120
|
+
* Absent means no checkable wake was printed for this session — a cold start
|
|
121
|
+
* whose bundle is the bootstrap line, or a session whose SessionStart stood
|
|
122
|
+
* down — which is how "nothing was supposed to arrive" is told apart from "it
|
|
123
|
+
* was lost". Still host state, still no content: the sentinel is an HTML
|
|
124
|
+
* comment of counts (`<!-- counterparts:wake/end day=190 identity=3 … -->`),
|
|
125
|
+
* the same numbers the durable row carries.
|
|
126
|
+
*/
|
|
127
|
+
readonly wakeSentinel?: string;
|
|
128
|
+
/**
|
|
129
|
+
* TRUE once the delivery check has run for this session. It runs at the first
|
|
130
|
+
* `UserPromptSubmit` and leaves one durable row; this is what keeps it from
|
|
131
|
+
* re-reading the transcript on every turn afterwards. One-way, like
|
|
132
|
+
* `askedScope`.
|
|
133
|
+
*/
|
|
134
|
+
readonly wakeChecked?: boolean;
|
|
135
|
+
/**
|
|
136
|
+
* THE DATE THIS SESSION WAS ASKED TO WRITE ITS PAGE ABOUT (2026-09-20, S2),
|
|
137
|
+
* `YYYY-MM-DD`, in the fallback `session` mode of the nightly page writer.
|
|
138
|
+
*
|
|
139
|
+
* It does two jobs, and the second is why it is here rather than only in the
|
|
140
|
+
* store's event log:
|
|
141
|
+
*
|
|
142
|
+
* - it stops the same session being asked twice, exactly as `askedScope`
|
|
143
|
+
* does for the first-launch question;
|
|
144
|
+
* - it is what lets the MCP server write `by: "writer"` rather than
|
|
145
|
+
* `by: "session"` on the revision that comes back. `by` is the DOOR's and
|
|
146
|
+
* is not claimable from outside (`self/page.ts`), so the server may not
|
|
147
|
+
* take the model's word for which door it came through — it reads this
|
|
148
|
+
* mark, which only the SessionStart hook writes, and which names a date
|
|
149
|
+
* rather than a boolean so a stale mark cannot re-label tomorrow's write.
|
|
150
|
+
*
|
|
151
|
+
* Still host state, still no content: one date beside the id and the scope.
|
|
152
|
+
*/
|
|
153
|
+
readonly pageWriterFor?: string;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* One path segment, and nothing that could climb out of it. This host's ids are
|
|
158
|
+
* UUIDs; the check is deliberately narrower than "no slashes" because the MCP
|
|
159
|
+
* server passes a MODEL-SUPPLIED string straight into it.
|
|
160
|
+
*/
|
|
161
|
+
export function isSessionId(value: unknown): value is string {
|
|
162
|
+
return (
|
|
163
|
+
typeof value === "string" &&
|
|
164
|
+
value.length > 0 &&
|
|
165
|
+
value.length <= 128 &&
|
|
166
|
+
value !== "." &&
|
|
167
|
+
value !== ".." &&
|
|
168
|
+
/^[A-Za-z0-9._-]+$/.test(value)
|
|
169
|
+
);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* THE OTHER HALF OF `pageWriterFor`, for a session that has no record to carry
|
|
174
|
+
* it: the date a WINDOWLESS nightly writer is writing about, pinned onto its
|
|
175
|
+
* environment by the launcher (`claude-code/page-writer.ts`).
|
|
176
|
+
*
|
|
177
|
+
* It lives beside the record's field rather than in the launcher, because the
|
|
178
|
+
* two are one mechanism read from two directions — the MCP server asks "is this
|
|
179
|
+
* the night's writer" and must not have to know which mode started it — and
|
|
180
|
+
* because a name read in one adapter and written in another is exactly the pair
|
|
181
|
+
* that drifts when it is spelled twice.
|
|
182
|
+
*/
|
|
183
|
+
export const PAGE_WRITER_ENV = "COUNTERPARTS_PAGE_WRITER";
|
|
184
|
+
|
|
185
|
+
export function sessionsDir(dataDir: string): string {
|
|
186
|
+
return join(dataDir, SESSIONS_DIR);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export function sessionPath(dataDir: string, sessionId: string): string | null {
|
|
190
|
+
if (!isSessionId(sessionId)) return null;
|
|
191
|
+
return join(sessionsDir(dataDir), `${sessionId}.json`);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* The physical path, for comparison. macOS reports `/private/tmp` from
|
|
196
|
+
* `getcwd()` while `os.tmpdir()` says `/tmp`, and a scope comparison that got
|
|
197
|
+
* that wrong would refuse every bind on this host. `realpath` first; `resolve`
|
|
198
|
+
* when the path does not exist (a scope may name a directory this process
|
|
199
|
+
* cannot see).
|
|
200
|
+
*/
|
|
201
|
+
export function canonicalScope(scope: string): string {
|
|
202
|
+
try {
|
|
203
|
+
return realpathSync(resolve(scope));
|
|
204
|
+
} catch {
|
|
205
|
+
return resolve(scope);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Same directory, whatever each side's symlinks call it. */
|
|
210
|
+
export function sameScope(a: string, b: string): boolean {
|
|
211
|
+
return canonicalScope(a) === canonicalScope(b);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Not ended, and its last boundary is inside the window. */
|
|
215
|
+
export function isLive(
|
|
216
|
+
record: SessionRecord,
|
|
217
|
+
now: number,
|
|
218
|
+
ttlMs: number = SESSION_TTL_MS,
|
|
219
|
+
): boolean {
|
|
220
|
+
if (record.endedAt !== null) return false;
|
|
221
|
+
return now - record.lastBoundaryAt <= ttlMs;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
export function readSession(dataDir: string, sessionId: string): SessionRecord | null {
|
|
225
|
+
const path = sessionPath(dataDir, sessionId);
|
|
226
|
+
if (path === null) return null;
|
|
227
|
+
try {
|
|
228
|
+
return parseRecord(JSON.parse(readFileSync(path, "utf8")));
|
|
229
|
+
} catch {
|
|
230
|
+
// Absent, unreadable, or half-written by a host that died mid-rename: all
|
|
231
|
+
// three mean "no live session by that name", which is a refusal upstream.
|
|
232
|
+
return null;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Record the session at one of its three moments. Returns the record as written,
|
|
238
|
+
* or `null` if anything at all went wrong.
|
|
239
|
+
*
|
|
240
|
+
* The phases are not symmetric, and the asymmetry is the point:
|
|
241
|
+
*
|
|
242
|
+
* - **`start` owns the scope.** It is the only phase that sets it, so a hook
|
|
243
|
+
* firing from a git worktree cannot rewrite the scope the server matched
|
|
244
|
+
* against halfway through a session.
|
|
245
|
+
* - **`boundary` creates if missing.** Sessions already running when this
|
|
246
|
+
* ships never saw a SessionStart write; requiring one would leave every
|
|
247
|
+
* live session unbindable until the owner restarted it.
|
|
248
|
+
* - **`end` is one-way.** A later boundary refreshes the clock but never
|
|
249
|
+
* clears `endedAt`: a session the host closed does not come back.
|
|
250
|
+
*/
|
|
251
|
+
export function recordSession(
|
|
252
|
+
dataDir: string,
|
|
253
|
+
input: {
|
|
254
|
+
sessionId: string;
|
|
255
|
+
scope: string;
|
|
256
|
+
phase: SessionPhase;
|
|
257
|
+
at?: number;
|
|
258
|
+
/** The configuration the writing hook read. Carried forward when a later
|
|
259
|
+
* phase is written by a process that was told nothing. */
|
|
260
|
+
config?: string;
|
|
261
|
+
/** Set once, when the first-launch scope question is delivered (G41).
|
|
262
|
+
* Carried forward the same way, and never cleared by a later phase. */
|
|
263
|
+
askedScope?: boolean;
|
|
264
|
+
/** The sentinel the wake was printed with, written by SessionStart.
|
|
265
|
+
* Carried forward like `config`: the newest answer wins. */
|
|
266
|
+
wakeSentinel?: string;
|
|
267
|
+
/** Set once, when the delivery check has left its row. One-way. */
|
|
268
|
+
wakeChecked?: boolean;
|
|
269
|
+
/** The date the nightly page writer asked this session to write about
|
|
270
|
+
* (S2). Carried forward like `config`; the newest answer wins. */
|
|
271
|
+
pageWriterFor?: string;
|
|
272
|
+
},
|
|
273
|
+
): SessionRecord | null {
|
|
274
|
+
if (!isSessionId(input.sessionId)) return null;
|
|
275
|
+
const path = sessionPath(dataDir, input.sessionId);
|
|
276
|
+
if (path === null) return null;
|
|
277
|
+
const now = input.at ?? Date.now();
|
|
278
|
+
const prior = readSession(dataDir, input.sessionId);
|
|
279
|
+
|
|
280
|
+
const record: SessionRecord = {
|
|
281
|
+
sessionId: input.sessionId,
|
|
282
|
+
scope:
|
|
283
|
+
prior === null || input.phase === "start" ? canonicalScope(input.scope) : prior.scope,
|
|
284
|
+
startedAt: prior?.startedAt ?? now,
|
|
285
|
+
lastBoundaryAt: now,
|
|
286
|
+
endedAt:
|
|
287
|
+
input.phase === "end" ? now : input.phase === "start" ? null : (prior?.endedAt ?? null),
|
|
288
|
+
// The record is REWRITTEN whole at every phase, so a field only SessionStart
|
|
289
|
+
// knew would vanish at the first Stop. This one is carried: the newest
|
|
290
|
+
// answer wins, and a phase written by a process that was told nothing keeps
|
|
291
|
+
// what the last one said.
|
|
292
|
+
...(input.config !== undefined && input.config.length > 0
|
|
293
|
+
? { config: input.config }
|
|
294
|
+
: prior?.config !== undefined
|
|
295
|
+
? { config: prior.config }
|
|
296
|
+
: {}),
|
|
297
|
+
// ONE-WAY, like `endedAt`: a session that has been asked has been asked,
|
|
298
|
+
// and a later phase written by a process that knows nothing about the
|
|
299
|
+
// question must not un-ask it.
|
|
300
|
+
...(input.askedScope === true || prior?.askedScope === true ? { askedScope: true } : {}),
|
|
301
|
+
// Carried like `config` — newest answer wins — because a SessionStart that
|
|
302
|
+
// fires again inside one session (a compaction) renders a new bundle, and
|
|
303
|
+
// the expectation the next check tests has to be the one last printed.
|
|
304
|
+
...(input.wakeSentinel !== undefined && input.wakeSentinel.length > 0
|
|
305
|
+
? { wakeSentinel: input.wakeSentinel }
|
|
306
|
+
: prior?.wakeSentinel !== undefined
|
|
307
|
+
? { wakeSentinel: prior.wakeSentinel }
|
|
308
|
+
: {}),
|
|
309
|
+
// One-way, like `askedScope`: a session that has been checked has been
|
|
310
|
+
// checked, and the flag is what stops the transcript being re-read at every
|
|
311
|
+
// turn for the rest of the session.
|
|
312
|
+
...(input.wakeChecked === true || prior?.wakeChecked === true ? { wakeChecked: true } : {}),
|
|
313
|
+
// Carried like `config` rather than one-way, because it names a DATE: a
|
|
314
|
+
// session that lives across midnight and is asked again gets the new date,
|
|
315
|
+
// and a phase written by a process that knows nothing about the writer
|
|
316
|
+
// keeps the one already there.
|
|
317
|
+
...(input.pageWriterFor !== undefined && input.pageWriterFor.length > 0
|
|
318
|
+
? { pageWriterFor: input.pageWriterFor }
|
|
319
|
+
: prior?.pageWriterFor !== undefined
|
|
320
|
+
? { pageWriterFor: prior.pageWriterFor }
|
|
321
|
+
: {}),
|
|
322
|
+
};
|
|
323
|
+
|
|
324
|
+
try {
|
|
325
|
+
mkdirSync(sessionsDir(dataDir), { recursive: true });
|
|
326
|
+
const tmp = `${path}.${String(process.pid)}.tmp`;
|
|
327
|
+
writeFileSync(tmp, `${JSON.stringify(record)}\n`, { encoding: "utf8", mode: 0o600 });
|
|
328
|
+
renameSync(tmp, path);
|
|
329
|
+
} catch {
|
|
330
|
+
return null;
|
|
331
|
+
}
|
|
332
|
+
return record;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* Drop records nobody can claim any more. Called from SessionStart only — one
|
|
337
|
+
* `readdir` per session, never per turn, and never on the SessionEnd path that
|
|
338
|
+
* shares a 1.5 s budget with every other hook on that event.
|
|
339
|
+
*/
|
|
340
|
+
export function pruneSessions(
|
|
341
|
+
dataDir: string,
|
|
342
|
+
now: number = Date.now(),
|
|
343
|
+
maxAgeMs: number = SESSION_PRUNE_MS,
|
|
344
|
+
): number {
|
|
345
|
+
let removed = 0;
|
|
346
|
+
try {
|
|
347
|
+
for (const name of readdirSync(sessionsDir(dataDir))) {
|
|
348
|
+
const full = join(sessionsDir(dataDir), name);
|
|
349
|
+
try {
|
|
350
|
+
if (now - statSync(full).mtimeMs <= maxAgeMs) continue;
|
|
351
|
+
rmSync(full, { force: true });
|
|
352
|
+
removed += 1;
|
|
353
|
+
} catch {
|
|
354
|
+
continue;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
} catch {
|
|
358
|
+
return removed;
|
|
359
|
+
}
|
|
360
|
+
return removed;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
function parseRecord(raw: unknown): SessionRecord | null {
|
|
364
|
+
if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
|
|
365
|
+
const rec = raw as Record<string, unknown>;
|
|
366
|
+
const sessionId = rec["sessionId"];
|
|
367
|
+
const scope = rec["scope"];
|
|
368
|
+
const startedAt = rec["startedAt"];
|
|
369
|
+
const lastBoundaryAt = rec["lastBoundaryAt"];
|
|
370
|
+
const endedAt = rec["endedAt"] ?? null;
|
|
371
|
+
if (!isSessionId(sessionId)) return null;
|
|
372
|
+
if (typeof scope !== "string" || scope.length === 0) return null;
|
|
373
|
+
if (typeof startedAt !== "number" || typeof lastBoundaryAt !== "number") return null;
|
|
374
|
+
if (endedAt !== null && typeof endedAt !== "number") return null;
|
|
375
|
+
// Optional, and never a reason to reject a record: every record written before
|
|
376
|
+
// 2026-09-05 lacks it, and a registry that refused those would refuse every
|
|
377
|
+
// live session on the owner's host at the moment this ships.
|
|
378
|
+
const config = rec["config"];
|
|
379
|
+
return {
|
|
380
|
+
sessionId,
|
|
381
|
+
scope,
|
|
382
|
+
startedAt,
|
|
383
|
+
lastBoundaryAt,
|
|
384
|
+
endedAt,
|
|
385
|
+
...(typeof config === "string" && config.length > 0 ? { config } : {}),
|
|
386
|
+
// Optional for the same reason `config` is: every record written before
|
|
387
|
+
// 2026-09-10 lacks it, and "not asked" is exactly what its absence means.
|
|
388
|
+
...(rec["askedScope"] === true ? { askedScope: true } : {}),
|
|
389
|
+
// Optional for the same reason again, and its absence is a real answer:
|
|
390
|
+
// "no checkable wake was printed for this session".
|
|
391
|
+
...(typeof rec["wakeSentinel"] === "string" && rec["wakeSentinel"].length > 0
|
|
392
|
+
? { wakeSentinel: rec["wakeSentinel"] }
|
|
393
|
+
: {}),
|
|
394
|
+
...(rec["wakeChecked"] === true ? { wakeChecked: true } : {}),
|
|
395
|
+
// Optional for the same reason, and read as a DATE rather than a flag: a
|
|
396
|
+
// value that is not a date is no mark at all, so a hand-edited record
|
|
397
|
+
// cannot talk the MCP server into writing `by: "writer"`.
|
|
398
|
+
...(typeof rec["pageWriterFor"] === "string" && /^\d{4}-\d{2}-\d{2}$/.test(rec["pageWriterFor"])
|
|
399
|
+
? { pageWriterFor: rec["pageWriterFor"] }
|
|
400
|
+
: {}),
|
|
401
|
+
};
|
|
402
|
+
}
|