@rucher/carnet 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,14 +1,15 @@
1
- import { $ as renderMemory, $n as LEGEND, $t as outsideRucherContext, A as TURNS, An as sandboxesDirectory, At as claudeCode, B as renderAgentLine, Bt as MARKDOWN_MARKER, C as openCarnet, Cn as corePromptPath, Ct as sessionWorkspaceName, D as STOPPED_NOTE, Dn as reportPath, Dt as DEFAULT_HOST, E as PAIRING_WINDOW_MILLISECONDS, En as promptsDirectory, Et as workspaceSessionCounts, F as MAIN_WAITING_SUFFIX, Fn as migrate, Ft as UndoList, G as renderSections, Gn as statusWhenDone, Gt as OUTSIDE_RUCHER_NOTICE, H as renderNoteLine, Hn as REPORTING_NOTE, Ht as mergeSettings, I as MAIN_WORKING_SUFFIX, In as migrations, It as moveTracked, J as DEFAULT_PURGE_DAYS, Jn as AGENT_STATUSES, Jt as SUBAGENT_RULES, K as renderStatus, Kn as NOTE_MAX, Kt as PROMPT_FILE, L as NOTES_FOLD_LINES, Ln as schemaVersion, Lt as relocateFailed, M as MAIN_FAILED_SUFFIX, Mn as workspacesDirectory, Mt as claudeProjectFolder, N as MAIN_HEADER, Nn as MEMORY_DB, Nt as transcriptTitle, O as buildStatusView, On as reportsDirectory, Ot as allHosts, P as MAIN_IDLE, Pn as openDatabase, Pt as workspaceSettings, Q as memoryMaxCharacters, Qn as KIND_TAG_PATTERN, Qt as compactReminder, R as NOTES_HEADER, Rn as AGENT_KINDS, Rt as shellQuote, S as Carnet, St as runningWorkspaceSessions, T as openWorkspaceCarnet, Tn as defaultRunDirectory, Tt as workspaceRowCounts, U as renderNotes, Un as SANDBOX_KINDS, Ut as removeStaleCopies, V as renderMainLine, Vn as PUBLISH_FALLBACK_MILLISECONDS, Vt as markdownCopy, W as renderNotesSummary, Wn as isAgentKind, Wt as writeGenerated, Xn as KIND_ABBREVIATIONS, Xt as assemblePrompt, Y as purgeDays, Yn as EMOJI, Yt as appendPromptFile, Z as MEMORY_MAX_CHARACTERS, Zn as KIND_LEGEND, Zt as baseRules, _n as removeWorkspaceRepo, _t as archiveWorkspaceSessions, a as formatEventLine, an as shortId, ar as isAgentStatus, at as isNoteKind, bt as nextNoteNumber, cn as WORKSPACE_FILE, cr as EVENT_TYPES, ct as sessionNoteActivity, dn as definitionInstructions, dr as CarnetError, dt as isInside, en as rulesText, er as MAIN_FAILED_EMOJI, et as DEFAULT_HALF_LIFE_DAYS, fn as dropWorkspace, ft as repoNameFor, g as nextAgent, gn as loadWorkspace, gt as workspaceLabel, h as locateAgent, hn as listWorkspaces, ht as resolveWorkspace, i as RESUME_MAX_CHARACTERS, in as MINIMUM_ID_PREFIX, ir as USER_ACTION_STATUSES, it as STALE_AFTER_ACTIVE_DAYS, j as BLOCKED_HEADER, jn as workspaceDefinition, jt as claudeConfigFile, k as formatClock, kn as rucherPaths, kt as hostById, ln as addWorkspaceRepo, lr as SESSION_EVENT_TYPES, lt as similarity, mn as isWorkspaceName, mt as requireWorkspace, n as stepAgent, nn as workspaceRules, nr as MAIN_WORKING_EMOJI, nt as NOTE_KINDS, o as resumeContext, on as AGENTS_FILE, or as isUserActionStatus, ot as localDay, pn as expandHome, pt as repoPathFor, q as renderTableLine, qn as sanitizeNote, qt as RULES_UPDATED_NOTICE, r as RESUME_EVENTS, rn as CORE_RULES, rt as NOTE_TEXT_LIMIT, s as sessionLabel, sn as INSTRUCTIONS_FILE, sr as kindTag, st as memoryHalfLife, t as AGENT_STEPS, tn as rulesVersion, tr as MAIN_WAITING_EMOJI, tt as DUPLICATE_SIMILARITY, u as findingsBrief, un as createWorkspace, ur as isEventType, ut as workspaceRepoNames, vn as workspaceExists, vt as deleteWorkspaceNotes, w as openResolvedCarnet, wn as databasePath, wt as workspaceLastActive, xt as renameWorkspaceRows, y as reportDocument, yn as workspaceHosts, yt as mergeWorkspaceRows, z as SIMILAR_PREFIX, zn as KIND_REQUIRED, zt as GENERATED_MARKER } from "./steps-DfvHqzF0.mjs";
1
+ import { $ as searchQuery, $n as definitionInstructions, $r as statusWhenDone, $t as workspaceRowCounts, A as resumeSummary, Ai as sessionNoteActivity, An as RULES_UPDATED_NOTICE, Ar as reportsDirectory, At as migrations, B as locateAgent, Bi as recommendedThen, Bn as workspaceRules, Bt as repoPathFor, C as builtInProfileSource, Ci as DUPLICATE_SIMILARITY, Cn as MARKDOWN_MARKER, Cr as isLeaf, Ct as DEFAULT_PURGE_DAYS, D as RESUME_MAX_CHARACTERS, Di as isNoteKind, Dn as writeGenerated, Dr as defaultRunDirectory, Dt as MEMORY_DB, E as RESUME_EVENTS, Ei as STALE_AFTER_ACTIVE_DAYS, En as removeStaleCopies, Er as databasePath, Et as agentMergePlan, Fi as attachmentInput, Fn as compactReminder, Fr as workspacesDirectory, Ft as planAsAnswered, Gn as workspaceContext, Gr as KIND_MODES, Gt as deleteWorkspaceNotes, Hi as CarnetError, Hn as CLAUDE_NATIVE_FILES, Ht as resolveWorkspace, Ii as attachments, In as contextText, Ir as MEMORY_MAX_CHARACTERS, It as MINIMUM_ID_PREFIX, J as openResolvedCarnet, Jn as INSTRUCTIONS_FILE, Jr as PUBLISH_FALLBACK_MILLISECONDS, Jt as realPathOf, K as Carnet, Kn as CORE_RULES, Kr as KIND_REQUIRED, Kt as mergeWorkspaceRows, L as forkStartContext, Li as attachmentsInput, Ln as outsideRucherContext, Lr as memoryMaxCharacters, Lt as shortId, M as AGENT_BRIEF_HINT, Mi as workspaceRepoNames, Mn as appendPromptFile, Mr as sandboxesDirectory, Mt as SEARCH_TRIGGERS, Ni as DELIVERABLES, Nn as assemblePrompt, Nr as serverSocketPath, Nt as SEARCH_TRIGGER_NAMES, O as formatEventLine, Oi as localDay, On as OUTSIDE_RUCHER_NOTICE, Or as promptsDirectory, Ot as openDatabase, Pi as attachment, Pn as baseRules, Pr as workspaceDefinition, Pt as buildBrief, Q as SNIPPET_OPEN, Qn as createWorkspace, Qr as isAgentKind, Qt as workspaceLastActive, Ri as deliverable, Rn as rulesText, Rr as renderMemory, Rt as isInside, S as DEFAULT_PROFILE, Si as DEFAULT_HALF_LIFE_DAYS, Sn as GENERATED_MARKER, Sr as GESTURES, St as renderTableLine, T as stepAgent, Ti as NOTE_TEXT_LIMIT, Tn as mergeSettings, Tr as corePromptPath, Un as REPO_INSTRUCTION_FILES, Ur as AGENT_KINDS, Ut as workspaceLabel, V as nextAgent, Vi as snapshot, Vn as CLAUDE_BACKEND_NOTES, Vt as requireWorkspace, W as reportDocument, Wn as contextAppend, Wr as CLAUDE_BACKEND, Wt as archiveWorkspaceSessions, X as SEARCH_LIMITS, Xn as WORKSPACE_FILE, Xr as SANDBOX_KINDS, Xt as runningWorkspaceSessions, Y as openWorkspaceCarnet, Yn as REPO_INSTRUCTIONS_DIRECTORY, Yr as REPORTING_NOTE, Yt as renameWorkspaceRows, Z as SNIPPET_CLOSE, Zn as addWorkspaceRepo, Zr as agentMode, Zt as sessionWorkspaceName, _ as LAYERS, _i as SESSION_EVENT_TYPES, _n as transcriptTitle, _r as readJson, _t as renderNoteLine, a as loadProfiles, ai as KIND_LEGEND, an as launchHost, ar as migrateInstructions, at as TURNS, b as BUILT_IN_PROFILE_NAMES, bi as formatBytes, bn as relocateFailed, br as DECIDER_PROVIDERS, bt as renderSections, c as profileSource, ci as MAIN_FAILED_EMOJI, cn as workspaceSettings, cr as repoInstructionsPath, ct as MAIN_HEADER, d as branchProblems, dn as claudeLastContext, dr as workspaceExists, dt as MAIN_WORKING_SUFFIX, ei as NOTE_MAX, en as workspaceSessionCounts, er as dropWorkspace, et as transcriptsIndexed, f as effectiveRun, fi as USER_ACTION_STATUSES, fn as claudeTranscriptUsage, fr as workspaceFileHosts, ft as NOTES_FOLD_LINES, g as sourceLabel, gi as EVENT_TYPES, gn as claudeProjectFolder, gr as loadGlobalConfig, gt as renderMainLine, h as resolveRun, hi as kindTag, hn as claudeConfigFile, hr as globalConfigPath, ht as renderAgentLine, i as PROFILES_DIRECTORY, ii as KIND_ABBREVIATIONS, in as hostById, ir as loadWorkspace, it as formatClock, j as sessionLabel, ji as similarity, jn as SUBAGENT_RULES, jr as rucherPaths, jt as schemaVersion, k as resumeContext, ki as memoryHalfLife, kn as PROMPT_FILE, kr as reportPath, kt as migrate, l as profileValues, li as MAIN_WAITING_EMOJI, ln as claudeCodeLaunch, lr as serializeWorkspaceFile, lt as MAIN_IDLE, m as resolveConfig, mi as isUserActionStatus, mn as claudeCodeHooks, mr as CONFIG_FILE, mt as SIMILAR_PREFIX, n as formatTokens, ni as AGENT_STATUSES, nn as allHosts, nr as isWorkspaceName, nt as STOPPED_NOTE, o as profileDirectories, oi as KIND_TAG_PATTERN, on as rucherServer, or as removeWorkspaceRepo, ot as BLOCKED_HEADER, p as overlay, pi as isAgentStatus, pn as readClaudeTranscript, pr as workspaceHosts, pt as NOTES_HEADER, q as openCarnet, qn as AGENTS_FILE, qt as nextNoteNumber, r as formatUsage, ri as EMOJI, rn as hookHost, rr as listWorkspaces, rt as buildStatusView, s as profileLookup, si as LEGEND, sn as claudeCode, sr as repoInstructionFiles, st as MAIN_FAILED_SUFFIX, t as eventUsage, ti as sanitizeNote, tn as DEFAULT_HOST, tr as expandHome, tt as PAIRING_WINDOW_MILLISECONDS, u as CONFIG_LEVELS, ui as MAIN_WORKING_EMOJI, un as claudeLiveSession, ur as usableWorkspaceConfig, ut as MAIN_WAITING_SUFFIX, v as loadLayered, vi as isEventType, vn as UndoList, vr as workspaceConfig, vt as renderNotes, w as AGENT_STEPS, wi as NOTE_KINDS, wn as markdownCopy, wr as parseConfig, wt as purgeDays, x as BUILT_IN_PROFILE_NOTES, xi as referenceLine, xn as shellQuote, xr as DECISION_USAGES, xt as renderStatus, y as parseFrontmatter, yi as REFERENCE_SCOPES, yn as moveTracked, yr as BACKENDS, yt as renderNotesSummary, zi as produced, zn as rulesVersion, zt as repoNameFor } from "./usage-D3xjR_RF.mjs";
2
2
  import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
