@rucher/carnet 0.2.0 → 0.3.0-beta.1

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,5 +1,7 @@
1
- import { $ as workspaceSessionCounts, $t as migrations, A as memoryMaxCharacters, At as addWorkspaceRepo, B as sessionNoteActivity, Bt as workspaceHosts, C as renderNotesSummary, Ct as workspaceRules, D as DEFAULT_PURGE_DAYS, Dt as AGENTS_FILE, E as renderTableLine, Et as shortId, F as NOTE_TEXT_LIMIT, Ft as isWorkspaceName, G as repoNameFor, Gt as reportPath, H as workspaceRepoNames, Ht as databasePath, I as STALE_AFTER_ACTIVE_DAYS, It as listWorkspaces, J as resolveWorkspace, Jt as workspaceDefinition, K as repoPathFor, Kt as reportsDirectory, L as isNoteKind, Lt as loadWorkspace, M as DEFAULT_HALF_LIFE_DAYS, Mt as definitionInstructions, N as DUPLICATE_SIMILARITY, Nt as dropWorkspace, O as purgeDays, Ot as INSTRUCTIONS_FILE, P as NOTE_KINDS, Pt as expandHome, Q as sessionWorkspaceName, Qt as migrate, R as localDay, Rt as removeWorkspaceRepo, S as renderNotes, St as rulesVersion, T as renderStatus, Tt as MINIMUM_ID_PREFIX, U as ambiguousWorkspaceContext, Ut as defaultRunDirectory, V as similarity, Vt as corePromptPath, W as isInside, Wt as promptsDirectory, X as archiveWorkspaceSessions, Xt as MEMORY_DB, Y as workspaceLabel, Yt as workspacesDirectory, Z as deleteWorkspaceNotes, Zt as openDatabase, _ as NOTES_FOLD_LINES, _t as assemblePrompt, a as formatEventLine, an as AGENT_STATUSES, at as workspaceSettings, b as renderAgentLine, bt as outsideRucherContext, c as Carnet, cn as MAIN_WORKING_EMOJI, ct as markdownCopy, d as openWorkspaceCarnet, dn as isAgentStatus, dt as writeGenerated, en as schemaVersion, et as DEFAULT_HOST, f as PAIRING_WINDOW_MILLISECONDS, fn as isUserActionStatus, ft as OUTSIDE_RUCHER_NOTICE, g as MAIN_WORKING_SUFFIX, gn as CarnetError, gt as appendPromptFile, h as formatClock, hn as isEventType, ht as SUBAGENT_RULES, i as RESUME_MAX_CHARACTERS, in as sanitizeNote, it as transcriptTitle, j as renderMemory, jt as createWorkspace, k as MEMORY_MAX_CHARACTERS, kt as WORKSPACE_FILE, l as openCarnet, lt as mergeSettings, m as buildStatusView, mn as SESSION_EVENT_TYPES, mt as RULES_UPDATED_NOTICE, n as stepAgent, nn as REPORTING_NOTE, nt as hostById, o as resumeContext, on as EMOJI, ot as GENERATED_MARKER, p as STOPPED_NOTE, pn as EVENT_TYPES, pt as PROMPT_FILE, q as requireWorkspace, qt as rucherPaths, r as RESUME_EVENTS, rn as NOTE_MAX, rt as claudeCode, s as sessionLabel, sn as LEGEND, st as MARKDOWN_MARKER, t as AGENT_STEPS, tn as PUBLISH_FALLBACK_MILLISECONDS, tt as allHosts, u as openResolvedCarnet, un as USER_ACTION_STATUSES, ut as removeStaleCopies, v as NOTES_HEADER, vt as baseRules, w as renderSections, wt as CORE_RULES, x as renderNoteLine, xt as rulesText, y as SIMILAR_PREFIX, yt as compactReminder, z as memoryHalfLife, zt as workspaceExists } from "./steps-4ZTrBzcd.mjs";
2
- import { mkdirSync } from "node:fs";
1
+ import { $ as renderMemory, $n as MAIN_FAILED_EMOJI, $t as rulesText, A as TURNS, An as workspaceDefinition, At as claudeCode, B as renderAgentLine, Bn as PUBLISH_FALLBACK_MILLISECONDS, Bt as markdownCopy, C as openCarnet, Cn as databasePath, Ct as sessionWorkspaceName, D as STOPPED_NOTE, Dn as reportsDirectory, Dt as DEFAULT_HOST, E as PAIRING_WINDOW_MILLISECONDS, En as reportPath, Et as workspaceSessionCounts, F as MAIN_WAITING_SUFFIX, Fn as migrations, Ft as UndoList, G as renderSections, Gn as NOTE_MAX, Gt as PROMPT_FILE, H as renderNoteLine, Hn as SANDBOX_KINDS, Ht as removeStaleCopies, I as MAIN_WORKING_SUFFIX, In as schemaVersion, It as moveTracked, J as DEFAULT_PURGE_DAYS, Jn as EMOJI, Jt as appendPromptFile, K as renderStatus, Kn as sanitizeNote, Kt as RULES_UPDATED_NOTICE, L as NOTES_FOLD_LINES, Ln as AGENT_KINDS, Lt as relocateFailed, M as MAIN_FAILED_SUFFIX, Mn as MEMORY_DB, Mt as claudeProjectFolder, N as MAIN_HEADER, Nn as openDatabase, Nt as transcriptTitle, O as buildStatusView, On as rucherPaths, Ot as allHosts, P as MAIN_IDLE, Pn as migrate, Pt as workspaceSettings, Q as memoryMaxCharacters, Qn as LEGEND, Qt as outsideRucherContext, R as NOTES_HEADER, Rn as KIND_REQUIRED, Rt as GENERATED_MARKER, S as Carnet, Sn as corePromptPath, St as runningWorkspaceSessions, T as openWorkspaceCarnet, Tn as promptsDirectory, Tt as workspaceRowCounts, U as renderNotes, Un as isAgentKind, Ut as writeGenerated, V as renderMainLine, Vn as REPORTING_NOTE, Vt as mergeSettings, W as renderNotesSummary, Wn as statusWhenDone, Wt as OUTSIDE_RUCHER_NOTICE, Xn as KIND_LEGEND, Xt as baseRules, Y as purgeDays, Yn as KIND_ABBREVIATIONS, Yt as assemblePrompt, Z as MEMORY_MAX_CHARACTERS, Zn as KIND_TAG_PATTERN, Zt as compactReminder, _n as workspaceExists, _t as archiveWorkspaceSessions, a as formatEventLine, an as AGENTS_FILE, ar as isUserActionStatus, at as isNoteKind, bt as nextNoteNumber, cn as addWorkspaceRepo, cr as SESSION_EVENT_TYPES, ct as sessionNoteActivity, dn as dropWorkspace, dt as isInside, en as rulesVersion, er as MAIN_WAITING_EMOJI, et as DEFAULT_HALF_LIFE_DAYS, fn as expandHome, ft as repoNameFor, g as nextAgent, gn as removeWorkspaceRepo, gt as workspaceLabel, h as locateAgent, hn as loadWorkspace, ht as resolveWorkspace, i as RESUME_MAX_CHARACTERS, in as shortId, ir as isAgentStatus, it as STALE_AFTER_ACTIVE_DAYS, j as BLOCKED_HEADER, jn as workspacesDirectory, jt as claudeConfigFile, k as formatClock, kn as sandboxesDirectory, kt as hostById, ln as createWorkspace, lr as isEventType, lt as similarity, mn as listWorkspaces, mt as requireWorkspace, n as stepAgent, nn as CORE_RULES, nt as NOTE_KINDS, o as resumeContext, on as INSTRUCTIONS_FILE, or as kindTag, ot as localDay, pn as isWorkspaceName, pt as repoPathFor, q as renderTableLine, qn as AGENT_STATUSES, qt as SUBAGENT_RULES, r as RESUME_EVENTS, rn as MINIMUM_ID_PREFIX, rr as USER_ACTION_STATUSES, rt as NOTE_TEXT_LIMIT, s as sessionLabel, sn as WORKSPACE_FILE, sr as EVENT_TYPES, st as memoryHalfLife, t as AGENT_STEPS, tn as workspaceRules, tr as MAIN_WORKING_EMOJI, tt as DUPLICATE_SIMILARITY, u as findingsBrief, un as definitionInstructions, ur as CarnetError, ut as workspaceRepoNames, vn as workspaceHosts, vt as deleteWorkspaceNotes, w as openResolvedCarnet, wn as defaultRunDirectory, wt as workspaceLastActive, xt as renameWorkspaceRows, y as reportDocument, yt as mergeWorkspaceRows, z as SIMILAR_PREFIX, zt as MARKDOWN_MARKER } from "./steps-DhCnOGCU.mjs";
2
+ import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
+ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
4
+ import { homedir } from "node:os";
3
5
  // src/move.ts
