@rucher/carnet 0.2.0-beta.1 → 0.2.0-beta.3
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--axAq8FF.d.mts → carnet-Du3xigg-.d.mts} +80 -36
- package/dist/carnet-Du3xigg-.d.mts.map +1 -0
- package/dist/index.d.mts +59 -35
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +46 -190
- package/dist/index.mjs.map +1 -1
- package/dist/mcp.d.mts +2 -3
- package/dist/mcp.d.mts.map +1 -1
- package/dist/mcp.mjs +82 -132
- package/dist/mcp.mjs.map +1 -1
- package/dist/{resume-D2FFakCl.mjs → steps-U_Ge5YFh.mjs} +871 -429
- package/dist/steps-U_Ge5YFh.mjs.map +1 -0
- package/package.json +1 -1
- package/dist/carnet--axAq8FF.d.mts.map +0 -1
- package/dist/resume-D2FFakCl.mjs.map +0 -1
|
@@ -1,7 +1,8 @@
|
|
|
1
|
+
import { closeSync, existsSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, 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();
|
|
@@ -54,7 +55,7 @@ function logEvent(ctx, session, input) {
|
|
|
54
55
|
}
|
|
55
56
|
function readEvents(ctx, { session, limit = 20, agentOnly = false }) {
|
|
56
57
|
const filter = agentOnly ? "AND type NOT LIKE 'session.%'" : "";
|
|
57
|
-
return ctx.db.prepare(`SELECT * FROM (SELECT * FROM events WHERE session = ? ${filter} ORDER BY id DESC LIMIT ?) ORDER BY id
|
|
58
|
+
return ctx.db.prepare(`SELECT * FROM (SELECT * FROM events WHERE session = ? ${filter} ORDER BY at DESC, id DESC LIMIT ?) ORDER BY at, id`).all(session, limit).map(toEvent);
|
|
58
59
|
}
|
|
59
60
|
// src/status/model.ts
|
|
60
61
|
const AGENT_STATUSES = [
|
|
@@ -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,396 @@ 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/sessions.ts
|
|
529
|
+
const COLUMNS = `id, group_name, name, purpose, kind, status, cwd, repo, host, host_pid, hooked_at, last_title,
|
|
530
|
+
parent_id, prompt_version, created_at, last_active_at, ended_at`;
|
|
531
|
+
function toSession(row) {
|
|
532
|
+
return {
|
|
533
|
+
id: row.id,
|
|
534
|
+
groupName: row.group_name,
|
|
535
|
+
name: row.name,
|
|
536
|
+
purpose: row.purpose,
|
|
537
|
+
kind: row.kind,
|
|
538
|
+
status: row.status,
|
|
539
|
+
cwd: row.cwd,
|
|
540
|
+
repo: row.repo,
|
|
541
|
+
host: row.host,
|
|
542
|
+
hostPid: row.host_pid,
|
|
543
|
+
hookedAt: row.hooked_at,
|
|
544
|
+
lastTitle: row.last_title,
|
|
545
|
+
parentId: row.parent_id,
|
|
546
|
+
promptVersion: row.prompt_version,
|
|
547
|
+
createdAt: row.created_at,
|
|
548
|
+
lastActiveAt: row.last_active_at,
|
|
549
|
+
endedAt: row.ended_at
|
|
550
|
+
};
|
|
551
|
+
}
|
|
552
|
+
function getSession(ctx, id) {
|
|
553
|
+
const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE id = ?`).get(id);
|
|
554
|
+
return row && toSession(row);
|
|
555
|
+
}
|
|
556
|
+
function requireSession(ctx, id) {
|
|
557
|
+
const session = getSession(ctx, id);
|
|
558
|
+
if (!session) throw new CarnetError("SESSION_NOT_FOUND", `Unknown session ${id}`);
|
|
559
|
+
return session;
|
|
560
|
+
}
|
|
561
|
+
function ensureSession(ctx, id, cwd, group) {
|
|
562
|
+
const existing = getSession(ctx, id);
|
|
563
|
+
if (existing) return existing;
|
|
564
|
+
const at = nowIso(ctx);
|
|
565
|
+
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);
|
|
566
|
+
return requireSession(ctx, id);
|
|
567
|
+
}
|
|
568
|
+
function nameTaken(error, name) {
|
|
569
|
+
if (name && error instanceof Error && error.message.includes("UNIQUE")) throw new CarnetError("SESSION_NAME_TAKEN", `A session named "${name}" already exists`);
|
|
570
|
+
throw error;
|
|
571
|
+
}
|
|
572
|
+
function createSession(ctx, input) {
|
|
573
|
+
if (input.kind === "active" && !input.name) throw new CarnetError("SESSION_NAME_REQUIRED", "An active session needs a name");
|
|
574
|
+
const at = nowIso(ctx);
|
|
575
|
+
try {
|
|
576
|
+
ctx.db.prepare(`INSERT INTO sessions (id, group_name, name, kind, status, cwd, repo, host, last_title,
|
|
577
|
+
created_at, last_active_at)
|
|
578
|
+
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);
|
|
579
|
+
} catch (error) {
|
|
580
|
+
nameTaken(error, input.name);
|
|
581
|
+
}
|
|
582
|
+
return requireSession(ctx, input.id);
|
|
583
|
+
}
|
|
584
|
+
function setSessionKind(ctx, id, kind, name) {
|
|
585
|
+
const session = requireSession(ctx, id);
|
|
586
|
+
const nextName = name ?? session.name;
|
|
587
|
+
if (kind === "active" && !nextName) throw new CarnetError("SESSION_NAME_REQUIRED", "An active session needs a name");
|
|
588
|
+
try {
|
|
589
|
+
ctx.db.prepare("UPDATE sessions SET kind = ?, name = ?, last_title = ? WHERE id = ?").run(kind, nextName, nextName ?? session.lastTitle, id);
|
|
590
|
+
} catch (error) {
|
|
591
|
+
nameTaken(error, nextName);
|
|
592
|
+
}
|
|
593
|
+
return requireSession(ctx, id);
|
|
594
|
+
}
|
|
595
|
+
function endSession(ctx, id) {
|
|
596
|
+
const session = requireSession(ctx, id);
|
|
597
|
+
if (session.status !== "running") return session;
|
|
598
|
+
const ended = setSessionStatus(ctx, id, "idle");
|
|
599
|
+
logEvent(ctx, id, { type: "session.ended" });
|
|
600
|
+
return ended;
|
|
601
|
+
}
|
|
602
|
+
function titleAvailable(ctx, id, title) {
|
|
603
|
+
const owner = sessionByName(ctx, title);
|
|
604
|
+
return !owner || owner.id === id;
|
|
605
|
+
}
|
|
606
|
+
function adoptTitle(ctx, id, rawTitle) {
|
|
607
|
+
const session = requireSession(ctx, id);
|
|
608
|
+
const title = rawTitle?.trim() || null;
|
|
609
|
+
if (title === null || title === session.lastTitle) return session;
|
|
610
|
+
ctx.db.prepare("UPDATE sessions SET last_title = ? WHERE id = ?").run(title, id);
|
|
611
|
+
if (title === session.name || !titleAvailable(ctx, id, title)) return requireSession(ctx, id);
|
|
612
|
+
ctx.db.prepare(`UPDATE sessions
|
|
613
|
+
SET name = ?, kind = CASE WHEN name IS NULL THEN 'active' ELSE kind END
|
|
614
|
+
WHERE id = ?`).run(title, id);
|
|
615
|
+
return requireSession(ctx, id);
|
|
616
|
+
}
|
|
617
|
+
function upsertFromHook(ctx, group, payload, env = {}) {
|
|
618
|
+
const at = nowIso(ctx);
|
|
619
|
+
const host = env.host ?? "claude-code";
|
|
620
|
+
const hostPid = env.processId ?? null;
|
|
621
|
+
const repo = group ? repoNameFor(group, payload.cwd) : null;
|
|
622
|
+
const existing = getSession(ctx, payload.session_id);
|
|
623
|
+
if (!existing) ctx.db.prepare(`INSERT INTO sessions (id, group_name, cwd, repo, host, host_pid, hooked_at, created_at,
|
|
624
|
+
last_active_at)
|
|
625
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(payload.session_id, ctx.group, payload.cwd ?? null, repo, host, hostPid, at, at, at);
|
|
626
|
+
else ctx.db.prepare(`UPDATE sessions
|
|
627
|
+
SET last_active_at = ?, hooked_at = ?, cwd = ?, repo = ?, host = ?, host_pid = ?
|
|
628
|
+
WHERE id = ?`).run(at, at, existing.cwd ?? payload.cwd ?? null, existing.cwd ? existing.repo : repo ?? existing.repo, host, hostPid ?? existing.hostPid, payload.session_id);
|
|
629
|
+
return adoptTitle(ctx, payload.session_id, payload.session_title);
|
|
630
|
+
}
|
|
631
|
+
function touchSession(ctx, id) {
|
|
632
|
+
ctx.db.prepare("UPDATE sessions SET last_active_at = ? WHERE id = ?").run(nowIso(ctx), id);
|
|
633
|
+
}
|
|
634
|
+
function nameSession(ctx, id, name, purpose) {
|
|
635
|
+
requireSession(ctx, id);
|
|
636
|
+
try {
|
|
637
|
+
ctx.db.prepare(`UPDATE sessions
|
|
638
|
+
SET name = ?, purpose = COALESCE(?, purpose), last_active_at = ?,
|
|
639
|
+
kind = 'active'
|
|
640
|
+
WHERE id = ?`).run(name, purpose ?? null, nowIso(ctx), id);
|
|
641
|
+
} catch (error) {
|
|
642
|
+
if (error instanceof Error && error.message.includes("UNIQUE")) throw new CarnetError("SESSION_NAME_TAKEN", `A session named "${name}" already exists`);
|
|
643
|
+
throw error;
|
|
644
|
+
}
|
|
645
|
+
return requireSession(ctx, id);
|
|
646
|
+
}
|
|
647
|
+
function listSessions(ctx, options = {}) {
|
|
648
|
+
const conditions = ["group_name IS ?"];
|
|
649
|
+
if (!options.includeTemp) conditions.push("kind != 'temp'");
|
|
650
|
+
if (!options.includeArchived) conditions.push("status != 'archived'");
|
|
651
|
+
return ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE ${conditions.join(" AND ")} ORDER BY last_active_at DESC`).all(ctx.group).map(toSession);
|
|
652
|
+
}
|
|
653
|
+
function dropSession(ctx, id) {
|
|
654
|
+
requireSession(ctx, id);
|
|
655
|
+
const at = nowIso(ctx);
|
|
656
|
+
ctx.db.prepare("UPDATE agents SET status = 'closed', updated_at = ? WHERE session = ? AND status != 'closed'").run(at, id);
|
|
657
|
+
ctx.db.prepare("UPDATE sessions SET status = 'archived', last_active_at = ? WHERE id = ?").run(at, id);
|
|
658
|
+
return requireSession(ctx, id);
|
|
659
|
+
}
|
|
660
|
+
function defaultSession(ctx) {
|
|
661
|
+
const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE group_name IS ? AND status != 'archived'
|
|
662
|
+
ORDER BY last_active_at DESC LIMIT 1`).get(ctx.group);
|
|
663
|
+
return row && toSession(row);
|
|
664
|
+
}
|
|
665
|
+
function sessionByName(ctx, name) {
|
|
666
|
+
const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE group_name IS ? AND name = ?`).get(ctx.group, name);
|
|
667
|
+
return row && toSession(row);
|
|
668
|
+
}
|
|
669
|
+
const MINIMUM_ID_PREFIX = 4;
|
|
670
|
+
function shortId(id) {
|
|
671
|
+
return id.slice(0, 8);
|
|
672
|
+
}
|
|
673
|
+
function findSession(ctx, reference) {
|
|
674
|
+
const byName = sessionByName(ctx, reference);
|
|
675
|
+
if (byName) return byName;
|
|
676
|
+
const byId = getSession(ctx, reference);
|
|
677
|
+
if (byId) return byId;
|
|
678
|
+
const isIdPrefix = /^[0-9a-f-]+$/i.test(reference);
|
|
679
|
+
if (isIdPrefix && reference.length >= 4) {
|
|
680
|
+
const rows = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions WHERE group_name IS ? AND id LIKE ?
|
|
681
|
+
ORDER BY last_active_at DESC`).all(ctx.group, `${reference.toLowerCase()}%`);
|
|
682
|
+
const [only, ...others] = rows;
|
|
683
|
+
if (only && others.length === 0) return toSession(only);
|
|
684
|
+
if (only) throw new CarnetError("SESSION_AMBIGUOUS", `Session id "${reference}" matches several sessions: ${rows.map((row) => shortId(row.id)).join(", ")}`);
|
|
685
|
+
}
|
|
686
|
+
throw new CarnetError("SESSION_NOT_FOUND", `Unknown session "${reference}"${isIdPrefix && reference.length < 4 ? ` (an id prefix needs at least 4 characters)` : ""}`);
|
|
687
|
+
}
|
|
688
|
+
function sessionByHostProcess(ctx, host, processId) {
|
|
689
|
+
const row = ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions
|
|
690
|
+
WHERE host = ? AND host_pid = ? AND hooked_at IS NOT NULL
|
|
691
|
+
ORDER BY hooked_at DESC LIMIT 1`).get(host, processId);
|
|
692
|
+
return row && toSession(row);
|
|
693
|
+
}
|
|
694
|
+
function recordPromptVersion(ctx, id, version) {
|
|
695
|
+
requireSession(ctx, id);
|
|
696
|
+
ctx.db.prepare("UPDATE sessions SET prompt_version = ? WHERE id = ?").run(version, id);
|
|
697
|
+
return requireSession(ctx, id);
|
|
698
|
+
}
|
|
699
|
+
function setParent(ctx, id, parentId) {
|
|
700
|
+
requireSession(ctx, id);
|
|
701
|
+
requireSession(ctx, parentId);
|
|
702
|
+
ctx.db.prepare("UPDATE sessions SET parent_id = ? WHERE id = ?").run(parentId, id);
|
|
703
|
+
return requireSession(ctx, id);
|
|
704
|
+
}
|
|
705
|
+
function setSessionStatus(ctx, id, status) {
|
|
706
|
+
requireSession(ctx, id);
|
|
707
|
+
const at = nowIso(ctx);
|
|
708
|
+
ctx.db.prepare(`UPDATE sessions
|
|
709
|
+
SET status = ?, last_active_at = ?,
|
|
710
|
+
ended_at = CASE WHEN ? = 'running' THEN NULL WHEN ? = 'idle' THEN ? ELSE ended_at END
|
|
711
|
+
WHERE id = ?`).run(status, at, status, status, at, id);
|
|
712
|
+
return requireSession(ctx, id);
|
|
713
|
+
}
|
|
714
|
+
function refuseWhileRunning(session, action) {
|
|
715
|
+
if (session.status === "running") throw new CarnetError("SESSION_RUNNING", `Session ${session.name ?? shortId(session.id)} is running: ${action} it once it has ended`);
|
|
716
|
+
}
|
|
717
|
+
function renameSession(ctx, id, name) {
|
|
718
|
+
refuseWhileRunning(requireSession(ctx, id), "rename");
|
|
719
|
+
try {
|
|
720
|
+
ctx.db.prepare("UPDATE sessions SET name = ? WHERE id = ?").run(name, id);
|
|
721
|
+
} catch (error) {
|
|
722
|
+
nameTaken(error, name);
|
|
723
|
+
}
|
|
724
|
+
return requireSession(ctx, id);
|
|
725
|
+
}
|
|
726
|
+
function promoteSession(ctx, id, name) {
|
|
727
|
+
const session = requireSession(ctx, id);
|
|
728
|
+
if (session.kind === "active") throw new CarnetError("SESSION_KIND_INVALID", `Session ${session.name} is already active`);
|
|
729
|
+
const nextName = name ?? session.name;
|
|
730
|
+
if (!nextName) throw new CarnetError("SESSION_NAME_REQUIRED", "An active session needs a name");
|
|
731
|
+
if (nextName !== session.name) refuseWhileRunning(session, "rename");
|
|
732
|
+
try {
|
|
733
|
+
ctx.db.prepare("UPDATE sessions SET kind = 'active', name = ? WHERE id = ?").run(nextName, id);
|
|
734
|
+
} catch (error) {
|
|
735
|
+
nameTaken(error, nextName);
|
|
736
|
+
}
|
|
737
|
+
return requireSession(ctx, id);
|
|
738
|
+
}
|
|
739
|
+
function demoteSession(ctx, id) {
|
|
740
|
+
const session = requireSession(ctx, id);
|
|
741
|
+
if (session.kind === "temp") throw new CarnetError("SESSION_KIND_INVALID", `Session ${session.name ?? shortId(session.id)} is already temp`);
|
|
742
|
+
ctx.db.prepare("UPDATE sessions SET kind = 'temp' WHERE id = ?").run(id);
|
|
743
|
+
return requireSession(ctx, id);
|
|
744
|
+
}
|
|
745
|
+
function staleTempSessions(ctx, olderThanMilliseconds) {
|
|
746
|
+
const before = new Date(ctx.now().getTime() - olderThanMilliseconds).toISOString();
|
|
747
|
+
return ctx.db.prepare(`SELECT ${COLUMNS} FROM sessions
|
|
748
|
+
WHERE group_name IS ? AND kind = 'temp' AND status = 'idle' AND last_active_at < ?
|
|
749
|
+
ORDER BY last_active_at ASC`).all(ctx.group, before).map(toSession);
|
|
750
|
+
}
|
|
751
|
+
function resetDeadSessions(ctx, isAlive) {
|
|
752
|
+
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));
|
|
753
|
+
}
|
|
754
|
+
// src/prompt/core-rules.ts
|
|
755
|
+
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.
|
|
756
|
+
- The human keeps the hand: only the human launches forks, applies, tests and commits. Agents propose, they never push.
|
|
757
|
+
- 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.
|
|
758
|
+
- 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.
|
|
759
|
+
- 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.
|
|
760
|
+
- To dispatch, apply or review forks, load the rucher skill: it holds the full workflow.`;
|
|
761
|
+
// src/prompt/prompt.ts
|
|
762
|
+
const PROMPT_FILE = "prompt.md";
|
|
763
|
+
function readIfPresent(path) {
|
|
764
|
+
if (!existsSync(path)) return void 0;
|
|
765
|
+
return readFileSync(path, "utf8").trim() || void 0;
|
|
766
|
+
}
|
|
767
|
+
function baseRules(env = process.env) {
|
|
768
|
+
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.";
|
|
769
|
+
}
|
|
770
|
+
function groupRules(group) {
|
|
771
|
+
return group ? readIfPresent(join(group.source, PROMPT_FILE)) : void 0;
|
|
772
|
+
}
|
|
773
|
+
function rulesText(group, env = process.env) {
|
|
774
|
+
const extra = groupRules(group);
|
|
775
|
+
const base = `Rucher rules, always follow them:\n${baseRules(env)}`;
|
|
776
|
+
return extra && group ? `${base}\n\nRules of the ${group.name} group:\n${extra}` : base;
|
|
777
|
+
}
|
|
778
|
+
function rulesVersion(group, env = process.env) {
|
|
779
|
+
return createHash("sha256").update(rulesText(group, env)).digest("hex").slice(0, 12);
|
|
780
|
+
}
|
|
781
|
+
function assemblePrompt(group, session, env = process.env) {
|
|
782
|
+
const label = session.name ?? shortId(session.id);
|
|
783
|
+
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.`;
|
|
784
|
+
return {
|
|
785
|
+
text: `${rulesText(group, env)}\n\n${identity}\n`,
|
|
786
|
+
version: rulesVersion(group, env)
|
|
787
|
+
};
|
|
788
|
+
}
|
|
789
|
+
function appendPromptFile(group, session, env = process.env) {
|
|
790
|
+
const { text, version } = assemblePrompt(group, session, env);
|
|
791
|
+
const directory = promptsDirectory(env);
|
|
792
|
+
mkdirSync(directory, { recursive: true });
|
|
793
|
+
const path = join(directory, `${session.id}.md`);
|
|
794
|
+
writeFileSync(path, text);
|
|
795
|
+
return {
|
|
796
|
+
path,
|
|
797
|
+
version
|
|
798
|
+
};
|
|
799
|
+
}
|
|
800
|
+
function compactReminder(group, env = process.env) {
|
|
801
|
+
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)}`;
|
|
802
|
+
}
|
|
803
|
+
function outsideRucherContext(group, env = process.env) {
|
|
804
|
+
return `This session was started without rucher, so its system prompt does not hold the Rucher rules. ${rulesText(group, env)}`;
|
|
805
|
+
}
|
|
806
|
+
const OUTSIDE_RUCHER_NOTICE = "rucher: session started without rucher, the Rucher rules are not in its system prompt (use rucher new, tmp or resume)";
|
|
807
|
+
const RULES_UPDATED_NOTICE = "rucher: rules updated, will apply after the next compaction or in a new session";
|
|
808
|
+
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.";
|
|
809
|
+
// src/workspace-files.ts
|
|
810
|
+
const GENERATED_MARKER = "generated by rucher, do not edit";
|
|
811
|
+
function refuse(path) {
|
|
812
|
+
throw new CarnetError("WORKSPACE_FILE_CONFLICT", `${path} was not written by rucher: move its content to the group source, then remove it`);
|
|
813
|
+
}
|
|
814
|
+
function entry(path) {
|
|
815
|
+
try {
|
|
816
|
+
return lstatSync(path);
|
|
817
|
+
} catch {
|
|
818
|
+
return;
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
const MARKDOWN_MARKER = `<!-- ${GENERATED_MARKER} -->\n`;
|
|
822
|
+
function markdownCopy(content) {
|
|
823
|
+
return `${MARKDOWN_MARKER}${content}`;
|
|
824
|
+
}
|
|
825
|
+
function isMarkdownCopy(path) {
|
|
826
|
+
if (!entry(path)?.isFile()) return false;
|
|
827
|
+
return readFileSync(path, "utf8").startsWith(MARKDOWN_MARKER);
|
|
828
|
+
}
|
|
829
|
+
function removeStaleCopies(directory, keep) {
|
|
830
|
+
const removed = [];
|
|
831
|
+
for (const name of readdirSync(directory)) {
|
|
832
|
+
if (!name.endsWith(".md") || keep.has(name)) continue;
|
|
833
|
+
const path = join(directory, name);
|
|
834
|
+
if (!isMarkdownCopy(path)) continue;
|
|
835
|
+
rmSync(path, { force: true });
|
|
836
|
+
removed.push(name);
|
|
837
|
+
}
|
|
838
|
+
return removed;
|
|
839
|
+
}
|
|
840
|
+
function writeGenerated(path, content) {
|
|
841
|
+
const current = entry(path);
|
|
842
|
+
if (current?.isSymbolicLink()) rmSync(path, { force: true });
|
|
843
|
+
else if (current) {
|
|
844
|
+
const existing = readFileSync(path, "utf8");
|
|
845
|
+
if (existing === content) return false;
|
|
846
|
+
if (!existing.includes("generated by rucher, do not edit")) refuse(path);
|
|
847
|
+
}
|
|
848
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
849
|
+
writeFileSync(path, content);
|
|
850
|
+
return true;
|
|
851
|
+
}
|
|
852
|
+
function isObject(value) {
|
|
853
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
854
|
+
}
|
|
855
|
+
function mergeSettings(base, extra) {
|
|
856
|
+
const merged = { ...base };
|
|
857
|
+
for (const [key, value] of Object.entries(extra)) {
|
|
858
|
+
const current = merged[key];
|
|
859
|
+
if (Array.isArray(current) && Array.isArray(value)) {
|
|
860
|
+
const seen = new Set(current.map((item) => JSON.stringify(item)));
|
|
861
|
+
merged[key] = [...current, ...value.filter((item) => !seen.has(JSON.stringify(item)))];
|
|
862
|
+
} else if (isObject(current) && isObject(value)) merged[key] = mergeSettings(current, value);
|
|
863
|
+
else merged[key] = value;
|
|
864
|
+
}
|
|
865
|
+
return merged;
|
|
866
|
+
}
|
|
429
867
|
// src/hosts/claude-code.ts
|
|
430
868
|
const TRANSCRIPT_TAIL_BYTES = 262144;
|
|
431
869
|
const TITLE_PATTERN = /"type":"custom-title","customTitle":("(?:[^"\\]|\\.)*")/g;
|
|
432
870
|
const FORK_NAME_PATTERN = /You are fork `([^`]+)`/;
|
|
433
|
-
const REPOS_START = "<!-- rucher:repos start -->";
|
|
434
|
-
const REPOS_END = "<!-- rucher:repos end -->";
|
|
435
871
|
function payloadObject(json) {
|
|
436
872
|
const data = JSON.parse(json);
|
|
437
873
|
if (typeof data.session_id !== "string" || !data.session_id) throw new TypeError("Hook payload has no session_id");
|
|
@@ -484,77 +920,40 @@ function transcriptTitle(path) {
|
|
|
484
920
|
if (descriptor !== void 0) closeSync(descriptor);
|
|
485
921
|
}
|
|
486
922
|
}
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
return
|
|
490
|
-
}
|
|
491
|
-
function replaceReposBlock(content, group) {
|
|
492
|
-
const start = content.indexOf(REPOS_START);
|
|
493
|
-
const end = content.indexOf(REPOS_END);
|
|
494
|
-
if (start === -1 || end === -1 || end < start) return null;
|
|
495
|
-
return content.slice(0, start) + reposBlock(group) + content.slice(end + 25);
|
|
496
|
-
}
|
|
497
|
-
function groupInstructions(group) {
|
|
498
|
-
return `# ${group.name}
|
|
499
|
-
|
|
500
|
-
Meta directory of the ${group.name} group: context only, the repos live at their own paths below and are reachable through \`.claude/settings.json\`. Start Claude Code sessions here.
|
|
501
|
-
|
|
502
|
-
${reposBlock(group)}
|
|
503
|
-
|
|
504
|
-
## Multi-agent work
|
|
505
|
-
|
|
506
|
-
Use the rucher tools (Carnet) for agent statuses and the journal, and the rucher skill for the workflow.
|
|
507
|
-
|
|
508
|
-
## Shared instructions
|
|
509
|
-
|
|
510
|
-
(what every session of this group should know)
|
|
511
|
-
`;
|
|
923
|
+
const SETTINGS_FILE = join(".claude", "settings.json");
|
|
924
|
+
function instructionFiles(group) {
|
|
925
|
+
if (!existsSync(group.source)) return [];
|
|
926
|
+
return readdirSync(group.source, { withFileTypes: true }).filter((item) => item.isFile() && item.name.endsWith(".md") && item.name !== "prompt.md").map((item) => item.name).sort();
|
|
512
927
|
}
|
|
513
928
|
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";
|
|
929
|
+
return mergeSettings({
|
|
930
|
+
"//": GENERATED_MARKER,
|
|
931
|
+
permissions: {
|
|
932
|
+
additionalDirectories: group.repos.map((repo) => repo.path),
|
|
933
|
+
deny: instructionFiles(group).map((name) => `Edit(/${name})`)
|
|
523
934
|
}
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
}
|
|
531
|
-
|
|
532
|
-
const
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
const path = join(group.root, ".claude", "settings.json");
|
|
536
|
-
if (!existsSync(path)) {
|
|
537
|
-
if (group.repos.length === 0) return "unchanged";
|
|
538
|
-
mkdirSync(dirname(path), { recursive: true });
|
|
539
|
-
writeFileSync(path, groupSettings(group));
|
|
540
|
-
return "written";
|
|
541
|
-
}
|
|
542
|
-
const settings = JSON.parse(readFileSync(path, "utf8"));
|
|
543
|
-
const current = settings.permissions?.additionalDirectories ?? [];
|
|
544
|
-
const next = mode === "exact" ? group.repos : [...current, ...group.repos.filter((repo) => !current.includes(repo))];
|
|
545
|
-
if (next.length === current.length && next.every((repo, index) => repo === current[index])) return "unchanged";
|
|
546
|
-
settings.permissions = {
|
|
547
|
-
...settings.permissions,
|
|
548
|
-
additionalDirectories: next
|
|
549
|
-
};
|
|
550
|
-
writeFileSync(path, `${JSON.stringify(settings, null, 2)}\n`);
|
|
551
|
-
return "updated";
|
|
935
|
+
}, group.backends["claude-code"]?.settings ?? {});
|
|
936
|
+
}
|
|
937
|
+
function renderClaudeWorkspace(group) {
|
|
938
|
+
const rendered = {
|
|
939
|
+
written: [],
|
|
940
|
+
removed: []
|
|
941
|
+
};
|
|
942
|
+
const names = instructionFiles(group);
|
|
943
|
+
for (const name of names) {
|
|
944
|
+
const content = markdownCopy(readFileSync(join(group.source, name), "utf8"));
|
|
945
|
+
if (writeGenerated(join(group.workspace, name), content)) rendered.written.push(name);
|
|
552
946
|
}
|
|
553
|
-
|
|
947
|
+
rendered.removed.push(...removeStaleCopies(group.workspace, new Set(names)));
|
|
948
|
+
const settings = `${JSON.stringify(groupSettings(group), null, 2)}\n`;
|
|
949
|
+
if (writeGenerated(join(group.workspace, SETTINGS_FILE), settings)) rendered.written.push(SETTINGS_FILE);
|
|
950
|
+
return rendered;
|
|
951
|
+
}
|
|
554
952
|
function launchArguments(options = {}) {
|
|
555
953
|
return [
|
|
556
954
|
...options.name ? ["--name", options.name] : [],
|
|
557
955
|
...options.appendPromptFile ? ["--append-system-prompt-file", options.appendPromptFile] : [],
|
|
956
|
+
...(options.directories ?? []).flatMap((directory) => ["--add-dir", directory]),
|
|
558
957
|
...options.passthrough ?? []
|
|
559
958
|
];
|
|
560
959
|
}
|
|
@@ -689,7 +1088,7 @@ const claudeCode = {
|
|
|
689
1088
|
renameInstruction(name) {
|
|
690
1089
|
return `Ask the human to run /rename ${name} in Claude Code so the titles match.`;
|
|
691
1090
|
},
|
|
692
|
-
|
|
1091
|
+
renderWorkspace: renderClaudeWorkspace
|
|
693
1092
|
};
|
|
694
1093
|
// src/hosts/host.ts
|
|
695
1094
|
const DEFAULT_HOST = "claude-code";
|
|
@@ -702,123 +1101,278 @@ function hostById(id) {
|
|
|
702
1101
|
if (!host) throw new CarnetError("UNKNOWN_HOST", `Unknown host "${id}" (available: ${Object.keys(HOSTS).join(", ")})`);
|
|
703
1102
|
return host;
|
|
704
1103
|
}
|
|
705
|
-
// src/group
|
|
706
|
-
function
|
|
707
|
-
|
|
1104
|
+
// src/group-rows.ts
|
|
1105
|
+
function inTransaction(db, run) {
|
|
1106
|
+
db.exec("BEGIN");
|
|
1107
|
+
try {
|
|
1108
|
+
const result = run();
|
|
1109
|
+
db.exec("COMMIT");
|
|
1110
|
+
return result;
|
|
1111
|
+
} catch (error) {
|
|
1112
|
+
db.exec("ROLLBACK");
|
|
1113
|
+
throw error;
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
function sessionGroupName(db, sessionId) {
|
|
1117
|
+
const row = db.prepare("SELECT group_name FROM sessions WHERE id = ?").get(sessionId);
|
|
1118
|
+
return row ? row.group_name : void 0;
|
|
1119
|
+
}
|
|
1120
|
+
function renameGroupRows(db, from, to) {
|
|
1121
|
+
inTransaction(db, () => {
|
|
1122
|
+
for (const table of [
|
|
1123
|
+
"sessions",
|
|
1124
|
+
"notes",
|
|
1125
|
+
"active_days"
|
|
1126
|
+
]) db.prepare(`UPDATE ${table} SET group_name = ? WHERE group_name = ?`).run(to, from);
|
|
1127
|
+
});
|
|
1128
|
+
}
|
|
1129
|
+
function archiveGroupSessions(db, name, at) {
|
|
1130
|
+
return inTransaction(db, () => {
|
|
1131
|
+
db.prepare(`UPDATE agents SET status = 'closed', updated_at = ?
|
|
1132
|
+
WHERE status != 'closed' AND session IN (SELECT id FROM sessions WHERE group_name = ?)`).run(at, name);
|
|
1133
|
+
return Number(db.prepare(`UPDATE sessions SET status = 'archived', last_active_at = ?
|
|
1134
|
+
WHERE group_name = ? AND status != 'archived'`).run(at, name).changes);
|
|
1135
|
+
});
|
|
1136
|
+
}
|
|
1137
|
+
function deleteGroupNotes(db, name) {
|
|
1138
|
+
return Number(db.prepare("DELETE FROM notes WHERE group_name = ?").run(name).changes);
|
|
708
1139
|
}
|
|
709
|
-
function
|
|
710
|
-
|
|
1140
|
+
function groupSessionCounts(db) {
|
|
1141
|
+
const rows = db.prepare(`SELECT group_name, COUNT(*) AS count FROM sessions
|
|
1142
|
+
WHERE group_name IS NOT NULL AND status != 'archived' GROUP BY group_name`).all();
|
|
1143
|
+
return new Map(rows.map((row) => [row.group_name, Number(row.count)]));
|
|
711
1144
|
}
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
1145
|
+
// src/group/group.ts
|
|
1146
|
+
const GROUP_FILE = "group.json";
|
|
1147
|
+
const INSTRUCTIONS_FILE = "CLAUDE.md";
|
|
1148
|
+
const GROUP_NAME = /^[a-z0-9-]+$/;
|
|
1149
|
+
function isGroupName(name) {
|
|
1150
|
+
return GROUP_NAME.test(name);
|
|
1151
|
+
}
|
|
1152
|
+
function requireGroupName(name) {
|
|
1153
|
+
if (!isGroupName(name)) throw new CarnetError("GROUP_NAME_INVALID", `Invalid group name ${JSON.stringify(name)}: use lowercase letters, digits and dashes`);
|
|
1154
|
+
}
|
|
1155
|
+
function expandHome(path, env = process.env) {
|
|
1156
|
+
if (path !== "~" && !path.startsWith("~/")) return path;
|
|
1157
|
+
return join(env.HOME || homedir(), path.slice(1));
|
|
716
1158
|
}
|
|
717
|
-
function
|
|
718
|
-
|
|
719
|
-
mkdirSync(rucherHome(env), { recursive: true });
|
|
720
|
-
writeFileSync(registryPath(env), `${JSON.stringify({ groups }, null, 2)}\n`);
|
|
721
|
-
return groups;
|
|
1159
|
+
function groupFilePath(name, env) {
|
|
1160
|
+
return join(groupSource(name, env), GROUP_FILE);
|
|
722
1161
|
}
|
|
723
|
-
function
|
|
724
|
-
return
|
|
1162
|
+
function groupExists(name, env) {
|
|
1163
|
+
return isGroupName(name) && existsSync(groupFilePath(name, env));
|
|
725
1164
|
}
|
|
726
|
-
function
|
|
727
|
-
|
|
1165
|
+
function readGroupFile(name, env) {
|
|
1166
|
+
if (!groupExists(name, env)) throw new CarnetError("GROUP_NOT_FOUND", `No group named ${name}: see "rucher groups list"`);
|
|
1167
|
+
return JSON.parse(readFileSync(groupFilePath(name, env), "utf8"));
|
|
1168
|
+
}
|
|
1169
|
+
function writeGroupFile(name, file, env) {
|
|
1170
|
+
writeFileSync(groupFilePath(name, env), `${JSON.stringify(file, null, 2)}\n`);
|
|
1171
|
+
}
|
|
1172
|
+
function loadGroup(name, env = process.env) {
|
|
1173
|
+
const file = readGroupFile(name, env);
|
|
1174
|
+
return {
|
|
1175
|
+
name,
|
|
1176
|
+
source: groupSource(name, env),
|
|
1177
|
+
workspace: resolve(expandHome(file.workspace ?? defaultWorkspace(name, env), env)),
|
|
1178
|
+
repos: (file.repos ?? []).map((repo) => {
|
|
1179
|
+
const path = resolve(expandHome(repo.path, env));
|
|
1180
|
+
return {
|
|
1181
|
+
path,
|
|
1182
|
+
name: repo.name ?? basename(path)
|
|
1183
|
+
};
|
|
1184
|
+
}),
|
|
1185
|
+
backends: file.backends ?? {}
|
|
1186
|
+
};
|
|
1187
|
+
}
|
|
1188
|
+
function listGroups(env = process.env) {
|
|
1189
|
+
const directory = groupsDirectory(env);
|
|
1190
|
+
if (!existsSync(directory)) return [];
|
|
1191
|
+
return readdirSync(directory).filter((name) => groupExists(name, env)).sort().map((name) => loadGroup(name, env));
|
|
1192
|
+
}
|
|
1193
|
+
function groupHosts(group) {
|
|
1194
|
+
const hosts = Object.keys(group.backends);
|
|
1195
|
+
return hosts.length ? hosts : [DEFAULT_HOST];
|
|
1196
|
+
}
|
|
1197
|
+
function checkedRepo(path, env) {
|
|
1198
|
+
const absolute = resolve(expandHome(path, env));
|
|
1199
|
+
if (!existsSync(absolute)) throw new CarnetError("REPO_NOT_FOUND", `Repo path does not exist: ${absolute}`);
|
|
1200
|
+
return absolute;
|
|
1201
|
+
}
|
|
1202
|
+
function requireDistinctNames(group, repos) {
|
|
1203
|
+
const names = repos.map((repo) => repo.name);
|
|
1204
|
+
const shared = names.find((name, index) => names.indexOf(name) !== index);
|
|
1205
|
+
if (shared) throw new CarnetError("REPO_NAME_TAKEN", `${group} would have two repos named ${shared}: give them distinct names`);
|
|
1206
|
+
}
|
|
1207
|
+
function createGroup(name, options = {}) {
|
|
1208
|
+
const { env } = options;
|
|
1209
|
+
requireGroupName(name);
|
|
1210
|
+
if (groupExists(name, env)) throw new CarnetError("GROUP_EXISTS", `Group ${name} already exists`);
|
|
1211
|
+
const repos = [...new Set((options.repos ?? []).map((repo) => checkedRepo(repo, env)))].map((path) => ({
|
|
1212
|
+
path,
|
|
1213
|
+
name: basename(path)
|
|
1214
|
+
}));
|
|
1215
|
+
requireDistinctNames(name, repos);
|
|
1216
|
+
const source = groupSource(name, env);
|
|
1217
|
+
const workspace = defaultWorkspace(name, env);
|
|
1218
|
+
mkdirSync(source, { recursive: true });
|
|
1219
|
+
mkdirSync(workspace, { recursive: true });
|
|
1220
|
+
writeGroupFile(name, {
|
|
1221
|
+
name,
|
|
1222
|
+
workspace,
|
|
1223
|
+
repos,
|
|
1224
|
+
backends: {}
|
|
1225
|
+
}, env);
|
|
1226
|
+
const instructions = join(source, INSTRUCTIONS_FILE);
|
|
1227
|
+
if (!existsSync(instructions)) writeFileSync(instructions, "");
|
|
1228
|
+
return loadGroup(name, env);
|
|
1229
|
+
}
|
|
1230
|
+
function addGroupRepo(name, repo, env) {
|
|
1231
|
+
const file = readGroupFile(name, env);
|
|
1232
|
+
const group = loadGroup(name, env);
|
|
1233
|
+
const path = checkedRepo(repo, env);
|
|
1234
|
+
if (group.repos.some((existing) => existing.path === path)) return group;
|
|
1235
|
+
requireDistinctNames(name, [...group.repos, {
|
|
1236
|
+
path,
|
|
1237
|
+
name: basename(path)
|
|
1238
|
+
}]);
|
|
1239
|
+
writeGroupFile(name, {
|
|
1240
|
+
...file,
|
|
1241
|
+
repos: [...file.repos ?? [], {
|
|
1242
|
+
path,
|
|
1243
|
+
name: basename(path)
|
|
1244
|
+
}]
|
|
1245
|
+
}, env);
|
|
1246
|
+
return loadGroup(name, env);
|
|
1247
|
+
}
|
|
1248
|
+
function removeGroupRepo(name, repo, env) {
|
|
1249
|
+
const file = readGroupFile(name, env);
|
|
1250
|
+
const group = loadGroup(name, env);
|
|
1251
|
+
const path = resolve(expandHome(repo, env));
|
|
1252
|
+
const index = group.repos.findIndex((existing) => existing.path === path || existing.name === repo);
|
|
1253
|
+
if (index === -1) throw new CarnetError("REPO_NOT_FOUND", `${repo} is not a repo of ${name}`);
|
|
1254
|
+
writeGroupFile(name, {
|
|
1255
|
+
...file,
|
|
1256
|
+
repos: (file.repos ?? []).filter((_, position) => position !== index)
|
|
1257
|
+
}, env);
|
|
1258
|
+
return loadGroup(name, env);
|
|
1259
|
+
}
|
|
1260
|
+
function renameGroup(from, to, env) {
|
|
1261
|
+
const file = readGroupFile(from, env);
|
|
1262
|
+
requireGroupName(to);
|
|
1263
|
+
if (existsSync(groupSource(to, env))) throw new CarnetError("GROUP_EXISTS", `Group ${to} already exists`);
|
|
1264
|
+
const workspace = loadGroup(from, env).workspace;
|
|
1265
|
+
renameSync(groupSource(from, env), groupSource(to, env));
|
|
1266
|
+
writeGroupFile(to, {
|
|
1267
|
+
...file,
|
|
1268
|
+
name: to,
|
|
1269
|
+
workspace
|
|
1270
|
+
}, env);
|
|
1271
|
+
return loadGroup(to, env);
|
|
1272
|
+
}
|
|
1273
|
+
function dropGroup(name, options = {}) {
|
|
1274
|
+
const group = loadGroup(name, options.env);
|
|
1275
|
+
rmSync(group.source, {
|
|
1276
|
+
recursive: true,
|
|
1277
|
+
force: true
|
|
1278
|
+
});
|
|
1279
|
+
if (options.purge) rmSync(group.workspace, {
|
|
1280
|
+
recursive: true,
|
|
1281
|
+
force: true
|
|
1282
|
+
});
|
|
1283
|
+
return group;
|
|
728
1284
|
}
|
|
729
1285
|
// 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
1286
|
function isInside(directory, path) {
|
|
735
1287
|
const relativePath = relative(directory, path);
|
|
736
1288
|
return relativePath === "" || !relativePath.startsWith("..") && !resolve(relativePath).startsWith(relativePath);
|
|
737
1289
|
}
|
|
1290
|
+
function repoOf(group, path) {
|
|
1291
|
+
const absolutePath = resolve(path);
|
|
1292
|
+
return group?.repos.find((repo) => isInside(repo.path, absolutePath));
|
|
1293
|
+
}
|
|
738
1294
|
function repoNameFor(group, path) {
|
|
739
|
-
|
|
740
|
-
const repo = group.repos.find((repo) => isInside(repo, resolve(path)));
|
|
741
|
-
return repo ? basename(repo) : null;
|
|
1295
|
+
return path ? repoOf(group, path)?.name ?? null : null;
|
|
742
1296
|
}
|
|
743
1297
|
function repoPathFor(group, path) {
|
|
744
1298
|
if (!path) return null;
|
|
745
|
-
const
|
|
746
|
-
const repo = group.repos.find((candidate) => isInside(candidate, absolutePath));
|
|
1299
|
+
const repo = repoOf(group, path);
|
|
747
1300
|
if (!repo) return null;
|
|
748
|
-
const relativePath = relative(repo,
|
|
749
|
-
return relativePath ? join(
|
|
750
|
-
}
|
|
751
|
-
function
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
1301
|
+
const relativePath = relative(repo.path, resolve(path));
|
|
1302
|
+
return relativePath ? join(repo.name, relativePath) : repo.name;
|
|
1303
|
+
}
|
|
1304
|
+
function namedGroup(name, env) {
|
|
1305
|
+
if (!groupExists(name, env)) throw new CarnetError("GROUP_NOT_FOUND", `No group named ${name}: see "rucher groups list"`);
|
|
1306
|
+
return loadGroup(name, env);
|
|
1307
|
+
}
|
|
1308
|
+
function byWorkspace(groups, directories) {
|
|
1309
|
+
return groups.find((group) => directories.some((directory) => isInside(group.workspace, directory)));
|
|
1310
|
+
}
|
|
1311
|
+
function byRepo(groups, directory) {
|
|
1312
|
+
let best = [];
|
|
1313
|
+
for (const group of groups) for (const repo of group.repos) {
|
|
1314
|
+
if (!isInside(repo.path, directory)) continue;
|
|
1315
|
+
const length = best[0]?.repo.path.length ?? -1;
|
|
1316
|
+
if (repo.path.length > length) best = [{
|
|
1317
|
+
group,
|
|
1318
|
+
repo
|
|
1319
|
+
}];
|
|
1320
|
+
else if (repo.path.length === length) best.push({
|
|
1321
|
+
group,
|
|
1322
|
+
repo
|
|
1323
|
+
});
|
|
758
1324
|
}
|
|
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);
|
|
1325
|
+
const names = [...new Set(best.map((match) => match.group.name))];
|
|
1326
|
+
if (names.length > 1) throw new CarnetError("GROUP_AMBIGUOUS", `${directory} is in repos of several groups (${names.join(", ")}): pass --group`);
|
|
1327
|
+
return best[0];
|
|
1328
|
+
}
|
|
1329
|
+
function resolveGroup({ db, sessionId, group, cwd = process.cwd(), env = process.env } = {}) {
|
|
1330
|
+
if (db && sessionId) {
|
|
1331
|
+
const name = sessionGroupName(db, sessionId);
|
|
1332
|
+
if (name === null) return {
|
|
1333
|
+
group: null,
|
|
1334
|
+
origin: "session"
|
|
1335
|
+
};
|
|
1336
|
+
if (name !== void 0 && groupExists(name, env)) return {
|
|
1337
|
+
group: loadGroup(name, env),
|
|
1338
|
+
origin: "session"
|
|
1339
|
+
};
|
|
785
1340
|
}
|
|
786
|
-
return
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
}
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
1341
|
+
if (group) return {
|
|
1342
|
+
group: namedGroup(group, env),
|
|
1343
|
+
origin: "option"
|
|
1344
|
+
};
|
|
1345
|
+
if (env.RUCHER_GROUP) return {
|
|
1346
|
+
group: namedGroup(env.RUCHER_GROUP, env),
|
|
1347
|
+
origin: "env"
|
|
1348
|
+
};
|
|
1349
|
+
const projectDirectories = allHosts().map((host) => host.projectDirectory(env)).filter((directory) => directory !== void 0);
|
|
1350
|
+
const directories = [resolve(cwd), ...projectDirectories.map((directory) => resolve(directory))];
|
|
1351
|
+
const groups = listGroups(env);
|
|
1352
|
+
const workspaceGroup = byWorkspace(groups, directories);
|
|
1353
|
+
if (workspaceGroup) return {
|
|
1354
|
+
group: workspaceGroup,
|
|
1355
|
+
origin: "workspace"
|
|
1356
|
+
};
|
|
1357
|
+
for (const directory of directories) {
|
|
1358
|
+
const match = byRepo(groups, directory);
|
|
1359
|
+
if (match) return {
|
|
1360
|
+
group: match.group,
|
|
1361
|
+
origin: "repo",
|
|
1362
|
+
repo: match.repo
|
|
1363
|
+
};
|
|
797
1364
|
}
|
|
1365
|
+
return {
|
|
1366
|
+
group: null,
|
|
1367
|
+
origin: "none"
|
|
1368
|
+
};
|
|
798
1369
|
}
|
|
799
|
-
function
|
|
800
|
-
|
|
801
|
-
return root && isGroupRoot(resolve(root)) ? loadGroup(resolve(root)) : null;
|
|
1370
|
+
function groupLabel(group) {
|
|
1371
|
+
return group?.name ?? "no group";
|
|
802
1372
|
}
|
|
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`);
|
|
1373
|
+
function requireGroup(group) {
|
|
1374
|
+
if (group) return group;
|
|
1375
|
+
throw new CarnetError("NO_GROUP", "No Rucher group here: pass --group, or run this from a repo or workspace of a group");
|
|
822
1376
|
}
|
|
823
1377
|
function ambiguousGroupContext(reason) {
|
|
824
1378
|
return `Rucher could not tell which group this session belongs to, so Carnet records nothing for it: ${reason}.`;
|
|
@@ -841,6 +1395,11 @@ function memoryHalfLife(value) {
|
|
|
841
1395
|
const days = Number(value);
|
|
842
1396
|
return Number.isFinite(days) && days > 0 ? days : 20;
|
|
843
1397
|
}
|
|
1398
|
+
const NOTE_COLUMNS = `notes.id, notes.number, notes.kind, notes.text, notes.session, notes.agent,
|
|
1399
|
+
notes.similar_notes, notes.created_at, notes.dropped_at, notes.dropped_reason,
|
|
1400
|
+
notes.dropped_session,
|
|
1401
|
+
(SELECT replaced.number FROM notes AS replaced WHERE replaced.id = notes.replaced_by)
|
|
1402
|
+
AS replaced_number`;
|
|
844
1403
|
const MARKDOWN = /\*\*|__|\[[^\]]*\]\([^)]*\)|^#{1,6}\s|^[-*+]\s/;
|
|
845
1404
|
function cleanText(value, label) {
|
|
846
1405
|
const text = value.trim().replace(/[ \t]+/g, " ");
|
|
@@ -852,7 +1411,7 @@ function cleanText(value, label) {
|
|
|
852
1411
|
return text;
|
|
853
1412
|
}
|
|
854
1413
|
function groupRepoNames(group) {
|
|
855
|
-
return group.repos.map((repo) =>
|
|
1414
|
+
return group.repos.map((repo) => repo.name);
|
|
856
1415
|
}
|
|
857
1416
|
function cleanRepos(group, repos) {
|
|
858
1417
|
const known = groupRepoNames(group);
|
|
@@ -878,21 +1437,22 @@ function localDay(date) {
|
|
|
878
1437
|
return `${date.getFullYear()}-${month}-${day}`;
|
|
879
1438
|
}
|
|
880
1439
|
function recordActiveDay(ctx) {
|
|
881
|
-
ctx.
|
|
1440
|
+
if (ctx.group === null) return;
|
|
1441
|
+
ctx.db.prepare("INSERT OR IGNORE INTO active_days (group_name, day) VALUES (?, ?)").run(ctx.group, localDay(ctx.now()));
|
|
882
1442
|
}
|
|
883
1443
|
function activeDays(ctx) {
|
|
884
|
-
return ctx.db.prepare("SELECT day FROM active_days ORDER BY day").all().map((row) => row.day);
|
|
1444
|
+
return ctx.db.prepare("SELECT day FROM active_days WHERE group_name IS ? ORDER BY day").all(ctx.group).map((row) => row.day);
|
|
885
1445
|
}
|
|
886
1446
|
function activeDaysSince(days, at) {
|
|
887
1447
|
const since = localDay(new Date(at));
|
|
888
1448
|
return days.filter((day) => day > since).length;
|
|
889
1449
|
}
|
|
890
|
-
function reposOf(ctx,
|
|
891
|
-
return ctx.db.prepare("SELECT repo FROM note_repos WHERE note = ? ORDER BY repo").all(
|
|
1450
|
+
function reposOf(ctx, noteId) {
|
|
1451
|
+
return ctx.db.prepare("SELECT repo FROM note_repos WHERE note = ? ORDER BY repo").all(noteId).map((row) => row.repo);
|
|
892
1452
|
}
|
|
893
1453
|
function toNote(ctx, row) {
|
|
894
1454
|
return {
|
|
895
|
-
id: row.
|
|
1455
|
+
id: row.number,
|
|
896
1456
|
kind: row.kind,
|
|
897
1457
|
text: row.text,
|
|
898
1458
|
repos: reposOf(ctx, row.id),
|
|
@@ -903,11 +1463,19 @@ function toNote(ctx, row) {
|
|
|
903
1463
|
droppedAt: row.dropped_at,
|
|
904
1464
|
droppedReason: row.dropped_reason,
|
|
905
1465
|
droppedSession: row.dropped_session,
|
|
906
|
-
replacedBy: row.
|
|
1466
|
+
replacedBy: row.replaced_number
|
|
907
1467
|
};
|
|
908
1468
|
}
|
|
1469
|
+
function noteRow(ctx, number) {
|
|
1470
|
+
return ctx.db.prepare(`SELECT ${NOTE_COLUMNS} FROM notes WHERE group_name IS ? AND number = ?`).get(ctx.group, number);
|
|
1471
|
+
}
|
|
1472
|
+
function noteId(ctx, number) {
|
|
1473
|
+
const row = noteRow(ctx, number);
|
|
1474
|
+
if (!row) throw new CarnetError("NOTE_NOT_FOUND", `Unknown note #${number}`);
|
|
1475
|
+
return row.id;
|
|
1476
|
+
}
|
|
909
1477
|
function getNote(ctx, id) {
|
|
910
|
-
const row = ctx
|
|
1478
|
+
const row = noteRow(ctx, id);
|
|
911
1479
|
return row ? toNote(ctx, row) : null;
|
|
912
1480
|
}
|
|
913
1481
|
function requireNote(ctx, id) {
|
|
@@ -920,8 +1488,11 @@ function requireActiveNote(ctx, id) {
|
|
|
920
1488
|
if (note.droppedAt) throw new CarnetError("INVALID_NOTE", `Note #${id} is dropped`);
|
|
921
1489
|
return note;
|
|
922
1490
|
}
|
|
923
|
-
|
|
924
|
-
|
|
1491
|
+
const CITATION_COLUMNS = `note_citations.id, notes.number AS note, note_citations.session,
|
|
1492
|
+
note_citations.agent, note_citations.why, note_citations.at`;
|
|
1493
|
+
function citationsOf(ctx, number) {
|
|
1494
|
+
return ctx.db.prepare(`SELECT ${CITATION_COLUMNS} FROM note_citations JOIN notes ON notes.id = note_citations.note
|
|
1495
|
+
WHERE notes.group_name IS ? AND notes.number = ? ORDER BY note_citations.at`).all(ctx.group, number);
|
|
925
1496
|
}
|
|
926
1497
|
function weightOf(citations, days, halfLifeDays) {
|
|
927
1498
|
const latest = /* @__PURE__ */ new Map();
|
|
@@ -949,9 +1520,10 @@ function compareNotes(first, second) {
|
|
|
949
1520
|
return second.id - first.id;
|
|
950
1521
|
}
|
|
951
1522
|
function activeNotesOfKind(ctx, kind) {
|
|
952
|
-
return ctx.db.prepare(
|
|
1523
|
+
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
1524
|
}
|
|
954
1525
|
function addNote(ctx, group, input) {
|
|
1526
|
+
if (group === null || ctx.group === null) throw new CarnetError("NO_GROUP", "Notes belong to a group: this session has none");
|
|
955
1527
|
if (!isNoteKind(input.kind)) throw new CarnetError("INVALID_NOTE", `Invalid note kind "${input.kind}" (use ${NOTE_KINDS.join(", ")})`);
|
|
956
1528
|
const kind = input.kind;
|
|
957
1529
|
const text = cleanText(input.text, "Note text");
|
|
@@ -962,13 +1534,15 @@ function addNote(ctx, group, input) {
|
|
|
962
1534
|
})).filter((candidate) => candidate.score >= DUPLICATE_SIMILARITY).sort((first, second) => second.score - first.score).slice(0, SIMILAR_SHOWN).map((candidate) => candidate.note);
|
|
963
1535
|
ctx.db.exec("BEGIN");
|
|
964
1536
|
try {
|
|
965
|
-
const
|
|
1537
|
+
const next = ctx.db.prepare("SELECT COALESCE(MAX(number), 0) + 1 AS number FROM notes WHERE group_name = ?").get(ctx.group);
|
|
1538
|
+
const result = ctx.db.prepare(`INSERT INTO notes (group_name, number, kind, text, session, agent, similar_notes, created_at)
|
|
1539
|
+
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
1540
|
const id = Number(result.lastInsertRowid);
|
|
967
1541
|
const addRepo = ctx.db.prepare("INSERT INTO note_repos (note, repo) VALUES (?, ?)");
|
|
968
1542
|
for (const repo of repos) addRepo.run(id, repo);
|
|
969
1543
|
ctx.db.exec("COMMIT");
|
|
970
1544
|
return {
|
|
971
|
-
note: requireNote(ctx,
|
|
1545
|
+
note: requireNote(ctx, next.number),
|
|
972
1546
|
similar
|
|
973
1547
|
};
|
|
974
1548
|
} catch (error) {
|
|
@@ -978,8 +1552,8 @@ function addNote(ctx, group, input) {
|
|
|
978
1552
|
}
|
|
979
1553
|
function listNotes(ctx, options = {}) {
|
|
980
1554
|
if (options.kind !== void 0 && !isNoteKind(options.kind)) throw new CarnetError("INVALID_NOTE", `Invalid note kind "${options.kind}"`);
|
|
981
|
-
const conditions = [];
|
|
982
|
-
const parameters = [];
|
|
1555
|
+
const conditions = ["group_name IS ?"];
|
|
1556
|
+
const parameters = [ctx.group];
|
|
983
1557
|
if (!options.includeDropped) conditions.push("dropped_at IS NULL");
|
|
984
1558
|
if (options.kind) {
|
|
985
1559
|
conditions.push("kind = ?");
|
|
@@ -994,8 +1568,7 @@ function listNotes(ctx, options = {}) {
|
|
|
994
1568
|
conditions.push("LOWER(text) LIKE ? ESCAPE '\\'");
|
|
995
1569
|
parameters.push(`%${options.query.toLowerCase().replace(/[\\%_]/g, "\\$&")}%`);
|
|
996
1570
|
}
|
|
997
|
-
const
|
|
998
|
-
const rows = ctx.db.prepare(`SELECT * FROM notes ${where}`).all(...parameters);
|
|
1571
|
+
const rows = ctx.db.prepare(`SELECT ${NOTE_COLUMNS} FROM notes WHERE ${conditions.join(" AND ")}`).all(...parameters);
|
|
999
1572
|
const days = activeDays(ctx);
|
|
1000
1573
|
const halfLifeDays = options.halfLifeDays ?? 20;
|
|
1001
1574
|
return rows.map((row) => weigh(ctx, toNote(ctx, row), days, halfLifeDays)).sort(compareNotes);
|
|
@@ -1021,14 +1594,16 @@ function dropNote(ctx, id, input) {
|
|
|
1021
1594
|
if (input.replacedBy === id) throw new CarnetError("INVALID_NOTE", `Note #${id} cannot replace itself`);
|
|
1022
1595
|
requireActiveNote(ctx, input.replacedBy);
|
|
1023
1596
|
}
|
|
1024
|
-
|
|
1597
|
+
const replacedBy = input.replacedBy === void 0 ? null : noteId(ctx, input.replacedBy);
|
|
1598
|
+
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
1599
|
return requireNote(ctx, id);
|
|
1026
1600
|
}
|
|
1027
1601
|
function citeNote(ctx, id, input) {
|
|
1028
1602
|
requireActiveNote(ctx, id);
|
|
1029
1603
|
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(
|
|
1604
|
+
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));
|
|
1605
|
+
return ctx.db.prepare(`SELECT ${CITATION_COLUMNS} FROM note_citations JOIN notes ON notes.id = note_citations.note
|
|
1606
|
+
WHERE note_citations.id = ?`).get(Number(result.lastInsertRowid));
|
|
1032
1607
|
}
|
|
1033
1608
|
const ACTIVITY_ORDER = {
|
|
1034
1609
|
dropped: 0,
|
|
@@ -1037,19 +1612,20 @@ const ACTIVITY_ORDER = {
|
|
|
1037
1612
|
};
|
|
1038
1613
|
function activeIds(ctx, json) {
|
|
1039
1614
|
if (!json) return [];
|
|
1040
|
-
const active = ctx.db.prepare("SELECT 1 FROM notes WHERE
|
|
1041
|
-
return JSON.parse(json).filter((
|
|
1615
|
+
const active = ctx.db.prepare("SELECT 1 FROM notes WHERE group_name IS ? AND number = ? AND dropped_at IS NULL");
|
|
1616
|
+
return JSON.parse(json).filter((number) => active.get(ctx.group, number) !== void 0);
|
|
1042
1617
|
}
|
|
1043
1618
|
function sessionNoteActivity(ctx, session) {
|
|
1044
|
-
const added = ctx.db.prepare(
|
|
1045
|
-
|
|
1619
|
+
const added = ctx.db.prepare(`SELECT number, kind, text, similar_notes, created_at FROM notes
|
|
1620
|
+
WHERE group_name IS ? AND session = ?`).all(ctx.group, session);
|
|
1621
|
+
const cited = ctx.db.prepare(`SELECT notes.number AS note, notes.kind, note_citations.why, note_citations.at
|
|
1046
1622
|
FROM note_citations JOIN notes ON notes.id = note_citations.note
|
|
1047
|
-
WHERE note_citations.session = ?`).all(session);
|
|
1048
|
-
const dropped = ctx.db.prepare(
|
|
1623
|
+
WHERE notes.group_name IS ? AND note_citations.session = ?`).all(ctx.group, session);
|
|
1624
|
+
const dropped = ctx.db.prepare(`SELECT ${NOTE_COLUMNS} FROM notes WHERE group_name IS ? AND dropped_session = ?`).all(ctx.group, session);
|
|
1049
1625
|
return [
|
|
1050
1626
|
...added.map((row) => ({
|
|
1051
1627
|
activity: "added",
|
|
1052
|
-
note: row.
|
|
1628
|
+
note: row.number,
|
|
1053
1629
|
kind: row.kind,
|
|
1054
1630
|
text: row.text,
|
|
1055
1631
|
similarNotes: activeIds(ctx, row.similar_notes),
|
|
@@ -1067,11 +1643,11 @@ function sessionNoteActivity(ctx, session) {
|
|
|
1067
1643
|
})),
|
|
1068
1644
|
...dropped.map((row) => ({
|
|
1069
1645
|
activity: "dropped",
|
|
1070
|
-
note: row.
|
|
1646
|
+
note: row.number,
|
|
1071
1647
|
kind: row.kind,
|
|
1072
1648
|
text: row.dropped_reason ?? "",
|
|
1073
1649
|
similarNotes: [],
|
|
1074
|
-
replacedBy: row.
|
|
1650
|
+
replacedBy: row.replaced_number,
|
|
1075
1651
|
at: row.dropped_at ?? ""
|
|
1076
1652
|
}))
|
|
1077
1653
|
].sort((first, second) => second.at.localeCompare(first.at) || ACTIVITY_ORDER[first.activity] - ACTIVITY_ORDER[second.activity] || second.note - first.note);
|
|
@@ -1140,7 +1716,7 @@ function notesFor(ctx, repos, general, halfLifeDays) {
|
|
|
1140
1716
|
return [...byId.values()].sort(compareNotes);
|
|
1141
1717
|
}
|
|
1142
1718
|
function groupTitle(group) {
|
|
1143
|
-
return `Rucher memory of the ${group.name} group
|
|
1719
|
+
return group ? `Rucher memory of the ${group.name} group` : "Rucher memory";
|
|
1144
1720
|
}
|
|
1145
1721
|
function sessionStartMemory(ctx, group, session, options = {}) {
|
|
1146
1722
|
const halfLifeDays = options.halfLifeDays ?? 20;
|
|
@@ -1179,229 +1755,6 @@ function repoMemory(ctx, session, repo, options = {}) {
|
|
|
1179
1755
|
function copyInjectedRepos(ctx, from, into) {
|
|
1180
1756
|
for (const repo of injectedRepos(ctx, from)) recordRepo(ctx, into, repo);
|
|
1181
1757
|
}
|
|
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
1758
|
// src/merge.ts
|
|
1406
1759
|
function namesOf(ctx, session) {
|
|
1407
1760
|
return ctx.db.prepare("SELECT name FROM agents WHERE session = ?").all(session).map((row) => row.name);
|
|
@@ -1450,7 +1803,7 @@ function purgeDays(value) {
|
|
|
1450
1803
|
return Number.isFinite(days) && days > 0 ? days : 3;
|
|
1451
1804
|
}
|
|
1452
1805
|
const PURGEABLE = `
|
|
1453
|
-
id != ? AND last_active_at < ?
|
|
1806
|
+
group_name IS ? AND id != ? AND last_active_at < ?
|
|
1454
1807
|
AND NOT EXISTS (
|
|
1455
1808
|
SELECT 1 FROM events WHERE events.session = sessions.id AND events.type NOT LIKE 'session.%'
|
|
1456
1809
|
)
|
|
@@ -1462,7 +1815,7 @@ function purgeSessions(ctx, keepId, days) {
|
|
|
1462
1815
|
const cutoff = (/* @__PURE__ */ new Date(ctx.now().getTime() - days * DAY_MILLISECONDS)).toISOString();
|
|
1463
1816
|
ctx.db.exec("BEGIN");
|
|
1464
1817
|
try {
|
|
1465
|
-
const ids = ctx.db.prepare(`SELECT id FROM sessions WHERE ${PURGEABLE}`).all(keepId, cutoff).map((row) => row.id);
|
|
1818
|
+
const ids = ctx.db.prepare(`SELECT id FROM sessions WHERE ${PURGEABLE}`).all(ctx.group, keepId, cutoff).map((row) => row.id);
|
|
1466
1819
|
for (const table of [
|
|
1467
1820
|
"table_items",
|
|
1468
1821
|
"agents",
|
|
@@ -1565,11 +1918,12 @@ function getTable(ctx, session) {
|
|
|
1565
1918
|
return row && toItem(row);
|
|
1566
1919
|
}
|
|
1567
1920
|
function setTable(ctx, session, input) {
|
|
1568
|
-
|
|
1921
|
+
const mainWorking = input.mainWorking ?? (input.status ? false : getTable(ctx, session)?.mainWorking ?? false);
|
|
1922
|
+
if (mainWorking && input.status) throw new CarnetError("TABLE_STATUS_WITH_MAIN_WORKING", "A user-action status cannot be set while main is working");
|
|
1569
1923
|
if (input.status !== void 0 && !isUserActionStatus(input.status)) throw new CarnetError("INVALID_STATUS", `Invalid table status "${String(input.status)}"`);
|
|
1570
1924
|
ctx.db.prepare(`INSERT INTO table_items (session, text, status, main_working, updated_at) VALUES (?, ?, ?, ?, ?)
|
|
1571
1925
|
ON CONFLICT(session) DO UPDATE SET text = excluded.text, status = excluded.status,
|
|
1572
|
-
main_working = excluded.main_working, updated_at = excluded.updated_at`).run(session, sanitizeNote(input.text), input.status ?? null,
|
|
1926
|
+
main_working = excluded.main_working, updated_at = excluded.updated_at`).run(session, sanitizeNote(input.text), input.status ?? null, mainWorking ? 1 : 0, nowIso(ctx));
|
|
1573
1927
|
return getTable(ctx, session);
|
|
1574
1928
|
}
|
|
1575
1929
|
function clearTable(ctx, session) {
|
|
@@ -1668,19 +2022,23 @@ var Carnet = class {
|
|
|
1668
2022
|
group;
|
|
1669
2023
|
db;
|
|
1670
2024
|
ctx;
|
|
1671
|
-
constructor(
|
|
2025
|
+
constructor(db, group, options = {}) {
|
|
1672
2026
|
this.group = group;
|
|
1673
2027
|
this.db = db;
|
|
1674
2028
|
this.ctx = {
|
|
1675
2029
|
db,
|
|
1676
|
-
now: options.now ?? (() => /* @__PURE__ */ new Date())
|
|
2030
|
+
now: options.now ?? (() => /* @__PURE__ */ new Date()),
|
|
2031
|
+
group: group?.name ?? null
|
|
1677
2032
|
};
|
|
1678
2033
|
}
|
|
2034
|
+
requireGroup() {
|
|
2035
|
+
return requireGroup(this.group);
|
|
2036
|
+
}
|
|
1679
2037
|
sessions = {
|
|
1680
2038
|
get: (id) => getSession(this.ctx, id),
|
|
1681
2039
|
find: (reference) => findSession(this.ctx, reference),
|
|
1682
2040
|
require: (id) => requireSession(this.ctx, id),
|
|
1683
|
-
ensure: (id, cwd) => ensureSession(this.ctx, id, cwd, this.group),
|
|
2041
|
+
ensure: (id, cwd) => ensureSession(this.ctx, id, cwd, this.group ?? void 0),
|
|
1684
2042
|
upsertFromHook: (payload, env) => upsertFromHook(this.ctx, this.group, payload, env),
|
|
1685
2043
|
touch: (id) => touchSession(this.ctx, id),
|
|
1686
2044
|
merge: (fromId, intoId) => mergeSessions(this.ctx, fromId, intoId),
|
|
@@ -1754,11 +2112,32 @@ var Carnet = class {
|
|
|
1754
2112
|
this.db.close();
|
|
1755
2113
|
}
|
|
1756
2114
|
};
|
|
2115
|
+
function openStore(options) {
|
|
2116
|
+
const path = options.dbPath ?? databasePath(options.env);
|
|
2117
|
+
if (path !== ":memory:") mkdirSync(dirname(path), { recursive: true });
|
|
2118
|
+
return openDatabase(path);
|
|
2119
|
+
}
|
|
1757
2120
|
function openCarnet(options = {}) {
|
|
1758
|
-
return
|
|
2121
|
+
return openResolvedCarnet(options).carnet;
|
|
2122
|
+
}
|
|
2123
|
+
function openResolvedCarnet(options = {}) {
|
|
2124
|
+
const db = openStore(options);
|
|
2125
|
+
try {
|
|
2126
|
+
const resolution = resolveGroup({
|
|
2127
|
+
...options,
|
|
2128
|
+
db
|
|
2129
|
+
});
|
|
2130
|
+
return {
|
|
2131
|
+
carnet: new Carnet(db, resolution.group, options),
|
|
2132
|
+
resolution
|
|
2133
|
+
};
|
|
2134
|
+
} catch (error) {
|
|
2135
|
+
db.close();
|
|
2136
|
+
throw error;
|
|
2137
|
+
}
|
|
1759
2138
|
}
|
|
1760
2139
|
function openGroupCarnet(group, options = {}) {
|
|
1761
|
-
return new Carnet(
|
|
2140
|
+
return new Carnet(openStore(options), group, options);
|
|
1762
2141
|
}
|
|
1763
2142
|
// src/resume.ts
|
|
1764
2143
|
const RESUME_EVENTS = 20;
|
|
@@ -1787,6 +2166,69 @@ function resumeContext(carnet, session, { events = 20, maxCharacters = RESUME_MA
|
|
|
1787
2166
|
}
|
|
1788
2167
|
return text.length > maxCharacters ? `${text.slice(0, maxCharacters - 1)}…` : text;
|
|
1789
2168
|
}
|
|
1790
|
-
|
|
2169
|
+
// src/steps.ts
|
|
2170
|
+
const AGENT_STEPS = [
|
|
2171
|
+
"answered",
|
|
2172
|
+
"applying",
|
|
2173
|
+
"applied",
|
|
2174
|
+
"tested",
|
|
2175
|
+
"committed",
|
|
2176
|
+
"dropped"
|
|
2177
|
+
];
|
|
2178
|
+
const DEFAULT_NEXT = {
|
|
2179
|
+
answered: "apply",
|
|
2180
|
+
applied: "test",
|
|
2181
|
+
tested: "commit"
|
|
2182
|
+
};
|
|
2183
|
+
function tableIsAbout(carnet, session, name) {
|
|
2184
|
+
const text = carnet.table.get(session)?.text;
|
|
2185
|
+
return text?.startsWith(name) === true && !/[\w-]/.test(text.charAt(name.length));
|
|
2186
|
+
}
|
|
2187
|
+
function clearTableOf(carnet, session, name) {
|
|
2188
|
+
if (tableIsAbout(carnet, session, name)) carnet.table.clear(session);
|
|
2189
|
+
}
|
|
2190
|
+
function stepAgent(carnet, session, input) {
|
|
2191
|
+
const { name, step, commit, note } = input;
|
|
2192
|
+
if (!carnet.agents.get(session, name)) throw new CarnetError("AGENT_NOT_FOUND", `No agent "${name}" in this session`);
|
|
2193
|
+
switch (step) {
|
|
2194
|
+
case "applying":
|
|
2195
|
+
carnet.table.set(session, {
|
|
2196
|
+
text: `${name} applying`,
|
|
2197
|
+
mainWorking: true
|
|
2198
|
+
});
|
|
2199
|
+
return `⚙️ ${name} applying`;
|
|
2200
|
+
case "committed":
|
|
2201
|
+
if (!commit) throw new CarnetError("COMMIT_REQUIRED", "The committed step needs the commit");
|
|
2202
|
+
carnet.events.log(session, {
|
|
2203
|
+
type: "committed",
|
|
2204
|
+
agent: name,
|
|
2205
|
+
commit,
|
|
2206
|
+
note
|
|
2207
|
+
});
|
|
2208
|
+
carnet.agents.drop(session, name, `committed ${commit}`);
|
|
2209
|
+
clearTableOf(carnet, session, name);
|
|
2210
|
+
return `${EMOJI.commit} ${name} committed ${commit}, closed`;
|
|
2211
|
+
case "dropped":
|
|
2212
|
+
carnet.agents.drop(session, name, note);
|
|
2213
|
+
clearTableOf(carnet, session, name);
|
|
2214
|
+
return `${name} dropped, closed`;
|
|
2215
|
+
default: {
|
|
2216
|
+
const next = input.next ?? DEFAULT_NEXT[step];
|
|
2217
|
+
carnet.events.log(session, {
|
|
2218
|
+
type: step,
|
|
2219
|
+
agent: name,
|
|
2220
|
+
note
|
|
2221
|
+
});
|
|
2222
|
+
carnet.agents.update(session, name, { status: next });
|
|
2223
|
+
if (next === "running") clearTableOf(carnet, session, name);
|
|
2224
|
+
else if (step !== "answered") carnet.table.set(session, {
|
|
2225
|
+
text: `${name} ${step}, ${next} next`,
|
|
2226
|
+
status: next
|
|
2227
|
+
});
|
|
2228
|
+
return `logged ${step} · ${EMOJI[next]} ${name} ${next}`;
|
|
2229
|
+
}
|
|
2230
|
+
}
|
|
2231
|
+
}
|
|
2232
|
+
export { createGroup as $, migrations as $t, memoryMaxCharacters as A, appendPromptFile as At, memoryHalfLife as B, shortId as Bt, renderNotesSummary as C, mergeSettings as Ct, DEFAULT_PURGE_DAYS as D, PROMPT_FILE as Dt, renderTableLine as E, OUTSIDE_RUCHER_NOTICE as Et, NOTE_TEXT_LIMIT as F, outsideRucherContext as Ft, isInside as G, groupsDirectory as Gt, similarity as H, databasePath as Ht, STALE_AFTER_ACTIVE_DAYS as I, rulesText as It, requireGroup as J, reportsDirectory as Jt, repoNameFor as K, promptsDirectory as Kt, groupRepoNames as L, rulesVersion as Lt, DEFAULT_HALF_LIFE_DAYS as M, baseRules as Mt, DUPLICATE_SIMILARITY as N, compactReminder as Nt, purgeDays as O, RULES_UPDATED_NOTICE as Ot, NOTE_KINDS as P, groupRules as Pt, addGroupRepo as Q, migrate as Qt, isNoteKind as R, CORE_RULES as Rt, renderNotes as S, markdownCopy as St, renderStatus as T, writeGenerated as Tt, ambiguousGroupContext as U, defaultWorkspace as Ut, sessionNoteActivity as V, corePromptPath as Vt, groupLabel as W, groupSource as Wt, GROUP_FILE as X, MEMORY_DB as Xt, resolveGroup as Y, rucherPaths as Yt, INSTRUCTIONS_FILE as Z, openDatabase as Zt, NOTES_FOLD_LINES as _, claudeCode as _t, formatEventLine as a, AGENT_STATUSES as an, listGroups as at, renderAgentLine as b, GENERATED_MARKER as bt, Carnet as c, MAIN_WORKING_EMOJI as cn, renameGroup as ct, openResolvedCarnet as d, isAgentStatus as dn, groupSessionCounts as dt, schemaVersion as en, dropGroup as et, PAIRING_WINDOW_MILLISECONDS as f, isUserActionStatus as fn, renameGroupRows as ft, MAIN_WORKING_SUFFIX as g, CarnetError as gn, hostById as gt, formatClock as h, isEventType as hn, allHosts as ht, RESUME_MAX_CHARACTERS as i, sanitizeNote as in, isGroupName as it, renderMemory as j, assemblePrompt as jt, MEMORY_MAX_CHARACTERS as k, SUBAGENT_RULES as kt, openCarnet as l, OPEN_AGENT_STATUSES as ln, archiveGroupSessions as lt, buildStatusView as m, SESSION_EVENT_TYPES as mn, DEFAULT_HOST as mt, stepAgent as n, REPORTING_NOTE as nn, groupExists as nt, resumeContext as o, EMOJI as on, loadGroup as ot, STOPPED_NOTE as p, EVENT_TYPES as pn, sessionGroupName as pt, repoPathFor as q, reportPath as qt, RESUME_EVENTS as r, NOTE_MAX as rn, groupHosts as rt, sessionLabel as s, LEGEND as sn, removeGroupRepo as st, AGENT_STEPS as t, PUBLISH_FALLBACK_MILLISECONDS as tn, expandHome as tt, openGroupCarnet as u, USER_ACTION_STATUSES as un, deleteGroupNotes as ut, NOTES_HEADER as v, groupSettings as vt, renderSections as w, removeStaleCopies as wt, renderNoteLine as x, MARKDOWN_MARKER as xt, SIMILAR_PREFIX as y, transcriptTitle as yt, localDay as z, MINIMUM_ID_PREFIX as zt };
|
|
1791
2233
|
|
|
1792
|
-
//# sourceMappingURL=
|
|
2234
|
+
//# sourceMappingURL=steps-U_Ge5YFh.mjs.map
|