sideby 0.41.3 → 0.42.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/dist/build.json +1 -1
- package/dist/src/cli/commands.d.ts +2 -0
- package/dist/src/cli/commands.js +100 -0
- package/dist/src/cli/json-schemas.js +44 -0
- package/dist/src/cli/main.js +32 -1
- package/dist/src/core/claude-memory.d.ts +236 -0
- package/dist/src/core/claude-memory.js +937 -0
- package/dist/src/core/cli-commands.js +15 -2
- package/dist/src/core/config.d.ts +1 -0
- package/dist/src/core/config.js +4 -1
- package/dist/src/core/search-catalog.js +22 -0
- package/dist/src/core/session-hooks.d.ts +12 -2
- package/dist/src/core/session-hooks.js +12 -8
- package/dist/src/families/claude/layout.d.ts +7 -0
- package/dist/src/families/claude/layout.js +17 -0
- package/dist/src/families/claude/live-sessions.js +2 -1
- package/dist/src/panel/handler.d.ts +11 -0
- package/dist/src/panel/handler.js +21 -0
- package/dist/src/panel/i18n.d.ts +12 -0
- package/dist/src/panel/i18n.js +24 -0
- package/dist/src/panel/page-script.js +35 -1
- package/dist/src/panel/page-styles.js +1 -0
- package/dist/src/runtime.d.ts +30 -0
- package/dist/src/runtime.js +85 -1
- package/package.json +1 -1
- package/schemas/config.json +5 -1
- package/schemas/memory-set.json +117 -0
- package/schemas/memory.json +210 -0
- package/skills/sideby/SKILL.md +2 -1
- package/skills/sideby/references/sharing.md +23 -1
|
@@ -0,0 +1,937 @@
|
|
|
1
|
+
// Shared Project Memory (spec §3.44, ADR-0081). Claude Code keeps auto memory per config directory, at
|
|
2
|
+
// `<config dir>/projects/<project>/memory/`, so every Claude Account holds its own copy for the same Project. With
|
|
3
|
+
// config `claude.shareMemory` on, a Launch names the Main Account's real folder for the Project as
|
|
4
|
+
// `autoMemoryDirectory` (through sideby's own `--settings` file, `memoryHookPart`), and Doctor folds what an Account
|
|
5
|
+
// wrote on its own (sessions sideby did not start) into the Main Account.
|
|
6
|
+
//
|
|
7
|
+
// Nothing here follows a link out of an Account folder or into the Main Account: a link anywhere on the way is
|
|
8
|
+
// reported and left alone. Nothing is deleted: a folder that was emptied goes to the system trash, or into sideby's
|
|
9
|
+
// state folder when there is no trash sideby may use.
|
|
10
|
+
import { randomBytes } from 'node:crypto';
|
|
11
|
+
import { constants } from 'node:fs';
|
|
12
|
+
import { link, lstat, mkdir, open, readdir, realpath, rename, rm, rmdir, unlink, utimes, } from 'node:fs/promises';
|
|
13
|
+
import { userInfo } from 'node:os';
|
|
14
|
+
import { basename, dirname, extname, join, posix } from 'node:path';
|
|
15
|
+
import { claudeProjectDirName } from '../families/claude/layout.js';
|
|
16
|
+
import { readSessionRecord, recordRunsOn, recordStart } from '../families/claude/session-files.js';
|
|
17
|
+
import { trustRoot } from './claude-trust.js';
|
|
18
|
+
import { assertInside, lstatOrNull, ownedFolder, readSmallFile, sha256, writeFileAtomic, writeIfUnchanged, } from './fs-safe.js';
|
|
19
|
+
/** The index Claude Code keeps in each memory folder. */
|
|
20
|
+
export const MEMORY_INDEX = 'MEMORY.md';
|
|
21
|
+
/** An index larger than this is not read or merged. */
|
|
22
|
+
const MAX_INDEX_BYTES = 1024 * 1024;
|
|
23
|
+
/** Folders sideby looks into for the name check, at most; each is one small read. */
|
|
24
|
+
const NAME_CHECK_FOLDERS = 40;
|
|
25
|
+
/** The entry at `p` is a real folder (not a link), missing (`null`), or something else (`false`). */
|
|
26
|
+
async function realFolder(p) {
|
|
27
|
+
const st = await lstatOrNull(p);
|
|
28
|
+
if (!st)
|
|
29
|
+
return null;
|
|
30
|
+
return st.isDirectory() && !st.isSymbolicLink();
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Where Claude Code keeps auto memory for `cwd`, by its own rule (ADR-0081): the git repository's main checkout root
|
|
34
|
+
* (a linked worktree and every subfolder use it), elsewhere the folder itself; real paths; named with
|
|
35
|
+
* `claudeProjectDirName`. Read from files only, never by running `git` (`trustRoot`). `skip` when sideby cannot tell
|
|
36
|
+
* (a submodule, a separate git folder), when the Main Account has no folder yet, or when a folder on the way under
|
|
37
|
+
* the Main Account is a link (Claude Code refuses memory writes through one, anthropics/claude-code#108770).
|
|
38
|
+
*/
|
|
39
|
+
export async function memoryTarget(mainDir, cwd) {
|
|
40
|
+
const root = await trustRoot(cwd);
|
|
41
|
+
if (root.kind === 'unclear')
|
|
42
|
+
return { status: 'skip', why: root.why };
|
|
43
|
+
let main;
|
|
44
|
+
try {
|
|
45
|
+
main = await realpath(mainDir);
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return { status: 'skip', why: `${mainDir} does not exist yet (start the main account once)` };
|
|
49
|
+
}
|
|
50
|
+
const name = claudeProjectDirName(root.path);
|
|
51
|
+
const dir = join(main, 'projects', name, 'memory');
|
|
52
|
+
for (const p of [join(main, 'projects'), join(main, 'projects', name), dir])
|
|
53
|
+
if ((await realFolder(p)) === false)
|
|
54
|
+
return { status: 'skip', why: `${p} is a link or not a folder` };
|
|
55
|
+
return { status: 'ok', root: root.path, name, dir };
|
|
56
|
+
}
|
|
57
|
+
/** The session settings part that sends a Claude session's auto memory to `dir` (one file per folder, ADR-0081). */
|
|
58
|
+
export function memoryHookPart(dir) {
|
|
59
|
+
return {
|
|
60
|
+
id: 'memory',
|
|
61
|
+
claude: {},
|
|
62
|
+
codex: {},
|
|
63
|
+
settings: { autoMemoryDirectory: dir },
|
|
64
|
+
fileKey: sha256(dir).slice(0, 12),
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
const prefersChinese = (env) => /^zh/i.test(env.LC_ALL || env.LC_MESSAGES || env.LANG || '');
|
|
68
|
+
/** The line a Claude Launch prints when the user's own `--settings` leaves no room for the memory folder. */
|
|
69
|
+
export function memorySettingsLine(env) {
|
|
70
|
+
return prefersChinese(env)
|
|
71
|
+
? 'sideby:已经给了 `--settings`,这个会话不用共享记忆,用这个账号自己的记忆(`sideby doctor --fix` 之后会把它移进主账号)。'
|
|
72
|
+
: "sideby: `--settings` is already given, so this session uses this account's own memory instead of the shared one (`sideby doctor --fix` moves it into the main account later).";
|
|
73
|
+
}
|
|
74
|
+
/** The line a Claude Launch prints when sideby cannot tell where the Project's memory belongs. */
|
|
75
|
+
export function memorySkipLine(env, why) {
|
|
76
|
+
return prefersChinese(env)
|
|
77
|
+
? `sideby:这个会话不用共享记忆(${why}),用这个账号自己的记忆。`
|
|
78
|
+
: `sideby: this session uses this account's own memory instead of the shared one (${why}).`;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* An Account's own memory: every `projects/<project>/memory` folder with at least one entry. A link anywhere on the
|
|
82
|
+
* way (`projects`, the Project folder, `memory`) is not followed: it is named in `links`.
|
|
83
|
+
*/
|
|
84
|
+
export async function accountMemories(accountDir) {
|
|
85
|
+
const projects = join(accountDir, 'projects');
|
|
86
|
+
const links = [];
|
|
87
|
+
const kind = await realFolder(projects);
|
|
88
|
+
if (kind === null)
|
|
89
|
+
return { list: [], links };
|
|
90
|
+
if (kind === false) {
|
|
91
|
+
if ((await lstatOrNull(projects))?.isSymbolicLink())
|
|
92
|
+
links.push(projects);
|
|
93
|
+
return { list: [], links };
|
|
94
|
+
}
|
|
95
|
+
const list = [];
|
|
96
|
+
for (const project of (await readdir(projects).catch(() => [])).sort()) {
|
|
97
|
+
const folder = join(projects, project);
|
|
98
|
+
const st = await lstatOrNull(folder);
|
|
99
|
+
if (!st?.isDirectory())
|
|
100
|
+
continue;
|
|
101
|
+
const dir = join(folder, 'memory');
|
|
102
|
+
// A stage left by a fold that stopped halfway still holds memory, even when `memory/` is empty or gone.
|
|
103
|
+
const staged = await stagedFiles(join(folder, FOLD_STAGE));
|
|
104
|
+
const mem = await lstatOrNull(dir);
|
|
105
|
+
if (!mem) {
|
|
106
|
+
if (staged)
|
|
107
|
+
list.push({ project, dir, files: staged });
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
if (mem.isSymbolicLink()) {
|
|
111
|
+
links.push(dir);
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
if (!mem.isDirectory())
|
|
115
|
+
continue;
|
|
116
|
+
const files = (await readdir(dir).catch(() => [])).filter((n) => n !== '.DS_Store').length + staged;
|
|
117
|
+
if (files)
|
|
118
|
+
list.push({ project, dir, files });
|
|
119
|
+
}
|
|
120
|
+
return { list, links };
|
|
121
|
+
}
|
|
122
|
+
/** How many entries a fold's stage still holds (a stage that is a link or not a folder counts as one, for Fix to report). */
|
|
123
|
+
async function stagedFiles(stage) {
|
|
124
|
+
const st = await lstatOrNull(stage);
|
|
125
|
+
if (!st)
|
|
126
|
+
return 0;
|
|
127
|
+
if (!st.isDirectory() || st.isSymbolicLink())
|
|
128
|
+
return 1;
|
|
129
|
+
return (await readdir(stage).catch(() => [])).filter((n) => n !== '.DS_Store').length;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Moves `path` to the system trash with the `trash` command on PATH (macOS 14 and later ship `/usr/bin/trash`; Linux
|
|
133
|
+
* has `trash-cli`), only when HOME is the user's own home (a demo or test HOME never reaches the real trash). Without
|
|
134
|
+
* one, it moves the folder into `<state>/memory/trash/` and names it there. Never deletes anything.
|
|
135
|
+
*/
|
|
136
|
+
export function systemTrash(env, stateDir, now) {
|
|
137
|
+
return async (path) => {
|
|
138
|
+
// The home of the user's account (the password database), not `$HOME`: a demo or test HOME sets `$HOME`.
|
|
139
|
+
const own = await Promise.all([
|
|
140
|
+
realpath(env.HOME ?? '').catch(() => ''),
|
|
141
|
+
realpath(userHome()).catch(() => ''),
|
|
142
|
+
]);
|
|
143
|
+
if (own[0] && own[0] === own[1]) {
|
|
144
|
+
const { which } = await import('./launch.js');
|
|
145
|
+
const bin = await which('trash', env);
|
|
146
|
+
if (bin) {
|
|
147
|
+
const { execFile } = await import('node:child_process');
|
|
148
|
+
const ok = await new Promise((resolve) => execFile(bin, [path], { env: env, timeout: 30_000 }, (err) => resolve(!err)));
|
|
149
|
+
if (ok && !(await lstatOrNull(path)))
|
|
150
|
+
return { ok: true, to: 'the trash' };
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return keepInState(path, stateDir, now());
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
function userHome() {
|
|
157
|
+
try {
|
|
158
|
+
return userInfo().homedir;
|
|
159
|
+
}
|
|
160
|
+
catch {
|
|
161
|
+
return '';
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
/** Moves `path` into `<state>/memory/trash/<time>-<name>`; the folder is the user's own (700). */
|
|
165
|
+
export async function keepInState(path, stateDir, at) {
|
|
166
|
+
try {
|
|
167
|
+
const dir = await ownedFolder(stateDir, ['memory', 'trash'], { create: true, private: true });
|
|
168
|
+
if (!dir)
|
|
169
|
+
return { ok: false, why: "sideby's state folder cannot be used" };
|
|
170
|
+
const stamp = at.toISOString().replace(/[:.]/g, '-');
|
|
171
|
+
const parts = path.split(/[\\/]+/).filter(Boolean);
|
|
172
|
+
const label = parts
|
|
173
|
+
.slice(-4)
|
|
174
|
+
.join('_')
|
|
175
|
+
.replace(/[^A-Za-z0-9._-]/g, '-');
|
|
176
|
+
const to = join(dir, `${stamp}-${label}`);
|
|
177
|
+
await rename(path, to);
|
|
178
|
+
return { ok: true, to };
|
|
179
|
+
}
|
|
180
|
+
catch (err) {
|
|
181
|
+
return {
|
|
182
|
+
ok: false,
|
|
183
|
+
why: `${path} could not be moved (${err.code ?? 'error'})`,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
const PID_FILE = /^(\d+)\.json$/;
|
|
188
|
+
/**
|
|
189
|
+
* The working folders of a Claude Account's Live Sessions, from Claude Code's `sessions/<pid>.json` files and the
|
|
190
|
+
* process list. It fails closed: a record of a running process that cannot be read (one Claude Code is rewriting),
|
|
191
|
+
* lacks its session id, working folder or start time, or a process list that cannot be read, means sideby cannot
|
|
192
|
+
* tell which Projects are in use, so the Fix moves nothing of that Account. Only a record whose process is gone, or
|
|
193
|
+
* whose pid now belongs to another process (its start time differs), counts as ended.
|
|
194
|
+
*/
|
|
195
|
+
export async function claudeLiveCwds(account, procs) {
|
|
196
|
+
const root = join(account.dir, 'sessions');
|
|
197
|
+
let names;
|
|
198
|
+
try {
|
|
199
|
+
names = await readdir(root);
|
|
200
|
+
}
|
|
201
|
+
catch (err) {
|
|
202
|
+
if (err.code === 'ENOENT')
|
|
203
|
+
return { cwds: [] };
|
|
204
|
+
return { unknown: `${root} cannot be read` };
|
|
205
|
+
}
|
|
206
|
+
const files = names.filter((n) => PID_FILE.test(n)).sort();
|
|
207
|
+
if (!files.length)
|
|
208
|
+
return { cwds: [] };
|
|
209
|
+
try {
|
|
210
|
+
await procs.list();
|
|
211
|
+
}
|
|
212
|
+
catch (err) {
|
|
213
|
+
return { unknown: `the running programs cannot be listed (${err.message})` };
|
|
214
|
+
}
|
|
215
|
+
const cwds = [];
|
|
216
|
+
for (const name of files) {
|
|
217
|
+
const proc = await procs.get(Number(PID_FILE.exec(name)[1]));
|
|
218
|
+
if (!proc)
|
|
219
|
+
continue;
|
|
220
|
+
const file = join(root, name);
|
|
221
|
+
const rec = await readSessionRecord(file);
|
|
222
|
+
if (!rec)
|
|
223
|
+
return { unknown: `${file} cannot be read right now (Claude Code rewrites it as it runs)` };
|
|
224
|
+
if (Number.isNaN(recordStart(rec)))
|
|
225
|
+
return { unknown: `${file} has no start time sideby can read` };
|
|
226
|
+
// The pid belongs to another process now: that session ended.
|
|
227
|
+
if (!recordRunsOn(rec, proc))
|
|
228
|
+
continue;
|
|
229
|
+
const cwd = typeof rec.cwd === 'string' && rec.cwd ? rec.cwd : undefined;
|
|
230
|
+
const id = typeof rec.sessionId === 'string' && rec.sessionId ? rec.sessionId : undefined;
|
|
231
|
+
if (!cwd || !id)
|
|
232
|
+
return { unknown: `${file} does not say which ${cwd ? 'session' : 'folder'} it runs` };
|
|
233
|
+
cwds.push(cwd);
|
|
234
|
+
}
|
|
235
|
+
return { cwds };
|
|
236
|
+
}
|
|
237
|
+
/** The names of the session folders a Live Session in each of `cwds` uses for memory (its Project, and itself). */
|
|
238
|
+
export async function liveProjects(cwds) {
|
|
239
|
+
const out = new Set();
|
|
240
|
+
for (const cwd of cwds) {
|
|
241
|
+
out.add(claudeProjectDirName(cwd));
|
|
242
|
+
const real = await realpath(cwd).catch(() => null);
|
|
243
|
+
if (real)
|
|
244
|
+
out.add(claudeProjectDirName(real));
|
|
245
|
+
const root = await trustRoot(cwd);
|
|
246
|
+
if (root.kind !== 'unclear')
|
|
247
|
+
out.add(claudeProjectDirName(root.path));
|
|
248
|
+
}
|
|
249
|
+
return out;
|
|
250
|
+
}
|
|
251
|
+
/** `name` with `.<account>` before its extension, then `-2`, `-3`… (`notes.md` → `notes.work.md`, `notes.work-2.md`). */
|
|
252
|
+
function altName(name, account, n) {
|
|
253
|
+
const ext = extname(name);
|
|
254
|
+
const stem = ext ? name.slice(0, -ext.length) : name;
|
|
255
|
+
return `${stem}.${account}${n > 1 ? `-${n}` : ''}${ext}`;
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* The memory file a link in `MEMORY.md` points at, with its `#fragment`: the target resolved against the memory
|
|
259
|
+
* folder (`a.md`, `./a.md`, `../memory/a.md` and `a.md#section` all name `a.md`). Null for a link with a scheme, an
|
|
260
|
+
* absolute path, or a file outside the memory folder.
|
|
261
|
+
*/
|
|
262
|
+
export function memoryLink(target) {
|
|
263
|
+
const at = target.indexOf('#');
|
|
264
|
+
const path = at < 0 ? target : target.slice(0, at);
|
|
265
|
+
const fragment = at < 0 ? '' : target.slice(at);
|
|
266
|
+
if (!path || path.startsWith('/') || /^[A-Za-z][A-Za-z0-9+.-]*:/.test(path))
|
|
267
|
+
return null;
|
|
268
|
+
const resolved = posix.normalize(posix.join('project/memory', path));
|
|
269
|
+
return posix.dirname(resolved) === 'project/memory' ? { file: posix.basename(resolved), fragment } : null;
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* An index with every link to a renamed file pointing at its new name (its `#fragment` kept), in one pass over the
|
|
273
|
+
* links, each resolved against the memory folder, so one rename never feeds another.
|
|
274
|
+
*/
|
|
275
|
+
export function rewriteLinks(text, renamed) {
|
|
276
|
+
if (!renamed.size)
|
|
277
|
+
return text;
|
|
278
|
+
return text.replace(/\]\(([^)\s]+)\)/g, (all, target) => {
|
|
279
|
+
const link = memoryLink(target);
|
|
280
|
+
const to = link && renamed.get(link.file);
|
|
281
|
+
return to === undefined || to === null ? all : `](${to}${link.fragment})`;
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
/** A memory note larger than this is not moved (Claude Code keeps them to a few KB). */
|
|
285
|
+
const MAX_NOTE_BYTES = 4 * 1024 * 1024;
|
|
286
|
+
/** Every entry of a memory folder, read once without following a link; or why sideby leaves the folder alone. */
|
|
287
|
+
async function readFolder(dir) {
|
|
288
|
+
const names = (await readdir(dir)).filter((n) => n !== '.DS_Store').sort();
|
|
289
|
+
const files = new Map();
|
|
290
|
+
for (const n of names) {
|
|
291
|
+
const p = join(dir, n);
|
|
292
|
+
const st = await lstat(p);
|
|
293
|
+
if (!st.isFile())
|
|
294
|
+
return {
|
|
295
|
+
why: `${p} is ${st.isSymbolicLink() ? 'a link' : 'not a file'}; sideby moves only folders of plain files and left this one as it is`,
|
|
296
|
+
};
|
|
297
|
+
if (st.size > MAX_NOTE_BYTES)
|
|
298
|
+
return { why: `${p} is too large to move` };
|
|
299
|
+
const data = await readNoFollow(p);
|
|
300
|
+
if (!data)
|
|
301
|
+
return { why: `${p} cannot be read` };
|
|
302
|
+
files.set(n, { data, hash: sha256(data), atime: st.atime, mtime: st.mtime });
|
|
303
|
+
}
|
|
304
|
+
return { names, files };
|
|
305
|
+
}
|
|
306
|
+
/** The bytes of a regular file, opened without following a link; null when that fails. */
|
|
307
|
+
async function readNoFollow(p) {
|
|
308
|
+
let fh;
|
|
309
|
+
try {
|
|
310
|
+
fh = await open(p, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
311
|
+
if (!(await fh.stat()).isFile())
|
|
312
|
+
return null;
|
|
313
|
+
return await fh.readFile();
|
|
314
|
+
}
|
|
315
|
+
catch {
|
|
316
|
+
return null;
|
|
317
|
+
}
|
|
318
|
+
finally {
|
|
319
|
+
await fh?.close().catch(() => { });
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* Writes a new file at `path` and never over one: the bytes go to a temp file beside it (fsynced, times set), which is
|
|
324
|
+
* then hard-linked to `path` (that fails when the name is taken) and removed. A write that fails partway leaves only
|
|
325
|
+
* the temp file, which is removed, so a retry finds the name free.
|
|
326
|
+
*/
|
|
327
|
+
async function writeNew(path, note, write) {
|
|
328
|
+
const tmp = join(dirname(path), `.${basename(path)}.sideby-${randomBytes(6).toString('hex')}.tmp`);
|
|
329
|
+
const fh = await open(tmp, 'wx', 0o644);
|
|
330
|
+
try {
|
|
331
|
+
try {
|
|
332
|
+
await write(fh, note.data);
|
|
333
|
+
await fh.sync();
|
|
334
|
+
}
|
|
335
|
+
finally {
|
|
336
|
+
await fh.close();
|
|
337
|
+
}
|
|
338
|
+
await utimes(tmp, note.atime, note.mtime);
|
|
339
|
+
await link(tmp, path);
|
|
340
|
+
}
|
|
341
|
+
finally {
|
|
342
|
+
await rm(tmp, { force: true });
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
const hashOf = async (p) => {
|
|
346
|
+
const data = await readNoFollow(p);
|
|
347
|
+
return data ? sha256(data) : null;
|
|
348
|
+
};
|
|
349
|
+
/** `into` with every line of `from` it does not hold yet (trailing spaces ignored), in order; and how many. */
|
|
350
|
+
export function mergeIndex(into, from) {
|
|
351
|
+
const have = new Set(into.split('\n').map((l) => l.trimEnd()));
|
|
352
|
+
const add = [];
|
|
353
|
+
for (const line of from.split('\n')) {
|
|
354
|
+
const l = line.trimEnd();
|
|
355
|
+
if (!l.trim() || have.has(l))
|
|
356
|
+
continue;
|
|
357
|
+
have.add(l);
|
|
358
|
+
add.push(l);
|
|
359
|
+
}
|
|
360
|
+
if (!add.length)
|
|
361
|
+
return { text: into, added: 0 };
|
|
362
|
+
const base = into.length && !into.endsWith('\n') ? `${into}\n` : into;
|
|
363
|
+
return { text: `${base}${add.join('\n')}\n`, added: add.length };
|
|
364
|
+
}
|
|
365
|
+
/** The folder beside an Account's `memory` that holds the files being taken out, until they go to the trash. */
|
|
366
|
+
export const FOLD_STAGE = 'memory-folded-by-sideby';
|
|
367
|
+
/**
|
|
368
|
+
* Moves a plain file to `to` without ever replacing one there: a hard link (which fails when the name is taken), then
|
|
369
|
+
* the old name removed. `taken` when `to` exists, `error` when the move cannot be made at all.
|
|
370
|
+
*/
|
|
371
|
+
async function moveNoClobber(from, to) {
|
|
372
|
+
try {
|
|
373
|
+
await link(from, to);
|
|
374
|
+
}
|
|
375
|
+
catch (err) {
|
|
376
|
+
return err.code === 'EEXIST' ? 'taken' : 'error';
|
|
377
|
+
}
|
|
378
|
+
// Should removing the old name fail, both names point at the same file: trashing the stage leaves `to` intact.
|
|
379
|
+
await unlink(from).catch(() => { });
|
|
380
|
+
return 'moved';
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* A stage left by a fold that stopped halfway: each plain file goes back into the memory folder where its name is
|
|
384
|
+
* free (never over a file there); the stage is removed once empty, else the Project is left for the user.
|
|
385
|
+
*/
|
|
386
|
+
async function recoverStage(src, stage) {
|
|
387
|
+
const st = await lstatOrNull(stage);
|
|
388
|
+
if (!st)
|
|
389
|
+
return null;
|
|
390
|
+
if (!st.isDirectory() || st.isSymbolicLink())
|
|
391
|
+
return `${stage} is a link or not a folder; sideby left it as it is`;
|
|
392
|
+
for (const n of await readdir(stage)) {
|
|
393
|
+
if ((await lstatOrNull(join(stage, n)))?.isFile())
|
|
394
|
+
await moveNoClobber(join(stage, n), join(src, n));
|
|
395
|
+
}
|
|
396
|
+
return rmdir(stage).then(() => null, () => `${stage} still holds files whose names are taken in ${src}; move them by hand`);
|
|
397
|
+
}
|
|
398
|
+
const fail = (project, why, part = {}) => ({
|
|
399
|
+
project,
|
|
400
|
+
status: 'failed',
|
|
401
|
+
moved: [],
|
|
402
|
+
renamed: [],
|
|
403
|
+
same: [],
|
|
404
|
+
indexLines: 0,
|
|
405
|
+
...part,
|
|
406
|
+
why,
|
|
407
|
+
});
|
|
408
|
+
/**
|
|
409
|
+
* Folds one Project's memory of `account` into the Main Account (ADR-0081). When the Main Account has no memory for
|
|
410
|
+
* it, the folder moves whole. Otherwise every file is read once, and copied in from that read (temp file, fsync, then
|
|
411
|
+
* a hard link to its name, so never over another file and never half-written; times kept): a file the Main Account
|
|
412
|
+
* holds with the same content counts as there, one with other content is kept as `<name>.<account>.md` (a name
|
|
413
|
+
* neither folder uses), and `MEMORY.md` gets the Account's lines it lacks, with links to renamed files rewritten in
|
|
414
|
+
* one pass. Then each file read is taken out on its own: renamed into a stage beside the memory folder, hashed there,
|
|
415
|
+
* and kept out only when it still holds what was copied (else renamed back). The stage goes to the trash, and the
|
|
416
|
+
* memory folder is removed only when empty, so a file written meanwhile is never trashed: it stays for the next fold.
|
|
417
|
+
*/
|
|
418
|
+
export async function foldProject(input) {
|
|
419
|
+
const { account, project } = input;
|
|
420
|
+
const accountDir = account.dir;
|
|
421
|
+
const srcParent = join(accountDir, 'projects', project);
|
|
422
|
+
const src = join(srcParent, 'memory');
|
|
423
|
+
const stage = join(srcParent, FOLD_STAGE);
|
|
424
|
+
// A fold that stopped after its last file left `memory/` gone or empty: recreate it so the stage can be put back.
|
|
425
|
+
if ((await realFolder(srcParent)) === true && !(await lstatOrNull(src)) && (await lstatOrNull(stage)))
|
|
426
|
+
await mkdir(src).catch(() => { });
|
|
427
|
+
for (const p of [join(accountDir, 'projects'), srcParent, src])
|
|
428
|
+
if ((await realFolder(p)) !== true)
|
|
429
|
+
return fail(project, `${p} is a link or not a folder; sideby left it as it is`);
|
|
430
|
+
await assertInside(accountDir, src);
|
|
431
|
+
await assertInside(accountDir, join(stage, 'x'));
|
|
432
|
+
const leftover = await recoverStage(src, stage);
|
|
433
|
+
if (leftover)
|
|
434
|
+
return fail(project, leftover);
|
|
435
|
+
let main;
|
|
436
|
+
try {
|
|
437
|
+
main = await realpath(input.mainDir);
|
|
438
|
+
}
|
|
439
|
+
catch {
|
|
440
|
+
return fail(project, `${input.mainDir} does not exist`);
|
|
441
|
+
}
|
|
442
|
+
const dstParent = join(main, 'projects', project);
|
|
443
|
+
const dst = join(dstParent, 'memory');
|
|
444
|
+
for (const p of [join(main, 'projects'), dstParent, dst])
|
|
445
|
+
if ((await realFolder(p)) === false)
|
|
446
|
+
return fail(project, `${p} is a link or not a folder; sideby left it as it is`);
|
|
447
|
+
const read = await readFolder(src);
|
|
448
|
+
if ('why' in read)
|
|
449
|
+
return fail(project, read.why);
|
|
450
|
+
const { names, files } = read;
|
|
451
|
+
const accountName = account.name.replace(/[^A-Za-z0-9._-]/g, '-');
|
|
452
|
+
// The Main Account has no memory for this Project: the folder moves whole (one rename takes whatever it holds).
|
|
453
|
+
if ((await realFolder(dst)) === null) {
|
|
454
|
+
await mkdir(dstParent, { recursive: true, mode: 0o700 });
|
|
455
|
+
if ((await realFolder(dstParent)) !== true)
|
|
456
|
+
return fail(project, `${dstParent} is a link or not a folder`);
|
|
457
|
+
await assertInside(main, dst);
|
|
458
|
+
try {
|
|
459
|
+
await rename(src, dst);
|
|
460
|
+
return { project, status: 'moved', moved: names, renamed: [], same: [], indexLines: 0 };
|
|
461
|
+
}
|
|
462
|
+
catch (err) {
|
|
463
|
+
if (err.code !== 'EXDEV')
|
|
464
|
+
return fail(project, `${src} could not be moved (${err.code ?? 'error'})`);
|
|
465
|
+
await mkdir(dst, { mode: 0o700 });
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
await assertInside(main, join(dst, MEMORY_INDEX));
|
|
469
|
+
// Where each file goes, decided before anything is written: a kept name is free in both folders and among the
|
|
470
|
+
// names this fold already gave out.
|
|
471
|
+
const plan = [];
|
|
472
|
+
const taken = new Set();
|
|
473
|
+
for (const n of names) {
|
|
474
|
+
if (n === MEMORY_INDEX)
|
|
475
|
+
continue;
|
|
476
|
+
const note = files.get(n);
|
|
477
|
+
let pick = null;
|
|
478
|
+
for (let i = 0; i <= 50 && !pick; i++) {
|
|
479
|
+
const to = i === 0 ? n : altName(n, accountName, i);
|
|
480
|
+
if (taken.has(to) || (i > 0 && files.has(to)))
|
|
481
|
+
continue;
|
|
482
|
+
const there = await lstatOrNull(join(dst, to));
|
|
483
|
+
if (!there)
|
|
484
|
+
pick = { to, copy: true };
|
|
485
|
+
else if (there.isFile() && (await hashOf(join(dst, to))) === note.hash)
|
|
486
|
+
pick = { to, copy: false };
|
|
487
|
+
}
|
|
488
|
+
if (!pick)
|
|
489
|
+
return fail(project, `no free name for ${n} in ${dst}`);
|
|
490
|
+
taken.add(pick.to);
|
|
491
|
+
plan.push({ from: n, ...pick });
|
|
492
|
+
}
|
|
493
|
+
const moved = plan.filter((x) => x.to === x.from && x.copy).map((x) => x.from);
|
|
494
|
+
const same = plan.filter((x) => x.to === x.from && !x.copy).map((x) => x.from);
|
|
495
|
+
const renamed = plan.filter((x) => x.to !== x.from).map(({ from, to }) => ({ from, to }));
|
|
496
|
+
const sofar = { moved, renamed, same };
|
|
497
|
+
const write = input.write ?? ((fh, data) => fh.writeFile(data));
|
|
498
|
+
for (const x of plan) {
|
|
499
|
+
if (!x.copy)
|
|
500
|
+
continue;
|
|
501
|
+
try {
|
|
502
|
+
await writeNew(join(dst, x.to), files.get(x.from), write);
|
|
503
|
+
}
|
|
504
|
+
catch (err) {
|
|
505
|
+
return fail(project, `${join(dst, x.to)} could not be written (${err.code ?? 'error'}); nothing was left under that name`, sofar);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
let indexLines = 0;
|
|
509
|
+
const index = files.get(MEMORY_INDEX);
|
|
510
|
+
if (index) {
|
|
511
|
+
if (index.data.length > MAX_INDEX_BYTES)
|
|
512
|
+
return fail(project, `${join(src, MEMORY_INDEX)} is too large`, sofar);
|
|
513
|
+
const text = rewriteLinks(index.data.toString('utf8'), new Map(renamed.map((r) => [r.from, r.to])));
|
|
514
|
+
const target = join(dst, MEMORY_INDEX);
|
|
515
|
+
const st = await lstatOrNull(target);
|
|
516
|
+
if (st && !st.isFile())
|
|
517
|
+
return fail(project, `${target} is a link or not a file; sideby left the index as it is`, sofar);
|
|
518
|
+
const ours = st ? await readSmallFile(target, MAX_INDEX_BYTES) : '';
|
|
519
|
+
if (ours === undefined)
|
|
520
|
+
return fail(project, `${target} cannot be read or is too large`, sofar);
|
|
521
|
+
const merged = st
|
|
522
|
+
? mergeIndex(ours, text)
|
|
523
|
+
: { text, added: text.split('\n').filter((l) => l.trim()).length };
|
|
524
|
+
if (merged.text !== ours) {
|
|
525
|
+
const wrote = await writeIfUnchanged(target, st ? sha256(ours) : null, merged.text, 0o644).catch(() => false);
|
|
526
|
+
if (!wrote)
|
|
527
|
+
return fail(project, `${target} changed while sideby merged it; run the fix again`, sofar);
|
|
528
|
+
}
|
|
529
|
+
indexLines = merged.added;
|
|
530
|
+
}
|
|
531
|
+
for (const x of plan)
|
|
532
|
+
if ((await hashOf(join(dst, x.to))) !== files.get(x.from).hash)
|
|
533
|
+
return fail(project, `${join(dst, x.to)} does not match ${join(src, x.from)} after copying`, {
|
|
534
|
+
...sofar,
|
|
535
|
+
indexLines,
|
|
536
|
+
});
|
|
537
|
+
await input.afterCopy?.();
|
|
538
|
+
// Each file read is taken out on its own: renamed into the stage (one atomic step, so a write by its name after it
|
|
539
|
+
// makes a new file in the memory folder), then kept out only when it still holds what was copied or merged.
|
|
540
|
+
try {
|
|
541
|
+
await mkdir(stage, { mode: 0o700 });
|
|
542
|
+
}
|
|
543
|
+
catch (err) {
|
|
544
|
+
return fail(project, `${stage} could not be made (${err.code ?? 'error'})`, {
|
|
545
|
+
...sofar,
|
|
546
|
+
indexLines,
|
|
547
|
+
});
|
|
548
|
+
}
|
|
549
|
+
const back = [];
|
|
550
|
+
const stuck = [];
|
|
551
|
+
for (const n of names) {
|
|
552
|
+
try {
|
|
553
|
+
await rename(join(src, n), join(stage, n));
|
|
554
|
+
}
|
|
555
|
+
catch {
|
|
556
|
+
continue; // gone meanwhile: its copy is in the Main Account
|
|
557
|
+
}
|
|
558
|
+
await input.staged?.(n);
|
|
559
|
+
if ((await hashOf(join(stage, n))) === files.get(n).hash)
|
|
560
|
+
continue;
|
|
561
|
+
// Changed after the read: back into the memory folder, never over a file there. When a new file took its name, it
|
|
562
|
+
// goes back as `<name>.changed.md` (the next free one), so the stage keeps only files that match their copies.
|
|
563
|
+
let to = null;
|
|
564
|
+
for (let i = 0; i <= 50 && to === null; i++) {
|
|
565
|
+
const name = i === 0 ? n : altName(n, 'changed', i);
|
|
566
|
+
const how = await moveNoClobber(join(stage, n), join(src, name));
|
|
567
|
+
if (how === 'moved')
|
|
568
|
+
to = name;
|
|
569
|
+
else if (how === 'error')
|
|
570
|
+
break;
|
|
571
|
+
}
|
|
572
|
+
if (to === null)
|
|
573
|
+
stuck.push(n);
|
|
574
|
+
else
|
|
575
|
+
back.push(to === n ? n : `${n} (as ${to})`);
|
|
576
|
+
}
|
|
577
|
+
if (stuck.length) {
|
|
578
|
+
// An unchecked file cannot go back: nothing goes to the trash, the verified files go back too.
|
|
579
|
+
await recoverStage(src, stage);
|
|
580
|
+
return fail(project, `${stuck.join(', ')} changed while sideby moved ${stuck.length === 1 ? 'it' : 'them'} and could not be put back in ${src}; ${stuck.length === 1 ? 'it is' : 'they are'} in ${stage}, move ${stuck.length === 1 ? 'it' : 'them'} back by hand`, { ...sofar, indexLines });
|
|
581
|
+
}
|
|
582
|
+
const leftInStage = (await readdir(stage).catch(() => [])).length;
|
|
583
|
+
let trashed;
|
|
584
|
+
if (leftInStage) {
|
|
585
|
+
const gone = await input.trash(stage);
|
|
586
|
+
if (!gone.ok) {
|
|
587
|
+
await recoverStage(src, stage);
|
|
588
|
+
return fail(project, `the files are in the main account, but ${gone.why}; they stay in ${account.ref} too`, {
|
|
589
|
+
...sofar,
|
|
590
|
+
indexLines,
|
|
591
|
+
});
|
|
592
|
+
}
|
|
593
|
+
trashed = gone.to;
|
|
594
|
+
}
|
|
595
|
+
else
|
|
596
|
+
await rmdir(stage).catch(() => { });
|
|
597
|
+
const emptied = await rmdir(src).then(() => true, () => false);
|
|
598
|
+
const result = { project, moved, renamed, same, indexLines, ...(trashed ? { trashed } : {}) };
|
|
599
|
+
if (emptied && !back.length)
|
|
600
|
+
return { ...result, status: 'merged' };
|
|
601
|
+
return {
|
|
602
|
+
...result,
|
|
603
|
+
status: 'partial',
|
|
604
|
+
why: back.length
|
|
605
|
+
? `${back.join(', ')} changed while sideby moved ${back.length === 1 ? 'it' : 'them'}, so ${back.length === 1 ? 'it stays' : 'they stay'} in ${account.ref}; the next fix moves ${back.length === 1 ? 'it' : 'them'}`
|
|
606
|
+
: `new memory appeared in ${src} while sideby moved the rest; the next fix moves it`,
|
|
607
|
+
};
|
|
608
|
+
}
|
|
609
|
+
const RECORDS = 'folded.json';
|
|
610
|
+
const MAX_RECORDS = 500;
|
|
611
|
+
/** Every fold sideby recorded, oldest first; a file that cannot be read gives none. */
|
|
612
|
+
export async function readFolds(stateDir) {
|
|
613
|
+
const dir = await ownedFolder(stateDir, ['memory'], { create: false }).catch(() => null);
|
|
614
|
+
if (!dir)
|
|
615
|
+
return [];
|
|
616
|
+
const text = await readSmallFile(join(dir, RECORDS), 4 * 1024 * 1024);
|
|
617
|
+
if (text === undefined)
|
|
618
|
+
return [];
|
|
619
|
+
try {
|
|
620
|
+
const v = JSON.parse(text);
|
|
621
|
+
if (!Array.isArray(v.folds))
|
|
622
|
+
return [];
|
|
623
|
+
return v.folds.filter((f) => !!f &&
|
|
624
|
+
typeof f === 'object' &&
|
|
625
|
+
typeof f.account === 'string' &&
|
|
626
|
+
typeof f.project === 'string' &&
|
|
627
|
+
typeof f.files === 'number' &&
|
|
628
|
+
typeof f.at === 'string');
|
|
629
|
+
}
|
|
630
|
+
catch {
|
|
631
|
+
return [];
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
async function recordFolds(stateDir, add) {
|
|
635
|
+
if (!add.length)
|
|
636
|
+
return;
|
|
637
|
+
const dir = await ownedFolder(stateDir, ['memory'], { create: true, private: true });
|
|
638
|
+
if (!dir)
|
|
639
|
+
return;
|
|
640
|
+
const folds = [...(await readFolds(stateDir)), ...add].slice(-MAX_RECORDS);
|
|
641
|
+
await writeFileAtomic(join(dir, RECORDS), `${JSON.stringify({ version: 1, folds }, null, 2)}\n`, 0o600);
|
|
642
|
+
}
|
|
643
|
+
/** Every Project of `account` with memory of its own, folded unless a Live Session of the Account works in it. */
|
|
644
|
+
export async function foldAccount(ctx, account) {
|
|
645
|
+
const { list } = await accountMemories(account.dir);
|
|
646
|
+
if (!list.length)
|
|
647
|
+
return { ok: true, message: `${account.ref} keeps no memory of its own now` };
|
|
648
|
+
const running = await ctx.liveCwds(account);
|
|
649
|
+
if ('unknown' in running)
|
|
650
|
+
return {
|
|
651
|
+
ok: false,
|
|
652
|
+
message: `sideby cannot tell which sessions of ${account.ref} are running (${ctx.show(running.unknown)}), so it moved nothing of ${account.ref}; run the fix again in a moment`,
|
|
653
|
+
};
|
|
654
|
+
const live = await liveProjects(running.cwds);
|
|
655
|
+
const outcomes = [];
|
|
656
|
+
for (const m of list) {
|
|
657
|
+
if (live.has(m.project)) {
|
|
658
|
+
outcomes.push({
|
|
659
|
+
project: m.project,
|
|
660
|
+
status: 'skipped',
|
|
661
|
+
moved: [],
|
|
662
|
+
renamed: [],
|
|
663
|
+
same: [],
|
|
664
|
+
indexLines: 0,
|
|
665
|
+
});
|
|
666
|
+
continue;
|
|
667
|
+
}
|
|
668
|
+
outcomes.push(await foldProject({ mainDir: ctx.mainDir, account, project: m.project, trash: ctx.trash }).catch((err) => fail(m.project, err.message)));
|
|
669
|
+
}
|
|
670
|
+
const done = outcomes.filter((o) => o.status === 'moved' || o.status === 'merged' || o.status === 'partial');
|
|
671
|
+
await recordFolds(ctx.stateDir, done.map((o) => ({
|
|
672
|
+
account: account.ref,
|
|
673
|
+
project: o.project,
|
|
674
|
+
files: [...o.moved, ...o.renamed.map((r) => r.from), ...o.same].filter((n) => n !== MEMORY_INDEX)
|
|
675
|
+
.length,
|
|
676
|
+
at: ctx.now().toISOString(),
|
|
677
|
+
}))).catch(() => { });
|
|
678
|
+
const parts = [];
|
|
679
|
+
if (done.length)
|
|
680
|
+
parts.push(`moved ${account.ref}'s memory of ${done.length} ${done.length === 1 ? 'project' : 'projects'} into the main account`);
|
|
681
|
+
const kept = outcomes.flatMap((o) => o.renamed);
|
|
682
|
+
if (kept.length)
|
|
683
|
+
parts.push(`kept ${kept.length} ${kept.length === 1 ? 'file' : 'files'} that differed under a new name (${kept
|
|
684
|
+
.slice(0, 3)
|
|
685
|
+
.map((r) => r.to)
|
|
686
|
+
.join(', ')}${kept.length > 3 ? ', …' : ''})`);
|
|
687
|
+
const where = [...new Set(done.map((o) => o.trashed).filter((t) => !!t))];
|
|
688
|
+
if (where.length)
|
|
689
|
+
parts.push(`the emptied folders went to ${where.map((w) => ctx.show(w)).join(', ')}`);
|
|
690
|
+
const skipped = outcomes.filter((o) => o.status === 'skipped');
|
|
691
|
+
if (skipped.length)
|
|
692
|
+
parts.push(`left ${skipped.length} ${skipped.length === 1 ? 'project' : 'projects'} while a session of ${account.ref} works there (${skipped
|
|
693
|
+
.map((o) => o.project)
|
|
694
|
+
.join(', ')}); run the fix again once it ends`);
|
|
695
|
+
const failed = outcomes.filter((o) => o.status === 'failed' || o.status === 'partial');
|
|
696
|
+
for (const f of failed)
|
|
697
|
+
parts.push(`${f.project}: ${ctx.show(f.why ?? 'not moved')}`);
|
|
698
|
+
return { ok: failed.length === 0, message: parts.join('; ') || `nothing to move for ${account.ref}` };
|
|
699
|
+
}
|
|
700
|
+
/** Doctor's check of one Claude Account that is not the Main Account (only while config `claude.shareMemory` is on). */
|
|
701
|
+
export async function memoryFindings(ctx, account) {
|
|
702
|
+
if (account.family !== 'claude' || account.isMain)
|
|
703
|
+
return [];
|
|
704
|
+
const { list, links } = await accountMemories(account.dir);
|
|
705
|
+
const out = [];
|
|
706
|
+
if (list.length) {
|
|
707
|
+
const files = list.reduce((n, m) => n + m.files, 0);
|
|
708
|
+
const names = list.map((m) => m.project);
|
|
709
|
+
out.push({
|
|
710
|
+
level: 'warn',
|
|
711
|
+
item: 'projects/*/memory',
|
|
712
|
+
code: 'memory.unfolded',
|
|
713
|
+
message: `${account.ref} keeps its own memory for ${list.length} ${list.length === 1 ? 'project' : 'projects'} (${files} ${files === 1 ? 'file' : 'files'}) that your other Claude accounts do not see: ${names.slice(0, 3).join(', ')}${names.length > 3 ? ', …' : ''}`,
|
|
714
|
+
hint: `\`sideby doctor ${account.ref} --fix\` moves it into the main account (shared memory is on); a file that differs is kept beside the main one under a new name, and emptied folders go to the trash`,
|
|
715
|
+
fixable: true,
|
|
716
|
+
fix: () => foldAccount(ctx, account),
|
|
717
|
+
});
|
|
718
|
+
}
|
|
719
|
+
for (const l of links)
|
|
720
|
+
out.push({
|
|
721
|
+
level: 'warn',
|
|
722
|
+
item: 'projects/*/memory',
|
|
723
|
+
code: 'memory.link',
|
|
724
|
+
message: `${ctx.show(l)} is a link; Claude Code refuses memory writes through a link, and sideby does not follow it`,
|
|
725
|
+
hint: 'replace the link with a real folder (move its files into the main account first), then run `sideby doctor --fix`',
|
|
726
|
+
fixable: false,
|
|
727
|
+
});
|
|
728
|
+
return out;
|
|
729
|
+
}
|
|
730
|
+
/** The memory files an index links to (`memoryLink`); links to anything else are left out. */
|
|
731
|
+
export function indexTargets(text) {
|
|
732
|
+
const out = new Set();
|
|
733
|
+
for (const m of text.matchAll(/\]\(([^)\s]+)\)/g)) {
|
|
734
|
+
const link = memoryLink(m[1]);
|
|
735
|
+
if (link)
|
|
736
|
+
out.add(link.file);
|
|
737
|
+
}
|
|
738
|
+
return [...out];
|
|
739
|
+
}
|
|
740
|
+
/** Every memory folder of the Main Account whose `MEMORY.md` lists a missing file or misses a file that is there. */
|
|
741
|
+
export async function indexProblems(mainDir) {
|
|
742
|
+
const { list } = await accountMemories(mainDir);
|
|
743
|
+
const out = [];
|
|
744
|
+
for (const m of list) {
|
|
745
|
+
const entries = await readdir(m.dir).catch(() => []);
|
|
746
|
+
const files = [];
|
|
747
|
+
for (const n of entries)
|
|
748
|
+
if ((await lstatOrNull(join(m.dir, n)))?.isFile())
|
|
749
|
+
files.push(n);
|
|
750
|
+
const notes = files.filter((n) => n !== MEMORY_INDEX && n.endsWith('.md'));
|
|
751
|
+
const text = files.includes(MEMORY_INDEX)
|
|
752
|
+
? await readSmallFile(join(m.dir, MEMORY_INDEX), MAX_INDEX_BYTES)
|
|
753
|
+
: '';
|
|
754
|
+
if (text === undefined)
|
|
755
|
+
continue;
|
|
756
|
+
const targets = indexTargets(text);
|
|
757
|
+
const missing = targets.filter((t) => !files.includes(t)).sort();
|
|
758
|
+
const unlisted = notes.filter((n) => !targets.includes(n)).sort();
|
|
759
|
+
if (missing.length || unlisted.length)
|
|
760
|
+
out.push({ project: m.project, missing, unlisted });
|
|
761
|
+
}
|
|
762
|
+
return out;
|
|
763
|
+
}
|
|
764
|
+
/**
|
|
765
|
+
* Every `cwd` the first and the last records of a session file name, from its first and last 64 KB only. Both ends:
|
|
766
|
+
* a session resumed in another folder keeps the earlier records, and their `cwd`, of the folder it came from.
|
|
767
|
+
*/
|
|
768
|
+
async function transcriptCwds(file) {
|
|
769
|
+
const out = new Set();
|
|
770
|
+
let fh;
|
|
771
|
+
try {
|
|
772
|
+
fh = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
773
|
+
const st = await fh.stat();
|
|
774
|
+
if (!st.isFile())
|
|
775
|
+
return [];
|
|
776
|
+
const size = Math.min(st.size, 64 * 1024);
|
|
777
|
+
for (const at of new Set([0, Math.max(0, st.size - size)])) {
|
|
778
|
+
const buf = Buffer.alloc(size);
|
|
779
|
+
await fh.read(buf, 0, size, at);
|
|
780
|
+
const lines = buf.toString('utf8').split('\n');
|
|
781
|
+
for (const line of at === 0 ? lines.slice(0, 40) : lines.slice(-40)) {
|
|
782
|
+
if (!line.includes('"cwd"'))
|
|
783
|
+
continue;
|
|
784
|
+
try {
|
|
785
|
+
const v = JSON.parse(line);
|
|
786
|
+
if (typeof v.cwd === 'string' && v.cwd.startsWith('/'))
|
|
787
|
+
out.add(v.cwd);
|
|
788
|
+
}
|
|
789
|
+
catch {
|
|
790
|
+
// a line cut at the 64 KB edge
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
return [...out];
|
|
795
|
+
}
|
|
796
|
+
catch {
|
|
797
|
+
return [...out];
|
|
798
|
+
}
|
|
799
|
+
finally {
|
|
800
|
+
await fh?.close().catch(() => { });
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
/**
|
|
804
|
+
* Whether Claude Code still names Project folders the way sideby does (ADR-0081). Claude Code names a session's
|
|
805
|
+
* folder after the session's working folder, by the same rule as its memory folder; a folder that holds memory and
|
|
806
|
+
* session files none of whose `cwd`s (first and last records, folders that still exist) names it means the rule
|
|
807
|
+
* changed. The three newest session files of up to 40 folders are looked at, and a folder counts only when none of
|
|
808
|
+
* them agrees.
|
|
809
|
+
*/
|
|
810
|
+
export async function nameMismatches(accounts) {
|
|
811
|
+
const out = [];
|
|
812
|
+
let looked = 0;
|
|
813
|
+
for (const a of accounts) {
|
|
814
|
+
if (a.family !== 'claude')
|
|
815
|
+
continue;
|
|
816
|
+
const { list } = await accountMemories(a.dir);
|
|
817
|
+
for (const m of list) {
|
|
818
|
+
if (looked >= NAME_CHECK_FOLDERS)
|
|
819
|
+
return out;
|
|
820
|
+
const folder = join(a.dir, 'projects', m.project);
|
|
821
|
+
const named = (await readdir(folder).catch(() => [])).filter((n) => n.endsWith('.jsonl'));
|
|
822
|
+
if (!named.length)
|
|
823
|
+
continue;
|
|
824
|
+
const timed = await Promise.all(named.map(async (n) => ({ n, at: (await lstatOrNull(join(folder, n)))?.mtimeMs ?? 0 })));
|
|
825
|
+
const sessions = timed
|
|
826
|
+
.sort((x, y) => y.at - x.at)
|
|
827
|
+
.slice(0, 3)
|
|
828
|
+
.map((x) => x.n);
|
|
829
|
+
looked++;
|
|
830
|
+
// A working folder that is gone says nothing: a moved project's folder is often renamed by hand to follow it.
|
|
831
|
+
const seen = [
|
|
832
|
+
...new Set((await Promise.all(sessions.map((s) => transcriptCwds(join(folder, s))))).flat()),
|
|
833
|
+
];
|
|
834
|
+
const cwds = [];
|
|
835
|
+
for (const c of seen)
|
|
836
|
+
if ((await lstatOrNull(c))?.isDirectory())
|
|
837
|
+
cwds.push(c);
|
|
838
|
+
if (cwds.length && !cwds.some((c) => claudeProjectDirName(c) === m.project))
|
|
839
|
+
out.push({
|
|
840
|
+
account: a.ref,
|
|
841
|
+
folder: m.project,
|
|
842
|
+
cwd: cwds[0],
|
|
843
|
+
derived: claudeProjectDirName(cwds[0]),
|
|
844
|
+
});
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
return out;
|
|
848
|
+
}
|
|
849
|
+
/** Doctor's warnings about the Main Account's memory (only while config `claude.shareMemory` is on); never `fail`. */
|
|
850
|
+
export async function mainMemoryFindings(ctx, accounts) {
|
|
851
|
+
const out = [];
|
|
852
|
+
const bad = await indexProblems(ctx.mainDir);
|
|
853
|
+
if (bad.length) {
|
|
854
|
+
const say = (p) => `${p.project} (${[
|
|
855
|
+
p.missing.length
|
|
856
|
+
? `lists missing ${p.missing.slice(0, 2).join(', ')}${p.missing.length > 2 ? ', …' : ''}`
|
|
857
|
+
: '',
|
|
858
|
+
p.unlisted.length
|
|
859
|
+
? `does not list ${p.unlisted.slice(0, 2).join(', ')}${p.unlisted.length > 2 ? ', …' : ''}`
|
|
860
|
+
: '',
|
|
861
|
+
]
|
|
862
|
+
.filter(Boolean)
|
|
863
|
+
.join('; ')})`;
|
|
864
|
+
out.push({
|
|
865
|
+
level: 'warn',
|
|
866
|
+
account: 'claude:main',
|
|
867
|
+
item: 'memory',
|
|
868
|
+
code: 'memory.index',
|
|
869
|
+
message: `the memory index (MEMORY.md) of ${bad.length} ${bad.length === 1 ? 'project' : 'projects'} in the main account does not match its files: ${bad.slice(0, 3).map(say).join(', ')}${bad.length > 3 ? ', …' : ''}`,
|
|
870
|
+
hint: 'Claude reads only what MEMORY.md lists. Ask Claude in that project to tidy its memory index, or edit MEMORY.md in that folder; two accounts writing at the same moment can overwrite it',
|
|
871
|
+
source: 'core',
|
|
872
|
+
fixable: false,
|
|
873
|
+
});
|
|
874
|
+
}
|
|
875
|
+
const odd = await nameMismatches(accounts);
|
|
876
|
+
if (odd.length) {
|
|
877
|
+
const first = odd[0];
|
|
878
|
+
out.push({
|
|
879
|
+
level: 'warn',
|
|
880
|
+
account: 'claude:main',
|
|
881
|
+
item: 'memory',
|
|
882
|
+
code: 'memory.name-mismatch',
|
|
883
|
+
message: `Claude Code named the folder of ${ctx.show(first.cwd)} "${first.folder}" (${first.account}), but sideby would name it "${first.derived}"${odd.length > 1 ? ` (and ${odd.length - 1} more)` : ''}: Claude Code may have changed how it names project folders, so shared memory may land in another folder than Claude Code's own`,
|
|
884
|
+
hint: 'turn shared memory off with `sideby memory off --yes` until sideby is updated (`sideby update`); the memory already in the main account stays',
|
|
885
|
+
source: 'core',
|
|
886
|
+
fixable: false,
|
|
887
|
+
});
|
|
888
|
+
}
|
|
889
|
+
return out;
|
|
890
|
+
}
|
|
891
|
+
/** `sideby memory` (spec §3.44): reads no Account folder while the setting is off. */
|
|
892
|
+
export async function memoryStatus(opts, on, cwd) {
|
|
893
|
+
const folded = await readFolds(opts.stateDir);
|
|
894
|
+
const main = join(opts.mainDir, 'projects');
|
|
895
|
+
if (!on)
|
|
896
|
+
return { on, main, folded };
|
|
897
|
+
const projects = new Map();
|
|
898
|
+
const entry = (name) => {
|
|
899
|
+
let e = projects.get(name);
|
|
900
|
+
if (!e) {
|
|
901
|
+
e = { name, main: 0, pending: [], folded: [] };
|
|
902
|
+
projects.set(name, e);
|
|
903
|
+
}
|
|
904
|
+
return e;
|
|
905
|
+
};
|
|
906
|
+
for (const m of (await accountMemories(opts.mainDir)).list)
|
|
907
|
+
entry(m.project).main = m.files;
|
|
908
|
+
for (const a of await opts.accounts()) {
|
|
909
|
+
if (a.family !== 'claude' || a.isMain)
|
|
910
|
+
continue;
|
|
911
|
+
for (const m of (await accountMemories(a.dir)).list)
|
|
912
|
+
entry(m.project).pending.push({ account: a.ref, files: m.files });
|
|
913
|
+
}
|
|
914
|
+
for (const f of folded) {
|
|
915
|
+
if (!projects.has(f.project))
|
|
916
|
+
continue;
|
|
917
|
+
const e = entry(f.project);
|
|
918
|
+
const had = e.folded.find((x) => x.account === f.account);
|
|
919
|
+
if (had)
|
|
920
|
+
had.files += f.files;
|
|
921
|
+
else
|
|
922
|
+
e.folded.push({ account: f.account, files: f.files });
|
|
923
|
+
}
|
|
924
|
+
let dir;
|
|
925
|
+
if (cwd !== undefined) {
|
|
926
|
+
const t = await memoryTarget(opts.mainDir, cwd);
|
|
927
|
+
const real = await realpath(cwd).catch(() => cwd);
|
|
928
|
+
dir = t.status === 'ok' ? { path: real, name: t.name, memory: t.dir } : { path: real, why: t.why };
|
|
929
|
+
}
|
|
930
|
+
return {
|
|
931
|
+
on,
|
|
932
|
+
main,
|
|
933
|
+
folded,
|
|
934
|
+
...(dir ? { dir } : {}),
|
|
935
|
+
projects: [...projects.values()].sort((a, b) => a.name.localeCompare(b.name)),
|
|
936
|
+
};
|
|
937
|
+
}
|