4
6
  function count(carnet, sql, ...parameters) {
5
7
  return Number(carnet.db.prepare(sql).get(...parameters).total);
@@ -34,11 +36,373 @@ function moveSession(carnet, sessionId, targetWorkspace, options = {}) {
34
36
  carnet.db.prepare("UPDATE sessions SET workspace = ? WHERE id = ?").run(targetWorkspace, session.id);
35
37
  return result;
36
38
  }
39
+ // src/render.ts
40
+ function renderRunDirectory(workspace, options = {}) {
41
+ mkdirSync(workspace.runDirectory, { recursive: true });
42
+ mkdirSync(reportsDirectory(workspace), { recursive: true });
43
+ const result = {
44
+ runDirectory: workspace.runDirectory,
45
+ written: [],
46
+ removed: []
47
+ };
48
+ for (const id of options.host ? [options.host] : workspaceHosts(workspace)) {
49
+ const rendered = hostById(id).renderRunDirectory(workspace);
50
+ result.written.push(...rendered.written);
51
+ result.removed.push(...rendered.removed);
52
+ }
53
+ return result;
54
+ }
55
+ // src/workspace/backup.ts
56
+ function backupsDirectory(env) {
57
+ return join(rucherPaths(env).state, "backups");
58
+ }
59
+ function backupFolder(operation, name, at, env) {
60
+ const stamp = at.toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z");
61
+ return join(backupsDirectory(env), `${stamp}-${operation}-${name}`);
62
+ }
63
+ function writeBackup(db, folder, plan) {
64
+ mkdirSync(folder, { recursive: true });
65
+ db.prepare("VACUUM INTO ?").run(join(folder, "carnet.db"));
66
+ writeFileSync(join(folder, "plan.json"), `${JSON.stringify(plan, null, 2)}\n`);
67
+ }
68
+ // src/workspace/rename.ts
69
+ function requireFree(db, name, env) {
70
+ const rows = workspaceRowCounts(db, name);
71
+ const taken = [
72
+ workspaceExists(name, env) ? "a definition" : null,
73
+ existsSync(workspaceDefinition(name, env)) && !workspaceExists(name, env) ? "a definition folder" : null,
74
+ existsSync(defaultRunDirectory(name, env)) ? "a run directory" : null,
75
+ rows.sessions + rows.notes + rows.activeDays > 0 ? "sessions or notes kept after a drop" : null
76
+ ].filter((reason) => reason !== null);
77
+ if (taken.length) throw new CarnetError("WORKSPACE_EXISTS", `Workspace ${name} already has ${taken.join(", ")}: pick another name`);
78
+ }
79
+ function planWorkspaceRename(db, from, to, options) {
80
+ const env = options.env ?? process.env;
81
+ if (!isWorkspaceName(to)) throw new CarnetError("WORKSPACE_NAME_INVALID", `Invalid workspace name ${JSON.stringify(to)}: use lowercase letters, digits and dashes`);
82
+ const workspace = loadWorkspace(from, env);
83
+ if (from === to) throw new CarnetError("WORKSPACE_EXISTS", `Workspace ${from} already has this name`);
84
+ requireFree(db, to, env);
85
+ const moves = [{
86
+ what: "definition",
87
+ from: workspace.definition,
88
+ to: workspaceDefinition(to, env)
89
+ }];
90
+ const runDirectory = defaultRunDirectory(to, env);
91
+ if (existsSync(workspace.runDirectory)) moves.push({
92
+ what: "run directory",
93
+ from: workspace.runDirectory,
94
+ to: runDirectory
95
+ });
96
+ return {
97
+ from,
98
+ to,
99
+ moves,
100
+ rows: workspaceRowCounts(db, from),
101
+ running: runningWorkspaceSessions(db, from).filter((row) => options.isAlive(row.hostPid))
102
+ };
103
+ }
104
+ function rewriteName(definition, name) {
105
+ const file = join(definition, WORKSPACE_FILE);
106
+ const content = JSON.parse(readFileSync(file, "utf8"));
107
+ if (!("name" in content)) return;
108
+ writeFileSync(file, `${JSON.stringify({
109
+ ...content,
110
+ name
111
+ }, null, 2)}\n`);
112
+ }
113
+ function renameWorkspace(db, from, to, options) {
114
+ const env = options.env ?? process.env;
115
+ const plan = planWorkspaceRename(db, from, to, options);
116
+ if (options.dryRun) return plan;
117
+ if (plan.running.length) throw new CarnetError("WORKSPACE_BUSY", `${plan.running.length} session${plan.running.length === 1 ? "" : "s"} of ${from} still running: ${plan.running.map((row) => row.name ?? row.id.slice(0, 8)).join(", ")}`);
118
+ const workspace = loadWorkspace(from, env);
119
+ const runDirectories = {
120
+ from: workspace.runDirectory,
121
+ to: defaultRunDirectory(to, env)
122
+ };
123
+ const backup = backupFolder("rename", from, (options.now ?? (() => /* @__PURE__ */ new Date()))(), env);
124
+ writeBackup(db, backup, plan);
125
+ const hosts = workspaceHosts(workspace).map((id) => hostById(id));
126
+ const undo = new UndoList();
127
+ let paths = 0;
128
+ try {
129
+ for (const move of plan.moves) moveTracked(undo, move);
130
+ rewriteName(workspaceDefinition(to, env), to);
131
+ for (const host of hosts) {
132
+ const relocation = host.relocateProject?.(runDirectories.from, runDirectories.to, env);
133
+ if (!relocation) continue;
134
+ for (const moved of relocation.moves) plan.moves.push({
135
+ what: `${host.displayName} project folder`,
136
+ ...moved
137
+ });
138
+ for (const step of relocation.undo) undo.push(step);
139
+ }
140
+ paths = renameWorkspaceRows(db, {
141
+ from,
142
+ to
143
+ }, runDirectories).paths;
144
+ } catch (error) {
145
+ relocateFailed(error, undo, backup);
146
+ }
147
+ const warnings = [];
148
+ let trustMoved = false;
149
+ for (const host of hosts) try {
150
+ trustMoved = host.moveTrust?.(runDirectories.from, runDirectories.to, env) || trustMoved;
151
+ } catch (error) {
152
+ warnings.push(`${host.displayName} trust entry not moved: ${error.message}`);
153
+ }
154
+ try {
155
+ renderRunDirectory(loadWorkspace(to, env), { env });
156
+ } catch (error) {
157
+ warnings.push(`run directory not synced: ${error.message}`);
158
+ }
159
+ return {
160
+ ...plan,
161
+ backup,
162
+ paths,
163
+ trustMoved,
164
+ warnings
165
+ };
166
+ }
167
+ // src/workspace/merge.ts
168
+ const BACKENDS_NOTES = join("backends", "claude.md");
169
+ const REPORT_FAMILY = /(\.plan\.md|\.research\.md|\.md)$/;
170
+ function readFile(workspace) {
171
+ return JSON.parse(readFileSync(join(workspace.definition, WORKSPACE_FILE), "utf8"));
172
+ }
173
+ function entries(folder) {
174
+ return existsSync(folder) ? readdirSync(folder).sort() : [];
175
+ }
176
+ function busy(db, names, isAlive) {
177
+ return names.flatMap((name) => runningWorkspaceSessions(db, name).filter((row) => isAlive(row.hostPid)));
178
+ }
179
+ function sessionNameConflicts(db, from, into) {
180
+ return db.prepare(`SELECT name FROM sessions WHERE workspace = ? AND name IS NOT NULL
181
+ AND name IN (SELECT name FROM sessions WHERE workspace = ? AND name IS NOT NULL)
182
+ ORDER BY name`).all(from, into).map((row) => row.name);
183
+ }
184
+ function repoPlan(from, into) {
185
+ const added = [];
186
+ const renamed = [];
187
+ for (const repo of from.repos) {
188
+ const samePath = into.repos.find((existing) => existing.path === repo.path);
189
+ if (samePath) {
190
+ if (samePath.name !== repo.name) renamed.push([repo.name, samePath.name]);
191
+ continue;
192
+ }
193
+ if (into.repos.some((existing) => existing.name === repo.name)) throw new CarnetError("REPO_NAME_TAKEN", `${into.name} already has a repo named ${repo.name} at another path than ${repo.path}: rename one of them first`);
194
+ added.push(repo.path);
195
+ }
196
+ return {
197
+ added,
198
+ renamed
199
+ };
200
+ }
201
+ function conflicts(base, extra, path = []) {
202
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
203
+ if (isObject(base) && isObject(extra)) return Object.keys(extra).flatMap((key) => key in base ? conflicts(base[key], extra[key], [...path, key]) : []);
204
+ if (Array.isArray(base) && Array.isArray(extra)) return [];
205
+ return JSON.stringify(base) === JSON.stringify(extra) ? [] : [path.join(".")];
206
+ }
207
+ function settingsOf(file) {
208
+ const { name: _name, repos: _repos, ...rest } = file;
209
+ return rest;
210
+ }
211
+ function reportMoves(from, into) {
212
+ const source = join(from.runDirectory, "reports");
213
+ const target = join(into.runDirectory, "reports");
214
+ const families = /* @__PURE__ */ new Map();
215
+ for (const file of entries(source)) {
216
+ const family = file.replace(REPORT_FAMILY, "");
217
+ families.set(family, [...families.get(family) ?? [], file]);
218
+ }
219
+ return [...families].flatMap(([family, files]) => {
220
+ const taken = files.some((file) => existsSync(join(target, file)));
221
+ return files.map((file) => ({
222
+ from: join(source, file),
223
+ to: join(target, taken ? `${from.name}-${family}${file.slice(family.length)}` : file)
224
+ }));
225
+ });
226
+ }
227
+ function sandboxMoves(from, into) {
228
+ const source = join(from.runDirectory, "sandboxes");
229
+ const target = join(into.runDirectory, "sandboxes");
230
+ return entries(source).map((name) => ({
231
+ from: join(source, name),
232
+ to: join(target, existsSync(join(target, name)) ? `${from.name}-${name}` : name)
233
+ }));
234
+ }
235
+ function generated(path) {
236
+ if (!lstatSync(path).isFile()) return false;
237
+ return readFileSync(path, "utf8").includes(GENERATED_MARKER);
238
+ }
239
+ function fileMoves(from, into) {
240
+ const moves = [];
241
+ const visit = (folder) => {
242
+ for (const name of entries(folder)) {
243
+ const path = join(folder, name);
244
+ const rest = relative(from.runDirectory, path);
245
+ if (rest === "reports" || rest === "sandboxes") continue;
246
+ if (lstatSync(path).isDirectory()) {
247
+ visit(path);
248
+ continue;
249
+ }
250
+ if (generated(path)) continue;
251
+ const target = join(into.runDirectory, rest);
252
+ moves.push({
253
+ from: path,
254
+ to: existsSync(target) ? join(into.runDirectory, `merged-${from.name}`, rest) : target
255
+ });
256
+ }
257
+ };
258
+ visit(from.runDirectory);
259
+ return moves;
260
+ }
261
+ function planWorkspaceMerge(db, fromName, intoName, options) {
262
+ const env = options.env ?? process.env;
263
+ if (fromName === intoName) throw new CarnetError("WORKSPACE_EXISTS", "Cannot merge a workspace into itself");
264
+ const from = loadWorkspace(fromName, env);
265
+ const into = loadWorkspace(intoName, env);
266
+ const names = sessionNameConflicts(db, fromName, intoName);
267
+ 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})`);
268
+ const repos = repoPlan(from, into);
269
+ const instructions = definitionInstructions(from);
270
+ 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`);
271
+ const rows = workspaceRowCounts(db, fromName);
272
+ const firstNumber = nextNoteNumber(db, intoName);
273
+ const top = db.prepare("SELECT COALESCE(MAX(number), 0) AS top FROM notes WHERE workspace = ?").get(fromName);
274
+ return {
275
+ from: fromName,
276
+ into: intoName,
277
+ rows,
278
+ firstNumber,
279
+ lastNumber: firstNumber - 1 + Number(top.top),
280
+ running: busy(db, [fromName, intoName], options.isAlive),
281
+ reposAdded: repos.added,
282
+ reposRenamed: repos.renamed,
283
+ settingsConflicts: conflicts(settingsOf(readFile(into)), settingsOf(readFile(from))),
284
+ reports: reportMoves(from, into),
285
+ sandboxes: sandboxMoves(from, into),
286
+ files: fileMoves(from, into),
287
+ instructions
288
+ };
289
+ }
290
+ function appendUnder(target, source, heading) {
291
+ if (!existsSync(source)) return;
292
+ const added = readFileSync(source, "utf8").trim();
293
+ if (!added) return;
294
+ mkdirSync(dirname(target), { recursive: true });
295
+ const current = existsSync(target) ? readFileSync(target, "utf8").trimEnd() : "";
296
+ writeFileSync(target, `${current ? `${current}\n\n` : ""}${heading}\n\n${added}\n`);
297
+ }
298
+ function writeDefinition(from, into, plan) {
299
+ const fromFile = readFile(from);
300
+ const intoFile = readFile(into);
301
+ const merged = {
302
+ ...mergeSettings(settingsOf(fromFile), settingsOf(intoFile)),
303
+ name: into.name,
304
+ repos: [...intoFile.repos ?? [], ...(fromFile.repos ?? []).filter((_, index) => plan.reposAdded.includes(from.repos[index]?.path ?? ""))]
305
+ };
306
+ writeFileSync(join(into.definition, WORKSPACE_FILE), `${JSON.stringify(merged, null, 2)}\n`);
307
+ const heading = `## Ex-workspace ${from.name}`;
308
+ appendUnder(join(into.definition, plan.instructions), join(from.definition, plan.instructions), heading);
309
+ appendUnder(join(into.definition, BACKENDS_NOTES), join(from.definition, BACKENDS_NOTES), heading);
310
+ }
311
+ function moveAway(from, to) {
312
+ if (!existsSync(from)) return;
313
+ mkdirSync(dirname(to), { recursive: true });
314
+ try {
315
+ renameSync(from, to);
316
+ } catch (error) {
317
+ if (error.code !== "EXDEV") throw error;
318
+ cpSync(from, to, { recursive: true });
319
+ rmSync(from, {
320
+ recursive: true,
321
+ force: true
322
+ });
323
+ }
324
+ }
325
+ function mergeWorkspaces(db, fromName, intoName, options) {
326
+ const env = options.env ?? process.env;
327
+ const plan = planWorkspaceMerge(db, fromName, intoName, options);
328
+ if (plan.running.length) throw new CarnetError("WORKSPACE_BUSY", `${plan.running.length} session${plan.running.length === 1 ? "" : "s"} still running in ${fromName} or ${intoName}: ${plan.running.map((row) => row.name ?? row.id.slice(0, 8)).join(", ")}`);
329
+ const from = loadWorkspace(fromName, env);
330
+ const into = loadWorkspace(intoName, env);
331
+ const backup = backupFolder("merge", fromName, (options.now ?? (() => /* @__PURE__ */ new Date()))(), env);
332
+ writeBackup(db, backup, plan);
333
+ const hosts = workspaceHosts(from).map((id) => hostById(id));
334
+ const undo = new UndoList();
335
+ let projectMoves = 0;
336
+ try {
337
+ for (const host of hosts) {
338
+ const relocation = host.relocateProject?.(from.runDirectory, into.runDirectory, env, "merge");
339
+ if (!relocation) continue;
340
+ projectMoves += relocation.moves.length;
341
+ for (const step of relocation.undo) undo.push(step);
342
+ }
343
+ for (const move of [
344
+ ...plan.reports,
345
+ ...plan.sandboxes,
346
+ ...plan.files
347
+ ]) {
348
+ mkdirSync(dirname(move.to), { recursive: true });
349
+ moveTracked(undo, move);
350
+ }
351
+ const renamed = new Map([...plan.reports, ...plan.sandboxes].filter((move) => move.to !== join(into.runDirectory, relative(from.runDirectory, move.from))).map((move) => [move.from, move.to]));
352
+ mergeWorkspaceRows(db, {
353
+ names: {
354
+ from: fromName,
355
+ into: intoName
356
+ },
357
+ runDirectories: {
358
+ from: from.runDirectory,
359
+ into: into.runDirectory
360
+ },
361
+ paths: renamed,
362
+ repos: new Map(plan.reposRenamed)
363
+ });
364
+ } catch (error) {
365
+ relocateFailed(error, undo, backup);
366
+ }
367
+ const warnings = [];
368
+ const attempt = (what, run) => {
369
+ try {
370
+ run();
371
+ } catch (error) {
372
+ warnings.push(`${what}: ${error.message}`);
373
+ }
374
+ };
375
+ attempt("definition not merged", () => writeDefinition(from, into, plan));
376
+ attempt("definition of the merged workspace not moved to the backup", () => {
377
+ moveAway(from.definition, join(backup, "definition"));
378
+ moveAway(from.runDirectory, join(backup, "run-directory"));
379
+ });
380
+ let trustDropped = false;
381
+ for (const host of hosts) attempt(`${host.displayName} trust entry not dropped`, () => {
382
+ trustDropped = host.moveTrust?.(from.runDirectory, null, env) || trustDropped;
383
+ });
384
+ attempt("run directory not synced", () => {
385
+ renderRunDirectory(loadWorkspace(intoName, env), { env });
386
+ });
387
+ return {
388
+ ...plan,
389
+ backup,
390
+ projectMoves,
391
+ trustDropped,
392
+ instructionsPath: join(into.definition, plan.instructions),
393
+ warnings
394
+ };
395
+ }
37
396
  // src/hook/session-end.ts