4
- import { homedir } from "node:os";
4
+ import { homedir, tmpdir } from "node:os";
5
+ import { randomUUID } from "node:crypto";
5
6
  import { execFileSync } from "node:child_process";
6
7
  // src/move.ts
7
8
  function count(carnet, sql, ...parameters) {
8
9
  return Number(carnet.db.prepare(sql).get(...parameters).total);
9
10
  }
10
11
  function agentNames(carnet, session) {
11
- return carnet.db.prepare("SELECT name FROM agents WHERE session = ? ORDER BY started_at, rowid").all(session).map((row) => row.name);
12
+ return [...new Set(carnet.db.prepare("SELECT name FROM agents WHERE session = ? ORDER BY started_at, id").all(session).map((row) => row.name))];
12
13
  }
13
14
  function sessionNamed(carnet, workspace, name) {
14
15
  const row = carnet.db.prepare("SELECT id FROM sessions WHERE workspace = ? AND name = ?").get(workspace, name);
@@ -20,14 +21,13 @@ function moveSession(carnet, sessionId, targetWorkspace, options = {}) {
20
21
  if (session.workspace === targetWorkspace) throw new CarnetError("SESSION_MOVE_INVALID", "The session is already in this workspace");
21
22
  const into = session.name ? sessionNamed(carnet, targetWorkspace, session.name) : null;
22
23
  if (into && !options.merge) throw new CarnetError("SESSION_NAME_TAKEN", `Workspace ${targetWorkspace} already has session ${into.name}: pass --merge to merge into it`);
23
- const agents = agentNames(carnet, session.id);
24
- const taken = new Set(into ? agentNames(carnet, into.id) : []);
24
+ const plan = into ? agentMergePlan(carnet.db, session.id, into.id) : void 0;
25
25
  const hasTable = (id) => carnet.db.prepare("SELECT 1 FROM table_items WHERE session = ?").get(id) !== void 0;
26
26
  const result = {
27
27
  session,
28
28
  into,
29
- movedAgents: agents.filter((name) => !taken.has(name)),
30
- skippedAgents: agents.filter((name) => taken.has(name)),
29
+ movedAgents: plan?.moved ?? agentNames(carnet, session.id),
30
+ skippedAgents: plan?.closed.map((agent) => agent.name) ?? [],
31
31
  movedEvents: count(carnet, "SELECT COUNT(*) AS total FROM events WHERE session = ?", session.id),
32
32
  movedTable: hasTable(session.id) && !(into && hasTable(into.id)),
33
33
  keptNotes: count(carnet, "SELECT COUNT(*) AS total FROM notes WHERE session = ? OR dropped_session = ?", session.id, session.id)
@@ -44,8 +44,10 @@ function renderRunDirectory(workspace, options = {}) {
44
44
  const result = {
45
45
  runDirectory: workspace.runDirectory,
46
46
  written: [],
47
- removed: []
47
+ removed: [],
48
+ notices: []
48
49
  };
50
+ if (migrateInstructions(workspace)) result.notices.push(`renamed ${INSTRUCTIONS_FILE} to ${AGENTS_FILE} in the definition of ${workspace.name}`);
49
51
  for (const id of options.host ? [options.host] : workspaceHosts(workspace)) {
50
52
  const rendered = hostById(id).renderRunDirectory(workspace);
51
53
  result.written.push(...rendered.written);
@@ -187,10 +189,10 @@ function rewriteName(definition, name) {
187
189
  const file = join(definition, WORKSPACE_FILE);
188
190
  const content = JSON.parse(readFileSync(file, "utf8"));
189
191
  if (!("name" in content)) return;
190
- writeFileSync(file, `${JSON.stringify({
192
+ writeFileSync(file, serializeWorkspaceFile({
191
193
  ...content,
192
194
  name
193
- }, null, 2)}\n`);
195
+ }));
194
196
  }
195
197
  function renameWorkspace(db, from, to, options) {
196
198
  const env = options.env ?? process.env;
@@ -207,6 +209,7 @@ function renameWorkspace(db, from, to, options) {
207
209
  const hosts = workspaceHosts(workspace).map((id) => hostById(id));
208
210
  const undo = new UndoList();
209
211
  let paths = 0;
212
+ const realFrom = realPathOf(runDirectories.from);
210
213
  try {
211
214
  for (const move of plan.moves) if (move.what === "run directory") moveWithTrees(undo, move, plan.trees);
212
215
  else moveTracked(undo, move);
@@ -223,7 +226,7 @@ function renameWorkspace(db, from, to, options) {
223
226
  paths = renameWorkspaceRows(db, {
224
227
  from,
225
228
  to
226
- }, runDirectories).paths;
229
+ }, runDirectories, realFrom).paths;
227
230
  } catch (error) {
228
231
  relocateFailed(error, undo, backup);
229
232
  }
@@ -288,8 +291,12 @@ function conflicts(base, extra, path = []) {
288
291
  return JSON.stringify(base) === JSON.stringify(extra) ? [] : [path.join(".")];
289
292
  }
290
293
  function settingsOf(file) {
291
- const { name: _name, repos: _repos, ...rest } = file;
292
- return rest;
294
+ const { name: _name, repos: _repos, backends: _backends, ...rest } = file;
295
+ const hosts = workspaceFileHosts(file);
296
+ return Object.keys(hosts).length ? {
297
+ ...rest,
298
+ hosts
299
+ } : rest;
293
300
  }
294
301
  function reportMoves(from, into) {
295
302
  const source = join(from.runDirectory, "reports");
@@ -363,7 +370,7 @@ function planWorkspaceMerge(db, fromName, intoName, options) {
363
370
  if (names.length) throw new CarnetError("SESSION_NAME_TAKEN", `${intoName} already has sessions named ${names.join(", ")}: rename them in ${fromName} first (rucher sessions rename <name> <new> --ws ${fromName})`);
364
371
  const repos = repoPlan(from, into);
365
372
  const instructions = definitionInstructions(from);
366
- if (instructions !== definitionInstructions(into)) throw new CarnetError("WORKSPACE_INSTRUCTIONS_CONFLICT", `${fromName} keeps its instructions in ${instructions} and ${intoName} in ${definitionInstructions(into)}: use the same file in both first`);
373
+ definitionInstructions(into);
367
374
  const rows = workspaceRowCounts(db, fromName);
368
375
  const firstNumber = nextNoteNumber(db, intoName);
369
376
  const trees = treeMoves(db, from, into);
@@ -382,9 +389,17 @@ function planWorkspaceMerge(db, fromName, intoName, options) {
382
389
  sandboxes: sandboxMoves(from, into),
383
390
  trees,
384
391
  files: fileMoves(from, into, trees),
385
- instructions
392
+ instructions,
393
+ repoInstructions: repoInstructionMoves(from, into, repos.renamed)
386
394
  };
387
395
  }
396
+ function repoInstructionMoves(from, into, renamed) {
397
+ const names = new Map(renamed);
398
+ return repoInstructionFiles(from).map((file) => ({
399
+ from: file.path,
400
+ to: repoInstructionsPath(into, names.get(file.repo) ?? file.repo)
401
+ }));
402
+ }
388
403
  function appendUnder(target, source, heading) {
389
404
  if (!existsSync(source)) return;
390
405
  const added = readFileSync(source, "utf8").trim();
@@ -393,17 +408,39 @@ function appendUnder(target, source, heading) {
393
408
  const current = existsSync(target) ? readFileSync(target, "utf8").trimEnd() : "";
394
409
  writeFileSync(target, `${current ? `${current}\n\n` : ""}${heading}\n\n${added}\n`);
395
410
  }
411
+ function isRecord(value) {
412
+ return typeof value === "object" && value !== null && !Array.isArray(value);
413
+ }
414
+ function normalizeRun(settings) {
415
+ const run = settings.run;
416
+ if (!isRecord(run)) return settings;
417
+ const { default: fallback, kinds, ...shorthand } = run;
418
+ const named = isRecord(kinds) ? kinds : {};
419
+ const mergedKinds = {
420
+ ...shorthand,
421
+ ...named
422
+ };
423
+ const next = {};
424
+ if (fallback !== void 0) next.default = fallback;
425
+ if (Object.keys(mergedKinds).length > 0) next.kinds = mergedKinds;
426
+ return {
427
+ ...settings,
428
+ run: next
429
+ };
430
+ }
396
431
  function writeDefinition(from, into, plan) {
397
432
  const fromFile = readFile(from);
398
433
  const intoFile = readFile(into);
399
434
  const merged = {
400
- ...mergeSettings(settingsOf(fromFile), settingsOf(intoFile)),
435
+ ...mergeSettings(normalizeRun(settingsOf(fromFile)), normalizeRun(settingsOf(intoFile)), isLeaf),
401
436
  name: into.name,
402
437
  repos: [...intoFile.repos ?? [], ...(fromFile.repos ?? []).filter((_, index) => plan.reposAdded.includes(from.repos[index]?.path ?? ""))]
403
438
  };
404
- writeFileSync(join(into.definition, WORKSPACE_FILE), `${JSON.stringify(merged, null, 2)}\n`);
439
+ writeFileSync(join(into.definition, WORKSPACE_FILE), serializeWorkspaceFile(merged));
405
440
  const heading = `## Ex-workspace ${from.name}`;
406
- appendUnder(join(into.definition, plan.instructions), join(from.definition, plan.instructions), heading);
441
+ migrateInstructions(into);
442
+ appendUnder(join(into.definition, AGENTS_FILE), join(from.definition, plan.instructions), heading);
443
+ for (const move of plan.repoInstructions) appendUnder(move.to, move.from, heading);
407
444
  appendUnder(join(into.definition, BACKENDS_NOTES), join(from.definition, BACKENDS_NOTES), heading);
408
445
  }
409
446
  function moveAway(from, to) {
@@ -431,6 +468,7 @@ function mergeWorkspaces(db, fromName, intoName, options) {
431
468
  const hosts = workspaceHosts(from).map((id) => hostById(id));
432
469
  const undo = new UndoList();
433
470
  let projectMoves = 0;
471
+ const realFrom = realPathOf(from.runDirectory);
434
472
  try {
435
473
  for (const host of hosts) {
436
474
  const relocation = host.relocateProject?.(from.runDirectory, into.runDirectory, env, "merge");
@@ -471,7 +509,8 @@ function mergeWorkspaces(db, fromName, intoName, options) {
471
509
  into: into.runDirectory
472
510
  },
473
511
  paths: renamed,
474
- repos: new Map(plan.reposRenamed)
512
+ repos: new Map(plan.reposRenamed),
513
+ realFrom
475
514
  });
476
515
  } catch (error) {
477
516
  relocateFailed(error, undo, backup);
@@ -501,7 +540,7 @@ function mergeWorkspaces(db, fromName, intoName, options) {
501
540
  backup,
502
541
  projectMoves,
503
542
  trustDropped,
504
- instructionsPath: join(into.definition, plan.instructions),
543
+ instructionsPath: join(into.definition, AGENTS_FILE),
505
544
  warnings
506
545
  };
507
546
  }
@@ -525,7 +564,6 @@ function adoptFork(carnet, session, env) {
525
564
  const parentId = env.RUCHER_SESSION_ID;
526
565
  if (!parentId || parentId === session.id || !carnet.sessions.get(parentId)) return session;
527
566
  let fork = carnet.sessions.setParent(session.id, parentId);
528
- carnet.memory.copyRepos(parentId, session.id);
529
567
  const kind = env.RUCHER_SESSION_KIND;
530
568
  if (kind === "active" || kind === "temp") fork = carnet.sessions.setKind(session.id, kind, env.RUCHER_SESSION_NAME || null);
531
569
  return fork;
@@ -535,8 +573,7 @@ function adoptContinuation(carnet, session, env) {
535
573
  const parent = parentId && parentId !== session.id ? carnet.sessions.get(parentId) : void 0;
536
574
  if (!parent) return void 0;
537
575
  const hostEnv = env.CLAUDE_CONFIG_DIR ? { CLAUDE_CONFIG_DIR: env.CLAUDE_CONFIG_DIR } : {};
538
- if (!hostById(session.host).continues(parent, session.id, hostEnv)) return void 0;
539
- carnet.memory.copyRepos(parent.id, session.id);
576
+ if (!hostById(session.host).launch?.continues(parent, session.id, hostEnv)) return void 0;
540
577
  let merged = carnet.sessions.merge(parent.id, session.id).session;
541
578
  merged = carnet.sessions.recordPromptVersion(merged.id, parent.promptVersion);
542
579
  return parent.parentId ? carnet.sessions.setParent(merged.id, parent.parentId) : merged;
@@ -546,8 +583,24 @@ function startMemory(carnet, session, source, env) {
546
583
  maxCharacters: memoryMaxCharacters(env.RUCHER_MEMORY_MAX_CHARACTERS),
547
584
  halfLifeDays: memoryHalfLife(env.RUCHER_MEMORY_HALF_LIFE_DAYS)
548
585
  };
549
- if (source === "startup" || source === "clear") return carnet.memory.atStart(session, options);
550
- if (source === "resume" || source === "compact") return carnet.memory.ofSession(session, options);
586
+ if (source === "startup" || source === "clear" || source === "compact") return carnet.memory.atStart(session, options);
587
+ }
588
+ function invalidConfigNotice(problem) {
589
+ return `rucher: workspace config ignored, cold agents refused until it is fixed (rucher config check): ${problem}`;
590
+ }
591
+ const LISTED_REFERENCES = 10;
592
+ function listedReferences(carnet, session) {
593
+ try {
594
+ return carnet.references.list(session);
595
+ } catch {
596
+ return [];
597
+ }
598
+ }
599
+ function referencesContext(carnet, session) {
600
+ const references = listedReferences(carnet, session);
601
+ if (!references.length) return void 0;
602
+ const more = references.length > LISTED_REFERENCES ? ", ref_list for the rest" : "";
603
+ return [`Reference documents of this session (${references.length}${more}), read them when the work needs them:`, ...references.slice(0, LISTED_REFERENCES).map((reference) => ` ${referenceLine(reference)}`)].join("\n");
551
604
  }
552
605
  function handleSessionStart(carnet, payload, env) {
553
606
  let session = carnet.sessions.upsertFromHook(payload, env);
@@ -568,15 +621,19 @@ function handleSessionStart(carnet, payload, env) {
568
621
  const launchedVersion = env.RUCHER_PROMPT_VERSION || null;
569
622
  const contextParts = [];
570
623
  const notices = [];
571
- if (hostById(session.host).rendersSystemPrompt(source)) session = carnet.sessions.recordPromptVersion(session.id, launchedVersion);
572
- if (source === "resume") contextParts.push(resumeContext(carnet, session));
624
+ if (hostById(session.host).hooks?.rendersSystemPrompt(source)) session = carnet.sessions.recordPromptVersion(session.id, launchedVersion);
625
+ if (source === "resume") contextParts.push(resumeSummary(carnet, session));
573
626
  const memory = startMemory(carnet, session, source, env);
574
627
  if (memory) contextParts.push(memory);
628
+ const references = referencesContext(carnet, session.id);
629
+ if (references) contextParts.push(references);
575
630
  if (source === "compact" && !launchedVersion) contextParts.push(compactReminder(carnet.workspace, promptEnv));
576
631
  else if (!env.RUCHER_SESSION_ID && !session.promptVersion) {
577
632
  contextParts.push(outsideRucherContext(carnet.workspace, promptEnv));
578
633
  notices.push(OUTSIDE_RUCHER_NOTICE);
579
634
  } else if (session.promptVersion && session.promptVersion !== rulesVersion(carnet.workspace, promptEnv)) notices.push(RULES_UPDATED_NOTICE);
635
+ const configProblem = carnet.workspace?.configProblem;
636
+ if (configProblem) notices.push(invalidConfigNotice(configProblem));
580
637
  const additionalContext = contextParts.length ? contextParts.join("\n\n") : void 0;
581
638
  return {
582
639
  session,
@@ -592,6 +649,54 @@ function handleUserPromptSubmit(carnet, host, payload, options = {}) {
592
649
  carnet.notes.recordActiveDay();
593
650
  return carnet.sessions.adoptTitle(payload.session_id, host.promptTitle(payload));
594
651
  }
652
+ // src/launch.ts
653
+ const LAUNCH_TOOLS = /* @__PURE__ */ new Set([
654
+ "Agent",
655
+ "Task",
656
+ "EnterPlanMode"
657
+ ]);
658
+ const BUILT_IN_PLAN_DENIED = "In a Rucher session a plan agent is a Rucher fork, never the built-in Plan subagent: use /rucher:start:plan (agent_start with kind plan, then Agent with subagent_type fork and the agent name as description). For a question with no change, use /rucher:start:research.";
659
+ const EXPECTED_TYPES = {
660
+ research: "fork, or the rucher research agent with --cold",
661
+ plan: "fork, or the rucher plan agent with --cold",
662
+ implement: "fork, or the rucher implement agent with --cold",
663
+ review: "the rucher review agent"
664
+ };
665
+ function fitsKind(agent, subagentType) {
666
+ const type = subagentType ?? "";
667
+ const cold = new RegExp(`(^|:)${agent.kind}$`).test(type);
668
+ if (agent.kind === "review") return cold;
669
+ if (agent.context === "cold") return cold;
670
+ if (agent.context === "fork") return type === "fork";
671
+ return type === "fork" || cold;
672
+ }
673
+ function expectedType(agent) {
674
+ if (agent.kind === "review" || agent.context === null) return EXPECTED_TYPES[agent.kind];
675
+ return agent.context === "cold" ? `the rucher ${agent.kind} agent (it started cold)` : "fork";
676
+ }
677
+ function launchVerdict(call) {
678
+ if (call.toolName === "EnterPlanMode") {
679
+ const pending = call.pendingPlan;
680
+ if (!pending) return { allow: true };
681
+ return {
682
+ allow: false,
683
+ rule: "plan-mode",
684
+ reason: `${pending.name} is a Rucher plan agent waiting for its fork: launch it with Agent, subagent_type fork and description ${pending.name}, instead of plan mode.`
685
+ };
686
+ }
687
+ if (call.subagentType === "Plan") return {
688
+ allow: false,
689
+ rule: "built-in-plan",
690
+ reason: BUILT_IN_PLAN_DENIED
691
+ };
692
+ const named = call.named;
693
+ if (!named || fitsKind(named, call.subagentType)) return { allow: true };
694
+ return {
695
+ allow: false,
696
+ rule: "launch-type",
697
+ reason: `${named.name} is a Rucher ${named.kind} agent: launch it with subagent_type ${expectedType(named)}, not ${call.subagentType ?? "no subagent_type"}.`
698
+ };
699
+ }
595
700
  // src/shell.ts
596
701
  const GIT_ENV = /* @__PURE__ */ new Set(["GIT_DIR", "GIT_WORK_TREE"]);
597
702
  const KEYWORDS = /* @__PURE__ */ new Set([
@@ -1023,6 +1128,20 @@ const FILE_TOOLS = /* @__PURE__ */ new Set([
1023
1128
  "Write",
1024
1129
  "NotebookEdit"
1025
1130
  ]);
1131
+ const KIND_ACCESS = {
1132
+ research: "read-only",
1133
+ plan: "read-only",
1134
+ review: "read-only",
1135
+ implement: "worktree"
1136
+ };
1137
+ const ALLOW = { allow: true };
1138
+ function deny(rule, reason) {
1139
+ return {
1140
+ allow: false,
1141
+ rule,
1142
+ reason
1143
+ };
1144
+ }
1026
1145
  const PUBLISHING = /* @__PURE__ */ new Set([
1027
1146
  "commit",
1028
1147
  "push",
@@ -1046,116 +1165,297 @@ function absolute(path, cwd) {
1046
1165
  if (path === "~" || path.startsWith("~/")) return join(homedir(), path.slice(1));
1047
1166
  return isAbsolute(path) ? path : resolve(cwd ?? "/", path);
1048
1167
  }
1049
- function inScratch(path, input) {
1050
- return input.scratchRoots.some((root) => inside(path, root));
1168
+ function inScratch(path, ctx) {
1169
+ return ctx.scratchRoots.some((root) => inside(path, root));
1051
1170
  }
1052
- function writable(path, input) {
1053
- return inScratch(path, input) || !!input.sandbox && inside(path, input.sandbox);
1171
+ function writable(path, ctx) {
1172
+ return inScratch(path, ctx) || !!ctx.sandbox && inside(path, ctx.sandbox);
1054
1173
  }
1055
1174
  function publishing(call) {
1056
1175
  return PUBLISHING.has(call.verb) && !(call.verb === "stash" && READ_ONLY_STASH.has(call.sub ?? ""));
1057
1176
  }
1058
- function fileToolViolation(input, contract) {
1059
- if (input.kind === "implement") {
1060
- if (!input.worktree || !input.filePath) return void 0;
1061
- const path = absolute(input.filePath, input.cwd);
1062
- if (inside(path, input.worktree) || inScratch(path, input)) return void 0;
1063
- return `${contract} limits writes to its worktree ${input.worktree}`;
1177
+ function fileToolVerdict(access, call, ctx) {
1178
+ if (access === "worktree") {
1179
+ if (!ctx.worktree) {
1180
+ if (ctx.unpaired && call.filePath && !inScratch(absolute(call.filePath, call.cwd), ctx)) return deny("write-read-only", `${ctx.label} is read-only: write only the report in the scratchpad`);
1181
+ return ALLOW;
1182
+ }
1183
+ if (!call.filePath) return ALLOW;
1184
+ const path = absolute(call.filePath, call.cwd);
1185
+ if (inside(path, ctx.worktree) || inScratch(path, ctx)) return ALLOW;
1186
+ return deny("write-outside-worktree", `${ctx.label} limits writes to its worktree ${ctx.worktree}`);
1064
1187
  }
1065
- if (input.filePath && writable(absolute(input.filePath, input.cwd), input)) return void 0;
1066
- return input.sandbox ? `${contract} limits writes to its sandbox ${input.sandbox} and the scratchpad` : `${contract} is read-only: write only the report in the scratchpad`;
1067
- }
1068
- function guardToolCall(input) {
1069
- const contract = `the ${input.kind} contract`;
1070
- if (FILE_TOOLS.has(input.toolName)) return fileToolViolation(input, contract);
1071
- if (input.toolName !== "Bash") return void 0;
1072
- const calls = gitCalls(input.command ?? "", input.cwd).filter(publishing);
1073
- if (calls.length === 0) return void 0;
1074
- const sandbox = input.sandbox;
1075
- if (!sandbox || input.kind === "implement") return `${contract} forbids git commit, push and stash: the human commits`;
1076
- if (calls.some((call) => call.verb === "push")) return `${contract} forbids git push`;
1188
+ if (call.filePath && writable(absolute(call.filePath, call.cwd), ctx)) return ALLOW;
1189
+ return ctx.sandbox ? deny("write-outside-sandbox", `${ctx.label} limits writes to its sandbox ${ctx.sandbox} and the scratchpad`) : deny("write-read-only", `${ctx.label} is read-only: write only the report in the scratchpad`);
1190
+ }
1191
+ function bashVerdict(access, call, ctx) {
1192
+ const calls = gitCalls(call.command ?? "", call.cwd).filter(publishing);
1193
+ if (calls.length === 0) return ALLOW;
1194
+ const sandbox = ctx.sandbox;
1195
+ if (!sandbox || access === "worktree") return deny("git-publish", `${ctx.label} forbids git commit, push and stash: the human commits`);
1196
+ if (calls.some((git) => git.verb === "push")) return deny("git-push", `${ctx.label} forbids git push`);
1077
1197
  const confined = (dir) => dir !== void 0 && inside(dir, sandbox);
1078
- if (calls.every((call) => call.dirs.every(confined))) return void 0;
1079
- return `${contract} allows git commit and stash only in its sandbox ${sandbox}`;
1198
+ if (calls.every((git) => git.dirs.every(confined))) return ALLOW;
1199
+ return deny("git-outside-sandbox", `${ctx.label} allows git commit and stash only in its sandbox ${sandbox}`);
1200
+ }
1201
+ function checkToolCall(access, call, ctx) {
1202
+ if (access === "main") {
1203
+ if (!LAUNCH_TOOLS.has(call.tool) || !ctx.launch) return ALLOW;
1204
+ return launchVerdict({
1205
+ toolName: call.tool,
1206
+ subagentType: call.subagentType,
1207
+ ...ctx.launch
1208
+ });
1209
+ }
1210
+ if (FILE_TOOLS.has(call.tool)) return fileToolVerdict(access, call, ctx);
1211
+ if (call.tool === "Bash") return bashVerdict(access, call, ctx);
1212
+ return ALLOW;
1080
1213
  }
1081
- function kindOfAgentType(agentType) {
1082
- return /^rucher[\w-]*:(research|review)$/.exec(agentType ?? "")?.[1];
1214
+ function text(fields, key) {
1215
+ const value = fields[key];
1216
+ return typeof value === "string" && value !== "" ? value : void 0;
1083
1217
  }
1084
- // src/launch.ts
1085
- const LAUNCH_TOOLS = /* @__PURE__ */ new Set([
1086
- "Agent",
1087
- "Task",
1088
- "EnterPlanMode"
1089
- ]);
1090
- const BUILT_IN_PLAN_DENIED = "In a Rucher session a plan agent is a Rucher fork, never the built-in Plan subagent: use /rucher:start:plan (agent_start with kind plan, then Agent with subagent_type fork and the agent name as description). For a question with no change, use /rucher:start:research.";
1091
- const EXPECTED_TYPES = {
1092
- research: "fork, or the rucher research agent with --cold",
1093
- plan: "fork",
1094
- implement: "fork",
1095
- review: "the rucher review agent"
1096
- };
1097
- function fitsKind(kind, subagentType) {
1098
- const type = subagentType ?? "";
1099
- if (kind === "plan" || kind === "implement") return type === "fork";
1100
- if (kind === "research") return type === "fork" || /(^|:)research$/.test(type);
1101
- return /(^|:)review$/.test(type);
1218
+ function toolCallOf(tool, input, cwd) {
1219
+ const fields = typeof input === "object" && input !== null ? input : {};
1220
+ return {
1221
+ tool,
1222
+ filePath: text(fields, "file_path") ?? text(fields, "notebook_path"),
1223
+ command: text(fields, "command"),
1224
+ cwd,
1225
+ subagentType: text(fields, "subagent_type")
1226
+ };
1102
1227
  }
1103
- function guardLaunch(call) {
1104
- if (call.toolName === "EnterPlanMode") {
1105
- const pending = call.pendingPlan;
1106
- if (!pending) return void 0;
1107
- return `${pending.name} is a Rucher plan agent waiting for its fork: launch it with Agent, subagent_type fork and description ${pending.name}, instead of plan mode.`;
1108
- }
1109
- if (call.subagentType === "Plan") return BUILT_IN_PLAN_DENIED;
1110
- const named = call.named;
1111
- if (!named || fitsKind(named.kind, call.subagentType)) return void 0;
1112
- return `${named.name} is a Rucher ${named.kind} agent: launch it with subagent_type ${EXPECTED_TYPES[named.kind]}, not ${call.subagentType ?? "no subagent_type"}.`;
1228
+ function scratchRoots(env) {
1229
+ const folder = `claude-${process.getuid?.() ?? 0}`;
1230
+ const parents = [
1231
+ env.CLAUDE_CODE_TMPDIR,
1232
+ process.platform === "win32" ? void 0 : "/tmp",
1233
+ tmpdir()
1234
+ ].filter((parent) => Boolean(parent));
1235
+ return [...new Set(parents.map((parent) => join(parent, folder)))];
1236
+ }
1237
+ function kindOfAgentType(agentType) {
1238
+ return /^rucher[\w-]*:(research|plan|implement|review)$/.exec(agentType ?? "")?.[1];
1113
1239
  }
1114
1240
  // src/hook/post-tool-use.ts
1115
- function handleToolUse(carnet, payload, env, options = {}) {
1116
- if (payload.agent_id) return void 0;
1241
+ function handleToolUse(carnet, payload, options = {}) {
1242
+ if (payload.agent_id) return;
1117
1243
  if (options.trackTurn ?? true) carnet.turn.start(payload.session_id);
1118
- const repo = repoNameFor(carnet.workspace, payload.path);
1119
- if (!repo) return void 0;
1120
- const session = carnet.sessions.ensure(payload.session_id, payload.cwd);
1121
- return carnet.memory.forRepo(session, repo, {
1122
- maxCharacters: memoryMaxCharacters(env.RUCHER_MEMORY_MAX_CHARACTERS),
1123
- halfLifeDays: memoryHalfLife(env.RUCHER_MEMORY_HALF_LIFE_DAYS)
1124
- });
1125
1244
  }
1126
1245
  const WAITING_TOOL = "AskUserQuestion";
1127
1246
  function handleToolStart(carnet, payload) {
1128
1247
  if (payload.agent_id || payload.tool_name !== "AskUserQuestion") return;
1129
1248
  carnet.turn.wait(payload.session_id);
1130
1249
  }
1131
- function guardSubagentCall(carnet, payload, scratchRoots) {
1132
- if (!payload.agent_id || !payload.tool_name) return void 0;
1133
- const agent = carnet.agents.byHostAgentId(payload.session_id, payload.agent_id);
1250
+ function subagentVerdict(carnet, payload, scratchRoots, names = [], namedUnreadable = false) {
1251
+ if (!payload.agent_id || !payload.tool_name) return ALLOW;
1252
+ const agent = carnet.agents.confirmSubagent(payload.session_id, payload.agent_id, names);
1134
1253
  const kind = agent?.kind ?? kindOfAgentType(payload.agent_type);
1135
- if (!kind) return void 0;
1136
- return guardToolCall({
1137
- kind,
1138
- toolName: payload.tool_name,
1254
+ if (!kind) {
1255
+ if (namedUnreadable && payload.agent_type === "fork") return deny("write-read-only", "The named workspace cannot be opened, so writes stay closed.");
1256
+ return ALLOW;
1257
+ }
1258
+ return checkToolCall(KIND_ACCESS[kind], {
1259
+ tool: payload.tool_name,
1139
1260
  filePath: payload.file_path,
1140
1261
  command: payload.command,
1141
- cwd: payload.cwd,
1262
+ cwd: payload.cwd
1263
+ }, {
1264
+ label: `the ${kind} contract`,
1142
1265
  worktree: agent?.worktree,
1143
1266
  sandbox: agent?.sandbox,
1144
- scratchRoots
1267
+ scratchRoots,
1268
+ unpaired: !agent
1145
1269
  });
1146
1270
  }
1147
- function guardMainLaunch(carnet, payload) {
1148
- if (payload.agent_id || !payload.tool_name) return void 0;
1149
- if (!carnet.sessions.get(payload.session_id)) return void 0;
1271
+ function mainLaunchVerdict(carnet, payload, namedUnreadable = false) {
1272
+ if (payload.agent_id || !payload.tool_name) return ALLOW;
1273
+ if (!carnet.sessions.get(payload.session_id)) {
1274
+ if (!namedUnreadable) return ALLOW;
1275
+ if (payload.tool_name === "EnterPlanMode") return deny("plan-mode", "The named workspace cannot be opened, so plan mode stays closed.");
1276
+ return launchVerdict({
1277
+ toolName: payload.tool_name,
1278
+ subagentType: payload.subagent_type
1279
+ });
1280
+ }
1150
1281
  const named = carnet.agents.unpaired(payload.session_id, payload.launched_names ?? []);
1151
- const reason = guardLaunch({
1152
- toolName: payload.tool_name,
1153
- subagentType: payload.subagent_type,
1154
- named,
1155
- pendingPlan: payload.tool_name === "EnterPlanMode" ? carnet.agents.pendingPlan(payload.session_id) : void 0
1282
+ const planMode = payload.tool_name === "EnterPlanMode";
1283
+ const verdict = checkToolCall("main", {
1284
+ tool: payload.tool_name,
1285
+ subagentType: payload.subagent_type
1286
+ }, {
1287
+ label: "the main session",
1288
+ scratchRoots: [],
1289
+ launch: {
1290
+ named,
1291
+ pendingPlan: planMode ? carnet.agents.pendingPlan(payload.session_id) : void 0
1292
+ }
1156
1293
  });
1157
- if (!reason && named && payload.tool_name !== "EnterPlanMode") carnet.agents.requestLaunch(payload.session_id, named.name);
1158
- return reason;
1294
+ if (verdict.allow && named && !planMode) carnet.agents.requestLaunch(payload.session_id, named.name);
1295
+ return verdict;
1296
+ }
1297
+ // src/launch-plan.ts
1298
+ function withWorkspace(command, workspace) {
1299
+ return workspace ? `${command} --ws ${workspace}` : command;
1300
+ }
1301
+ function launchEnv(workspace, session, promptVersion, kind) {
1302
+ return {
1303
+ RUCHER_SESSION_ID: session.id,
1304
+ RUCHER_PROMPT_VERSION: promptVersion,
1305
+ RUCHER_SESSION_NAME: session.name ?? "",
1306
+ ...workspace ? { RUCHER_WS: workspace.name } : {},
1307
+ ...kind ? { RUCHER_SESSION_KIND: kind } : {}
1308
+ };
1309
+ }
1310
+ function carnetServer(input) {
1311
+ return {
1312
+ command: "rucher",
1313
+ args: ["mcp"],
1314
+ env: {
1315
+ RUCHER_SESSION_ID: input.session.id,
1316
+ ...input.agentId ? { RUCHER_AGENT_ID: input.agentId } : {},
1317
+ ...input.workspace ? { RUCHER_WS: input.workspace.name } : {}
1318
+ }
1319
+ };
1320
+ }
1321
+ function buildLaunchPlan(input) {
1322
+ const { mode, host, session } = input;
1323
+ if (mode === "agent" && !input.agentId) throw new TypeError("An agent launch needs an agent id");
1324
+ const fork = mode === "fork";
1325
+ const name = input.name === void 0 ? session.name : input.name;
1326
+ const env = fork ? {
1327
+ ...launchEnv(input.workspace, session, session.promptVersion ?? "", input.kind),
1328
+ RUCHER_SESSION_NAME: name ?? ""
1329
+ } : launchEnv(input.workspace, session, input.systemAppend.version, input.kind);
1330
+ const server = host.orchestration === "server";
1331
+ return {
1332
+ mode,
1333
+ host: host.id,
1334
+ orchestration: host.orchestration,
1335
+ ...fork ? { parentId: session.id } : { sessionId: session.id },
1336
+ ...input.agentId ? { agentId: input.agentId } : {},
1337
+ name,
1338
+ cwd: input.cwd,
1339
+ dirs: input.dirs,
1340
+ systemAppend: input.systemAppend,
1341
+ env,
1342
+ ...input.model ? { model: input.model } : {},
1343
+ ...server ? { mcp: { carnet: carnetServer(input) } } : {},
1344
+ rucherPlugin: server ? "exclude" : "load",
1345
+ ...input.knownChildren ? { knownChildren: input.knownChildren } : {}
1346
+ };
1347
+ }
1348
+ function repoDirectories(workspace) {
1349
+ return (workspace?.repos ?? []).map((repo) => repo.path).filter((path) => existsSync(path));
1350
+ }
1351
+ function sessionWorkspace(carnet, session, env) {
1352
+ if (!isWorkspaceName(session.workspace)) return null;
1353
+ return carnet.workspace?.name === session.workspace ? carnet.workspace : loadWorkspace(session.workspace, env);
1354
+ }
1355
+ function prepareSession(carnet, session, env) {
1356
+ const workspace = sessionWorkspace(carnet, session, env);
1357
+ if (workspace) renderRunDirectory(workspace, {
1358
+ env,
1359
+ host: session.host
1360
+ });
1361
+ return workspace;
1362
+ }
1363
+ function sessionLabel$1(session) {
1364
+ return session.name ?? session.id.slice(0, 8);
1365
+ }
1366
+ function sessionDirectory(session) {
1367
+ if (session.cwd && existsSync(session.cwd)) return session.cwd;
1368
+ throw new CarnetError("SESSION_CWD_MISSING", `The directory of session ${sessionLabel$1(session)} no longer exists: ${session.cwd ?? "none recorded"}`);
1369
+ }
1370
+ function prepareNew(carnet, options) {
1371
+ if (options.kind === "active" && !options.name) throw new CarnetError("SESSION_NAME_REQUIRED", "An active session needs a name", withWorkspace("rucher new <name>", carnet.workspace?.name));
1372
+ const workspace = carnet.requireWorkspace();
1373
+ const session = carnet.sessions.create({
1374
+ id: randomUUID(),
1375
+ kind: options.kind,
1376
+ name: options.name,
1377
+ cwd: workspace.runDirectory,
1378
+ repo: repoNameFor(workspace, options.repoCwd)
1379
+ });
1380
+ const host = hostById(session.host);
1381
+ renderRunDirectory(workspace, {
1382
+ env: options.env,
1383
+ host: session.host
1384
+ });
1385
+ return buildLaunchPlan({
1386
+ mode: "new",
1387
+ host,
1388
+ workspace,
1389
+ session,
1390
+ cwd: workspace.runDirectory,
1391
+ dirs: repoDirectories(workspace),
1392
+ systemAppend: appendPromptFile(workspace, session, options.env),
1393
+ model: options.model
1394
+ });
1395
+ }
1396
+ function prepareResume(carnet, session, env, options = {}) {
1397
+ const workspace = prepareSession(carnet, session, env);
1398
+ const cwd = sessionDirectory(session);
1399
+ const systemAppend = appendPromptFile(workspace, session, env);
1400
+ const host = hostById(session.host);
1401
+ const fresh = !launchHost(host.id).hasConversation(session, env);
1402
+ return {
1403
+ plan: buildLaunchPlan({
1404
+ mode: fresh ? "new" : "resume",
1405
+ host,
1406
+ workspace,
1407
+ session,
1408
+ cwd,
1409
+ dirs: repoDirectories(workspace),
1410
+ systemAppend,
1411
+ model: options.model
1412
+ }),
1413
+ notices: fresh ? [`no conversation yet for ${sessionLabel$1(session)}: starting it\n`] : []
1414
+ };
1415
+ }
1416
+ function checkForkOptions(carnet, options) {
1417
+ if (options.active && !options.name) throw new CarnetError("SESSION_NAME_REQUIRED", "An active fork needs a name", withWorkspace("rucher fork <session> <name> --active", carnet.workspace?.name));
1418
+ if (options.name && carnet.sessions.byName(options.name)) throw new CarnetError("SESSION_NAME_TAKEN", `A session named "${options.name}" already exists`);
1419
+ }
1420
+ function childrenOf(carnet, parentId) {
1421
+ return carnet.sessions.list({
1422
+ includeTemp: true,
1423
+ includeArchived: true
1424
+ }).filter((session) => session.parentId === parentId);
1425
+ }
1426
+ function prepareFork(carnet, parent, options) {
1427
+ checkForkOptions(carnet, options);
1428
+ const host = hostById(parent.host);
1429
+ if (!launchHost(host.id).hasConversation(parent, options.env)) {
1430
+ const label = sessionLabel$1(parent);
1431
+ throw new CarnetError("NO_CONVERSATION", `Session ${label} has no conversation yet, nothing to fork`, withWorkspace(`rucher resume ${label}`, parent.workspace));
1432
+ }
1433
+ const workspace = prepareSession(carnet, parent, options.env);
1434
+ return buildLaunchPlan({
1435
+ mode: "fork",
1436
+ host,
1437
+ workspace,
1438
+ session: parent,
1439
+ cwd: sessionDirectory(parent),
1440
+ dirs: repoDirectories(workspace),
1441
+ systemAppend: appendPromptFile(workspace, parent, options.env),
1442
+ kind: options.active ? "active" : "temp",
1443
+ name: options.name ?? null,
1444
+ model: options.model,
1445
+ knownChildren: childrenOf(carnet, parent.id).map((session) => session.id)
1446
+ });
1447
+ }
1448
+ function forkChild(carnet, plan) {
1449
+ if (!plan.parentId) return void 0;
1450
+ const known = new Set(plan.knownChildren);
1451
+ return childrenOf(carnet, plan.parentId).find((session) => !known.has(session.id));
1452
+ }
1453
+ function launchStarted(carnet, plan) {
1454
+ if (plan.sessionId) carnet.sessions.setStatus(plan.sessionId, "running");
1455
+ }
1456
+ function launchEnded(carnet, plan) {
1457
+ const id = plan.sessionId ?? forkChild(carnet, plan)?.id;
1458
+ if (id && carnet.sessions.get(id)) carnet.sessions.end(id);
1159
1459
  }
1160
1460
  // src/status/line.ts
1161
1461
  const STATUS_LINE_LABEL = "rucher";
@@ -1202,6 +1502,6 @@ function writeStatusLine(carnet, sessionId, options = {}) {
1202
1502
  writeFileSync(temporary, line ? `${line}\n` : "");
1203
1503
  renameSync(temporary, path);
1204
1504
  }
1205
- export { AGENTS_FILE, AGENT_KINDS, AGENT_STATUSES, AGENT_STEPS, BLOCKED_HEADER, BUILT_IN_PLAN_DENIED, CORE_RULES, Carnet, CarnetError, DEFAULT_HALF_LIFE_DAYS, DEFAULT_HOST, DEFAULT_PURGE_DAYS, DUPLICATE_SIMILARITY, EMOJI, EVENT_TYPES, GENERATED_MARKER, GUARDED_TOOLS, INSTRUCTIONS_FILE, KIND_ABBREVIATIONS, KIND_LEGEND, KIND_REQUIRED, KIND_TAG_PATTERN, LAUNCH_TOOLS, LEGEND, MAIN_FAILED_EMOJI, MAIN_FAILED_SUFFIX, MAIN_HEADER, MAIN_IDLE, MAIN_WAITING_EMOJI, MAIN_WAITING_SUFFIX, MAIN_WORKING_EMOJI, MAIN_WORKING_SUFFIX, MARKDOWN_MARKER, MEMORY_DB, MEMORY_MAX_CHARACTERS, MINIMUM_ID_PREFIX, NOTES_FOLD_LINES, NOTES_HEADER, NOTE_KINDS, NOTE_MAX, NOTE_TEXT_LIMIT, OUTSIDE_RUCHER_NOTICE, PAIRING_WINDOW_MILLISECONDS, PROMPT_FILE, PUBLISH_FALLBACK_MILLISECONDS, REPORTING_NOTE, RESUME_EVENTS, RESUME_MAX_CHARACTERS, RULES_UPDATED_NOTICE, SANDBOX_KINDS, SESSION_EVENT_TYPES, SIMILAR_PREFIX, STALE_AFTER_ACTIVE_DAYS, STATUS_LINE_LABEL, STOPPED_NOTE, SUBAGENT_RULES, TURNS, USER_ACTION_STATUSES, WAITING_TOOL, WORKSPACE_FILE, addWorkspaceRepo, allHosts, appendPromptFile, archiveWorkspaceSessions, assemblePrompt, backupsDirectory, baseRules, buildStatusView, claudeCode, claudeConfigFile, claudeProjectFolder, compactReminder, corePromptPath, createWorkspace, databasePath, defaultRunDirectory, definitionInstructions, deleteWorkspaceNotes, dropWorkspace, expandHome, findGitTrees, findingsBrief, formatClock, formatEventLine, guardLaunch, guardMainLaunch, guardSubagentCall, guardToolCall, handleSessionEnd, handleSessionStart, handleStop, handleToolStart, handleToolUse, handleUserPromptSubmit, hostById, isAgentKind, isAgentStatus, isEventType, isInside, isNoteKind, isUserActionStatus, isWorkspaceName, kindOfAgentType, kindTag, labelStatusLine, listWorkspaces, loadWorkspace, localDay, locateAgent, markdownCopy, memoryHalfLife, memoryMaxCharacters, mergeSettings, mergeWorkspaces, migrate, migrations, moveSession, nextAgent, openCarnet, openDatabase, openResolvedCarnet, openWorkspaceCarnet, outsideRucherContext, planWorkspaceMerge, planWorkspaceRename, promptsDirectory, purgeDays, removeStaleCopies, removeWorkspaceRepo, renameWorkspace, renderAgentLine, renderMainLine, renderMemory, renderNoteLine, renderNotes, renderNotesSummary, renderRunDirectory, renderSections, renderStatus, renderStatusLine, renderTableLine, repoNameFor, repoPathFor, reportDocument, reportPath, reportsDirectory, requireWorkspace, resolveWorkspace, resumeContext, rucherPaths, rulesText, rulesVersion, sandboxesDirectory, sanitizeNote, schemaVersion, sessionLabel, sessionNoteActivity, sessionWorkspaceName, shortId, similarity, statusLinePath, statusWhenDone, stepAgent, transcriptTitle, workspaceDefinition, workspaceExists, workspaceHosts, workspaceLabel, workspaceLastActive, workspaceRepoNames, workspaceRules, workspaceSessionCounts, workspaceSettings, workspacesDirectory, writeGenerated, writeStatusLine };
1505
+ export { AGENTS_FILE, AGENT_BRIEF_HINT, AGENT_KINDS, AGENT_STATUSES, AGENT_STEPS, BACKENDS, BLOCKED_HEADER, BUILT_IN_PLAN_DENIED, BUILT_IN_PROFILE_NAMES, BUILT_IN_PROFILE_NOTES, CLAUDE_BACKEND, CLAUDE_BACKEND_NOTES, CLAUDE_NATIVE_FILES, CONFIG_FILE, CONFIG_LEVELS, CORE_RULES, Carnet, CarnetError, DECIDER_PROVIDERS, DECISION_USAGES, DEFAULT_HALF_LIFE_DAYS, DEFAULT_HOST, DEFAULT_PROFILE, DEFAULT_PURGE_DAYS, DELIVERABLES, DUPLICATE_SIMILARITY, EMOJI, EVENT_TYPES, GENERATED_MARKER, GESTURES, GUARDED_TOOLS, INSTRUCTIONS_FILE, KIND_ABBREVIATIONS, KIND_ACCESS, KIND_LEGEND, KIND_MODES, KIND_REQUIRED, KIND_TAG_PATTERN, LAUNCH_TOOLS, LAYERS, LEGEND, MAIN_FAILED_EMOJI, MAIN_FAILED_SUFFIX, MAIN_HEADER, MAIN_IDLE, MAIN_WAITING_EMOJI, MAIN_WAITING_SUFFIX, MAIN_WORKING_EMOJI, MAIN_WORKING_SUFFIX, MARKDOWN_MARKER, MEMORY_DB, MEMORY_MAX_CHARACTERS, MINIMUM_ID_PREFIX, NOTES_FOLD_LINES, NOTES_HEADER, NOTE_KINDS, NOTE_MAX, NOTE_TEXT_LIMIT, OUTSIDE_RUCHER_NOTICE, PAIRING_WINDOW_MILLISECONDS, PROFILES_DIRECTORY, PROMPT_FILE, PUBLISH_FALLBACK_MILLISECONDS, REFERENCE_SCOPES, REPORTING_NOTE, REPO_INSTRUCTIONS_DIRECTORY, REPO_INSTRUCTION_FILES, RESUME_EVENTS, RESUME_MAX_CHARACTERS, RULES_UPDATED_NOTICE, SANDBOX_KINDS, SEARCH_LIMITS, SEARCH_TRIGGERS, SEARCH_TRIGGER_NAMES, SESSION_EVENT_TYPES, SIMILAR_PREFIX, SNIPPET_CLOSE, SNIPPET_OPEN, STALE_AFTER_ACTIVE_DAYS, STATUS_LINE_LABEL, STOPPED_NOTE, SUBAGENT_RULES, TURNS, USER_ACTION_STATUSES, WAITING_TOOL, WORKSPACE_FILE, addWorkspaceRepo, agentMode, allHosts, appendPromptFile, archiveWorkspaceSessions, assemblePrompt, attachment, attachmentInput, attachments, attachmentsInput, backupsDirectory, baseRules, branchProblems, buildBrief, buildLaunchPlan, buildStatusView, builtInProfileSource, checkForkOptions, checkToolCall, claudeCode, claudeCodeHooks, claudeCodeLaunch, claudeConfigFile, claudeLastContext, claudeLiveSession, claudeProjectFolder, claudeTranscriptUsage, compactReminder, contextAppend, contextText, corePromptPath, createWorkspace, databasePath, defaultRunDirectory, definitionInstructions, deleteWorkspaceNotes, deliverable, dropWorkspace, effectiveRun, eventUsage, expandHome, findGitTrees, forkStartContext, formatBytes, formatClock, formatEventLine, formatTokens, formatUsage, globalConfigPath, handleSessionEnd, handleSessionStart, handleStop, handleToolStart, handleToolUse, handleUserPromptSubmit, hookHost, hostById, invalidConfigNotice, isAgentKind, isAgentStatus, isEventType, isInside, isNoteKind, isUserActionStatus, isWorkspaceName, kindOfAgentType, kindTag, labelStatusLine, launchEnded, launchHost, launchStarted, launchVerdict, listWorkspaces, loadGlobalConfig, loadLayered, loadProfiles, loadWorkspace, localDay, locateAgent, mainLaunchVerdict, markdownCopy, memoryHalfLife, memoryMaxCharacters, mergeSettings, mergeWorkspaces, migrate, migrateInstructions, migrations, moveSession, nextAgent, openCarnet, openDatabase, openResolvedCarnet, openWorkspaceCarnet, outsideRucherContext, overlay, parseConfig, parseFrontmatter, planAsAnswered, planWorkspaceMerge, planWorkspaceRename, prepareFork, prepareNew, prepareResume, produced, profileDirectories, profileLookup, profileSource, profileValues, promptsDirectory, purgeDays, readClaudeTranscript, readJson, recommendedThen, referenceLine, removeStaleCopies, removeWorkspaceRepo, renameWorkspace, renderAgentLine, renderMainLine, renderMemory, renderNoteLine, renderNotes, renderNotesSummary, renderRunDirectory, renderSections, renderStatus, renderStatusLine, renderTableLine, repoInstructionFiles, repoInstructionsPath, repoNameFor, repoPathFor, reportDocument, reportPath, reportsDirectory, requireWorkspace, resolveConfig, resolveRun, resolveWorkspace, resumeContext, resumeSummary, rucherPaths, rucherServer, rulesText, rulesVersion, sandboxesDirectory, sanitizeNote, schemaVersion, scratchRoots, searchQuery, serializeWorkspaceFile, serverSocketPath, sessionLabel, sessionNoteActivity, sessionWorkspaceName, shortId, similarity, snapshot, sourceLabel, statusLinePath, statusWhenDone, stepAgent, subagentVerdict, toolCallOf, transcriptTitle, transcriptsIndexed, usableWorkspaceConfig, withWorkspace, workspaceConfig, workspaceContext, workspaceDefinition, workspaceExists, workspaceFileHosts, workspaceHosts, workspaceLabel, workspaceLastActive, workspaceRepoNames, workspaceRules, workspaceSessionCounts, workspaceSettings, workspacesDirectory, writeGenerated, writeStatusLine };
1206
1506
 
1207
1507
  //# sourceMappingURL=index.mjs.map