@rucher/carnet 0.2.0-beta.2 → 0.2.0-beta.4
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/README.md +2 -2
- package/dist/{carnet-Dbkz_bzM.d.mts → carnet-DptiZiz8.d.mts} +80 -35
- package/dist/carnet-DptiZiz8.d.mts.map +1 -0
- package/dist/index.d.mts +48 -35
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +45 -191
- package/dist/index.mjs.map +1 -1
- package/dist/mcp.d.mts +1 -1
- package/dist/mcp.d.mts.map +1 -1
- package/dist/mcp.mjs +11 -9
- package/dist/mcp.mjs.map +1 -1
- package/dist/{steps-CIQ9Nay1.mjs → steps-BeTGxQk4.mjs} +835 -427
- package/dist/steps-BeTGxQk4.mjs.map +1 -0
- package/package.json +1 -1
- package/dist/carnet-Dbkz_bzM.d.mts.map +0 -1
- package/dist/steps-CIQ9Nay1.mjs.map +0 -1
|
@@ -1,7 +1,8 @@
|
|
|
1
|
+
import { closeSync, existsSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, rmdirSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
1
3
|
import { DatabaseSync } from "node:sqlite";
|
|
2
|
-
import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, writeFileSync } from "node:fs";
|
|
3
|
-
import { basename, dirname, join, relative, resolve } from "node:path";
|
|
4
4
|
import { homedir } from "node:os";
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
5
6
|
// src/context.ts
|
|
6
7
|
function nowIso(ctx) {
|
|
7
8
|
return ctx.now().toISOString();
|
|
@@ -385,6 +386,57 @@ CREATE TABLE session_repos (
|
|
|
385
386
|
injected_at TEXT NOT NULL,
|
|
386
387
|
PRIMARY KEY (session, repo)
|
|
387
388
|
);
|
|
389
|
+
`,
|
|
390
|
+
`
|
|
391
|
+
CREATE TABLE sessions_new (
|
|
392
|
+
id TEXT PRIMARY KEY,
|
|
393
|
+
group_name TEXT,
|
|
394
|
+
name TEXT,
|
|
395
|
+
purpose TEXT,
|
|
396
|
+
kind TEXT NOT NULL DEFAULT 'temp' CHECK (kind IN ('active', 'temp')),
|
|
397
|
+
status TEXT NOT NULL DEFAULT 'idle' CHECK (status IN ('running', 'idle', 'archived')),
|
|
398
|
+
cwd TEXT,
|
|
399
|
+
repo TEXT,
|
|
400
|
+
host TEXT NOT NULL DEFAULT 'claude-code',
|
|
401
|
+
host_pid INTEGER,
|
|
402
|
+
hooked_at TEXT,
|
|
403
|
+
last_title TEXT,
|
|
404
|
+
parent_id TEXT REFERENCES sessions(id),
|
|
405
|
+
prompt_version TEXT,
|
|
406
|
+
created_at TEXT NOT NULL,
|
|
407
|
+
last_active_at TEXT NOT NULL,
|
|
408
|
+
ended_at TEXT,
|
|
409
|
+
CHECK (kind = 'temp' OR name IS NOT NULL)
|
|
410
|
+
);
|
|
411
|
+
INSERT INTO sessions_new (id, group_name, name, purpose, kind, status, cwd, repo, host, host_pid,
|
|
412
|
+
hooked_at, last_title, parent_id, prompt_version, created_at, last_active_at, ended_at)
|
|
413
|
+
SELECT id, '', name, purpose, kind, status, cwd, repo, host, host_pid,
|
|
414
|
+
hooked_at, last_title, parent_id, prompt_version, created_at, last_active_at, ended_at
|
|
415
|
+
FROM sessions;
|
|
416
|
+
DROP TABLE sessions;
|
|
417
|
+
ALTER TABLE sessions_new RENAME TO sessions;
|
|
418
|
+
CREATE INDEX sessions_host_pid ON sessions(host, host_pid, hooked_at);
|
|
419
|
+
CREATE INDEX sessions_group_status ON sessions(group_name, status, last_active_at);
|
|
420
|
+
CREATE UNIQUE INDEX sessions_group_name ON sessions(group_name, name)
|
|
421
|
+
WHERE group_name IS NOT NULL AND name IS NOT NULL;
|
|
422
|
+
CREATE UNIQUE INDEX sessions_free_name ON sessions(name)
|
|
423
|
+
WHERE group_name IS NULL AND name IS NOT NULL;
|
|
424
|
+
|
|
425
|
+
ALTER TABLE notes ADD COLUMN group_name TEXT NOT NULL DEFAULT '';
|
|
426
|
+
ALTER TABLE notes ADD COLUMN number INTEGER NOT NULL DEFAULT 0;
|
|
427
|
+
UPDATE notes SET number = id;
|
|
428
|
+
DROP INDEX notes_active;
|
|
429
|
+
CREATE INDEX notes_active ON notes(group_name, dropped_at, kind);
|
|
430
|
+
CREATE UNIQUE INDEX notes_group_number ON notes(group_name, number);
|
|
431
|
+
|
|
432
|
+
CREATE TABLE active_days_new (
|
|
433
|
+
group_name TEXT NOT NULL,
|
|
434
|
+
day TEXT NOT NULL,
|
|
435
|
+
PRIMARY KEY (group_name, day)
|
|
436
|
+
);
|
|
437
|
+
INSERT INTO active_days_new (group_name, day) SELECT '', day FROM active_days;
|
|
438
|
+
DROP TABLE active_days;
|
|
439
|
+
ALTER TABLE active_days_new RENAME TO active_days;
|
|
388
440
|
`
|
|
389
441
|
];
|
|
390
442
|
function schemaVersion(db) {
|
|
@@ -426,12 +478,543 @@ function openDatabase(path) {
|
|
|
426
478
|
migrate(db);
|
|
427
479
|
return db;
|
|
428
480
|
}
|
|
481
|
+
// src/paths.ts
|
|
482
|
+
function xdgDirectory(value, fallback) {
|
|
483
|
+
return value && isAbsolute(value) ? value : fallback;
|
|
484
|
+
}
|
|
485
|
+
function rucherPaths(env = process.env) {
|
|
486
|
+
if (env.RUCHER_HOME) {
|
|
487
|
+
const home = env.RUCHER_HOME;
|
|
488
|
+
return {
|
|
489
|
+
config: join(home, "config"),
|
|
490
|
+
data: join(home, "data"),
|
|
491
|
+
state: join(home, "state"),
|
|
492
|
+
run: join(home, "run")
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
const home = env.HOME || homedir();
|
|
496
|
+
const state = join(xdgDirectory(env.XDG_STATE_HOME, join(home, ".local", "state")), "rucher");
|
|
497
|
+
return {
|
|
498
|
+
config: join(xdgDirectory(env.XDG_CONFIG_HOME, join(home, ".config")), "rucher"),
|
|
499
|
+
data: join(xdgDirectory(env.XDG_DATA_HOME, join(home, ".local", "share")), "rucher"),
|
|
500
|
+
state,
|
|
501
|
+
run: env.XDG_RUNTIME_DIR && isAbsolute(env.XDG_RUNTIME_DIR) ? join(env.XDG_RUNTIME_DIR, "rucher") : join(state, "run")
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
function databasePath(env) {
|
|
505
|
+
return join(rucherPaths(env).data, "carnet.db");
|
|
506
|
+
}
|
|
507
|
+
function groupsDirectory(env) {
|
|
508
|
+
return join(rucherPaths(env).config, "groups");
|
|
509
|
+
}
|
|
510
|
+
function groupSource(name, env) {
|
|
511
|
+
return join(groupsDirectory(env), name);
|
|
512
|
+
}
|
|
513
|
+
function defaultWorkspace(name, env) {
|
|
514
|
+
return join(rucherPaths(env).data, "workspaces", name);
|
|
515
|
+
}
|
|
516
|
+
function promptsDirectory(env) {
|
|
517
|
+
return join(rucherPaths(env).state, "prompts");
|
|
518
|
+
}
|
|
519
|
+
function corePromptPath(env) {
|
|
520
|
+
return join(rucherPaths(env).config, "prompt.md");
|
|
521
|
+
}
|
|
522
|
+
function reportsDirectory(group) {
|
|
523
|
+
return join(group.workspace, "reports");
|
|
524
|
+
}
|
|
525
|
+
function reportPath(group, agentName) {
|
|
526
|
+
return join(reportsDirectory(group), `${agentName}.md`);
|
|
527
|
+
}
|
|
528
|
+
// src/group/group.ts
|
|
529
|
+
const GROUP_FILE = "group.json";
|
|
530
|
+
const INSTRUCTIONS_FILE = "CLAUDE.md";
|
|
531
|
+
const AGENTS_FILE = "AGENTS.md";
|
|
532
|
+
const GROUP_NAME = /^[a-z0-9-]+$/;
|
|
533
|
+
function isGroupName(name) {
|
|
534
|
+
return GROUP_NAME.test(name);
|
|
535
|
+
}
|
|
536
|
+
function requireGroupName(name) {
|
|
537
|
+
if (!isGroupName(name)) throw new CarnetError("GROUP_NAME_INVALID", `Invalid group name ${JSON.stringify(name)}: use lowercase letters, digits and dashes`);
|
|
538
|
+
}
|
|
539
|
+
function expandHome(path, env = process.env) {
|
|
540
|
+
if (path !== "~" && !path.startsWith("~/")) return path;
|
|
541
|
+
return join(env.HOME || homedir(), path.slice(1));
|
|
542
|
+
}
|
|
543
|
+
function groupFilePath(name, env) {
|
|
544
|
+
return join(groupSource(name, env), GROUP_FILE);
|
|
545
|
+
}
|
|
546
|
+
function groupExists(name, env) {
|
|
547
|
+
return isGroupName(name) && existsSync(groupFilePath(name, env));
|
|
548
|
+
}
|
|
549
|
+
function readGroupFile(name, env) {
|
|
550
|
+
if (!groupExists(name, env)) throw new CarnetError("GROUP_NOT_FOUND", `No group named ${name}: see "rucher groups list"`);
|
|
551
|
+
return JSON.parse(readFileSync(groupFilePath(name, env), "utf8"));
|
|
552
|
+
}
|
|
553
|
+
function writeGroupFile(name, file, env) {
|
|
554
|
+
writeFileSync(groupFilePath(name, env), `${JSON.stringify(file, null, 2)}\n`);
|
|
555
|
+
}
|
|
556
|
+
function loadGroup(name, env = process.env) {
|
|
557
|
+
const file = readGroupFile(name, env);
|
|
558
|
+
return {
|
|
559
|
+
name,
|
|
560
|
+
source: groupSource(name, env),
|
|
561
|
+
workspace: resolve(expandHome(file.workspace ?? defaultWorkspace(name, env), env)),
|
|
562
|
+
repos: (file.repos ?? []).map((repo) => {
|
|
563
|
+
const path = resolve(expandHome(repo.path, env));
|
|
564
|
+
return {
|
|
565
|
+
path,
|
|
566
|
+
name: repo.name ?? basename(path)
|
|
567
|
+
};
|
|
568
|
+
}),
|
|
569
|
+
backends: file.backends ?? {}
|
|
570
|
+
};
|
|
571
|
+
}
|
|
572
|
+
function listGroups(env = process.env) {
|
|
573
|
+
const directory = groupsDirectory(env);
|
|
574
|
+
if (!existsSync(directory)) return [];
|
|
575
|
+
return readdirSync(directory).filter((name) => groupExists(name, env)).sort().map((name) => loadGroup(name, env));
|
|
576
|
+
}
|
|
577
|
+
function groupHosts(group) {
|
|
578
|
+
const hosts = Object.keys(group.backends);
|
|
579
|
+
return hosts.length ? hosts : [DEFAULT_HOST];
|
|
580
|
+
}
|
|
581
|
+
function checkedRepo(path, env) {
|
|
582
|
+
const absolute = resolve(expandHome(path, env));
|
|
583
|
+
if (!existsSync(absolute)) throw new CarnetError("REPO_NOT_FOUND", `Repo path does not exist: ${absolute}`);
|
|
584
|
+
return absolute;
|
|
585
|
+
}
|
|
586
|
+
function requireDistinctNames(group, repos) {
|
|
587
|
+
const names = repos.map((repo) => repo.name);
|
|
588
|
+
const shared = names.find((name, index) => names.indexOf(name) !== index);
|
|
589
|
+
if (shared) throw new CarnetError("REPO_NAME_TAKEN", `${group} would have two repos named ${shared}: give them distinct names`);
|
|
590
|
+
}
|
|
591
|
+
function createGroup(name, options = {}) {
|
|
592
|
+
const { env } = options;
|
|
593
|
+
requireGroupName(name);
|
|
594
|
+
if (groupExists(name, env)) throw new CarnetError("GROUP_EXISTS", `Group ${name} already exists`);
|
|
595
|
+
const repos = [...new Set((options.repos ?? []).map((repo) => checkedRepo(repo, env)))].map((path) => ({
|
|
596
|
+
path,
|
|
597
|
+
name: basename(path)
|
|
598
|
+
}));
|
|
599
|
+
requireDistinctNames(name, repos);
|
|
600
|
+
const source = groupSource(name, env);
|
|
601
|
+
const workspace = defaultWorkspace(name, env);
|
|
602
|
+
mkdirSync(source, { recursive: true });
|
|
603
|
+
mkdirSync(workspace, { recursive: true });
|
|
604
|
+
writeGroupFile(name, {
|
|
605
|
+
name,
|
|
606
|
+
workspace,
|
|
607
|
+
repos,
|
|
608
|
+
backends: {}
|
|
609
|
+
}, env);
|
|
610
|
+
const instructions = join(source, INSTRUCTIONS_FILE);
|
|
611
|
+
if (!existsSync(instructions)) writeFileSync(instructions, "");
|
|
612
|
+
return loadGroup(name, env);
|
|
613
|
+
}
|
|
614
|
+
function sourceInstructions(group) {
|
|
615
|
+
const agents = existsSync(join(group.source, AGENTS_FILE));
|
|
616
|
+
if (agents && existsSync(join(group.source, "CLAUDE.md"))) throw new CarnetError("GROUP_INSTRUCTIONS_CONFLICT", `Group ${group.name} has both ${AGENTS_FILE} and ${INSTRUCTIONS_FILE} in ${group.source}: remove ${INSTRUCTIONS_FILE}`);
|
|
617
|
+
return agents ? AGENTS_FILE : INSTRUCTIONS_FILE;
|
|
618
|
+
}
|
|
619
|
+
function addGroupRepo(name, repo, env) {
|
|
620
|
+
const file = readGroupFile(name, env);
|
|
621
|
+
const group = loadGroup(name, env);
|
|
622
|
+
const path = checkedRepo(repo, env);
|
|
623
|
+
if (group.repos.some((existing) => existing.path === path)) return group;
|
|
624
|
+
requireDistinctNames(name, [...group.repos, {
|
|
625
|
+
path,
|
|
626
|
+
name: basename(path)
|
|
627
|
+
}]);
|
|
628
|
+
writeGroupFile(name, {
|
|
629
|
+
...file,
|
|
630
|
+
repos: [...file.repos ?? [], {
|
|
631
|
+
path,
|
|
632
|
+
name: basename(path)
|
|
633
|
+
}]
|
|
634
|
+
}, env);
|
|
635
|
+
return loadGroup(name, env);
|
|
636
|
+
}
|
|
637
|
+
function removeGroupRepo(name, repo, env) {
|
|
638
|
+
const file = readGroupFile(name, env);
|
|
639
|
+
const group = loadGroup(name, env);
|
|
640
|
+
const path = resolve(expandHome(repo, env));
|
|
641
|
+
const index = group.repos.findIndex((existing) => existing.path === path || existing.name === repo);
|
|
642
|
+
if (index === -1) throw new CarnetError("REPO_NOT_FOUND", `${repo} is not a repo of ${name}`);
|
|
643
|
+
writeGroupFile(name, {
|
|
644
|
+
...file,
|
|
645
|
+
repos: (file.repos ?? []).filter((_, position) => position !== index)
|
|
646
|
+
}, env);
|
|
647
|
+
return loadGroup(name, env);
|
|
648
|
+
}
|
|
649
|
+
function renameGroup(from, to, env) {
|
|
650
|
+
const file = readGroupFile(from, env);
|
|
651
|
+
requireGroupName(to);
|
|
652
|
+
if (existsSync(groupSource(to, env))) throw new CarnetError("GROUP_EXISTS", `Group ${to} already exists`);
|
|
653
|
+
const workspace = loadGroup(from, env).workspace;
|
|
654
|
+
renameSync(groupSource(from, env), groupSource(to, env));
|
|
655
|
+
writeGroupFile(to, {
|
|
656
|
+
...file,
|
|
657
|
+
name: to,
|
|
658
|
+
workspace
|
|
659
|
+
}, env);
|
|
660
|
+
return loadGroup(to, env);
|
|
661
|
+
}
|
|
662
|
+
function dropGroup(name, options = {}) {
|
|
663
|
+
const group = loadGroup(name, options.env);
|
|
664
|
+
rmSync(group.source, {
|
|
665
|
+
recursive: true,
|
|
666
|
+
force: true
|
|
667
|
+
});
|
|
668
|
+
if (options.purge) rmSync(group.workspace, {
|
|
669
|
+
recursive: true,
|
|
670
|
+
force: true
|
|
671
|
+
});
|
|
672
|
+
return group;
|
|
673
|
+
}
|
|
674
|
+
// src/sessions.ts
|
|
675
|
+
const COLUMNS = `id, group_name, name, purpose, kind, status, cwd, repo, host, host_pid, hooked_at, last_title,
|
|
676
|
+
parent_id, prompt_version, created_at, last_active_at, ended_at`;
|
|
677
|
+
function toSession(row) {
|
|
678
|
+
return {
|
|
679
|
+
id: row.id,
|
|
680
|
+
groupName: row.group_name,
|
|
681
|
+
name: row.name,
|
|
682
|
+
purpose: row.purpose,
|
|
683
|
+
kind: row.kind,
|
|
684
|
+
status: row.status,
|
|
685
|
+
cwd: row.cwd,
|
|
686
|
+
repo: row.repo,
|
|
687
|
+
host: row.host,
|
|
688
|
+
hostPid: row.host_pid,
|
|
689
|
+
hookedAt: row.hooked_at,
|
|
690
|
+
lastTitle: row.last_title,
|
|
691
|
+
parentId: row.parent_id,
|
|
692
|
+
promptVersion: row.prompt_version,
|
|
693
|
+
createdAt: row.created_at,
|
|
694
|
+
lastActiveAt: row.last_active_at,
|
|
695
|
+
endedAt: row.ended_at
|
|
696
|
+
};
|
|
697
|
+
}
|
|
698
|
+
function getSession(ctx, id) {
|
|
699
|
+
const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE id = ?`).get(id);
|
|
700
|
+
return row && toSession(row);
|
|
701
|
+
}
|
|
702
|
+
function requireSession(ctx, id) {
|
|
703
|
+
const session = getSession(ctx, id);
|
|
704
|
+
if (!session) throw new CarnetError("SESSION_NOT_FOUND", `Unknown session ${id}`);
|
|
705
|
+
return session;
|
|
706
|
+
}
|
|
707
|
+
function ensureSession(ctx, id, cwd, group) {
|
|
708
|
+
const existing = getSession(ctx, id);
|
|
709
|
+
if (existing) return existing;
|
|
710
|
+
const at = nowIso(ctx);
|
|
711
|
+
ctx.db.prepare("INSERT INTO sessions (id, group_name, cwd, repo, created_at, last_active_at) VALUES (?, ?, ?, ?, ?, ?)").run(id, ctx.group, cwd ?? null, group ? repoNameFor(group, cwd) : null, at, at);
|
|
712
|
+
return requireSession(ctx, id);
|
|
713
|
+
}
|
|
714
|
+
function nameTaken(error, name) {
|
|
715
|
+
if (name && error instanceof Error && error.message.includes("UNIQUE")) throw new CarnetError("SESSION_NAME_TAKEN", `A session named "${name}" already exists`);
|
|
716
|
+
throw error;
|
|
717
|
+
}
|
|
718
|
+
function createSession(ctx, input) {
|
|
719
|
+
if (input.kind === "active" && !input.name) throw new CarnetError("SESSION_NAME_REQUIRED", "An active session needs a name");
|
|
720
|
+
const at = nowIso(ctx);
|
|
721
|
+
try {
|
|
722
|
+
ctx.db.prepare(`INSERT INTO sessions (id, group_name, name, kind, status, cwd, repo, host, last_title,
|
|
723
|
+
created_at, last_active_at)
|
|
724
|
+
VALUES (?, ?, ?, ?, 'running', ?, ?, ?, ?, ?, ?)`).run(input.id, ctx.group, input.name ?? null, input.kind, input.cwd, input.repo ?? null, input.host ?? "claude-code", input.name ?? null, at, at);
|
|
725
|
+
} catch (error) {
|
|
726
|
+
nameTaken(error, input.name);
|
|
727
|
+
}
|
|
728
|
+
return requireSession(ctx, input.id);
|
|
729
|
+
}
|
|
730
|
+
function setSessionKind(ctx, id, kind, name) {
|
|
731
|
+
const session = requireSession(ctx, id);
|
|
732
|
+
const nextName = name ?? session.name;
|
|
733
|
+
if (kind === "active" && !nextName) throw new CarnetError("SESSION_NAME_REQUIRED", "An active session needs a name");
|
|
734
|
+
try {
|
|
735
|
+
ctx.db.prepare("UPDATE sessions SET kind = ?, name = ?, last_title = ? WHERE id = ?").run(kind, nextName, nextName ?? session.lastTitle, id);
|
|
736
|
+
} catch (error) {
|
|
737
|
+
nameTaken(error, nextName);
|
|
738
|
+
}
|
|
739
|
+
return requireSession(ctx, id);
|
|
740
|
+
}
|
|
741
|
+
function endSession(ctx, id) {
|
|
742
|
+
const session = requireSession(ctx, id);
|
|
743
|
+
if (session.status !== "running") return session;
|
|
744
|
+
const ended = setSessionStatus(ctx, id, "idle");
|
|
745
|
+
logEvent(ctx, id, { type: "session.ended" });
|
|
746
|
+
return ended;
|
|
747
|
+
}
|
|
748
|
+
function titleAvailable(ctx, id, title) {
|
|
749
|
+
const owner = sessionByName(ctx, title);
|
|
750
|
+
return !owner || owner.id === id;
|
|
751
|
+
}
|
|
752
|
+
function adoptTitle(ctx, id, rawTitle) {
|
|
753
|
+
const session = requireSession(ctx, id);
|
|
754
|
+
const title = rawTitle?.trim() || null;
|
|
755
|
+
if (title === null || title === session.lastTitle) return session;
|
|
756
|
+
ctx.db.prepare("UPDATE sessions SET last_title = ? WHERE id = ?").run(title, id);
|
|
757
|
+
if (title === session.name || !titleAvailable(ctx, id, title)) return requireSession(ctx, id);
|
|
758
|
+
ctx.db.prepare(`UPDATE sessions
|
|
759
|
+
SET name = ?, kind = CASE WHEN name IS NULL THEN 'active' ELSE kind END
|
|
760
|
+
WHERE id = ?`).run(title, id);
|
|
761
|
+
return requireSession(ctx, id);
|
|
762
|
+
}
|
|
763
|
+
function upsertFromHook(ctx, group, payload, env = {}) {
|
|
764
|
+
const at = nowIso(ctx);
|
|
765
|
+
const host = env.host ?? "claude-code";
|
|
766
|
+
const hostPid = env.processId ?? null;
|
|
767
|
+
const repo = group ? repoNameFor(group, payload.cwd) : null;
|
|
768
|
+
const existing = getSession(ctx, payload.session_id);
|
|
769
|
+
if (!existing) ctx.db.prepare(`INSERT INTO sessions (id, group_name, cwd, repo, host, host_pid, hooked_at, created_at,
|
|
770
|
+
last_active_at)
|
|
771
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(payload.session_id, ctx.group, payload.cwd ?? null, repo, host, hostPid, at, at, at);
|
|
772
|
+
else ctx.db.prepare(`UPDATE sessions
|
|
773
|
+
SET last_active_at = ?, hooked_at = ?, cwd = ?, repo = ?, host = ?, host_pid = ?
|
|
774
|
+
WHERE id = ?`).run(at, at, existing.cwd ?? payload.cwd ?? null, existing.cwd ? existing.repo : repo ?? existing.repo, host, hostPid ?? existing.hostPid, payload.session_id);
|
|
775
|
+
return adoptTitle(ctx, payload.session_id, payload.session_title);
|
|
776
|
+
}
|
|
777
|
+
function touchSession(ctx, id) {
|
|
778
|
+
ctx.db.prepare("UPDATE sessions SET last_active_at = ? WHERE id = ?").run(nowIso(ctx), id);
|
|
779
|
+
}
|
|
780
|
+
function nameSession(ctx, id, name, purpose) {
|
|
781
|
+
requireSession(ctx, id);
|
|
782
|
+
try {
|
|
783
|
+
ctx.db.prepare(`UPDATE sessions
|
|
784
|
+
SET name = ?, purpose = COALESCE(?, purpose), last_active_at = ?,
|
|
785
|
+
kind = 'active'
|
|
786
|
+
WHERE id = ?`).run(name, purpose ?? null, nowIso(ctx), id);
|
|
787
|
+
} catch (error) {
|
|
788
|
+
if (error instanceof Error && error.message.includes("UNIQUE")) throw new CarnetError("SESSION_NAME_TAKEN", `A session named "${name}" already exists`);
|
|
789
|
+
throw error;
|
|
790
|
+
}
|
|
791
|
+
return requireSession(ctx, id);
|
|
792
|
+
}
|
|
793
|
+
function listSessions(ctx, options = {}) {
|
|
794
|
+
const conditions = ["group_name IS ?"];
|
|
795
|
+
if (!options.includeTemp) conditions.push("kind != 'temp'");
|
|
796
|
+
if (!options.includeArchived) conditions.push("status != 'archived'");
|
|
797
|
+
return ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE ${conditions.join(" AND ")} ORDER BY last_active_at DESC`).all(ctx.group).map(toSession);
|
|
798
|
+
}
|
|
799
|
+
function dropSession(ctx, id) {
|
|
800
|
+
requireSession(ctx, id);
|
|
801
|
+
const at = nowIso(ctx);
|
|
802
|
+
ctx.db.prepare("UPDATE agents SET status = 'closed', updated_at = ? WHERE session = ? AND status != 'closed'").run(at, id);
|
|
803
|
+
ctx.db.prepare("UPDATE sessions SET status = 'archived', last_active_at = ? WHERE id = ?").run(at, id);
|
|
804
|
+
return requireSession(ctx, id);
|
|
805
|
+
}
|
|
806
|
+
function defaultSession(ctx) {
|
|
807
|
+
const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE group_name IS ? AND status != 'archived'
|
|
808
|
+
ORDER BY last_active_at DESC LIMIT 1`).get(ctx.group);
|
|
809
|
+
return row && toSession(row);
|
|
810
|
+
}
|
|
811
|
+
function sessionByName(ctx, name) {
|
|
812
|
+
const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE group_name IS ? AND name = ?`).get(ctx.group, name);
|
|
813
|
+
return row && toSession(row);
|
|
814
|
+
}
|
|
815
|
+
const MINIMUM_ID_PREFIX = 4;
|
|
816
|
+
function shortId(id) {
|
|
817
|
+
return id.slice(0, 8);
|
|
818
|
+
}
|
|
819
|
+
function findSession(ctx, reference) {
|
|
820
|
+
const byName = sessionByName(ctx, reference);
|
|
821
|
+
if (byName) return byName;
|
|
822
|
+
const byId = getSession(ctx, reference);
|
|
823
|
+
if (byId) return byId;
|
|
824
|
+
const isIdPrefix = /^[0-9a-f-]+$/i.test(reference);
|
|
825
|
+
if (isIdPrefix && reference.length >= 4) {
|
|
826
|
+
const rows = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE group_name IS ? AND id LIKE ?
|
|
827
|
+
ORDER BY last_active_at DESC`).all(ctx.group, `${reference.toLowerCase()}%`);
|
|
828
|
+
const [only, ...others] = rows;
|
|
829
|
+
if (only && others.length === 0) return toSession(only);
|
|
830
|
+
if (only) throw new CarnetError("SESSION_AMBIGUOUS", `Session id "${reference}" matches several sessions: ${rows.map((row) => shortId(row.id)).join(", ")}`);
|
|
831
|
+
}
|
|
832
|
+
throw new CarnetError("SESSION_NOT_FOUND", `Unknown session "${reference}"${isIdPrefix && reference.length < 4 ? ` (an id prefix needs at least 4 characters)` : ""}`);
|
|
833
|
+
}
|
|
834
|
+
function sessionByHostProcess(ctx, host, processId) {
|
|
835
|
+
const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions
|
|
836
|
+
WHERE host = ? AND host_pid = ? AND hooked_at IS NOT NULL
|
|
837
|
+
ORDER BY hooked_at DESC LIMIT 1`).get(host, processId);
|
|
838
|
+
return row && toSession(row);
|
|
839
|
+
}
|
|
840
|
+
function recordPromptVersion(ctx, id, version) {
|
|
841
|
+
requireSession(ctx, id);
|
|
842
|
+
ctx.db.prepare("UPDATE sessions SET prompt_version = ? WHERE id = ?").run(version, id);
|
|
843
|
+
return requireSession(ctx, id);
|
|
844
|
+
}
|
|
845
|
+
function setParent(ctx, id, parentId) {
|
|
846
|
+
requireSession(ctx, id);
|
|
847
|
+
requireSession(ctx, parentId);
|
|
848
|
+
ctx.db.prepare("UPDATE sessions SET parent_id = ? WHERE id = ?").run(parentId, id);
|
|
849
|
+
return requireSession(ctx, id);
|
|
850
|
+
}
|
|
851
|
+
function setSessionStatus(ctx, id, status) {
|
|
852
|
+
requireSession(ctx, id);
|
|
853
|
+
const at = nowIso(ctx);
|
|
854
|
+
ctx.db.prepare(`UPDATE sessions
|
|
855
|
+
SET status = ?, last_active_at = ?,
|
|
856
|
+
ended_at = CASE WHEN ? = 'running' THEN NULL WHEN ? = 'idle' THEN ? ELSE ended_at END
|
|
857
|
+
WHERE id = ?`).run(status, at, status, status, at, id);
|
|
858
|
+
return requireSession(ctx, id);
|
|
859
|
+
}
|
|
860
|
+
function refuseWhileRunning(session, action) {
|
|
861
|
+
if (session.status === "running") throw new CarnetError("SESSION_RUNNING", `Session ${session.name ?? shortId(session.id)} is running: ${action} it once it has ended`);
|
|
862
|
+
}
|
|
863
|
+
function renameSession(ctx, id, name) {
|
|
864
|
+
refuseWhileRunning(requireSession(ctx, id), "rename");
|
|
865
|
+
try {
|
|
866
|
+
ctx.db.prepare("UPDATE sessions SET name = ? WHERE id = ?").run(name, id);
|
|
867
|
+
} catch (error) {
|
|
868
|
+
nameTaken(error, name);
|
|
869
|
+
}
|
|
870
|
+
return requireSession(ctx, id);
|
|
871
|
+
}
|
|
872
|
+
function promoteSession(ctx, id, name) {
|
|
873
|
+
const session = requireSession(ctx, id);
|
|
874
|
+
if (session.kind === "active") throw new CarnetError("SESSION_KIND_INVALID", `Session ${session.name} is already active`);
|
|
875
|
+
const nextName = name ?? session.name;
|
|
876
|
+
if (!nextName) throw new CarnetError("SESSION_NAME_REQUIRED", "An active session needs a name");
|
|
877
|
+
if (nextName !== session.name) refuseWhileRunning(session, "rename");
|
|
878
|
+
try {
|
|
879
|
+
ctx.db.prepare("UPDATE sessions SET kind = 'active', name = ? WHERE id = ?").run(nextName, id);
|
|
880
|
+
} catch (error) {
|
|
881
|
+
nameTaken(error, nextName);
|
|
882
|
+
}
|
|
883
|
+
return requireSession(ctx, id);
|
|
884
|
+
}
|
|
885
|
+
function demoteSession(ctx, id) {
|
|
886
|
+
const session = requireSession(ctx, id);
|
|
887
|
+
if (session.kind === "temp") throw new CarnetError("SESSION_KIND_INVALID", `Session ${session.name ?? shortId(session.id)} is already temp`);
|
|
888
|
+
ctx.db.prepare("UPDATE sessions SET kind = 'temp' WHERE id = ?").run(id);
|
|
889
|
+
return requireSession(ctx, id);
|
|
890
|
+
}
|
|
891
|
+
function staleTempSessions(ctx, olderThanMilliseconds) {
|
|
892
|
+
const before = new Date(ctx.now().getTime() - olderThanMilliseconds).toISOString();
|
|
893
|
+
return ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions
|
|
894
|
+
WHERE group_name IS ? AND kind = 'temp' AND status = 'idle' AND last_active_at < ?
|
|
895
|
+
ORDER BY last_active_at ASC`).all(ctx.group, before).map(toSession);
|
|
896
|
+
}
|
|
897
|
+
function resetDeadSessions(ctx, isAlive) {
|
|
898
|
+
return ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE status = 'running'`).all().map(toSession).filter((session) => session.hostPid === null || !isAlive(session.hostPid)).map((session) => endSession(ctx, session.id));
|
|
899
|
+
}
|
|
900
|
+
// src/prompt/core-rules.ts
|
|
901
|
+
const CORE_RULES = `- Work can be parallel, review stays sequential: forks work at the same time, the human handles their results one at a time.
|
|
902
|
+
- The human keeps the hand: only the human launches forks, applies, tests and commits. Agents propose, they never push.
|
|
903
|
+
- Status lives in Carnet: agent statuses, the "On the table" line and the journal go through the Carnet tools, never into status files nor chat updates. Update before and after each piece of work.
|
|
904
|
+
- When a fork finishes, say only "<name> finished, report ready". Never summarise, quote or act on its report or final message until the human asks for that fork's report, even when answering about something else.
|
|
905
|
+
- Forks never commit, push, stash or record notes. A fork writes its report to a file, ending with a Learnings section, calls agent_done as its last tool action, then replies with one line that carries no results, such as "<name> done, report written". Only the main agent records notes, at the end of a step.
|
|
906
|
+
- To dispatch, apply or review forks, load the rucher skill: it holds the full workflow.`;
|
|
907
|
+
// src/prompt/prompt.ts
|
|
908
|
+
const PROMPT_FILE = "prompt.md";
|
|
909
|
+
function readIfPresent(path) {
|
|
910
|
+
if (!existsSync(path)) return void 0;
|
|
911
|
+
return readFileSync(path, "utf8").trim() || void 0;
|
|
912
|
+
}
|
|
913
|
+
function baseRules(env = process.env) {
|
|
914
|
+
return readIfPresent(corePromptPath(env)) ?? "- Work can be parallel, review stays sequential: forks work at the same time, the human handles their results one at a time.\n- The human keeps the hand: only the human launches forks, applies, tests and commits. Agents propose, they never push.\n- Status lives in Carnet: agent statuses, the \"On the table\" line and the journal go through the Carnet tools, never into status files nor chat updates. Update before and after each piece of work.\n- When a fork finishes, say only \"<name> finished, report ready\". Never summarise, quote or act on its report or final message until the human asks for that fork's report, even when answering about something else.\n- Forks never commit, push, stash or record notes. A fork writes its report to a file, ending with a Learnings section, calls agent_done as its last tool action, then replies with one line that carries no results, such as \"<name> done, report written\". Only the main agent records notes, at the end of a step.\n- To dispatch, apply or review forks, load the rucher skill: it holds the full workflow.";
|
|
915
|
+
}
|
|
916
|
+
function groupRules(group) {
|
|
917
|
+
return group ? readIfPresent(join(group.source, PROMPT_FILE)) : void 0;
|
|
918
|
+
}
|
|
919
|
+
function rulesText(group, env = process.env) {
|
|
920
|
+
const extra = groupRules(group);
|
|
921
|
+
const base = `Rucher rules, always follow them:\n${baseRules(env)}`;
|
|
922
|
+
return extra && group ? `${base}\n\nRules of the ${group.name} group:\n${extra}` : base;
|
|
923
|
+
}
|
|
924
|
+
function rulesVersion(group, env = process.env) {
|
|
925
|
+
return createHash("sha256").update(rulesText(group, env)).digest("hex").slice(0, 12);
|
|
926
|
+
}
|
|
927
|
+
function assemblePrompt(group, session, env = process.env) {
|
|
928
|
+
const label = session.name ?? shortId(session.id);
|
|
929
|
+
const identity = group ? `This is the Rucher session ${label} (${session.kind}) of the ${group.name} group.` : `This is the Rucher session ${label} (${session.kind}), outside any group.`;
|
|
930
|
+
return {
|
|
931
|
+
text: `${rulesText(group, env)}\n\n${identity}\n`,
|
|
932
|
+
version: rulesVersion(group, env)
|
|
933
|
+
};
|
|
934
|
+
}
|
|
935
|
+
function appendPromptFile(group, session, env = process.env) {
|
|
936
|
+
const { text, version } = assemblePrompt(group, session, env);
|
|
937
|
+
const directory = promptsDirectory(env);
|
|
938
|
+
mkdirSync(directory, { recursive: true });
|
|
939
|
+
const path = join(directory, `${session.id}.md`);
|
|
940
|
+
writeFileSync(path, text);
|
|
941
|
+
return {
|
|
942
|
+
path,
|
|
943
|
+
version
|
|
944
|
+
};
|
|
945
|
+
}
|
|
946
|
+
function compactReminder(group, env = process.env) {
|
|
947
|
+
return `The conversation was just compacted and this session was not started by rucher, so its system prompt no longer holds the Rucher rules. ${rulesText(group, env)}`;
|
|
948
|
+
}
|
|
949
|
+
function outsideRucherContext(group, env = process.env) {
|
|
950
|
+
return `This session was started without rucher, so its system prompt does not hold the Rucher rules. ${rulesText(group, env)}`;
|
|
951
|
+
}
|
|
952
|
+
const OUTSIDE_RUCHER_NOTICE = "rucher: session started without rucher, the Rucher rules are not in its system prompt (use rucher new, tmp or resume)";
|
|
953
|
+
const RULES_UPDATED_NOTICE = "rucher: rules updated, will apply after the next compaction or in a new session";
|
|
954
|
+
const SUBAGENT_RULES = "Rucher rules for sub-agents: never commit, push or stash. When your task asks for a report, write it to the file it names. If your prompt names you as a Carnet agent, call agent_update at meaningful progress and agent_done as your last tool action, then reply with one line.";
|
|
955
|
+
// src/workspace-files.ts
|
|
956
|
+
const GENERATED_MARKER = "generated by rucher, do not edit";
|
|
957
|
+
function refuse(path) {
|
|
958
|
+
throw new CarnetError("WORKSPACE_FILE_CONFLICT", `${path} was not written by rucher: move its content to the group source, then remove it`);
|
|
959
|
+
}
|
|
960
|
+
function entry(path) {
|
|
961
|
+
try {
|
|
962
|
+
return lstatSync(path);
|
|
963
|
+
} catch {
|
|
964
|
+
return;
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
const MARKDOWN_MARKER = `<!-- ${GENERATED_MARKER} -->\n`;
|
|
968
|
+
function markdownCopy(content) {
|
|
969
|
+
return `${MARKDOWN_MARKER}${content}`;
|
|
970
|
+
}
|
|
971
|
+
function isMarkdownCopy(path) {
|
|
972
|
+
if (!entry(path)?.isFile()) return false;
|
|
973
|
+
return readFileSync(path, "utf8").startsWith(MARKDOWN_MARKER);
|
|
974
|
+
}
|
|
975
|
+
function removeStaleCopies(directory, keep) {
|
|
976
|
+
const removed = [];
|
|
977
|
+
if (!entry(directory)) return removed;
|
|
978
|
+
for (const name of readdirSync(directory)) {
|
|
979
|
+
if (!name.endsWith(".md") || keep.has(name)) continue;
|
|
980
|
+
const path = join(directory, name);
|
|
981
|
+
if (!isMarkdownCopy(path)) continue;
|
|
982
|
+
rmSync(path, { force: true });
|
|
983
|
+
removed.push(name);
|
|
984
|
+
}
|
|
985
|
+
return removed;
|
|
986
|
+
}
|
|
987
|
+
function writeGenerated(path, content) {
|
|
988
|
+
const current = entry(path);
|
|
989
|
+
if (current?.isSymbolicLink()) rmSync(path, { force: true });
|
|
990
|
+
else if (current) {
|
|
991
|
+
const existing = readFileSync(path, "utf8");
|
|
992
|
+
if (existing === content) return false;
|
|
993
|
+
if (!existing.includes("generated by rucher, do not edit")) refuse(path);
|
|
994
|
+
}
|
|
995
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
996
|
+
writeFileSync(path, content);
|
|
997
|
+
return true;
|
|
998
|
+
}
|
|
999
|
+
function isObject(value) {
|
|
1000
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1001
|
+
}
|
|
1002
|
+
function mergeSettings(base, extra) {
|
|
1003
|
+
const merged = { ...base };
|
|
1004
|
+
for (const [key, value] of Object.entries(extra)) {
|
|
1005
|
+
const current = merged[key];
|
|
1006
|
+
if (Array.isArray(current) && Array.isArray(value)) {
|
|
1007
|
+
const seen = new Set(current.map((item) => JSON.stringify(item)));
|
|
1008
|
+
merged[key] = [...current, ...value.filter((item) => !seen.has(JSON.stringify(item)))];
|
|
1009
|
+
} else if (isObject(current) && isObject(value)) merged[key] = mergeSettings(current, value);
|
|
1010
|
+
else merged[key] = value;
|
|
1011
|
+
}
|
|
1012
|
+
return merged;
|
|
1013
|
+
}
|
|
429
1014
|
// src/hosts/claude-code.ts
|
|
430
1015
|
const TRANSCRIPT_TAIL_BYTES = 262144;
|
|
431
1016
|
const TITLE_PATTERN = /"type":"custom-title","customTitle":("(?:[^"\\]|\\.)*")/g;
|
|
432
1017
|
const FORK_NAME_PATTERN = /You are fork `([^`]+)`/;
|
|
433
|
-
const REPOS_START = "<!-- rucher:repos start -->";
|
|
434
|
-
const REPOS_END = "<!-- rucher:repos end -->";
|
|
435
1018
|
function payloadObject(json) {
|
|
436
1019
|
const data = JSON.parse(json);
|
|
437
1020
|
if (typeof data.session_id !== "string" || !data.session_id) throw new TypeError("Hook payload has no session_id");
|
|
@@ -484,77 +1067,63 @@ function transcriptTitle(path) {
|
|
|
484
1067
|
if (descriptor !== void 0) closeSync(descriptor);
|
|
485
1068
|
}
|
|
486
1069
|
}
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
(what every session of this group should know)
|
|
511
|
-
`;
|
|
1070
|
+
const SETTINGS_FILE = join(".claude", "settings.json");
|
|
1071
|
+
const BACKEND_NOTES = "backends/claude.md";
|
|
1072
|
+
function instructionFiles(group) {
|
|
1073
|
+
if (!existsSync(group.source)) return [];
|
|
1074
|
+
return readdirSync(group.source, { withFileTypes: true }).filter((item) => item.isFile() && item.name.endsWith(".md") && item.name !== "prompt.md").map((item) => item.name).sort();
|
|
1075
|
+
}
|
|
1076
|
+
function repoAgentsImports(group) {
|
|
1077
|
+
return group.repos.filter((repo) => existsSync(join(repo.path, "AGENTS.md")) && !existsSync(join(repo.path, "CLAUDE.md")) && !existsSync(join(repo.path, ".claude", "CLAUDE.md"))).map((repo) => `@${join(repo.path, AGENTS_FILE)}`);
|
|
1078
|
+
}
|
|
1079
|
+
function workspaceCopies(group) {
|
|
1080
|
+
const agents = sourceInstructions(group) === AGENTS_FILE;
|
|
1081
|
+
const read = (name) => readFileSync(join(group.source, name), "utf8");
|
|
1082
|
+
const copies = new Map(instructionFiles(group).map((name) => [name, markdownCopy(read(name))]));
|
|
1083
|
+
if (!agents) return copies;
|
|
1084
|
+
const imports = [`@${AGENTS_FILE}`];
|
|
1085
|
+
if (existsSync(join(group.source, BACKEND_NOTES))) {
|
|
1086
|
+
copies.set(BACKEND_NOTES, markdownCopy(read(BACKEND_NOTES)));
|
|
1087
|
+
imports.push(`@${BACKEND_NOTES}`);
|
|
1088
|
+
}
|
|
1089
|
+
imports.push(...repoAgentsImports(group));
|
|
1090
|
+
copies.set(INSTRUCTIONS_FILE, markdownCopy(`${imports.join("\n")}\n`));
|
|
1091
|
+
return copies;
|
|
512
1092
|
}
|
|
513
1093
|
function groupSettings(group) {
|
|
514
|
-
return
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
const path = join(group.root, "CLAUDE.md");
|
|
520
|
-
if (!existsSync(path)) {
|
|
521
|
-
writeFileSync(path, groupInstructions(group));
|
|
522
|
-
return "written";
|
|
1094
|
+
return mergeSettings({
|
|
1095
|
+
"//": GENERATED_MARKER,
|
|
1096
|
+
permissions: {
|
|
1097
|
+
additionalDirectories: group.repos.map((repo) => repo.path),
|
|
1098
|
+
deny: [...workspaceCopies(group).keys()].sort().map((name) => `Edit(/${name})`)
|
|
523
1099
|
}
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
}
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
settings.permissions = {
|
|
547
|
-
...settings.permissions,
|
|
548
|
-
additionalDirectories: next
|
|
549
|
-
};
|
|
550
|
-
writeFileSync(path, `${JSON.stringify(settings, null, 2)}\n`);
|
|
551
|
-
return "updated";
|
|
552
|
-
}
|
|
553
|
-
};
|
|
1100
|
+
}, group.backends["claude-code"]?.settings ?? {});
|
|
1101
|
+
}
|
|
1102
|
+
function removeStaleBackendNotes(group, keep) {
|
|
1103
|
+
const directory = join(group.workspace, dirname(BACKEND_NOTES));
|
|
1104
|
+
const removed = removeStaleCopies(directory, new Set([...keep].filter((name) => dirname(name) === dirname(BACKEND_NOTES)).map((name) => basename(name))));
|
|
1105
|
+
if (existsSync(directory) && readdirSync(directory).length === 0) rmdirSync(directory);
|
|
1106
|
+
return removed.map((name) => join(dirname(BACKEND_NOTES), name));
|
|
1107
|
+
}
|
|
1108
|
+
function renderClaudeWorkspace(group) {
|
|
1109
|
+
const rendered = {
|
|
1110
|
+
written: [],
|
|
1111
|
+
removed: []
|
|
1112
|
+
};
|
|
1113
|
+
const copies = workspaceCopies(group);
|
|
1114
|
+
for (const [name, content] of [...copies].sort(([a], [b]) => a.localeCompare(b))) if (writeGenerated(join(group.workspace, name), content)) rendered.written.push(name);
|
|
1115
|
+
const names = new Set(copies.keys());
|
|
1116
|
+
rendered.removed.push(...removeStaleCopies(group.workspace, names));
|
|
1117
|
+
rendered.removed.push(...removeStaleBackendNotes(group, names));
|
|
1118
|
+
const settings = `${JSON.stringify(groupSettings(group), null, 2)}\n`;
|
|
1119
|
+
if (writeGenerated(join(group.workspace, SETTINGS_FILE), settings)) rendered.written.push(SETTINGS_FILE);
|
|
1120
|
+
return rendered;
|
|
1121
|
+
}
|
|
554
1122
|
function launchArguments(options = {}) {
|
|
555
1123
|
return [
|
|
556
1124
|
...options.name ? ["--name", options.name] : [],
|
|
557
1125
|
...options.appendPromptFile ? ["--append-system-prompt-file", options.appendPromptFile] : [],
|
|
1126
|
+
...(options.directories ?? []).flatMap((directory) => ["--add-dir", directory]),
|
|
558
1127
|
...options.passthrough ?? []
|
|
559
1128
|
];
|
|
560
1129
|
}
|
|
@@ -689,7 +1258,7 @@ const claudeCode = {
|
|
|
689
1258
|
renameInstruction(name) {
|
|
690
1259
|
return `Ask the human to run /rename ${name} in Claude Code so the titles match.`;
|
|
691
1260
|
},
|
|
692
|
-
|
|
1261
|
+
renderWorkspace: renderClaudeWorkspace
|
|
693
1262
|
};
|
|
694
1263
|
// src/hosts/host.ts
|
|
695
1264
|
const DEFAULT_HOST = "claude-code";
|
|
@@ -702,123 +1271,138 @@ function hostById(id) {
|
|
|
702
1271
|
if (!host) throw new CarnetError("UNKNOWN_HOST", `Unknown host "${id}" (available: ${Object.keys(HOSTS).join(", ")})`);
|
|
703
1272
|
return host;
|
|
704
1273
|
}
|
|
705
|
-
// src/group
|
|
706
|
-
function
|
|
707
|
-
|
|
1274
|
+
// src/group-rows.ts
|
|
1275
|
+
function inTransaction(db, run) {
|
|
1276
|
+
db.exec("BEGIN");
|
|
1277
|
+
try {
|
|
1278
|
+
const result = run();
|
|
1279
|
+
db.exec("COMMIT");
|
|
1280
|
+
return result;
|
|
1281
|
+
} catch (error) {
|
|
1282
|
+
db.exec("ROLLBACK");
|
|
1283
|
+
throw error;
|
|
1284
|
+
}
|
|
708
1285
|
}
|
|
709
|
-
function
|
|
710
|
-
|
|
1286
|
+
function sessionGroupName(db, sessionId) {
|
|
1287
|
+
const row = db.prepare("SELECT group_name FROM sessions WHERE id = ?").get(sessionId);
|
|
1288
|
+
return row ? row.group_name : void 0;
|
|
711
1289
|
}
|
|
712
|
-
function
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
1290
|
+
function renameGroupRows(db, from, to) {
|
|
1291
|
+
inTransaction(db, () => {
|
|
1292
|
+
for (const table of [
|
|
1293
|
+
"sessions",
|
|
1294
|
+
"notes",
|
|
1295
|
+
"active_days"
|
|
1296
|
+
]) db.prepare(`UPDATE ${table} SET group_name = ? WHERE group_name = ?`).run(to, from);
|
|
1297
|
+
});
|
|
716
1298
|
}
|
|
717
|
-
function
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
1299
|
+
function archiveGroupSessions(db, name, at) {
|
|
1300
|
+
return inTransaction(db, () => {
|
|
1301
|
+
db.prepare(`UPDATE agents SET status = 'closed', updated_at = ?
|
|
1302
|
+
WHERE status != 'closed' AND session IN (SELECT id FROM sessions WHERE group_name = ?)`).run(at, name);
|
|
1303
|
+
return Number(db.prepare(`UPDATE sessions SET status = 'archived', last_active_at = ?
|
|
1304
|
+
WHERE group_name = ? AND status != 'archived'`).run(at, name).changes);
|
|
1305
|
+
});
|
|
722
1306
|
}
|
|
723
|
-
function
|
|
724
|
-
return
|
|
1307
|
+
function deleteGroupNotes(db, name) {
|
|
1308
|
+
return Number(db.prepare("DELETE FROM notes WHERE group_name = ?").run(name).changes);
|
|
725
1309
|
}
|
|
726
|
-
function
|
|
727
|
-
|
|
1310
|
+
function groupSessionCounts(db) {
|
|
1311
|
+
const rows = db.prepare(`SELECT group_name, COUNT(*) AS count FROM sessions
|
|
1312
|
+
WHERE group_name IS NOT NULL AND status != 'archived' GROUP BY group_name`).all();
|
|
1313
|
+
return new Map(rows.map((row) => [row.group_name, Number(row.count)]));
|
|
728
1314
|
}
|
|
729
1315
|
// src/group/locate.ts
|
|
730
|
-
const GROUP_DIRECTORY = ".rucher";
|
|
731
|
-
const REPORTS_DIRECTORY = "reports";
|
|
732
|
-
const GROUP_FILE = "group.json";
|
|
733
|
-
const DB_FILE = "carnet.db";
|
|
734
1316
|
function isInside(directory, path) {
|
|
735
1317
|
const relativePath = relative(directory, path);
|
|
736
1318
|
return relativePath === "" || !relativePath.startsWith("..") && !resolve(relativePath).startsWith(relativePath);
|
|
737
1319
|
}
|
|
1320
|
+
function repoOf(group, path) {
|
|
1321
|
+
const absolutePath = resolve(path);
|
|
1322
|
+
return group?.repos.find((repo) => isInside(repo.path, absolutePath));
|
|
1323
|
+
}
|
|
738
1324
|
function repoNameFor(group, path) {
|
|
739
|
-
|
|
740
|
-
const repo = group.repos.find((repo) => isInside(repo, resolve(path)));
|
|
741
|
-
return repo ? basename(repo) : null;
|
|
1325
|
+
return path ? repoOf(group, path)?.name ?? null : null;
|
|
742
1326
|
}
|
|
743
1327
|
function repoPathFor(group, path) {
|
|
744
1328
|
if (!path) return null;
|
|
745
|
-
const
|
|
746
|
-
const repo = group.repos.find((candidate) => isInside(candidate, absolutePath));
|
|
1329
|
+
const repo = repoOf(group, path);
|
|
747
1330
|
if (!repo) return null;
|
|
748
|
-
const relativePath = relative(repo,
|
|
749
|
-
return relativePath ? join(
|
|
750
|
-
}
|
|
751
|
-
function
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
1331
|
+
const relativePath = relative(repo.path, resolve(path));
|
|
1332
|
+
return relativePath ? join(repo.name, relativePath) : repo.name;
|
|
1333
|
+
}
|
|
1334
|
+
function namedGroup(name, env) {
|
|
1335
|
+
if (!groupExists(name, env)) throw new CarnetError("GROUP_NOT_FOUND", `No group named ${name}: see "rucher groups list"`);
|
|
1336
|
+
return loadGroup(name, env);
|
|
1337
|
+
}
|
|
1338
|
+
function byWorkspace(groups, directories) {
|
|
1339
|
+
return groups.find((group) => directories.some((directory) => isInside(group.workspace, directory)));
|
|
1340
|
+
}
|
|
1341
|
+
function byRepo(groups, directory) {
|
|
1342
|
+
let best = [];
|
|
1343
|
+
for (const group of groups) for (const repo of group.repos) {
|
|
1344
|
+
if (!isInside(repo.path, directory)) continue;
|
|
1345
|
+
const length = best[0]?.repo.path.length ?? -1;
|
|
1346
|
+
if (repo.path.length > length) best = [{
|
|
1347
|
+
group,
|
|
1348
|
+
repo
|
|
1349
|
+
}];
|
|
1350
|
+
else if (repo.path.length === length) best.push({
|
|
1351
|
+
group,
|
|
1352
|
+
repo
|
|
1353
|
+
});
|
|
758
1354
|
}
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
return
|
|
762
|
-
}
|
|
763
|
-
function
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
repos: (file.repos ?? []).map((repo) => resolve(root, repo)),
|
|
775
|
-
hosts: file.hosts?.length ? file.hosts : [DEFAULT_HOST],
|
|
776
|
-
dbPath: join(root, GROUP_DIRECTORY, DB_FILE)
|
|
777
|
-
};
|
|
778
|
-
}
|
|
779
|
-
function groupsWithRepo(paths, env) {
|
|
780
|
-
const groups = [];
|
|
781
|
-
for (const reference of readRegistry(env)) {
|
|
782
|
-
if (!isGroupRoot(reference.path)) continue;
|
|
783
|
-
const group = loadGroup(reference.path);
|
|
784
|
-
if (paths.some((path) => group.repos.some((repo) => isInside(repo, path)))) groups.push(group);
|
|
1355
|
+
const names = [...new Set(best.map((match) => match.group.name))];
|
|
1356
|
+
if (names.length > 1) throw new CarnetError("GROUP_AMBIGUOUS", `${directory} is in repos of several groups (${names.join(", ")}): pass --group`);
|
|
1357
|
+
return best[0];
|
|
1358
|
+
}
|
|
1359
|
+
function resolveGroup({ db, sessionId, group, cwd = process.cwd(), env = process.env } = {}) {
|
|
1360
|
+
if (db && sessionId) {
|
|
1361
|
+
const name = sessionGroupName(db, sessionId);
|
|
1362
|
+
if (name === null) return {
|
|
1363
|
+
group: null,
|
|
1364
|
+
origin: "session"
|
|
1365
|
+
};
|
|
1366
|
+
if (name !== void 0 && groupExists(name, env)) return {
|
|
1367
|
+
group: loadGroup(name, env),
|
|
1368
|
+
origin: "session"
|
|
1369
|
+
};
|
|
785
1370
|
}
|
|
786
|
-
return
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
}
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
1371
|
+
if (group) return {
|
|
1372
|
+
group: namedGroup(group, env),
|
|
1373
|
+
origin: "option"
|
|
1374
|
+
};
|
|
1375
|
+
if (env.RUCHER_GROUP) return {
|
|
1376
|
+
group: namedGroup(env.RUCHER_GROUP, env),
|
|
1377
|
+
origin: "env"
|
|
1378
|
+
};
|
|
1379
|
+
const projectDirectories = allHosts().map((host) => host.projectDirectory(env)).filter((directory) => directory !== void 0);
|
|
1380
|
+
const directories = [resolve(cwd), ...projectDirectories.map((directory) => resolve(directory))];
|
|
1381
|
+
const groups = listGroups(env);
|
|
1382
|
+
const workspaceGroup = byWorkspace(groups, directories);
|
|
1383
|
+
if (workspaceGroup) return {
|
|
1384
|
+
group: workspaceGroup,
|
|
1385
|
+
origin: "workspace"
|
|
1386
|
+
};
|
|
1387
|
+
for (const directory of directories) {
|
|
1388
|
+
const match = byRepo(groups, directory);
|
|
1389
|
+
if (match) return {
|
|
1390
|
+
group: match.group,
|
|
1391
|
+
origin: "repo",
|
|
1392
|
+
repo: match.repo
|
|
1393
|
+
};
|
|
797
1394
|
}
|
|
1395
|
+
return {
|
|
1396
|
+
group: null,
|
|
1397
|
+
origin: "none"
|
|
1398
|
+
};
|
|
798
1399
|
}
|
|
799
|
-
function
|
|
800
|
-
|
|
801
|
-
return root && isGroupRoot(resolve(root)) ? loadGroup(resolve(root)) : null;
|
|
1400
|
+
function groupLabel(group) {
|
|
1401
|
+
return group?.name ?? "no group";
|
|
802
1402
|
}
|
|
803
|
-
function
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
const projectDirectories = allHosts().map((host) => host.projectDirectory(env)).filter((directory) => directory !== void 0);
|
|
807
|
-
const candidates = [resolve(cwd), ...projectDirectories.map((directory) => resolve(directory))];
|
|
808
|
-
for (const directory of candidates) {
|
|
809
|
-
const root = findGroupRoot(directory);
|
|
810
|
-
if (root) return loadGroup(root);
|
|
811
|
-
}
|
|
812
|
-
const matches = groupsWithRepo(candidates, env);
|
|
813
|
-
const [only] = matches;
|
|
814
|
-
if (matches.length === 1 && only) return only;
|
|
815
|
-
if (matches.length > 1) {
|
|
816
|
-
const owners = sessionId ? matches.filter((group) => knowsSession(group, sessionId)) : [];
|
|
817
|
-
const [owner] = owners;
|
|
818
|
-
if (owners.length === 1 && owner) return owner;
|
|
819
|
-
throw new CarnetError("GROUP_AMBIGUOUS", `${cwd} is in repos of several groups (${matches.map((group) => group.name).join(", ")}): launch with "rucher new" or "rucher resume", or start from the group's meta directory`);
|
|
820
|
-
}
|
|
821
|
-
throw new CarnetError("NO_GROUP", `No Rucher group for ${cwd}: run "rucher init" in a meta directory, or "rucher group add <this repo>" there`);
|
|
1403
|
+
function requireGroup(group) {
|
|
1404
|
+
if (group) return group;
|
|
1405
|
+
throw new CarnetError("NO_GROUP", "No Rucher group here: pass --group, or run this from a repo or workspace of a group");
|
|
822
1406
|
}
|
|
823
1407
|
function ambiguousGroupContext(reason) {
|
|
824
1408
|
return `Rucher could not tell which group this session belongs to, so Carnet records nothing for it: ${reason}.`;
|
|
@@ -841,6 +1425,11 @@ function memoryHalfLife(value) {
|
|
|
841
1425
|
const days = Number(value);
|
|
842
1426
|
return Number.isFinite(days) && days > 0 ? days : 20;
|
|
843
1427
|
}
|
|
1428
|
+
const NOTE_COLUMNS = `notes.id, notes.number, notes.kind, notes.text, notes.session, notes.agent,
|
|
1429
|
+
notes.similar_notes, notes.created_at, notes.dropped_at, notes.dropped_reason,
|
|
1430
|
+
notes.dropped_session,
|
|
1431
|
+
(SELECT replaced.number FROM notes AS replaced WHERE replaced.id = notes.replaced_by)
|
|
1432
|
+
AS replaced_number`;
|
|
844
1433
|
const MARKDOWN = /\*\*|__|\[[^\]]*\]\([^)]*\)|^#{1,6}\s|^[-*+]\s/;
|
|
845
1434
|
function cleanText(value, label) {
|
|
846
1435
|
const text = value.trim().replace(/[ \t]+/g, " ");
|
|
@@ -852,7 +1441,7 @@ function cleanText(value, label) {
|
|
|
852
1441
|
return text;
|
|
853
1442
|
}
|
|
854
1443
|
function groupRepoNames(group) {
|
|
855
|
-
return group.repos.map((repo) =>
|
|
1444
|
+
return group.repos.map((repo) => repo.name);
|
|
856
1445
|
}
|
|
857
1446
|
function cleanRepos(group, repos) {
|
|
858
1447
|
const known = groupRepoNames(group);
|
|
@@ -878,21 +1467,22 @@ function localDay(date) {
|
|
|
878
1467
|
return `${date.getFullYear()}-${month}-${day}`;
|
|
879
1468
|
}
|
|
880
1469
|
function recordActiveDay(ctx) {
|
|
881
|
-
ctx.
|
|
1470
|
+
if (ctx.group === null) return;
|
|
1471
|
+
ctx.db.prepare("INSERT OR IGNORE INTO active_days (group_name, day) VALUES (?, ?)").run(ctx.group, localDay(ctx.now()));
|
|
882
1472
|
}
|
|
883
1473
|
function activeDays(ctx) {
|
|
884
|
-
return ctx.db.prepare("SELECT day FROM active_days ORDER BY day").all().map((row) => row.day);
|
|
1474
|
+
return ctx.db.prepare("SELECT day FROM active_days WHERE group_name IS ? ORDER BY day").all(ctx.group).map((row) => row.day);
|
|
885
1475
|
}
|
|
886
1476
|
function activeDaysSince(days, at) {
|
|
887
1477
|
const since = localDay(new Date(at));
|
|
888
1478
|
return days.filter((day) => day > since).length;
|
|
889
1479
|
}
|
|
890
|
-
function reposOf(ctx,
|
|
891
|
-
return ctx.db.prepare("SELECT repo FROM note_repos WHERE note = ? ORDER BY repo").all(
|
|
1480
|
+
function reposOf(ctx, noteId) {
|
|
1481
|
+
return ctx.db.prepare("SELECT repo FROM note_repos WHERE note = ? ORDER BY repo").all(noteId).map((row) => row.repo);
|
|
892
1482
|
}
|
|
893
1483
|
function toNote(ctx, row) {
|
|
894
1484
|
return {
|
|
895
|
-
id: row.
|
|
1485
|
+
id: row.number,
|
|
896
1486
|
kind: row.kind,
|
|
897
1487
|
text: row.text,
|
|
898
1488
|
repos: reposOf(ctx, row.id),
|
|
@@ -903,11 +1493,19 @@ function toNote(ctx, row) {
|
|
|
903
1493
|
droppedAt: row.dropped_at,
|
|
904
1494
|
droppedReason: row.dropped_reason,
|
|
905
1495
|
droppedSession: row.dropped_session,
|
|
906
|
-
replacedBy: row.
|
|
1496
|
+
replacedBy: row.replaced_number
|
|
907
1497
|
};
|
|
908
1498
|
}
|
|
1499
|
+
function noteRow(ctx, number) {
|
|
1500
|
+
return ctx.db.prepare(`SELECT ${NOTE_COLUMNS} FROM notes WHERE group_name IS ? AND number = ?`).get(ctx.group, number);
|
|
1501
|
+
}
|
|
1502
|
+
function noteId(ctx, number) {
|
|
1503
|
+
const row = noteRow(ctx, number);
|
|
1504
|
+
if (!row) throw new CarnetError("NOTE_NOT_FOUND", `Unknown note #${number}`);
|
|
1505
|
+
return row.id;
|
|
1506
|
+
}
|
|
909
1507
|
function getNote(ctx, id) {
|
|
910
|
-
const row = ctx
|
|
1508
|
+
const row = noteRow(ctx, id);
|
|
911
1509
|
return row ? toNote(ctx, row) : null;
|
|
912
1510
|
}
|
|
913
1511
|
function requireNote(ctx, id) {
|
|
@@ -920,8 +1518,11 @@ function requireActiveNote(ctx, id) {
|
|
|
920
1518
|
if (note.droppedAt) throw new CarnetError("INVALID_NOTE", `Note #${id} is dropped`);
|
|
921
1519
|
return note;
|
|
922
1520
|
}
|
|
923
|
-
|
|
924
|
-
|
|
1521
|
+
const CITATION_COLUMNS = `note_citations.id, notes.number AS note, note_citations.session,
|
|
1522
|
+
note_citations.agent, note_citations.why, note_citations.at`;
|
|
1523
|
+
function citationsOf(ctx, number) {
|
|
1524
|
+
return ctx.db.prepare(`SELECT ${CITATION_COLUMNS} FROM note_citations JOIN notes ON notes.id = note_citations.note
|
|
1525
|
+
WHERE notes.group_name IS ? AND notes.number = ? ORDER BY note_citations.at`).all(ctx.group, number);
|
|
925
1526
|
}
|
|
926
1527
|
function weightOf(citations, days, halfLifeDays) {
|
|
927
1528
|
const latest = /* @__PURE__ */ new Map();
|
|
@@ -949,9 +1550,10 @@ function compareNotes(first, second) {
|
|
|
949
1550
|
return second.id - first.id;
|
|
950
1551
|
}
|
|
951
1552
|
function activeNotesOfKind(ctx, kind) {
|
|
952
|
-
return ctx.db.prepare(
|
|
1553
|
+
return ctx.db.prepare(`SELECT ${NOTE_COLUMNS} FROM notes WHERE group_name IS ? AND kind = ? AND dropped_at IS NULL`).all(ctx.group, kind).map((row) => toNote(ctx, row));
|
|
953
1554
|
}
|
|
954
1555
|
function addNote(ctx, group, input) {
|
|
1556
|
+
if (group === null || ctx.group === null) throw new CarnetError("NO_GROUP", "Notes belong to a group: this session has none");
|
|
955
1557
|
if (!isNoteKind(input.kind)) throw new CarnetError("INVALID_NOTE", `Invalid note kind "${input.kind}" (use ${NOTE_KINDS.join(", ")})`);
|
|
956
1558
|
const kind = input.kind;
|
|
957
1559
|
const text = cleanText(input.text, "Note text");
|
|
@@ -962,13 +1564,15 @@ function addNote(ctx, group, input) {
|
|
|
962
1564
|
})).filter((candidate) => candidate.score >= DUPLICATE_SIMILARITY).sort((first, second) => second.score - first.score).slice(0, SIMILAR_SHOWN).map((candidate) => candidate.note);
|
|
963
1565
|
ctx.db.exec("BEGIN");
|
|
964
1566
|
try {
|
|
965
|
-
const
|
|
1567
|
+
const next = ctx.db.prepare("SELECT COALESCE(MAX(number), 0) + 1 AS number FROM notes WHERE group_name = ?").get(ctx.group);
|
|
1568
|
+
const result = ctx.db.prepare(`INSERT INTO notes (group_name, number, kind, text, session, agent, similar_notes, created_at)
|
|
1569
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(ctx.group, next.number, kind, text, input.session ?? null, input.agent ?? null, similar.length ? JSON.stringify(similar.map((note) => note.id)) : null, nowIso(ctx));
|
|
966
1570
|
const id = Number(result.lastInsertRowid);
|
|
967
1571
|
const addRepo = ctx.db.prepare("INSERT INTO note_repos (note, repo) VALUES (?, ?)");
|
|
968
1572
|
for (const repo of repos) addRepo.run(id, repo);
|
|
969
1573
|
ctx.db.exec("COMMIT");
|
|
970
1574
|
return {
|
|
971
|
-
note: requireNote(ctx,
|
|
1575
|
+
note: requireNote(ctx, next.number),
|
|
972
1576
|
similar
|
|
973
1577
|
};
|
|
974
1578
|
} catch (error) {
|
|
@@ -978,8 +1582,8 @@ function addNote(ctx, group, input) {
|
|
|
978
1582
|
}
|
|
979
1583
|
function listNotes(ctx, options = {}) {
|
|
980
1584
|
if (options.kind !== void 0 && !isNoteKind(options.kind)) throw new CarnetError("INVALID_NOTE", `Invalid note kind "${options.kind}"`);
|
|
981
|
-
const conditions = [];
|
|
982
|
-
const parameters = [];
|
|
1585
|
+
const conditions = ["group_name IS ?"];
|
|
1586
|
+
const parameters = [ctx.group];
|
|
983
1587
|
if (!options.includeDropped) conditions.push("dropped_at IS NULL");
|
|
984
1588
|
if (options.kind) {
|
|
985
1589
|
conditions.push("kind = ?");
|
|
@@ -994,8 +1598,7 @@ function listNotes(ctx, options = {}) {
|
|
|
994
1598
|
conditions.push("LOWER(text) LIKE ? ESCAPE '\\'");
|
|
995
1599
|
parameters.push(`%${options.query.toLowerCase().replace(/[\\%_]/g, "\\$&")}%`);
|
|
996
1600
|
}
|
|
997
|
-
const
|
|
998
|
-
const rows = ctx.db.prepare(`SELECT * FROM notes ${where}`).all(...parameters);
|
|
1601
|
+
const rows = ctx.db.prepare(`SELECT ${NOTE_COLUMNS} FROM notes WHERE ${conditions.join(" AND ")}`).all(...parameters);
|
|
999
1602
|
const days = activeDays(ctx);
|
|
1000
1603
|
const halfLifeDays = options.halfLifeDays ?? 20;
|
|
1001
1604
|
return rows.map((row) => weigh(ctx, toNote(ctx, row), days, halfLifeDays)).sort(compareNotes);
|
|
@@ -1021,14 +1624,16 @@ function dropNote(ctx, id, input) {
|
|
|
1021
1624
|
if (input.replacedBy === id) throw new CarnetError("INVALID_NOTE", `Note #${id} cannot replace itself`);
|
|
1022
1625
|
requireActiveNote(ctx, input.replacedBy);
|
|
1023
1626
|
}
|
|
1024
|
-
|
|
1627
|
+
const replacedBy = input.replacedBy === void 0 ? null : noteId(ctx, input.replacedBy);
|
|
1628
|
+
ctx.db.prepare("UPDATE notes SET dropped_at = ?, dropped_reason = ?, dropped_session = ?, replaced_by = ? WHERE id = ?").run(nowIso(ctx), reason, input.session ?? null, replacedBy, noteId(ctx, id));
|
|
1025
1629
|
return requireNote(ctx, id);
|
|
1026
1630
|
}
|
|
1027
1631
|
function citeNote(ctx, id, input) {
|
|
1028
1632
|
requireActiveNote(ctx, id);
|
|
1029
1633
|
const why = cleanText(input.why, "Citation reason");
|
|
1030
|
-
const result = ctx.db.prepare("INSERT INTO note_citations (note, session, agent, why, at) VALUES (?, ?, ?, ?, ?)").run(id, input.session ?? null, input.agent ?? null, why, nowIso(ctx));
|
|
1031
|
-
return ctx.db.prepare(
|
|
1634
|
+
const result = ctx.db.prepare("INSERT INTO note_citations (note, session, agent, why, at) VALUES (?, ?, ?, ?, ?)").run(noteId(ctx, id), input.session ?? null, input.agent ?? null, why, nowIso(ctx));
|
|
1635
|
+
return ctx.db.prepare(`SELECT ${CITATION_COLUMNS} FROM note_citations JOIN notes ON notes.id = note_citations.note
|
|
1636
|
+
WHERE note_citations.id = ?`).get(Number(result.lastInsertRowid));
|
|
1032
1637
|
}
|
|
1033
1638
|
const ACTIVITY_ORDER = {
|
|
1034
1639
|
dropped: 0,
|
|
@@ -1037,19 +1642,20 @@ const ACTIVITY_ORDER = {
|
|
|
1037
1642
|
};
|
|
1038
1643
|
function activeIds(ctx, json) {
|
|
1039
1644
|
if (!json) return [];
|
|
1040
|
-
const active = ctx.db.prepare("SELECT 1 FROM notes WHERE
|
|
1041
|
-
return JSON.parse(json).filter((
|
|
1645
|
+
const active = ctx.db.prepare("SELECT 1 FROM notes WHERE group_name IS ? AND number = ? AND dropped_at IS NULL");
|
|
1646
|
+
return JSON.parse(json).filter((number) => active.get(ctx.group, number) !== void 0);
|
|
1042
1647
|
}
|
|
1043
1648
|
function sessionNoteActivity(ctx, session) {
|
|
1044
|
-
const added = ctx.db.prepare(
|
|
1045
|
-
|
|
1649
|
+
const added = ctx.db.prepare(`SELECT number, kind, text, similar_notes, created_at FROM notes
|
|
1650
|
+
WHERE group_name IS ? AND session = ?`).all(ctx.group, session);
|
|
1651
|
+
const cited = ctx.db.prepare(`SELECT notes.number AS note, notes.kind, note_citations.why, note_citations.at
|
|
1046
1652
|
FROM note_citations JOIN notes ON notes.id = note_citations.note
|
|
1047
|
-
WHERE note_citations.session = ?`).all(session);
|
|
1048
|
-
const dropped = ctx.db.prepare(
|
|
1653
|
+
WHERE notes.group_name IS ? AND note_citations.session = ?`).all(ctx.group, session);
|
|
1654
|
+
const dropped = ctx.db.prepare(`SELECT ${NOTE_COLUMNS} FROM notes WHERE group_name IS ? AND dropped_session = ?`).all(ctx.group, session);
|
|
1049
1655
|
return [
|
|
1050
1656
|
...added.map((row) => ({
|
|
1051
1657
|
activity: "added",
|
|
1052
|
-
note: row.
|
|
1658
|
+
note: row.number,
|
|
1053
1659
|
kind: row.kind,
|
|
1054
1660
|
text: row.text,
|
|
1055
1661
|
similarNotes: activeIds(ctx, row.similar_notes),
|
|
@@ -1067,11 +1673,11 @@ function sessionNoteActivity(ctx, session) {
|
|
|
1067
1673
|
})),
|
|
1068
1674
|
...dropped.map((row) => ({
|
|
1069
1675
|
activity: "dropped",
|
|
1070
|
-
note: row.
|
|
1676
|
+
note: row.number,
|
|
1071
1677
|
kind: row.kind,
|
|
1072
1678
|
text: row.dropped_reason ?? "",
|
|
1073
1679
|
similarNotes: [],
|
|
1074
|
-
replacedBy: row.
|
|
1680
|
+
replacedBy: row.replaced_number,
|
|
1075
1681
|
at: row.dropped_at ?? ""
|
|
1076
1682
|
}))
|
|
1077
1683
|
].sort((first, second) => second.at.localeCompare(first.at) || ACTIVITY_ORDER[first.activity] - ACTIVITY_ORDER[second.activity] || second.note - first.note);
|
|
@@ -1140,7 +1746,7 @@ function notesFor(ctx, repos, general, halfLifeDays) {
|
|
|
1140
1746
|
return [...byId.values()].sort(compareNotes);
|
|
1141
1747
|
}
|
|
1142
1748
|
function groupTitle(group) {
|
|
1143
|
-
return `Rucher memory of the ${group.name} group
|
|
1749
|
+
return group ? `Rucher memory of the ${group.name} group` : "Rucher memory";
|
|
1144
1750
|
}
|
|
1145
1751
|
function sessionStartMemory(ctx, group, session, options = {}) {
|
|
1146
1752
|
const halfLifeDays = options.halfLifeDays ?? 20;
|
|
@@ -1179,229 +1785,6 @@ function repoMemory(ctx, session, repo, options = {}) {
|
|
|
1179
1785
|
function copyInjectedRepos(ctx, from, into) {
|
|
1180
1786
|
for (const repo of injectedRepos(ctx, from)) recordRepo(ctx, into, repo);
|
|
1181
1787
|
}
|
|
1182
|
-
// src/sessions.ts
|
|
1183
|
-
const COLUMNS = `id, name, purpose, kind, status, cwd, repo, host, host_pid, hooked_at, last_title,
|
|
1184
|
-
parent_id, prompt_version, created_at, last_active_at, ended_at`;
|
|
1185
|
-
function toSession(row) {
|
|
1186
|
-
return {
|
|
1187
|
-
id: row.id,
|
|
1188
|
-
name: row.name,
|
|
1189
|
-
purpose: row.purpose,
|
|
1190
|
-
kind: row.kind,
|
|
1191
|
-
status: row.status,
|
|
1192
|
-
cwd: row.cwd,
|
|
1193
|
-
repo: row.repo,
|
|
1194
|
-
host: row.host,
|
|
1195
|
-
hostPid: row.host_pid,
|
|
1196
|
-
hookedAt: row.hooked_at,
|
|
1197
|
-
lastTitle: row.last_title,
|
|
1198
|
-
parentId: row.parent_id,
|
|
1199
|
-
promptVersion: row.prompt_version,
|
|
1200
|
-
createdAt: row.created_at,
|
|
1201
|
-
lastActiveAt: row.last_active_at,
|
|
1202
|
-
endedAt: row.ended_at
|
|
1203
|
-
};
|
|
1204
|
-
}
|
|
1205
|
-
function getSession(ctx, id) {
|
|
1206
|
-
const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE id = ?`).get(id);
|
|
1207
|
-
return row && toSession(row);
|
|
1208
|
-
}
|
|
1209
|
-
function requireSession(ctx, id) {
|
|
1210
|
-
const session = getSession(ctx, id);
|
|
1211
|
-
if (!session) throw new CarnetError("SESSION_NOT_FOUND", `Unknown session ${id}`);
|
|
1212
|
-
return session;
|
|
1213
|
-
}
|
|
1214
|
-
function ensureSession(ctx, id, cwd, group) {
|
|
1215
|
-
const existing = getSession(ctx, id);
|
|
1216
|
-
if (existing) return existing;
|
|
1217
|
-
const at = nowIso(ctx);
|
|
1218
|
-
ctx.db.prepare("INSERT INTO sessions (id, cwd, repo, created_at, last_active_at) VALUES (?, ?, ?, ?, ?)").run(id, cwd ?? null, group ? repoNameFor(group, cwd) : null, at, at);
|
|
1219
|
-
return requireSession(ctx, id);
|
|
1220
|
-
}
|
|
1221
|
-
function nameTaken(error, name) {
|
|
1222
|
-
if (name && error instanceof Error && error.message.includes("UNIQUE")) throw new CarnetError("SESSION_NAME_TAKEN", `A session named "${name}" already exists`);
|
|
1223
|
-
throw error;
|
|
1224
|
-
}
|
|
1225
|
-
function createSession(ctx, input) {
|
|
1226
|
-
if (input.kind === "active" && !input.name) throw new CarnetError("SESSION_NAME_REQUIRED", "An active session needs a name");
|
|
1227
|
-
const at = nowIso(ctx);
|
|
1228
|
-
try {
|
|
1229
|
-
ctx.db.prepare(`INSERT INTO sessions (id, name, kind, status, cwd, repo, host, last_title,
|
|
1230
|
-
created_at, last_active_at)
|
|
1231
|
-
VALUES (?, ?, ?, 'running', ?, ?, ?, ?, ?, ?)`).run(input.id, input.name ?? null, input.kind, input.cwd, input.repo ?? null, input.host ?? "claude-code", input.name ?? null, at, at);
|
|
1232
|
-
} catch (error) {
|
|
1233
|
-
nameTaken(error, input.name);
|
|
1234
|
-
}
|
|
1235
|
-
return requireSession(ctx, input.id);
|
|
1236
|
-
}
|
|
1237
|
-
function setSessionKind(ctx, id, kind, name) {
|
|
1238
|
-
const session = requireSession(ctx, id);
|
|
1239
|
-
const nextName = name ?? session.name;
|
|
1240
|
-
if (kind === "active" && !nextName) throw new CarnetError("SESSION_NAME_REQUIRED", "An active session needs a name");
|
|
1241
|
-
try {
|
|
1242
|
-
ctx.db.prepare("UPDATE sessions SET kind = ?, name = ?, last_title = ? WHERE id = ?").run(kind, nextName, nextName ?? session.lastTitle, id);
|
|
1243
|
-
} catch (error) {
|
|
1244
|
-
nameTaken(error, nextName);
|
|
1245
|
-
}
|
|
1246
|
-
return requireSession(ctx, id);
|
|
1247
|
-
}
|
|
1248
|
-
function endSession(ctx, id) {
|
|
1249
|
-
const session = requireSession(ctx, id);
|
|
1250
|
-
if (session.status !== "running") return session;
|
|
1251
|
-
const ended = setSessionStatus(ctx, id, "idle");
|
|
1252
|
-
logEvent(ctx, id, { type: "session.ended" });
|
|
1253
|
-
return ended;
|
|
1254
|
-
}
|
|
1255
|
-
function titleAvailable(ctx, id, title) {
|
|
1256
|
-
const owner = sessionByName(ctx, title);
|
|
1257
|
-
return !owner || owner.id === id;
|
|
1258
|
-
}
|
|
1259
|
-
function adoptTitle(ctx, id, rawTitle) {
|
|
1260
|
-
const session = requireSession(ctx, id);
|
|
1261
|
-
const title = rawTitle?.trim() || null;
|
|
1262
|
-
if (title === null || title === session.lastTitle) return session;
|
|
1263
|
-
ctx.db.prepare("UPDATE sessions SET last_title = ? WHERE id = ?").run(title, id);
|
|
1264
|
-
if (title === session.name || !titleAvailable(ctx, id, title)) return requireSession(ctx, id);
|
|
1265
|
-
ctx.db.prepare(`UPDATE sessions
|
|
1266
|
-
SET name = ?, kind = CASE WHEN name IS NULL THEN 'active' ELSE kind END
|
|
1267
|
-
WHERE id = ?`).run(title, id);
|
|
1268
|
-
return requireSession(ctx, id);
|
|
1269
|
-
}
|
|
1270
|
-
function upsertFromHook(ctx, group, payload, env = {}) {
|
|
1271
|
-
const at = nowIso(ctx);
|
|
1272
|
-
const host = env.host ?? "claude-code";
|
|
1273
|
-
const hostPid = env.processId ?? null;
|
|
1274
|
-
const repo = repoNameFor(group, payload.cwd);
|
|
1275
|
-
const existing = getSession(ctx, payload.session_id);
|
|
1276
|
-
if (!existing) ctx.db.prepare(`INSERT INTO sessions (id, cwd, repo, host, host_pid, hooked_at, created_at, last_active_at)
|
|
1277
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(payload.session_id, payload.cwd ?? null, repo, host, hostPid, at, at, at);
|
|
1278
|
-
else ctx.db.prepare(`UPDATE sessions
|
|
1279
|
-
SET last_active_at = ?, hooked_at = ?, cwd = ?, repo = ?, host = ?, host_pid = ?
|
|
1280
|
-
WHERE id = ?`).run(at, at, payload.cwd ?? existing.cwd, repo ?? existing.repo, host, hostPid ?? existing.hostPid, payload.session_id);
|
|
1281
|
-
return adoptTitle(ctx, payload.session_id, payload.session_title);
|
|
1282
|
-
}
|
|
1283
|
-
function touchSession(ctx, id) {
|
|
1284
|
-
ctx.db.prepare("UPDATE sessions SET last_active_at = ? WHERE id = ?").run(nowIso(ctx), id);
|
|
1285
|
-
}
|
|
1286
|
-
function nameSession(ctx, id, name, purpose) {
|
|
1287
|
-
requireSession(ctx, id);
|
|
1288
|
-
try {
|
|
1289
|
-
ctx.db.prepare(`UPDATE sessions
|
|
1290
|
-
SET name = ?, purpose = COALESCE(?, purpose), last_active_at = ?,
|
|
1291
|
-
kind = 'active'
|
|
1292
|
-
WHERE id = ?`).run(name, purpose ?? null, nowIso(ctx), id);
|
|
1293
|
-
} catch (error) {
|
|
1294
|
-
if (error instanceof Error && error.message.includes("UNIQUE")) throw new CarnetError("SESSION_NAME_TAKEN", `A session named "${name}" already exists`);
|
|
1295
|
-
throw error;
|
|
1296
|
-
}
|
|
1297
|
-
return requireSession(ctx, id);
|
|
1298
|
-
}
|
|
1299
|
-
function listSessions(ctx, options = {}) {
|
|
1300
|
-
const conditions = [];
|
|
1301
|
-
if (!options.includeTemp) conditions.push("kind != 'temp'");
|
|
1302
|
-
if (!options.includeArchived) conditions.push("status != 'archived'");
|
|
1303
|
-
const where = conditions.length ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
1304
|
-
return ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions ${where} ORDER BY last_active_at DESC`).all().map(toSession);
|
|
1305
|
-
}
|
|
1306
|
-
function dropSession(ctx, id) {
|
|
1307
|
-
requireSession(ctx, id);
|
|
1308
|
-
const at = nowIso(ctx);
|
|
1309
|
-
ctx.db.prepare("UPDATE agents SET status = 'closed', updated_at = ? WHERE session = ? AND status != 'closed'").run(at, id);
|
|
1310
|
-
ctx.db.prepare("UPDATE sessions SET status = 'archived', last_active_at = ? WHERE id = ?").run(at, id);
|
|
1311
|
-
return requireSession(ctx, id);
|
|
1312
|
-
}
|
|
1313
|
-
function defaultSession(ctx) {
|
|
1314
|
-
const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE status != 'archived' ORDER BY last_active_at DESC LIMIT 1`).get();
|
|
1315
|
-
return row && toSession(row);
|
|
1316
|
-
}
|
|
1317
|
-
function sessionByName(ctx, name) {
|
|
1318
|
-
const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE name = ?`).get(name);
|
|
1319
|
-
return row && toSession(row);
|
|
1320
|
-
}
|
|
1321
|
-
const MINIMUM_ID_PREFIX = 4;
|
|
1322
|
-
function shortId(id) {
|
|
1323
|
-
return id.slice(0, 8);
|
|
1324
|
-
}
|
|
1325
|
-
function findSession(ctx, reference) {
|
|
1326
|
-
const byName = sessionByName(ctx, reference);
|
|
1327
|
-
if (byName) return byName;
|
|
1328
|
-
const byId = getSession(ctx, reference);
|
|
1329
|
-
if (byId) return byId;
|
|
1330
|
-
const isIdPrefix = /^[0-9a-f-]+$/i.test(reference);
|
|
1331
|
-
if (isIdPrefix && reference.length >= 4) {
|
|
1332
|
-
const rows = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE id LIKE ? ORDER BY last_active_at DESC`).all(`${reference.toLowerCase()}%`);
|
|
1333
|
-
const [only, ...others] = rows;
|
|
1334
|
-
if (only && others.length === 0) return toSession(only);
|
|
1335
|
-
if (only) throw new CarnetError("SESSION_AMBIGUOUS", `Session id "${reference}" matches several sessions: ${rows.map((row) => shortId(row.id)).join(", ")}`);
|
|
1336
|
-
}
|
|
1337
|
-
throw new CarnetError("SESSION_NOT_FOUND", `Unknown session "${reference}"${isIdPrefix && reference.length < 4 ? ` (an id prefix needs at least 4 characters)` : ""}`);
|
|
1338
|
-
}
|
|
1339
|
-
function sessionByHostProcess(ctx, host, processId) {
|
|
1340
|
-
const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions
|
|
1341
|
-
WHERE host = ? AND host_pid = ? AND hooked_at IS NOT NULL
|
|
1342
|
-
ORDER BY hooked_at DESC LIMIT 1`).get(host, processId);
|
|
1343
|
-
return row && toSession(row);
|
|
1344
|
-
}
|
|
1345
|
-
function recordPromptVersion(ctx, id, version) {
|
|
1346
|
-
requireSession(ctx, id);
|
|
1347
|
-
ctx.db.prepare("UPDATE sessions SET prompt_version = ? WHERE id = ?").run(version, id);
|
|
1348
|
-
return requireSession(ctx, id);
|
|
1349
|
-
}
|
|
1350
|
-
function setParent(ctx, id, parentId) {
|
|
1351
|
-
requireSession(ctx, id);
|
|
1352
|
-
requireSession(ctx, parentId);
|
|
1353
|
-
ctx.db.prepare("UPDATE sessions SET parent_id = ? WHERE id = ?").run(parentId, id);
|
|
1354
|
-
return requireSession(ctx, id);
|
|
1355
|
-
}
|
|
1356
|
-
function setSessionStatus(ctx, id, status) {
|
|
1357
|
-
requireSession(ctx, id);
|
|
1358
|
-
const at = nowIso(ctx);
|
|
1359
|
-
ctx.db.prepare(`UPDATE sessions
|
|
1360
|
-
SET status = ?, last_active_at = ?,
|
|
1361
|
-
ended_at = CASE WHEN ? = 'running' THEN NULL WHEN ? = 'idle' THEN ? ELSE ended_at END
|
|
1362
|
-
WHERE id = ?`).run(status, at, status, status, at, id);
|
|
1363
|
-
return requireSession(ctx, id);
|
|
1364
|
-
}
|
|
1365
|
-
function refuseWhileRunning(session, action) {
|
|
1366
|
-
if (session.status === "running") throw new CarnetError("SESSION_RUNNING", `Session ${session.name ?? shortId(session.id)} is running: ${action} it once it has ended`);
|
|
1367
|
-
}
|
|
1368
|
-
function renameSession(ctx, id, name) {
|
|
1369
|
-
refuseWhileRunning(requireSession(ctx, id), "rename");
|
|
1370
|
-
try {
|
|
1371
|
-
ctx.db.prepare("UPDATE sessions SET name = ? WHERE id = ?").run(name, id);
|
|
1372
|
-
} catch (error) {
|
|
1373
|
-
nameTaken(error, name);
|
|
1374
|
-
}
|
|
1375
|
-
return requireSession(ctx, id);
|
|
1376
|
-
}
|
|
1377
|
-
function promoteSession(ctx, id, name) {
|
|
1378
|
-
const session = requireSession(ctx, id);
|
|
1379
|
-
if (session.kind === "active") throw new CarnetError("SESSION_KIND_INVALID", `Session ${session.name} is already active`);
|
|
1380
|
-
const nextName = name ?? session.name;
|
|
1381
|
-
if (!nextName) throw new CarnetError("SESSION_NAME_REQUIRED", "An active session needs a name");
|
|
1382
|
-
if (nextName !== session.name) refuseWhileRunning(session, "rename");
|
|
1383
|
-
try {
|
|
1384
|
-
ctx.db.prepare("UPDATE sessions SET kind = 'active', name = ? WHERE id = ?").run(nextName, id);
|
|
1385
|
-
} catch (error) {
|
|
1386
|
-
nameTaken(error, nextName);
|
|
1387
|
-
}
|
|
1388
|
-
return requireSession(ctx, id);
|
|
1389
|
-
}
|
|
1390
|
-
function demoteSession(ctx, id) {
|
|
1391
|
-
const session = requireSession(ctx, id);
|
|
1392
|
-
if (session.kind === "temp") throw new CarnetError("SESSION_KIND_INVALID", `Session ${session.name ?? shortId(session.id)} is already temp`);
|
|
1393
|
-
ctx.db.prepare("UPDATE sessions SET kind = 'temp' WHERE id = ?").run(id);
|
|
1394
|
-
return requireSession(ctx, id);
|
|
1395
|
-
}
|
|
1396
|
-
function staleTempSessions(ctx, olderThanMilliseconds) {
|
|
1397
|
-
const before = new Date(ctx.now().getTime() - olderThanMilliseconds).toISOString();
|
|
1398
|
-
return ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions
|
|
1399
|
-
WHERE kind = 'temp' AND status = 'idle' AND last_active_at < ?
|
|
1400
|
-
ORDER BY last_active_at ASC`).all(before).map(toSession);
|
|
1401
|
-
}
|
|
1402
|
-
function resetDeadSessions(ctx, isAlive) {
|
|
1403
|
-
return ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE status = 'running'`).all().map(toSession).filter((session) => session.hostPid === null || !isAlive(session.hostPid)).map((session) => endSession(ctx, session.id));
|
|
1404
|
-
}
|
|
1405
1788
|
// src/merge.ts
|
|
1406
1789
|
function namesOf(ctx, session) {
|
|
1407
1790
|
return ctx.db.prepare("SELECT name FROM agents WHERE session = ?").all(session).map((row) => row.name);
|
|
@@ -1450,7 +1833,7 @@ function purgeDays(value) {
|
|
|
1450
1833
|
return Number.isFinite(days) && days > 0 ? days : 3;
|
|
1451
1834
|
}
|
|
1452
1835
|
const PURGEABLE = `
|
|
1453
|
-
id != ? AND last_active_at < ?
|
|
1836
|
+
group_name IS ? AND id != ? AND last_active_at < ?
|
|
1454
1837
|
AND NOT EXISTS (
|
|
1455
1838
|
SELECT 1 FROM events WHERE events.session = sessions.id AND events.type NOT LIKE 'session.%'
|
|
1456
1839
|
)
|
|
@@ -1462,7 +1845,7 @@ function purgeSessions(ctx, keepId, days) {
|
|
|
1462
1845
|
const cutoff = (/* @__PURE__ */ new Date(ctx.now().getTime() - days * DAY_MILLISECONDS)).toISOString();
|
|
1463
1846
|
ctx.db.exec("BEGIN");
|
|
1464
1847
|
try {
|
|
1465
|
-
const ids = ctx.db.prepare(`SELECT id FROM sessions WHERE ${PURGEABLE}`).all(keepId, cutoff).map((row) => row.id);
|
|
1848
|
+
const ids = ctx.db.prepare(`SELECT id FROM sessions WHERE ${PURGEABLE}`).all(ctx.group, keepId, cutoff).map((row) => row.id);
|
|
1466
1849
|
for (const table of [
|
|
1467
1850
|
"table_items",
|
|
1468
1851
|
"agents",
|
|
@@ -1669,19 +2052,23 @@ var Carnet = class {
|
|
|
1669
2052
|
group;
|
|
1670
2053
|
db;
|
|
1671
2054
|
ctx;
|
|
1672
|
-
constructor(
|
|
2055
|
+
constructor(db, group, options = {}) {
|
|
1673
2056
|
this.group = group;
|
|
1674
2057
|
this.db = db;
|
|
1675
2058
|
this.ctx = {
|
|
1676
2059
|
db,
|
|
1677
|
-
now: options.now ?? (() => /* @__PURE__ */ new Date())
|
|
2060
|
+
now: options.now ?? (() => /* @__PURE__ */ new Date()),
|
|
2061
|
+
group: group?.name ?? null
|
|
1678
2062
|
};
|
|
1679
2063
|
}
|
|
2064
|
+
requireGroup() {
|
|
2065
|
+
return requireGroup(this.group);
|
|
2066
|
+
}
|
|
1680
2067
|
sessions = {
|
|
1681
2068
|
get: (id) => getSession(this.ctx, id),
|
|
1682
2069
|
find: (reference) => findSession(this.ctx, reference),
|
|
1683
2070
|
require: (id) => requireSession(this.ctx, id),
|
|
1684
|
-
ensure: (id, cwd) => ensureSession(this.ctx, id, cwd, this.group),
|
|
2071
|
+
ensure: (id, cwd) => ensureSession(this.ctx, id, cwd, this.group ?? void 0),
|
|
1685
2072
|
upsertFromHook: (payload, env) => upsertFromHook(this.ctx, this.group, payload, env),
|
|
1686
2073
|
touch: (id) => touchSession(this.ctx, id),
|
|
1687
2074
|
merge: (fromId, intoId) => mergeSessions(this.ctx, fromId, intoId),
|
|
@@ -1755,11 +2142,32 @@ var Carnet = class {
|
|
|
1755
2142
|
this.db.close();
|
|
1756
2143
|
}
|
|
1757
2144
|
};
|
|
2145
|
+
function openStore(options) {
|
|
2146
|
+
const path = options.dbPath ?? databasePath(options.env);
|
|
2147
|
+
if (path !== ":memory:") mkdirSync(dirname(path), { recursive: true });
|
|
2148
|
+
return openDatabase(path);
|
|
2149
|
+
}
|
|
1758
2150
|
function openCarnet(options = {}) {
|
|
1759
|
-
return
|
|
2151
|
+
return openResolvedCarnet(options).carnet;
|
|
2152
|
+
}
|
|
2153
|
+
function openResolvedCarnet(options = {}) {
|
|
2154
|
+
const db = openStore(options);
|
|
2155
|
+
try {
|
|
2156
|
+
const resolution = resolveGroup({
|
|
2157
|
+
...options,
|
|
2158
|
+
db
|
|
2159
|
+
});
|
|
2160
|
+
return {
|
|
2161
|
+
carnet: new Carnet(db, resolution.group, options),
|
|
2162
|
+
resolution
|
|
2163
|
+
};
|
|
2164
|
+
} catch (error) {
|
|
2165
|
+
db.close();
|
|
2166
|
+
throw error;
|
|
2167
|
+
}
|
|
1760
2168
|
}
|
|
1761
2169
|
function openGroupCarnet(group, options = {}) {
|
|
1762
|
-
return new Carnet(
|
|
2170
|
+
return new Carnet(openStore(options), group, options);
|
|
1763
2171
|
}
|
|
1764
2172
|
// src/resume.ts
|
|
1765
2173
|
const RESUME_EVENTS = 20;
|
|
@@ -1851,6 +2259,6 @@ function stepAgent(carnet, session, input) {
|
|
|
1851
2259
|
}
|
|
1852
2260
|
}
|
|
1853
2261
|
}
|
|
1854
|
-
export {
|
|
2262
|
+
export { renameGroupRows as $, openDatabase as $t, memoryMaxCharacters as A, INSTRUCTIONS_FILE as At, memoryHalfLife as B, removeGroupRepo as Bt, renderNotesSummary as C, rulesText as Ct, DEFAULT_PURGE_DAYS as D, shortId as Dt, renderTableLine as E, MINIMUM_ID_PREFIX as Et, NOTE_TEXT_LIMIT as F, groupExists as Ft, isInside as G, defaultWorkspace as Gt, similarity as H, sourceInstructions as Ht, STALE_AFTER_ACTIVE_DAYS as I, groupHosts as It, requireGroup as J, promptsDirectory as Jt, repoNameFor as K, groupSource as Kt, groupRepoNames as L, isGroupName as Lt, DEFAULT_HALF_LIFE_DAYS as M, createGroup as Mt, DUPLICATE_SIMILARITY as N, dropGroup as Nt, purgeDays as O, AGENTS_FILE as Ot, NOTE_KINDS as P, expandHome as Pt, groupSessionCounts as Q, MEMORY_DB as Qt, isNoteKind as R, listGroups as Rt, renderNotes as S, outsideRucherContext as St, renderStatus as T, CORE_RULES as Tt, ambiguousGroupContext as U, corePromptPath as Ut, sessionNoteActivity as V, renameGroup as Vt, groupLabel as W, databasePath as Wt, archiveGroupSessions as X, reportsDirectory as Xt, resolveGroup as Y, reportPath as Yt, deleteGroupNotes as Z, rucherPaths as Zt, NOTES_FOLD_LINES as _, isEventType as _n, appendPromptFile as _t, formatEventLine as a, NOTE_MAX as an, groupSettings as at, renderAgentLine as b, compactReminder as bt, Carnet as c, EMOJI as cn, MARKDOWN_MARKER as ct, openResolvedCarnet as d, OPEN_AGENT_STATUSES as dn, removeStaleCopies as dt, migrate as en, sessionGroupName as et, PAIRING_WINDOW_MILLISECONDS as f, USER_ACTION_STATUSES as fn, writeGenerated as ft, MAIN_WORKING_SUFFIX as g, SESSION_EVENT_TYPES as gn, SUBAGENT_RULES as gt, formatClock as h, EVENT_TYPES as hn, RULES_UPDATED_NOTICE as ht, RESUME_MAX_CHARACTERS as i, REPORTING_NOTE as in, claudeCode as it, renderMemory as j, addGroupRepo as jt, MEMORY_MAX_CHARACTERS as k, GROUP_FILE as kt, openCarnet as l, LEGEND as ln, markdownCopy as lt, buildStatusView as m, isUserActionStatus as mn, PROMPT_FILE as mt, stepAgent as n, schemaVersion as nn, allHosts as nt, resumeContext as o, sanitizeNote as on, transcriptTitle as ot, STOPPED_NOTE as p, isAgentStatus as pn, OUTSIDE_RUCHER_NOTICE as pt, repoPathFor as q, groupsDirectory as qt, RESUME_EVENTS as r, PUBLISH_FALLBACK_MILLISECONDS as rn, hostById as rt, sessionLabel as s, AGENT_STATUSES as sn, GENERATED_MARKER as st, AGENT_STEPS as t, migrations as tn, DEFAULT_HOST as tt, openGroupCarnet as u, MAIN_WORKING_EMOJI as un, mergeSettings as ut, NOTES_HEADER as v, CarnetError as vn, assemblePrompt as vt, renderSections as w, rulesVersion as wt, renderNoteLine as x, groupRules as xt, SIMILAR_PREFIX as y, baseRules as yt, localDay as z, loadGroup as zt };
|
|
1855
2263
|
|
|
1856
|
-
//# sourceMappingURL=steps-
|
|
2264
|
+
//# sourceMappingURL=steps-BeTGxQk4.mjs.map
|