38
397
  function handleSessionEnd(carnet, payload) {
39
398
  if (!carnet.sessions.get(payload.session_id)) return void 0;
399
+ carnet.turn.end(payload.session_id);
40
400
  return carnet.sessions.end(payload.session_id);
41
401
  }
402
+ function handleStop(carnet, payload) {
403
+ if (payload.failed) carnet.turn.fail(payload.session_id);
404
+ else carnet.turn.end(payload.session_id);
405
+ }
42
406
  // src/hook/session-start.ts
43
407
  const SOURCE_EVENTS = {
44
408
  startup: "session.started",
@@ -54,6 +418,17 @@ function adoptFork(carnet, session, env) {
54
418
  if (kind === "active" || kind === "temp") fork = carnet.sessions.setKind(session.id, kind, env.RUCHER_SESSION_NAME || null);
55
419
  return fork;
56
420
  }
421
+ function adoptContinuation(carnet, session, env) {
422
+ const parentId = env.RUCHER_SESSION_ID;
423
+ const parent = parentId && parentId !== session.id ? carnet.sessions.get(parentId) : void 0;
424
+ if (!parent) return void 0;
425
+ const hostEnv = env.CLAUDE_CONFIG_DIR ? { CLAUDE_CONFIG_DIR: env.CLAUDE_CONFIG_DIR } : {};
426
+ if (!hostById(session.host).continues(parent, session.id, hostEnv)) return void 0;
427
+ carnet.memory.copyRepos(parent.id, session.id);
428
+ let merged = carnet.sessions.merge(parent.id, session.id).session;
429
+ merged = carnet.sessions.recordPromptVersion(merged.id, parent.promptVersion);
430
+ return parent.parentId ? carnet.sessions.setParent(merged.id, parent.parentId) : merged;
431
+ }
57
432
  function startMemory(carnet, session, source, env) {
58
433
  const options = {
59
434
  maxCharacters: memoryMaxCharacters(env.RUCHER_MEMORY_MAX_CHARACTERS),
@@ -64,11 +439,18 @@ function startMemory(carnet, session, source, env) {
64
439
  }
65
440
  function handleSessionStart(carnet, payload, env) {
66
441
  let session = carnet.sessions.upsertFromHook(payload, env);
67
- const source = payload.source ?? "";
68
- if (source === "fork") session = adoptFork(carnet, session, env);
442
+ let source = payload.source ?? "";
443
+ if (source === "fork") {
444
+ const continued = adoptContinuation(carnet, session, env);
445
+ if (continued) {
446
+ session = continued;
447
+ source = "resume";
448
+ } else session = adoptFork(carnet, session, env);
449
+ }
69
450
  const event = SOURCE_EVENTS[source];
70
451
  if (event) carnet.events.log(session.id, { type: event });
71
452
  session = carnet.sessions.setStatus(session.id, "running");
453
+ if (source !== "compact") carnet.turn.end(session.id);
72
454
  carnet.sessions.purge(session.id, purgeDays(env.RUCHER_PURGE_DAYS));
73
455
  const promptEnv = { RUCHER_HOME: env.RUCHER_HOME };
74
456
  const launchedVersion = env.RUCHER_PROMPT_VERSION || null;
@@ -92,14 +474,535 @@ function handleSessionStart(carnet, payload, env) {
92
474
  };
93
475
  }
94
476
  // src/hook/user-prompt-submit.ts
95
- function handleUserPromptSubmit(carnet, host, payload) {
477
+ function handleUserPromptSubmit(carnet, host, payload, options = {}) {
96
478
  carnet.sessions.ensure(payload.session_id, payload.cwd);
479
+ if (options.trackTurn ?? true) carnet.turn.start(payload.session_id);
97
480
  carnet.notes.recordActiveDay();
98
481
  return carnet.sessions.adoptTitle(payload.session_id, host.promptTitle(payload));
99
482
  }
483
+ // src/shell.ts
484
+ const GIT_ENV = /* @__PURE__ */ new Set(["GIT_DIR", "GIT_WORK_TREE"]);
485
+ const KEYWORDS = /* @__PURE__ */ new Set([
486
+ "!",
487
+ "{",
488
+ "}",
489
+ "if",
490
+ "then",
491
+ "else",
492
+ "elif",
493
+ "do",
494
+ "while",
495
+ "until"
496
+ ]);
497
+ const SHELLS = /* @__PURE__ */ new Set([
498
+ "sh",
499
+ "bash",
500
+ "zsh",
501
+ "dash",
502
+ "ksh"
503
+ ]);
504
+ const PLAIN_WRAPPERS = /* @__PURE__ */ new Set([
505
+ "command",
506
+ "builtin",
507
+ "exec",
508
+ "nohup",
509
+ "time"
510
+ ]);
511
+ const SUDO_VALUES = /* @__PURE__ */ new Set([
512
+ "-u",
513
+ "-g",
514
+ "-h",
515
+ "-p",
516
+ "-C",
517
+ "-D",
518
+ "-r",
519
+ "-t",
520
+ "-U"
521
+ ]);
522
+ const XARGS_VALUES = /* @__PURE__ */ new Set([
523
+ "-I",
524
+ "-L",
525
+ "-n",
526
+ "-P",
527
+ "-d",
528
+ "-E",
529
+ "-s",
530
+ "-a"
531
+ ]);
532
+ const GIT_VALUES = /* @__PURE__ */ new Set([
533
+ "-C",
534
+ "-c",
535
+ "--git-dir",
536
+ "--work-tree",
537
+ "--namespace",
538
+ "--config-env",
539
+ "--super-prefix",
540
+ "--exec-path",
541
+ "--list-cmds",
542
+ "--attr-source"
543
+ ]);
544
+ const MAX_DEPTH = 1;
545
+ function absolute$1(path, cwd) {
546
+ if (path === "~" || path.startsWith("~/")) return join(homedir(), path.slice(1));
547
+ return isAbsolute(path) ? path : resolve(cwd, path);
548
+ }
549
+ function copy(state) {
550
+ return {
551
+ cwd: state.cwd,
552
+ env: new Map(state.env)
553
+ };
554
+ }
555
+ var Reader = class Reader {
556
+ src;
557
+ depth;
558
+ out;
559
+ pos = 0;
560
+ heredocs = [];
561
+ constructor(src, depth, out) {
562
+ this.src = src;
563
+ this.depth = depth;
564
+ this.out = out;
565
+ }
566
+ walk(state, closer) {
567
+ let words = [];
568
+ let text = "";
569
+ let dynamic = false;
570
+ let started = false;
571
+ let skipTarget = false;
572
+ let previous = null;
573
+ const endWord = () => {
574
+ if (started) {
575
+ if (skipTarget) skipTarget = false;
576
+ else words.push({
577
+ text,
578
+ dynamic
579
+ });
580
+ }
581
+ text = "";
582
+ dynamic = false;
583
+ started = false;
584
+ };
585
+ const endCommand = (separator) => {
586
+ endWord();
587
+ const piped = previous === "|" || separator === "|";
588
+ this.command(words, state, piped);
589
+ words = [];
590
+ skipTarget = false;
591
+ previous = separator;
592
+ };
593
+ const nested = (until) => {
594
+ this.walk(copy(state), until);
595
+ dynamic = true;
596
+ started = true;
597
+ };
598
+ while (this.pos < this.src.length) {
599
+ const c = this.src[this.pos] ?? "";
600
+ const next = this.src[this.pos + 1] ?? "";
601
+ if (closer !== null && c === closer) {
602
+ this.pos++;
603
+ endCommand(null);
604
+ return;
605
+ }
606
+ if (c === " " || c === " ") {
607
+ endWord();
608
+ this.pos++;
609
+ } else if (c === "\n") {
610
+ this.pos++;
611
+ endCommand("\n");
612
+ this.skipHeredocs();
613
+ } else if (c === "#" && !started) while (this.pos < this.src.length && this.src[this.pos] !== "\n") this.pos++;
614
+ else if (c === "\\") {
615
+ if (next !== "\n") {
616
+ text += next;
617
+ started = true;
618
+ }
619
+ this.pos += 2;
620
+ } else if (c === "'") {
621
+ const end = this.src.indexOf("'", this.pos + 1);
622
+ const stop = end === -1 ? this.src.length : end;
623
+ text += this.src.slice(this.pos + 1, stop);
624
+ started = true;
625
+ this.pos = stop + 1;
626
+ } else if (c === "\"") {
627
+ this.pos++;
628
+ started = true;
629
+ while (this.pos < this.src.length && this.src[this.pos] !== "\"") {
630
+ const d = this.src[this.pos] ?? "";
631
+ if (d === "\\" && "\"\\$`".includes(this.src[this.pos + 1] ?? "")) {
632
+ text += this.src[this.pos + 1];
633
+ this.pos += 2;
634
+ } else if (d === "$" && this.src[this.pos + 1] === "(") {
635
+ this.pos += 2;
636
+ nested(")");
637
+ } else if (d === "`") {
638
+ this.pos++;
639
+ nested("`");
640
+ } else {
641
+ if (d === "$") dynamic = true;
642
+ text += d;
643
+ this.pos++;
644
+ }
645
+ }
646
+ this.pos++;
647
+ } else if (c === "$" && next === "(" && this.src[this.pos + 2] === "(") {
648
+ const end = this.src.indexOf("))", this.pos);
649
+ this.pos = end === -1 ? this.src.length : end + 2;
650
+ dynamic = true;
651
+ started = true;
652
+ } else if (c === "$" && next === "(") {
653
+ this.pos += 2;
654
+ nested(")");
655
+ } else if (c === "$" && next === "'") {
656
+ this.pos += 2;
657
+ while (this.pos < this.src.length && this.src[this.pos] !== "'") {
658
+ if (this.src[this.pos] === "\\") this.pos++;
659
+ text += this.src[this.pos] ?? "";
660
+ this.pos++;
661
+ }
662
+ this.pos++;
663
+ started = true;
664
+ } else if (c === "$") {
665
+ text += c;
666
+ dynamic = true;
667
+ started = true;
668
+ this.pos++;
669
+ } else if (c === "`") {
670
+ this.pos++;
671
+ nested("`");
672
+ } else if (c === ";") {
673
+ this.pos += next === ";" ? 2 : 1;
674
+ endCommand(";");
675
+ } else if (c === "&" && next === "&") {
676
+ this.pos += 2;
677
+ endCommand("&&");
678
+ } else if (c === "&" && next === ">") {
679
+ endWord();
680
+ this.pos += this.src[this.pos + 2] === ">" ? 3 : 2;
681
+ skipTarget = true;
682
+ } else if (c === "&") {
683
+ this.pos++;
684
+ endCommand("&");
685
+ } else if (c === "|" && next === "|") {
686
+ this.pos += 2;
687
+ endCommand("||");
688
+ } else if (c === "|") {
689
+ this.pos += next === "&" ? 2 : 1;
690
+ endCommand("|");
691
+ } else if (c === "(" && !started && words.length === 0) {
692
+ this.pos++;
693
+ this.walk(copy(state), ")");
694
+ } else if ((c === "<" || c === ">") && next === "(") {
695
+ endWord();
696
+ this.pos += 2;
697
+ this.walk(copy(state), ")");
698
+ } else if (c === "<" || c === ">") {
699
+ if (started && /^\d+$/.test(text)) {
700
+ text = "";
701
+ started = false;
702
+ }
703
+ endWord();
704
+ skipTarget = this.redirect();
705
+ } else {
706
+ if (c === "*" || c === "?" || c === "[") dynamic = true;
707
+ text += c;
708
+ started = true;
709
+ this.pos++;
710
+ }
711
+ }
712
+ endCommand(null);
713
+ }
714
+ redirect() {
715
+ if (this.src.startsWith("<<<", this.pos)) {
716
+ this.pos += 3;
717
+ return true;
718
+ }
719
+ if (this.src.startsWith("<<", this.pos)) {
720
+ this.pos += 2;
721
+ const strip = this.src[this.pos] === "-";
722
+ if (strip) this.pos++;
723
+ while (this.src[this.pos] === " " || this.src[this.pos] === " ") this.pos++;
724
+ const match = /^(?:'([^']*)'|"([^"]*)"|([^\s;&|<>()]+))/.exec(this.src.slice(this.pos));
725
+ if (match) {
726
+ this.heredocs.push({
727
+ delimiter: match[1] ?? match[2] ?? match[3] ?? "",
728
+ strip
729
+ });
730
+ this.pos += match[0].length;
731
+ }
732
+ return false;
733
+ }
734
+ this.pos++;
735
+ if (">&|".includes(this.src[this.pos] ?? "")) this.pos++;
736
+ return true;
737
+ }
738
+ skipHeredocs() {
739
+ for (const { delimiter, strip } of this.heredocs) while (this.pos < this.src.length) {
740
+ const end = this.src.indexOf("\n", this.pos);
741
+ const stop = end === -1 ? this.src.length : end;
742
+ let line = this.src.slice(this.pos, stop);
743
+ if (strip) line = line.replace(/^\t+/, "");
744
+ this.pos = stop + 1;
745
+ if (line === delimiter) break;
746
+ }
747
+ this.heredocs = [];
748
+ }
749
+ command(all, state, piped) {
750
+ let words = all;
751
+ while (words[0] && KEYWORDS.has(words[0].text)) words = words.slice(1);
752
+ const env = new Map(state.env);
753
+ const assigned = /* @__PURE__ */ new Map();
754
+ const assign = (word) => {
755
+ const at = word.text.indexOf("=");
756
+ const name = word.text.slice(0, at);
757
+ if (GIT_ENV.has(name)) assigned.set(name, word.dynamic ? void 0 : word.text.slice(at + 1));
758
+ };
759
+ while (words[0] && /^[A-Za-z_]\w*=/.test(words[0].text)) {
760
+ assign(words[0]);
761
+ words = words.slice(1);
762
+ }
763
+ if (words.length === 0) {
764
+ if (!piped) for (const [name, value] of assigned) state.env.set(name, value);
765
+ return;
766
+ }
767
+ words = this.unwrap(words, assign);
768
+ for (const [name, value] of assigned) env.set(name, value);
769
+ const name = words[0]?.text ?? "";
770
+ const args = words.slice(1);
771
+ if (name === "cd" || name === "pushd" || name === "popd") {
772
+ if (!piped) state.cwd = this.cd(name, args, state.cwd);
773
+ return;
774
+ }
775
+ if (name === "export") {
776
+ for (const word of args) if (word.text.includes("=")) assign(word);
777
+ if (!piped) for (const [key, value] of assigned) state.env.set(key, value);
778
+ return;
779
+ }
780
+ if (this.depth < MAX_DEPTH && SHELLS.has(basename(name))) {
781
+ const flag = args.findIndex((word) => /^-[a-z]*c[a-z]*$/.test(word.text));
782
+ const script = flag === -1 ? void 0 : args[flag + 1];
783
+ if (script) this.nested(script.text, {
784
+ cwd: state.cwd,
785
+ env
786
+ });
787
+ return;
788
+ }
789
+ if (this.depth < MAX_DEPTH && name === "eval") {
790
+ this.nested(args.map((word) => word.text).join(" "), {
791
+ cwd: state.cwd,
792
+ env
793
+ });
794
+ return;
795
+ }
796
+ if (words.length > 0) this.out.push({
797
+ words,
798
+ cwd: state.cwd,
799
+ env
800
+ });
801
+ }
802
+ unwrap(start, assign) {
803
+ let words = start;
804
+ for (;;) {
805
+ const name = words[0]?.text ?? "";
806
+ let i = 1;
807
+ if (name === "env") while (words[i] && (words[i]?.text.startsWith("-") || words[i]?.text.includes("="))) {
808
+ const word = words[i];
809
+ if (word.text.includes("=") && !word.text.startsWith("-")) assign(word);
810
+ i += word.text === "-u" || word.text === "-C" ? 2 : 1;
811
+ }
812
+ else if (PLAIN_WRAPPERS.has(name)) while (words[i]?.text.startsWith("-")) i++;
813
+ else if (name === "sudo") while (words[i]?.text.startsWith("-")) i += SUDO_VALUES.has(words[i]?.text ?? "") ? 2 : 1;
814
+ else if (name === "xargs") while (words[i]?.text.startsWith("-")) i += XARGS_VALUES.has(words[i]?.text ?? "") ? 2 : 1;
815
+ else return words;
816
+ words = words.slice(i);
817
+ }
818
+ }
819
+ cd(name, args, cwd) {
820
+ if (name !== "cd") return void 0;
821
+ const target = args.find((word) => !/^-[LPe@]+$/.test(word.text));
822
+ if (!target) return homedir();
823
+ if (target.dynamic || target.text === "-") return void 0;
824
+ if (isAbsolute(target.text) || target.text.startsWith("~")) return absolute$1(target.text, "/");
825
+ return cwd === void 0 ? void 0 : absolute$1(target.text, cwd);
826
+ }
827
+ nested(script, state) {
828
+ new Reader(script, this.depth + 1, this.out).walk(state, null);
829
+ }
830
+ };
831
+ function commandsOf(command, cwd, depth) {
832
+ const out = [];
833
+ new Reader(command, depth, out).walk({
834
+ cwd,
835
+ env: /* @__PURE__ */ new Map()
836
+ }, null);
837
+ return out;
838
+ }
839
+ function shellCommands(command, cwd) {
840
+ return commandsOf(command, cwd, 0);
841
+ }
842
+ function gitCall(cmd) {
843
+ const words = cmd.words;
844
+ let base = cmd.cwd;
845
+ const paths = [];
846
+ const aliases = /* @__PURE__ */ new Map();
847
+ let i = 1;
848
+ while (i < words.length && words[i]?.text.startsWith("-")) {
849
+ const word = words[i];
850
+ const at = word.text.startsWith("--") ? word.text.indexOf("=") : -1;
851
+ const option = at === -1 ? word.text : word.text.slice(0, at);
852
+ let value;
853
+ if (at !== -1) {
854
+ value = {
855
+ text: word.text.slice(at + 1),
856
+ dynamic: word.dynamic
857
+ };
858
+ i++;
859
+ } else if (GIT_VALUES.has(option)) {
860
+ value = words[i + 1];
861
+ i += 2;
862
+ } else i++;
863
+ if (option === "-C") base = !value || value.dynamic || base === void 0 ? void 0 : absolute$1(value.text, base);
864
+ else if (option === "--git-dir" || option === "--work-tree") paths.push(value);
865
+ else if (option === "-c" && value?.text.startsWith("alias.")) {
866
+ const eq = value.text.indexOf("=");
867
+ if (eq !== -1) aliases.set(value.text.slice(6, eq), value.text.slice(eq + 1));
868
+ }
869
+ }
870
+ const verbWord = words[i];
871
+ if (!verbWord) return [];
872
+ let rest = words.slice(i + 1);
873
+ let verb = verbWord.text;
874
+ const alias = aliases.get(verb);
875
+ if (alias !== void 0) {
876
+ if (alias.startsWith("!")) return gitCallsIn(commandsOf(alias.slice(1), base, MAX_DEPTH));
877
+ const [first = "", ...more] = alias.trim().split(/\s+/);
878
+ verb = first;
879
+ rest = [...more.map((text) => ({
880
+ text,
881
+ dynamic: false
882
+ })), ...rest];
883
+ }
884
+ const resolved = (path) => path === void 0 || base === void 0 ? void 0 : absolute$1(path, base);
885
+ const dirs = [base];
886
+ for (const path of paths) dirs.push(!path || path.dynamic ? void 0 : resolved(path.text));
887
+ for (const name of GIT_ENV) if (cmd.env.has(name)) dirs.push(resolved(cmd.env.get(name)));
888
+ const first = rest[0]?.text;
889
+ const sub = first === void 0 || first.startsWith("-") ? void 0 : first;
890
+ return [{
891
+ verb,
892
+ sub,
893
+ dirs
894
+ }];
895
+ }
896
+ function gitCallsIn(commands) {
897
+ return commands.filter((cmd) => basename(cmd.words[0]?.text ?? "") === "git").flatMap((cmd) => gitCall(cmd));
898
+ }
899
+ function gitCalls(command, cwd) {
900
+ return gitCallsIn(shellCommands(command, cwd));
901
+ }
902
+ // src/guard.ts
903
+ const GUARDED_TOOLS = /* @__PURE__ */ new Set([
904
+ "Edit",
905
+ "Write",
906
+ "NotebookEdit",
907
+ "Bash"
908
+ ]);
909
+ const FILE_TOOLS = /* @__PURE__ */ new Set([
910
+ "Edit",
911
+ "Write",
912
+ "NotebookEdit"
913
+ ]);
914
+ const PUBLISHING = /* @__PURE__ */ new Set([
915
+ "commit",
916
+ "push",
917
+ "stash"
918
+ ]);
919
+ const READ_ONLY_STASH = /* @__PURE__ */ new Set(["list", "show"]);
920
+ function realish(path) {
921
+ const full = resolve(path);
922
+ const parent = dirname(full);
923
+ try {
924
+ return realpathSync(full);
925
+ } catch {
926
+ return parent === full ? full : join(realish(parent), basename(full));
927
+ }
928
+ }
929
+ function inside(path, folder) {
930
+ const rest = relative(realish(folder), realish(path));
931
+ return rest === "" || !rest.startsWith("..") && !isAbsolute(rest);
932
+ }
933
+ function absolute(path, cwd) {
934
+ if (path === "~" || path.startsWith("~/")) return join(homedir(), path.slice(1));
935
+ return isAbsolute(path) ? path : resolve(cwd ?? "/", path);
936
+ }
937
+ function inScratch(path, input) {
938
+ return input.scratchRoots.some((root) => inside(path, root));
939
+ }
940
+ function writable(path, input) {
941
+ return inScratch(path, input) || !!input.sandbox && inside(path, input.sandbox);
942
+ }
943
+ function publishing(call) {
944
+ return PUBLISHING.has(call.verb) && !(call.verb === "stash" && READ_ONLY_STASH.has(call.sub ?? ""));
945
+ }
946
+ function fileToolViolation(input, contract) {
947
+ if (input.kind === "implement") {
948
+ if (!input.worktree || !input.filePath) return void 0;
949
+ const path = absolute(input.filePath, input.cwd);
950
+ if (inside(path, input.worktree) || inScratch(path, input)) return void 0;
951
+ return `${contract} limits writes to its worktree ${input.worktree}`;
952
+ }
953
+ if (input.filePath && writable(absolute(input.filePath, input.cwd), input)) return void 0;
954
+ 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`;
955
+ }
956
+ function guardToolCall(input) {
957
+ const contract = `the ${input.kind} contract`;
958
+ if (FILE_TOOLS.has(input.toolName)) return fileToolViolation(input, contract);
959
+ if (input.toolName !== "Bash") return void 0;
960
+ const calls = gitCalls(input.command ?? "", input.cwd).filter(publishing);
961
+ if (calls.length === 0) return void 0;
962
+ const sandbox = input.sandbox;
963
+ if (!sandbox || input.kind === "implement") return `${contract} forbids git commit, push and stash: the human commits`;
964
+ if (calls.some((call) => call.verb === "push")) return `${contract} forbids git push`;
965
+ const confined = (dir) => dir !== void 0 && inside(dir, sandbox);
966
+ if (calls.every((call) => call.dirs.every(confined))) return void 0;
967
+ return `${contract} allows git commit and stash only in its sandbox ${sandbox}`;
968
+ }
969
+ function kindOfAgentType(agentType) {
970
+ return /^rucher[\w-]*:(research|review)$/.exec(agentType ?? "")?.[1];
971
+ }
972
+ // src/launch.ts
973
+ const LAUNCH_TOOLS = /* @__PURE__ */ new Set([
974
+ "Agent",
975
+ "Task",
976
+ "EnterPlanMode"
977
+ ]);
978
+ 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.";
979
+ const EXPECTED_TYPES = {
980
+ research: "fork, or the rucher research agent with --cold",
981
+ plan: "fork",
982
+ implement: "fork",
983
+ review: "the rucher review agent"
984
+ };
985
+ function fitsKind(kind, subagentType) {
986
+ const type = subagentType ?? "";
987
+ if (kind === "plan" || kind === "implement") return type === "fork";
988
+ if (kind === "research") return type === "fork" || /(^|:)research$/.test(type);
989
+ return /(^|:)review$/.test(type);
990
+ }
991
+ function guardLaunch(call) {
992
+ if (call.toolName === "EnterPlanMode") {
993
+ const pending = call.pendingPlan;
994
+ if (!pending) return void 0;
995
+ 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.`;
996
+ }
997
+ if (call.subagentType === "Plan") return BUILT_IN_PLAN_DENIED;
998
+ const named = call.named;
999
+ if (!named || fitsKind(named.kind, call.subagentType)) return void 0;
1000
+ return `${named.name} is a Rucher ${named.kind} agent: launch it with subagent_type ${EXPECTED_TYPES[named.kind]}, not ${call.subagentType ?? "no subagent_type"}.`;
1001
+ }
100
1002
  // src/hook/post-tool-use.ts
101
- function handleToolUse(carnet, payload, env) {
1003
+ function handleToolUse(carnet, payload, env, options = {}) {
102
1004
  if (payload.agent_id) return void 0;
1005
+ if (options.trackTurn ?? true) carnet.turn.start(payload.session_id);
103
1006
  const repo = repoNameFor(carnet.workspace, payload.path);
104
1007
  if (!repo) return void 0;
105
1008
  const session = carnet.sessions.ensure(payload.session_id, payload.cwd);
@@ -108,22 +1011,85 @@ function handleToolUse(carnet, payload, env) {
108
1011
  halfLifeDays: memoryHalfLife(env.RUCHER_MEMORY_HALF_LIFE_DAYS)
109
1012
  });
110
1013
  }
111
- // src/render.ts
112
- function renderRunDirectory(workspace, options = {}) {
113
- mkdirSync(workspace.runDirectory, { recursive: true });
114
- mkdirSync(reportsDirectory(workspace), { recursive: true });
115
- const result = {
116
- runDirectory: workspace.runDirectory,
117
- written: [],
118
- removed: []
119
- };
120
- for (const id of options.host ? [options.host] : workspaceHosts(workspace)) {
121
- const rendered = hostById(id).renderRunDirectory(workspace);
122
- result.written.push(...rendered.written);
123
- result.removed.push(...rendered.removed);
1014
+ const WAITING_TOOL = "AskUserQuestion";
1015
+ function handleToolStart(carnet, payload) {
1016
+ if (payload.agent_id || payload.tool_name !== "AskUserQuestion") return;
1017
+ carnet.turn.wait(payload.session_id);
1018
+ }
1019
+ function guardSubagentCall(carnet, payload, scratchRoots) {
1020
+ if (!payload.agent_id || !payload.tool_name) return void 0;
1021
+ const agent = carnet.agents.byHostAgentId(payload.session_id, payload.agent_id);
1022
+ const kind = agent?.kind ?? kindOfAgentType(payload.agent_type);
1023
+ if (!kind) return void 0;
1024
+ return guardToolCall({
1025
+ kind,
1026
+ toolName: payload.tool_name,
1027
+ filePath: payload.file_path,
1028
+ command: payload.command,
1029
+ cwd: payload.cwd,
1030
+ worktree: agent?.worktree,
1031
+ sandbox: agent?.sandbox,
1032
+ scratchRoots
1033
+ });
1034
+ }
1035
+ function guardMainLaunch(carnet, payload) {
1036
+ if (payload.agent_id || !payload.tool_name) return void 0;
1037
+ if (!carnet.sessions.get(payload.session_id)) return void 0;
1038
+ const named = carnet.agents.unpaired(payload.session_id, payload.launched_names ?? []);
1039
+ const reason = guardLaunch({
1040
+ toolName: payload.tool_name,
1041
+ subagentType: payload.subagent_type,
1042
+ named,
1043
+ pendingPlan: payload.tool_name === "EnterPlanMode" ? carnet.agents.pendingPlan(payload.session_id) : void 0
1044
+ });
1045
+ if (!reason && named && payload.tool_name !== "EnterPlanMode") carnet.agents.requestLaunch(payload.session_id, named.name);
1046
+ return reason;
1047
+ }
1048
+ // src/status/line.ts
1049
+ const STATUS_LINE_LABEL = "rucher";
1050
+ const TURN_LABELS = {
1051
+ working: "⚙️ working",
1052
+ waiting: "⏸ waiting on you",
1053
+ failed: "⚠ turn failed"
1054
+ };
1055
+ function counts(lines) {
1056
+ const byEmoji = /* @__PURE__ */ new Map();
1057
+ for (const line of lines) byEmoji.set(line.emoji, (byEmoji.get(line.emoji) ?? 0) + 1);
1058
+ return [...byEmoji].map(([emoji, count]) => `${emoji}${count}`).join(" ");
1059
+ }
1060
+ function renderStatusLine(view, lag = null) {
1061
+ if (lag) return lag;
1062
+ const parts = [];
1063
+ if (view.turn) parts.push(TURN_LABELS[view.turn]);
1064
+ const [next] = view.waiting;
1065
+ if (next) {
1066
+ const action = next.action ? ` ${next.action}` : "";
1067
+ parts.push(`next: ${next.emoji} ${kindTag(next.kind)} ${next.name}${action}`);
1068
+ parts.push(counts(view.waiting));
124
1069
  }
125
- return result;
1070
+ if (view.running.length > 0) parts.push(`${EMOJI.running}${view.running.length}`);
1071
+ if (view.blocked.length > 0) parts.push(`⛓${view.blocked.length}`);
1072
+ return parts.join(" · ");
1073
+ }
1074
+ function labelStatusLine(line) {
1075
+ return line ? `${STATUS_LINE_LABEL} · ${line}` : "";
1076
+ }
1077
+ function statusLinePath(sessionId, env) {
1078
+ return join(rucherPaths(env).state, "status", `${sessionId}.txt`);
1079
+ }
1080
+ function writeStatusLine(carnet, sessionId, options = {}) {
1081
+ const path = statusLinePath(sessionId, options.env);
1082
+ const session = carnet.sessions.get(sessionId);
1083
+ if (!session || session.status === "archived") {
1084
+ rmSync(path, { force: true });
1085
+ return;
1086
+ }
1087
+ const line = renderStatusLine(carnet.status.view(session), options.lag ?? null);
1088
+ mkdirSync(join(path, ".."), { recursive: true });
1089
+ const temporary = `${path}.${process.pid}.tmp`;
1090
+ writeFileSync(temporary, line ? `${line}\n` : "");
1091
+ renameSync(temporary, path);
126
1092
  }
127
- export { AGENTS_FILE, AGENT_STATUSES, AGENT_STEPS, CORE_RULES, Carnet, CarnetError, DEFAULT_HALF_LIFE_DAYS, DEFAULT_HOST, DEFAULT_PURGE_DAYS, DUPLICATE_SIMILARITY, EMOJI, EVENT_TYPES, GENERATED_MARKER, INSTRUCTIONS_FILE, LEGEND, 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, SESSION_EVENT_TYPES, SIMILAR_PREFIX, STALE_AFTER_ACTIVE_DAYS, STOPPED_NOTE, SUBAGENT_RULES, USER_ACTION_STATUSES, WORKSPACE_FILE, addWorkspaceRepo, allHosts, ambiguousWorkspaceContext, appendPromptFile, archiveWorkspaceSessions, assemblePrompt, baseRules, buildStatusView, claudeCode, compactReminder, corePromptPath, createWorkspace, databasePath, defaultRunDirectory, definitionInstructions, deleteWorkspaceNotes, dropWorkspace, expandHome, formatClock, formatEventLine, handleSessionEnd, handleSessionStart, handleToolUse, handleUserPromptSubmit, hostById, isAgentStatus, isEventType, isInside, isNoteKind, isUserActionStatus, isWorkspaceName, listWorkspaces, loadWorkspace, localDay, markdownCopy, memoryHalfLife, memoryMaxCharacters, mergeSettings, migrate, migrations, moveSession, openCarnet, openDatabase, openResolvedCarnet, openWorkspaceCarnet, outsideRucherContext, promptsDirectory, purgeDays, removeStaleCopies, removeWorkspaceRepo, renderAgentLine, renderMemory, renderNoteLine, renderNotes, renderNotesSummary, renderRunDirectory, renderSections, renderStatus, renderTableLine, repoNameFor, repoPathFor, reportPath, reportsDirectory, requireWorkspace, resolveWorkspace, resumeContext, rucherPaths, rulesText, rulesVersion, sanitizeNote, schemaVersion, sessionLabel, sessionNoteActivity, sessionWorkspaceName, shortId, similarity, stepAgent, transcriptTitle, workspaceDefinition, workspaceExists, workspaceHosts, workspaceLabel, workspaceRepoNames, workspaceRules, workspaceSessionCounts, workspaceSettings, workspacesDirectory, writeGenerated };
1093
+ 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, 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 };
128
1094
 
129
1095
  //# sourceMappingURL=index.mjs.map