counterparts 0.3.21 → 0.3.23
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/CHANGELOG.md +66 -0
- package/docs/module-map.md +1 -0
- package/package.json +1 -1
- package/src/adapters/claude-code/bin/hook.ts +3 -3
- package/src/adapters/claude-code/bin/runner.ts +27 -1
- package/src/adapters/claude-code/doctor-host.ts +28 -9
- package/src/adapters/claude-code/night-run.ts +2 -3
- package/src/adapters/claude-code/transcript.ts +1 -1
- package/src/adapters/cli/bin/counterparts.ts +9 -2
- package/src/adapters/cli/commands-dashboard.ts +31 -2
- package/src/adapters/cli/commands-start-fresh.ts +11 -2
- package/src/adapters/cli/desktop.ts +10 -5
- package/src/adapters/cli/help.ts +4 -3
- package/src/adapters/cli/install.ts +16 -8
- package/src/adapters/cli/removal.ts +7 -0
- package/src/adapters/cli/uninstall.ts +12 -4
- package/src/adapters/cli/wire.ts +41 -12
- package/src/adapters/dashboard/web/README.md +1 -1
- package/src/adapters/dashboard/web/actions.ts +6 -4
- package/src/adapters/dashboard/web/app.html +3 -0
- package/src/adapters/dashboard/web/favicon.svg +1 -0
- package/src/adapters/dashboard/web/pages/home/home.css +3 -0
- package/src/adapters/dashboard/web/pages/home/sections/brain.js +37 -9
- package/src/adapters/dashboard/web/probe.ts +33 -0
- package/src/adapters/dashboard/web/server.ts +49 -27
- package/src/adapters/dashboard/web/views/mechanism-panel.ts +13 -3
- package/src/adapters/host-wiring.ts +44 -6
- package/src/adapters/mcp/bin/serve.ts +33 -0
- package/src/adapters/mcp/index.ts +1 -0
- package/src/adapters/mcp/server-options.ts +7 -0
- package/src/adapters/mcp/server-words.ts +1 -1
- package/src/adapters/mcp/server.ts +7 -0
- package/src/adapters/mcp/tools.ts +58 -0
- package/src/adapters/plugin.ts +3 -2
- package/src/adapters/runtime.ts +80 -3
- package/src/adapters/scopes.ts +2 -1
- package/src/adapters/sidebar-status.ts +505 -0
- package/src/adapters/spawn.ts +2 -2
- package/src/core/dream/index.ts +1 -1
- package/src/core/dream/reflect.ts +6 -5
- package/src/core/onboarding.ts +5 -2
|
@@ -0,0 +1,505 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE SIDEBAR'S STATUS FILE (2026-10-14) — what the Claude Code sidebar mod
|
|
3
|
+
* (`hooks/sidebar/`) shows, written where it can read it without a network.
|
|
4
|
+
*
|
|
5
|
+
* The plugin directory's review holds a mod that can both fetch and run a
|
|
6
|
+
* command, so the sidebar stopped asking the dashboard on 127.0.0.1:4747 and
|
|
7
|
+
* reads this file with `$.fs.read` instead, on the timer it already had. The
|
|
8
|
+
* dashboard keeps every endpoint (its own page uses them); only the sidebar
|
|
9
|
+
* stopped calling them.
|
|
10
|
+
*
|
|
11
|
+
* **Where.** `<config dir>/sidebar.json`, beside `scopes.json` — the sidebar
|
|
12
|
+
* already finds that directory the way the hooks find their configuration
|
|
13
|
+
* (`hooks/sidebar/hooks/register.tsx#scopesFile`). NOT inside the store: every
|
|
14
|
+
* top-level name there is classified (`core/store/paths.ts#LAYOUT`) and an
|
|
15
|
+
* unclassified one refuses the store at open, an older build's included.
|
|
16
|
+
*
|
|
17
|
+
* **What.** The answers the sidebar used to ask for, computed by the same view
|
|
18
|
+
* functions the dashboard serves them from: which store (`storeId`, the
|
|
19
|
+
* `/api/whoami` id, so a sidebar never shows another memory's numbers), the
|
|
20
|
+
* pulse, today's counts per mechanism, the newest dreams, the newest rows of
|
|
21
|
+
* the activity log (and of the few names the sidebar reads deeper), each
|
|
22
|
+
* mechanism's panel, and the memories those rows name — title, kind, the date
|
|
23
|
+
* it was learned, and the first {@link TEXT_CAP} characters of its text (none
|
|
24
|
+
* for a confidential one). Capped throughout; measured on the demo store it is
|
|
25
|
+
* well under 256 KiB.
|
|
26
|
+
*
|
|
27
|
+
* **When.** Never on a hook's path. The detached worker writes it after every
|
|
28
|
+
* boundary (Stop, SessionEnd: `claude-code/bin/runner.ts`), and the MCP server
|
|
29
|
+
* a moment after it starts, after each tool call that wrote, and whenever the
|
|
30
|
+
* activity log moved under it (`mcp/bin/serve.ts`). Each write opens its own
|
|
31
|
+
* observer handle — the view functions refuse a writable one — and closes it.
|
|
32
|
+
*
|
|
33
|
+
* **How.** A temp file of this process's own, then a rename: a reader sees the
|
|
34
|
+
* old file or the new one, never half of either, and two writers racing each
|
|
35
|
+
* land whole. It never throws: the result says what happened.
|
|
36
|
+
*/
|
|
37
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
38
|
+
import { dirname, isAbsolute, join } from "node:path";
|
|
39
|
+
|
|
40
|
+
import { Dashboard } from "./dashboard/index.js";
|
|
41
|
+
import type { DashboardSource } from "./dashboard/source.js";
|
|
42
|
+
import { dreamsView } from "./dashboard/web/views/dreams.js";
|
|
43
|
+
import { narrate } from "./dashboard/web/narrate.js";
|
|
44
|
+
import { mechanismActivity } from "./dashboard/web/views/mechanism-panel.js";
|
|
45
|
+
import { mechanismsView } from "./dashboard/web/views/mechanisms.js";
|
|
46
|
+
import { memoriesHeld } from "./dashboard/web/views/shared.js";
|
|
47
|
+
import { memoryDetail } from "./dashboard/web/views.js";
|
|
48
|
+
import { pluginInstall } from "./host-wiring.js";
|
|
49
|
+
import { PLUGIN_ROOT_ENV } from "./plugin.js";
|
|
50
|
+
import { installedVersion } from "./sessions.js";
|
|
51
|
+
import { storeId } from "./store-id.js";
|
|
52
|
+
|
|
53
|
+
export const SIDEBAR_FILE_NAME = "sidebar.json";
|
|
54
|
+
/** The file's shape. A reader that does not know a version shows nothing from it. */
|
|
55
|
+
export const SIDEBAR_STATUS_VERSION = 1;
|
|
56
|
+
|
|
57
|
+
/** Newest rows of the whole log: what lights the sidebar's dot and moves its counts between two files. */
|
|
58
|
+
export const RECENT_ROWS = 100;
|
|
59
|
+
/** Newest rows of the names the sidebar reads deeper (a resumed session's surfaced and saved, a mechanism's firings). */
|
|
60
|
+
export const NAMED_ROWS: Readonly<Record<string, number>> = {
|
|
61
|
+
"recall.decision": 40,
|
|
62
|
+
"gate.deposit": 40,
|
|
63
|
+
"contradiction.settled": 20,
|
|
64
|
+
"dream.journaled": 5,
|
|
65
|
+
};
|
|
66
|
+
/** Dreams carried (the newest is shown; a dream's firings read the changes of the few newest). */
|
|
67
|
+
export const DREAMS = 3;
|
|
68
|
+
/**
|
|
69
|
+
* Memories carried, and how much of each one's text: what an opened memory
|
|
70
|
+
* shows in the pane (20 lines at the docked width, 32 cells on the terminal,
|
|
71
|
+
* about 38 in the desktop's font), so the pane reads as it did when it asked
|
|
72
|
+
* the dashboard; a longer text ends with `more` (the rest is on the dashboard).
|
|
73
|
+
*/
|
|
74
|
+
export const MEMORY_CAP = 60;
|
|
75
|
+
export const TEXT_CAP = 800;
|
|
76
|
+
/** The memory server writes the file at least this often while it runs, moved or not. */
|
|
77
|
+
export const REFRESH_MS = 30 * 60_000;
|
|
78
|
+
|
|
79
|
+
/** `<config dir>/sidebar.json` — beside the configuration, like `scopes.json`. */
|
|
80
|
+
export function sidebarStatusPath(configPath: string): string {
|
|
81
|
+
return join(dirname(configPath), SIDEBAR_FILE_NAME);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Where the store keeps the path of the status file last written for it, so a
|
|
86
|
+
* removal or a fresh start finds it whatever the layout (a `dataDir` outside
|
|
87
|
+
* the configuration's folder included). Host state, in `sessions/` like the
|
|
88
|
+
* rest of it (`core/store/paths.ts#LAYOUT`).
|
|
89
|
+
*/
|
|
90
|
+
export function sidebarPointerPath(dataDir: string): string {
|
|
91
|
+
return join(dataDir, "sessions", "sidebar-status-path");
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* IS THE SIDEBAR INSTALLED? The status file is written only for the plugin,
|
|
96
|
+
* which carries the sidebar: this process is the plugin's (`CLAUDE_PLUGIN_ROOT`
|
|
97
|
+
* set), or Claude Code's `plugins/installed_plugins.json` records a
|
|
98
|
+
* `counterparts@…` install that the settings leave on. `~/.claude.json` is
|
|
99
|
+
* never read. An npm-only install gets no file.
|
|
100
|
+
*/
|
|
101
|
+
export function sidebarInstalled(env: Record<string, string | undefined>, home: string): boolean {
|
|
102
|
+
if ((env[PLUGIN_ROOT_ENV] ?? "").trim().length > 0) return true;
|
|
103
|
+
try {
|
|
104
|
+
return pluginInstall({ home, env, cwd: null })?.enabled === true;
|
|
105
|
+
} catch {
|
|
106
|
+
return false;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** The file, gone (the sidebar is not installed, or the store it showed was set aside). Never throws. */
|
|
111
|
+
export function removeSidebarStatus(configPath: string): boolean {
|
|
112
|
+
try {
|
|
113
|
+
const file = sidebarStatusPath(configPath);
|
|
114
|
+
if (!existsSync(file)) return false;
|
|
115
|
+
rmSync(file, { force: true });
|
|
116
|
+
return true;
|
|
117
|
+
} catch {
|
|
118
|
+
return false;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
type Row = { seq: number } & Record<string, unknown>;
|
|
123
|
+
|
|
124
|
+
export interface SidebarMemory {
|
|
125
|
+
readonly title: string;
|
|
126
|
+
readonly text: string;
|
|
127
|
+
/** The text was cut at {@link TEXT_CAP}: the rest is on the dashboard. */
|
|
128
|
+
readonly cut: boolean;
|
|
129
|
+
readonly kind: string | null;
|
|
130
|
+
readonly learnedOn: string | null;
|
|
131
|
+
readonly journal: boolean;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export interface SidebarStatus {
|
|
135
|
+
readonly version: number;
|
|
136
|
+
/** `adapters/store-id.ts`: which store this is (an id, never the path). */
|
|
137
|
+
readonly storeId: string | null;
|
|
138
|
+
/** Epoch ms. */
|
|
139
|
+
readonly writtenAt: number;
|
|
140
|
+
/** The package version that wrote it. */
|
|
141
|
+
readonly build: string | null;
|
|
142
|
+
readonly pulse: { readonly day: number; readonly memories: number; readonly lastSeq: number };
|
|
143
|
+
/** Times each mechanism fired on the person's calendar day (`mechanismsView`). */
|
|
144
|
+
readonly today: { readonly date: string; readonly counts: Readonly<Record<string, number>> } | null;
|
|
145
|
+
readonly dreams: readonly unknown[];
|
|
146
|
+
/** Narrated rows (`activityView`'s), newest first, each seq once. */
|
|
147
|
+
readonly events: readonly Row[];
|
|
148
|
+
/** Each mechanism's panel rows (`mechanismPanel`). */
|
|
149
|
+
readonly panels: Readonly<Record<string, readonly Row[]>>;
|
|
150
|
+
/** The memories the rows above name. */
|
|
151
|
+
readonly memories: Readonly<Record<string, SidebarMemory | null>>;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* The detail keys the sidebar reads (`hooks/sidebar/hooks/feed.ts`: its
|
|
156
|
+
* rules, `classify`, `mechFirings`, `surfacedIds`, the session seed). The rest
|
|
157
|
+
* of a row's detail — a deposit's gate scores, a sleep cycle's phases — is the
|
|
158
|
+
* dashboard page's, and most of a row's bytes.
|
|
159
|
+
*/
|
|
160
|
+
export const DETAIL_KEYS: ReadonlySet<string> = new Set([
|
|
161
|
+
"accepted", "actor", "actorId", "applied", "challengerId", "credited", "deposited", "direction", "faded",
|
|
162
|
+
"footnoteCount", "footnotes", "gist", "holds", "how", "id", "ids", "linksReached", "memoryId", "merge",
|
|
163
|
+
"moodMatched", "over", "replayLinks", "session", "site", "source", "surfaced", "surfacedCount", "targetId", "turn",
|
|
164
|
+
]);
|
|
165
|
+
|
|
166
|
+
/** A row as the sidebar reads it: the narrated row less what only the dashboard's page draws. */
|
|
167
|
+
function slim(r: Row): Row {
|
|
168
|
+
const out: Row = { seq: r.seq };
|
|
169
|
+
for (const k of ["at", "day", "name", "text", "subject", "repeats"]) if (r[k] !== undefined) out[k] = r[k];
|
|
170
|
+
if (Array.isArray(r["detail"])) {
|
|
171
|
+
out["detail"] = (r["detail"] as { key?: unknown }[]).filter((d) => typeof d.key === "string" && DETAIL_KEYS.has(d.key));
|
|
172
|
+
}
|
|
173
|
+
return out;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Every `mem_…` id a row names, in its subject or its detail. */
|
|
177
|
+
const MEMORY_ID = /\bmem_[A-Za-z0-9]+\b/g;
|
|
178
|
+
|
|
179
|
+
/** The status, from an open observer source. Pure but for the reads. */
|
|
180
|
+
export function buildSidebarStatus(src: DashboardSource, now: number, build: string | null = installedVersion()): SidebarStatus {
|
|
181
|
+
const store = src.store;
|
|
182
|
+
// The newest rows, narrated as the activity feed narrates them, read by name
|
|
183
|
+
// and limit alone (the feed's own view also counts the whole log per call).
|
|
184
|
+
const newest = (filter: { name?: string; limit: number }): Row[] =>
|
|
185
|
+
store.eventLog({ ...filter, order: "desc" }).map((row) => narrate(store, row) as unknown as Row);
|
|
186
|
+
const recent = newest({ limit: RECENT_ROWS });
|
|
187
|
+
const p = { day: store.livedDay(), memories: memoriesHeld(src), lastSeq: recent[0]?.seq ?? 0 };
|
|
188
|
+
let today: SidebarStatus["today"] = null;
|
|
189
|
+
const panels: Record<string, Row[]> = {};
|
|
190
|
+
try {
|
|
191
|
+
const m = mechanismsView(src);
|
|
192
|
+
const counts: Record<string, number> = {};
|
|
193
|
+
for (const v of m.mechanisms as readonly { id: string; firedToday?: unknown }[]) {
|
|
194
|
+
if (typeof v.firedToday === "number") counts[v.id] = v.firedToday;
|
|
195
|
+
const activity = mechanismActivity(src, v.id) as unknown as Row[];
|
|
196
|
+
if (activity.length > 0) panels[v.id] = activity.map(slim);
|
|
197
|
+
}
|
|
198
|
+
today = { date: m.today, counts };
|
|
199
|
+
} catch {
|
|
200
|
+
today = null;
|
|
201
|
+
}
|
|
202
|
+
const bySeq = new Map<number, Row>();
|
|
203
|
+
const keep = (rows: readonly unknown[]): void => {
|
|
204
|
+
for (const r of rows as readonly Row[]) if (typeof r.seq === "number" && !bySeq.has(r.seq)) bySeq.set(r.seq, slim(r));
|
|
205
|
+
};
|
|
206
|
+
keep(recent);
|
|
207
|
+
for (const [name, limit] of Object.entries(NAMED_ROWS)) keep(newest({ name, limit }));
|
|
208
|
+
const events = [...bySeq.values()].sort((a, b) => b.seq - a.seq);
|
|
209
|
+
const dreams = dreamsView(src, DREAMS).dreams;
|
|
210
|
+
|
|
211
|
+
// The memories named, newest rows first, up to the cap.
|
|
212
|
+
const ids: string[] = [];
|
|
213
|
+
const seen = new Set<string>();
|
|
214
|
+
const collect = (v: unknown): void => {
|
|
215
|
+
for (const m of JSON.stringify(v).matchAll(MEMORY_ID)) {
|
|
216
|
+
if (ids.length >= MEMORY_CAP) return;
|
|
217
|
+
if (!seen.has(m[0])) {
|
|
218
|
+
seen.add(m[0]);
|
|
219
|
+
ids.push(m[0]);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
for (const e of events) collect(e);
|
|
224
|
+
for (const rows of Object.values(panels)) collect(rows);
|
|
225
|
+
collect(dreams);
|
|
226
|
+
const memories: Record<string, SidebarMemory | null> = {};
|
|
227
|
+
for (const id of ids) {
|
|
228
|
+
try {
|
|
229
|
+
const d = memoryDetail(src, id);
|
|
230
|
+
if (!d.found) {
|
|
231
|
+
memories[id] = null;
|
|
232
|
+
continue;
|
|
233
|
+
}
|
|
234
|
+
// A confidential body is the dashboard's own withheld sentence (`views/memory.ts`), never its words.
|
|
235
|
+
const text = d.text.trim();
|
|
236
|
+
memories[id] = {
|
|
237
|
+
title: d.title,
|
|
238
|
+
text: text.length > TEXT_CAP ? `${text.slice(0, TEXT_CAP).trimEnd()}…` : text,
|
|
239
|
+
cut: text.length > TEXT_CAP,
|
|
240
|
+
kind: d.journal ? null : d.kind,
|
|
241
|
+
learnedOn: d.learnedOn,
|
|
242
|
+
journal: d.journal,
|
|
243
|
+
};
|
|
244
|
+
} catch {
|
|
245
|
+
memories[id] = null;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
return {
|
|
249
|
+
version: SIDEBAR_STATUS_VERSION,
|
|
250
|
+
storeId: storeId(src.store.dir),
|
|
251
|
+
writtenAt: now,
|
|
252
|
+
build,
|
|
253
|
+
pulse: { day: p.day, memories: p.memories, lastSeq: p.lastSeq },
|
|
254
|
+
today,
|
|
255
|
+
dreams,
|
|
256
|
+
events,
|
|
257
|
+
panels,
|
|
258
|
+
memories,
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
export interface SidebarWrite {
|
|
263
|
+
readonly written: boolean;
|
|
264
|
+
/** `written`, or why not: `no-config`, `same` (the file already says this seq), or the error's code. */
|
|
265
|
+
readonly reason: string;
|
|
266
|
+
readonly bytes: number;
|
|
267
|
+
readonly ms: number;
|
|
268
|
+
readonly lastSeq: number | null;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** The `pulse.lastSeq` and `writtenAt` of the file as it stands, or null. */
|
|
272
|
+
export function readSidebarStamp(file: string): { lastSeq: number; writtenAt: number; storeId: string | null } | null {
|
|
273
|
+
try {
|
|
274
|
+
const v = JSON.parse(readFileSync(file, "utf8")) as Partial<SidebarStatus>;
|
|
275
|
+
if (v.version !== SIDEBAR_STATUS_VERSION || typeof v.pulse?.lastSeq !== "number" || typeof v.writtenAt !== "number") return null;
|
|
276
|
+
return { lastSeq: v.pulse.lastSeq, writtenAt: v.writtenAt, storeId: typeof v.storeId === "string" ? v.storeId : null };
|
|
277
|
+
} catch {
|
|
278
|
+
return null;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Open the store as an observer, build the status, write it beside the
|
|
284
|
+
* configuration. Never throws. `ifMoved`: skip when the file already stands at
|
|
285
|
+
* the log's newest seq for this store (another session's server wrote it) —
|
|
286
|
+
* unless it is older than `maxAgeMs`, so a calendar day's turn still lands.
|
|
287
|
+
*/
|
|
288
|
+
export function writeSidebarStatus(opts: {
|
|
289
|
+
readonly configPath: string;
|
|
290
|
+
readonly dataDir: string;
|
|
291
|
+
readonly timeZone?: string;
|
|
292
|
+
readonly ifMoved?: { readonly lastSeq: number; readonly maxAgeMs: number };
|
|
293
|
+
readonly now?: () => number;
|
|
294
|
+
}): SidebarWrite {
|
|
295
|
+
const clock = opts.now ?? Date.now;
|
|
296
|
+
const started = clock();
|
|
297
|
+
const out = (written: boolean, reason: string, bytes = 0, lastSeq: number | null = null): SidebarWrite => ({
|
|
298
|
+
written,
|
|
299
|
+
reason,
|
|
300
|
+
bytes,
|
|
301
|
+
ms: clock() - started,
|
|
302
|
+
lastSeq,
|
|
303
|
+
});
|
|
304
|
+
if (opts.configPath.length === 0 || opts.dataDir.length === 0) return out(false, "no-config");
|
|
305
|
+
const file = sidebarStatusPath(opts.configPath);
|
|
306
|
+
if (!existsSync(dirname(file))) return out(false, "no-config");
|
|
307
|
+
const ours = storeId(opts.dataDir);
|
|
308
|
+
if (opts.ifMoved !== undefined) {
|
|
309
|
+
const stamp = readSidebarStamp(file);
|
|
310
|
+
// Only this store's file stands in for this store's write: two stores sharing a folder never suppress each other.
|
|
311
|
+
if (stamp !== null && stamp.storeId === ours && stamp.lastSeq >= opts.ifMoved.lastSeq && started - stamp.writtenAt < opts.ifMoved.maxAgeMs) {
|
|
312
|
+
return out(false, "same", 0, stamp.lastSeq);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
let dash: Dashboard | null = null;
|
|
316
|
+
// One process writes one at a time (the write is synchronous), so its pid makes the name its own; `uninstall` knows the shape.
|
|
317
|
+
const tmp = `${file}.${String(process.pid)}.tmp`;
|
|
318
|
+
try {
|
|
319
|
+
dash = Dashboard.open({ dir: opts.dataDir, ...(opts.timeZone === undefined ? {} : { timeZone: opts.timeZone }) });
|
|
320
|
+
const status = buildSidebarStatus(dash.source, clock());
|
|
321
|
+
const text = JSON.stringify(status);
|
|
322
|
+
// Owner-only: it holds memories' words, as the store beside it does.
|
|
323
|
+
writeFileSync(tmp, text, { encoding: "utf8", mode: 0o600 });
|
|
324
|
+
try {
|
|
325
|
+
chmodSync(tmp, 0o600);
|
|
326
|
+
} catch {
|
|
327
|
+
// a filesystem without modes: the write stands
|
|
328
|
+
}
|
|
329
|
+
// Two writers racing: a file this store already wrote further on is not put back (the log only grows).
|
|
330
|
+
const there = readSidebarStamp(file);
|
|
331
|
+
if (there !== null && there.storeId !== null && there.storeId === status.storeId && there.lastSeq > status.pulse.lastSeq) {
|
|
332
|
+
rmSync(tmp, { force: true });
|
|
333
|
+
return out(false, "newer", 0, there.lastSeq);
|
|
334
|
+
}
|
|
335
|
+
renameSync(tmp, file);
|
|
336
|
+
notePointer(opts.dataDir, file);
|
|
337
|
+
return out(true, "written", Buffer.byteLength(text, "utf8"), status.pulse.lastSeq);
|
|
338
|
+
} catch (err) {
|
|
339
|
+
try {
|
|
340
|
+
rmSync(tmp, { force: true });
|
|
341
|
+
} catch {
|
|
342
|
+
// nothing more to do
|
|
343
|
+
}
|
|
344
|
+
const code =
|
|
345
|
+
err !== null && typeof err === "object" && typeof (err as { code?: unknown }).code === "string"
|
|
346
|
+
? (err as { code: string }).code
|
|
347
|
+
: err instanceof Error
|
|
348
|
+
? err.name
|
|
349
|
+
: "UNKNOWN";
|
|
350
|
+
return out(false, code);
|
|
351
|
+
} finally {
|
|
352
|
+
try {
|
|
353
|
+
dash?.close();
|
|
354
|
+
} catch {
|
|
355
|
+
// closed or never opened
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/** The path written for this store, kept in the store's `sessions/` (only when it changed). Never throws. */
|
|
361
|
+
function notePointer(dataDir: string, file: string): void {
|
|
362
|
+
try {
|
|
363
|
+
const at = sidebarPointerPath(dataDir);
|
|
364
|
+
if (existsSync(at) && readFileSync(at, "utf8") === file) return;
|
|
365
|
+
mkdirSync(dirname(at), { recursive: true });
|
|
366
|
+
writeFileSync(at, file, { encoding: "utf8", mode: 0o600 });
|
|
367
|
+
} catch {
|
|
368
|
+
// the beside-the-store guess still covers the usual layout
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* Every status file that may show this store: the one its pointer names (the
|
|
374
|
+
* last one written for it, wherever the configuration is) and the one beside
|
|
375
|
+
* the store's parent (the layout `install` writes: `<config dir>/store`).
|
|
376
|
+
*/
|
|
377
|
+
export function sidebarFilesFor(storeDir: string): string[] {
|
|
378
|
+
const out = [join(dirname(storeDir), SIDEBAR_FILE_NAME)];
|
|
379
|
+
try {
|
|
380
|
+
const named = readFileSync(sidebarPointerPath(storeDir), "utf8").trim();
|
|
381
|
+
if (isAbsolute(named) && named.endsWith(`/${SIDEBAR_FILE_NAME}`) && !out.includes(named)) out.push(named);
|
|
382
|
+
} catch {
|
|
383
|
+
// no pointer: the usual layout only
|
|
384
|
+
}
|
|
385
|
+
return out;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* A REMOVAL'S CHASE (the console's `remove`, which calls this): the status
|
|
390
|
+
* file holds a few memories' words, so a memory removed must not stay
|
|
391
|
+
* readable in it until the next write. Each file that may show this store
|
|
392
|
+
* (`sidebarFilesFor`) is deleted when it names the id; the next writer writes
|
|
393
|
+
* it again without the memory. Never throws: the answer is a surface line for
|
|
394
|
+
* the removal's report, or null when there was no file to look in.
|
|
395
|
+
*/
|
|
396
|
+
export function chaseSidebarStatus(storeDir: string, id: string): { chased: boolean; line: string } | null {
|
|
397
|
+
let looked = 0;
|
|
398
|
+
let deleted = 0;
|
|
399
|
+
const left: string[] = [];
|
|
400
|
+
for (const file of sidebarFilesFor(storeDir)) {
|
|
401
|
+
try {
|
|
402
|
+
if (!existsSync(file)) continue;
|
|
403
|
+
looked += 1;
|
|
404
|
+
if (!readFileSync(file, "utf8").includes(id)) continue;
|
|
405
|
+
rmSync(file, { force: true });
|
|
406
|
+
deleted += 1;
|
|
407
|
+
} catch {
|
|
408
|
+
left.push(file);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
if (left.length > 0) return { chased: false, line: `sidebar status file — ${left.join(", ")} may still name it until the next write` };
|
|
412
|
+
if (looked === 0) return null;
|
|
413
|
+
return {
|
|
414
|
+
chased: true,
|
|
415
|
+
line: deleted === 0 ? "sidebar status file (0, it did not name it)" : "sidebar status file (deleted; written again without it)",
|
|
416
|
+
};
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
/**
|
|
421
|
+
* The MCP server's writer: one timer at a time, never on a tool call's path
|
|
422
|
+
* (each write is scheduled after the answer went out), and a cheap look at the
|
|
423
|
+
* log's newest seq on an interval, so a turn's recall row, another session's
|
|
424
|
+
* deposit or a night's dream reaches the file within one interval; and once
|
|
425
|
+
* every {@link REFRESH_MS} whatever moved, so today's counts turn over at
|
|
426
|
+
* midnight and a file older than that says no writer is running (the sidebar
|
|
427
|
+
* shows its age then). Every timer is unref'd: none keeps the process alive.
|
|
428
|
+
*/
|
|
429
|
+
export class SidebarStatusWriter {
|
|
430
|
+
private timer: ReturnType<typeof setTimeout> | null = null;
|
|
431
|
+
private interval: ReturnType<typeof setInterval> | null = null;
|
|
432
|
+
private lastSeq = -1;
|
|
433
|
+
private lastLookAt = Date.now();
|
|
434
|
+
private stopped = false;
|
|
435
|
+
|
|
436
|
+
private readonly opts: {
|
|
437
|
+
readonly configPath: string;
|
|
438
|
+
readonly dataDir: string;
|
|
439
|
+
readonly timeZone?: string;
|
|
440
|
+
/** The log's newest seq, read cheaply on the server's own handle; null when it cannot say. */
|
|
441
|
+
readonly newestSeq: () => number | null;
|
|
442
|
+
readonly onWrite?: (w: SidebarWrite) => void;
|
|
443
|
+
};
|
|
444
|
+
|
|
445
|
+
constructor(opts: SidebarStatusWriter["opts"]) {
|
|
446
|
+
this.opts = opts;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/** Write once, `delayMs` from now; a write already waiting keeps its time. */
|
|
450
|
+
schedule(delayMs: number): void {
|
|
451
|
+
if (this.stopped || this.timer !== null) return;
|
|
452
|
+
this.timer = setTimeout(() => {
|
|
453
|
+
this.timer = null;
|
|
454
|
+
this.writeNow();
|
|
455
|
+
}, delayMs);
|
|
456
|
+
this.timer.unref?.();
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/** Look at the log every `everyMs`; a moved one schedules a write. */
|
|
460
|
+
watch(everyMs: number): void {
|
|
461
|
+
if (this.stopped || this.interval !== null) return;
|
|
462
|
+
this.interval = setInterval(() => {
|
|
463
|
+
let seq: number | null = null;
|
|
464
|
+
try {
|
|
465
|
+
seq = this.opts.newestSeq();
|
|
466
|
+
} catch {
|
|
467
|
+
seq = null;
|
|
468
|
+
}
|
|
469
|
+
if ((seq !== null && seq > this.lastSeq) || Date.now() - this.lastLookAt > REFRESH_MS) this.schedule(0);
|
|
470
|
+
}, everyMs);
|
|
471
|
+
this.interval.unref?.();
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
stop(): void {
|
|
475
|
+
this.stopped = true;
|
|
476
|
+
if (this.timer !== null) clearTimeout(this.timer);
|
|
477
|
+
if (this.interval !== null) clearInterval(this.interval);
|
|
478
|
+
this.timer = null;
|
|
479
|
+
this.interval = null;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
private writeNow(): void {
|
|
483
|
+
let seq: number | null = null;
|
|
484
|
+
try {
|
|
485
|
+
seq = this.opts.newestSeq();
|
|
486
|
+
} catch {
|
|
487
|
+
seq = null;
|
|
488
|
+
}
|
|
489
|
+
const w = writeSidebarStatus({
|
|
490
|
+
configPath: this.opts.configPath,
|
|
491
|
+
dataDir: this.opts.dataDir,
|
|
492
|
+
...(this.opts.timeZone === undefined ? {} : { timeZone: this.opts.timeZone }),
|
|
493
|
+
// Another session's server may have written this very seq a moment ago.
|
|
494
|
+
...(seq === null ? {} : { ifMoved: { lastSeq: seq, maxAgeMs: 10 * 60_000 } }),
|
|
495
|
+
});
|
|
496
|
+
this.lastLookAt = Date.now();
|
|
497
|
+
if (w.lastSeq !== null) this.lastSeq = Math.max(this.lastSeq, w.lastSeq);
|
|
498
|
+
else if (seq !== null) this.lastSeq = Math.max(this.lastSeq, seq);
|
|
499
|
+
try {
|
|
500
|
+
this.opts.onWrite?.(w);
|
|
501
|
+
} catch {
|
|
502
|
+
// a log that will not take the line costs nothing here
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
}
|
package/src/adapters/spawn.ts
CHANGED
|
@@ -44,7 +44,6 @@
|
|
|
44
44
|
* testing is in the pure half.
|
|
45
45
|
*/
|
|
46
46
|
import { spawn } from "node:child_process";
|
|
47
|
-
import { fileURLToPath } from "node:url";
|
|
48
47
|
|
|
49
48
|
import { TUNABLES as REMEMBER, validateWatchdog } from "../core/remember/index.js";
|
|
50
49
|
|
|
@@ -52,6 +51,7 @@ import { CONFIG_ENV as CONFIG_PATH_ENV } from "./config-path.js";
|
|
|
52
51
|
|
|
53
52
|
import { TUNABLES } from "./config.js";
|
|
54
53
|
import type { AdapterConfig } from "./config.js";
|
|
54
|
+
import { entryScript } from "./runtime.js";
|
|
55
55
|
|
|
56
56
|
/**
|
|
57
57
|
* THE WORKER SCRIPT, resolved from THIS file's location — never from a working
|
|
@@ -60,7 +60,7 @@ import type { AdapterConfig } from "./config.js";
|
|
|
60
60
|
* server — Claude Desktop's `wake` starts the worker too — can name it without
|
|
61
61
|
* importing that adapter. `claude-code/bin/hook.ts#RUNNER_PATH` is this value.
|
|
62
62
|
*/
|
|
63
|
-
export const WORKER_RUNNER_PATH =
|
|
63
|
+
export const WORKER_RUNNER_PATH = entryScript(new URL("./claude-code/bin/runner.ts", import.meta.url));
|
|
64
64
|
|
|
65
65
|
export const DATA_DIR_ENV = "COUNTERPARTS_DATA_DIR";
|
|
66
66
|
/** The child is told its own watchdog, so the worker can arm one internally too. */
|
package/src/core/dream/index.ts
CHANGED
|
@@ -2643,7 +2643,7 @@ export class Dreams {
|
|
|
2643
2643
|
const raise = theirs(a) || theirs(b) ? ` It is about ${who}, or the two of you: raise it with ${who}.` : "";
|
|
2644
2644
|
const when = c.dream_id === null ? "" : ` a dream on ${this.store.dream(c.dream_id)?.date ?? "a recent night"} flagged them;`;
|
|
2645
2645
|
out.push(
|
|
2646
|
-
`Counterparts: two memories disagree —${when} ${c.a} (the older) and ${c.b}.
|
|
2646
|
+
`Counterparts: two memories disagree —${when} ${c.a} (the older) and ${c.b}. You can look them up (recall by id) and settle which holds, awake, with the remember tool's settle {pair: ${c.id}, holds, how, why} — changed, corrected or open.${raise}`,
|
|
2647
2647
|
);
|
|
2648
2648
|
if (out.length >= 2) return out;
|
|
2649
2649
|
}
|
|
@@ -1511,8 +1511,8 @@ export class Reflections {
|
|
|
1511
1511
|
return `${head}\n${reflectionOpener(row.id)} I reflected afterwards${nothingMuch ? " — nothing much tonight" : ""}; nothing to share this morning.${pageLine}${also}`;
|
|
1512
1512
|
}
|
|
1513
1513
|
return (
|
|
1514
|
-
`${head}\n${reflectionOpener(row.id)} I reflected afterwards.${pageLine} Morning share for ${who} — tell it in your own words, as a telling ("While I slept I dreamed…", "I've been thinking…"), tentatively where it is about ${who}
|
|
1515
|
-
`
|
|
1514
|
+
`${head}\n${reflectionOpener(row.id)} I reflected afterwards.${pageLine} Morning share for ${who} — tell it in your own words, as a telling ("While I slept I dreamed…", "I've been thinking…"), tentatively where it is about ${who}. ` +
|
|
1515
|
+
`Once you have told it, the counterparts reflect tool's phase "told", reflection: ${row.id}, marks it told, so another session does not carry it and tell it again.\n${share}`
|
|
1516
1516
|
);
|
|
1517
1517
|
}
|
|
1518
1518
|
|
|
@@ -1556,7 +1556,8 @@ export class Reflections {
|
|
|
1556
1556
|
/**
|
|
1557
1557
|
* CARRY A SHARE the session that reflected never told — its session ended
|
|
1558
1558
|
* (the adapter checks that). Claimed once (`carried`); the line asks the
|
|
1559
|
-
* model to tell it and
|
|
1559
|
+
* model to tell it and notes that `told` marks it (a note, not an order:
|
|
1560
|
+
* Software Directory Policy §2D, 2026-10-14). Null when there is none to carry.
|
|
1560
1561
|
*/
|
|
1561
1562
|
carryLine(input: { session: string; reflection: string }): string | null {
|
|
1562
1563
|
if (this.ctx.observer) return null;
|
|
@@ -1571,8 +1572,8 @@ export class Reflections {
|
|
|
1571
1572
|
const who = this.ctx.ownerName() ?? "the owner";
|
|
1572
1573
|
const when = row.date ?? "recently";
|
|
1573
1574
|
return (
|
|
1574
|
-
`Counterparts: after reflecting on ${when}, you left a morning share for ${who} that was never told. At a natural moment — not mid-task — tell it in your own words, as a telling ("When I last reflected…"), tentatively where it is about ${who}
|
|
1575
|
-
`
|
|
1575
|
+
`Counterparts: after reflecting on ${when}, you left a morning share for ${who} that was never told. At a natural moment — not mid-task — tell it in your own words, as a telling ("When I last reflected…"), tentatively where it is about ${who}. ` +
|
|
1576
|
+
`Once you have told it, the counterparts reflect tool's phase "told", reflection: ${row.id}, marks it told. The share: ${row.share}`
|
|
1576
1577
|
);
|
|
1577
1578
|
}
|
|
1578
1579
|
|
package/src/core/onboarding.ts
CHANGED
|
@@ -606,7 +606,10 @@ export function finishText(ctx: Pick<MeetContext, "name" | "dreaming" | "plugin"
|
|
|
606
606
|
|
|
607
607
|
/**
|
|
608
608
|
* THE WAKE'S LINE (hosts with or without the mod): one short instruction,
|
|
609
|
-
* never a takeover.
|
|
609
|
+
* never a takeover. It OFFERS the meeting to the person and describes the
|
|
610
|
+
* `meet` tool as where the script lives and how the offer is recorded — it
|
|
611
|
+
* never orders a tool call ahead of what they asked (Software Directory
|
|
612
|
+
* Policy §2D, 2026-10-14). The mod's own prompt ("Meet your new counterpart." since
|
|
610
613
|
* 2026-10-12; any wording that asks to meet or for an introduction) is the
|
|
611
614
|
* same offer, and the line says so, so the two never make two offers.
|
|
612
615
|
* The offer is ASKED ONCE (B, 2026-10-12): one warm line of introduction, then
|
|
@@ -615,7 +618,7 @@ export function finishText(ctx: Pick<MeetContext, "name" | "dreaming" | "plugin"
|
|
|
615
618
|
export function offerLine(state: MeetState): string {
|
|
616
619
|
return [
|
|
617
620
|
"<counterparts-meet>",
|
|
618
|
-
`You and the person haven't properly met yet${state === "later" ? " (last time they said later)" : ""}.
|
|
621
|
+
`You and the person haven't properly met yet${state === "later" ? " (last time they said later)" : ""}. They installed a memory plugin to be known, so offer them a first meeting: at the end of your first reply, never instead of answering them, introduce yourself in one warm line and offer about five minutes to get to know each other — asked once, through the question dialog if the host has one, not also in prose. The counterparts \`meet\` tool holds the meeting's script and records that the offer was made, so make the offer through it. If their message asks to meet you or asks you to introduce yourself (the counterparts sidebar sends \"Meet your new counterpart.\"), that is this meeting: begin it with that introduction.`,
|
|
619
622
|
"</counterparts-meet>",
|
|
620
623
|
].join("\n");
|
|
621
624
|
}
|