@rucher/carnet 0.2.0-beta.9 → 0.3.0-beta.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/{carnet-DcHESFRd.d.mts → carnet-BFA2yya4.d.mts} +17 -3
- package/dist/carnet-BFA2yya4.d.mts.map +1 -0
- package/dist/index.d.mts +88 -6
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +819 -85
- package/dist/index.mjs.map +1 -1
- package/dist/mcp.d.mts +2 -2
- package/dist/mcp.d.mts.map +1 -1
- package/dist/mcp.mjs +9 -249
- package/dist/mcp.mjs.map +1 -1
- package/dist/{steps-wNm8GU_c.mjs → steps-j8vhVj8h.mjs} +624 -46
- package/dist/steps-j8vhVj8h.mjs.map +1 -0
- package/package.json +1 -1
- package/dist/carnet-DcHESFRd.d.mts.map +0 -1
- package/dist/steps-wNm8GU_c.mjs.map +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { $ as
|
|
2
|
-
import { mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
-
import { isAbsolute, join, relative, resolve } from "node:path";
|
|
1
|
+
import { $ as DEFAULT_HALF_LIFE_DAYS, $n as MAIN_WORKING_EMOJI, $t as rulesVersion, A as BLOCKED_HEADER, An as MEMORY_DB, At as claudeConfigFile, B as renderMainLine, Bn as SANDBOX_KINDS, Bt as mergeSettings, C as openResolvedCarnet, Cn as promptsDirectory, Ct as workspaceLastActive, D as buildStatusView, Dn as sandboxesDirectory, Dt as allHosts, E as STOPPED_NOTE, En as rucherPaths, Et as DEFAULT_HOST, F as MAIN_WORKING_SUFFIX, Fn as AGENT_KINDS, Ft as moveTracked, G as renderStatus, Gn as AGENT_STATUSES, Gt as RULES_UPDATED_NOTICE, H as renderNotes, Hn as statusWhenDone, Ht as writeGenerated, I as NOTES_FOLD_LINES, In as KIND_REQUIRED, It as relocateFailed, J as purgeDays, Jn as KIND_LEGEND, Jt as assemblePrompt, K as renderTableLine, Kn as EMOJI, Kt as SUBAGENT_RULES, L as NOTES_HEADER, Lt as GENERATED_MARKER, M as MAIN_HEADER, Mn as migrate, Mt as transcriptTitle, N as MAIN_IDLE, Nn as migrations, Nt as workspaceSettings, O as formatClock, On as workspaceDefinition, Ot as hostById, P as MAIN_WAITING_SUFFIX, Pn as schemaVersion, Pt as UndoList, Q as renderMemory, Qn as MAIN_WAITING_EMOJI, Qt as rulesText, R as SIMILAR_PREFIX, Rn as PUBLISH_FALLBACK_MILLISECONDS, Rt as MARKDOWN_MARKER, S as openCarnet, Sn as defaultRunDirectory, St as sessionWorkspaceName, T as PAIRING_WINDOW_MILLISECONDS, Tn as reportsDirectory, Tt as workspaceSessionCounts, U as renderNotesSummary, Un as NOTE_MAX, Ut as OUTSIDE_RUCHER_NOTICE, V as renderNoteLine, Vn as isAgentKind, Vt as removeStaleCopies, W as renderSections, Wn as sanitizeNote, Wt as PROMPT_FILE, X as MEMORY_MAX_CHARACTERS, Xn as LEGEND, Xt as compactReminder, Yn as KIND_TAG_PATTERN, Yt as baseRules, Z as memoryMaxCharacters, Zn as MAIN_FAILED_EMOJI, Zt as outsideRucherContext, _n as workspaceHosts, _t as deleteWorkspaceNotes, a as formatEventLine, an as INSTRUCTIONS_FILE, ar as EVENT_TYPES, at as localDay, bn as corePromptPath, bt as renameWorkspaceRows, cn as createWorkspace, cr as CarnetError, ct as similarity, dn as expandHome, dt as repoNameFor, en as workspaceRules, et as DUPLICATE_SIMILARITY, fn as isWorkspaceName, ft as repoPathFor, gn as workspaceExists, gt as archiveWorkspaceSessions, h as nextAgent, hn as removeWorkspaceRepo, ht as workspaceLabel, i as RESUME_MAX_CHARACTERS, in as AGENTS_FILE, ir as kindTag, it as isNoteKind, j as MAIN_FAILED_SUFFIX, jn as openDatabase, jt as claudeProjectFolder, k as TURNS, kn as workspacesDirectory, kt as claudeCode, ln as definitionInstructions, lt as workspaceRepoNames, m as locateAgent, mn as loadWorkspace, mt as resolveWorkspace, n as stepAgent, nn as MINIMUM_ID_PREFIX, nr as isAgentStatus, nt as NOTE_TEXT_LIMIT, o as resumeContext, on as WORKSPACE_FILE, or as SESSION_EVENT_TYPES, ot as memoryHalfLife, pn as listWorkspaces, pt as requireWorkspace, q as DEFAULT_PURGE_DAYS, qn as KIND_ABBREVIATIONS, qt as appendPromptFile, r as RESUME_EVENTS, rn as shortId, rr as isUserActionStatus, rt as STALE_AFTER_ACTIVE_DAYS, s as sessionLabel, sn as addWorkspaceRepo, sr as isEventType, st as sessionNoteActivity, t as AGENT_STEPS, tn as CORE_RULES, tr as USER_ACTION_STATUSES, tt as NOTE_KINDS, un as dropWorkspace, ut as isInside, v as reportDocument, vt as mergeWorkspaceRows, w as openWorkspaceCarnet, wn as reportPath, wt as workspaceRowCounts, x as Carnet, xn as databasePath, xt as runningWorkspaceSessions, yt as nextNoteNumber, z as renderAgentLine, zn as REPORTING_NOTE, zt as markdownCopy } from "./steps-j8vhVj8h.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
4
|
import { homedir } from "node:os";
|
|
5
5
|
// src/move.ts
|
|
6
6
|
function count(carnet, sql, ...parameters) {
|
|
@@ -36,6 +36,363 @@ function moveSession(carnet, sessionId, targetWorkspace, options = {}) {
|
|
|
36
36
|
carnet.db.prepare("UPDATE sessions SET workspace = ? WHERE id = ?").run(targetWorkspace, session.id);
|
|
37
37
|
return result;
|
|
38
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
|
+
}
|
|
39
396
|
// src/hook/session-end.ts
|
|
40
397
|
function handleSessionEnd(carnet, payload) {
|
|
41
398
|
if (!carnet.sessions.get(payload.session_id)) return void 0;
|
|
@@ -123,6 +480,425 @@ function handleUserPromptSubmit(carnet, host, payload, options = {}) {
|
|
|
123
480
|
carnet.notes.recordActiveDay();
|
|
124
481
|
return carnet.sessions.adoptTitle(payload.session_id, host.promptTitle(payload));
|
|
125
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
|
+
}
|
|
126
902
|
// src/guard.ts
|
|
127
903
|
const GUARDED_TOOLS = /* @__PURE__ */ new Set([
|
|
128
904
|
"Edit",
|
|
@@ -135,86 +911,60 @@ const FILE_TOOLS = /* @__PURE__ */ new Set([
|
|
|
135
911
|
"Write",
|
|
136
912
|
"NotebookEdit"
|
|
137
913
|
]);
|
|
138
|
-
const
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
{
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
{
|
|
152
|
-
pattern: /\b(npm|pnpm|yarn|bun)\s+(i|install|add|remove|rm|uninstall|update|up)\b|\bpip3?\s+install\b/,
|
|
153
|
-
label: "package install"
|
|
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));
|
|
154
927
|
}
|
|
155
|
-
|
|
156
|
-
const PUBLISH_BASH = /\bgit\s+(?:-[Cc]\s+\S+\s+)*(commit|push|stash)\b/;
|
|
157
|
-
const PUSH_BASH = /\bgit\s+(?:-[Cc]\s+\S+\s+)*push\b/;
|
|
158
|
-
const GLOBAL_INSTALL = /\b(npm|pnpm|yarn|bun)\s[^;&|]*(\s-g\b|\s--global\b)/;
|
|
159
|
-
const LEADING_CD = /^\s*cd\s+([^\s;&|]+)\s*(?:&&|;)/;
|
|
160
|
-
const SHELL_WORDS = /[\s;&|()<>]+/;
|
|
161
|
-
const REDIRECT = /(?:^|[^<>&\d=-])\d?>>?(?!=)\s*([^\s;&|)]+)/g;
|
|
162
|
-
const QUOTED = /'[^']*'|"(?:[^"\\]|\\.)*"/g;
|
|
928
|
+
}
|
|
163
929
|
function inside(path, folder) {
|
|
164
|
-
const rest = relative(
|
|
930
|
+
const rest = relative(realish(folder), realish(path));
|
|
165
931
|
return rest === "" || !rest.startsWith("..") && !isAbsolute(rest);
|
|
166
932
|
}
|
|
167
933
|
function absolute(path, cwd) {
|
|
168
934
|
if (path === "~" || path.startsWith("~/")) return join(homedir(), path.slice(1));
|
|
169
935
|
return isAbsolute(path) ? path : resolve(cwd ?? "/", path);
|
|
170
936
|
}
|
|
171
|
-
function
|
|
172
|
-
return
|
|
173
|
-
}
|
|
174
|
-
function writableRedirect(target, input) {
|
|
175
|
-
if (target === "/dev/null" || target.startsWith("&")) return true;
|
|
176
|
-
return writable(absolute(target, input.cwd), input);
|
|
177
|
-
}
|
|
178
|
-
function pathLike(word) {
|
|
179
|
-
return word.startsWith("/") || word.startsWith("~") || /(^|\/)\.\.(\/|$)/.test(word);
|
|
937
|
+
function inScratch(path, input) {
|
|
938
|
+
return input.scratchRoots.some((root) => inside(path, root));
|
|
180
939
|
}
|
|
181
|
-
function
|
|
182
|
-
|
|
183
|
-
const lead = LEADING_CD.exec(command);
|
|
184
|
-
const directory = lead ? absolute(lead[1] ?? "", input.cwd) : input.cwd ?? "/";
|
|
185
|
-
if (!inside(directory, sandbox)) return false;
|
|
186
|
-
return command.split(SHELL_WORDS).flatMap((word) => word.replace(/^['"]|['"]$/g, "").split("=")).filter(pathLike).every((word) => word === "/dev/null" || writable(absolute(word, directory), input));
|
|
940
|
+
function writable(path, input) {
|
|
941
|
+
return inScratch(path, input) || !!input.sandbox && inside(path, input.sandbox);
|
|
187
942
|
}
|
|
188
|
-
function
|
|
189
|
-
|
|
190
|
-
for (const rule of READ_ONLY_BASH) if (rule.pattern.test(command)) return rule.label;
|
|
191
|
-
for (const match of command.replace(QUOTED, "''").matchAll(REDIRECT)) if (!writableRedirect(match[1] ?? "", input)) return `redirect to ${match[1]}`;
|
|
943
|
+
function publishing(call) {
|
|
944
|
+
return PUBLISHING.has(call.verb) && !(call.verb === "stash" && READ_ONLY_STASH.has(call.sub ?? ""));
|
|
192
945
|
}
|
|
193
|
-
function
|
|
194
|
-
const contract = `the ${input.kind} contract`;
|
|
946
|
+
function fileToolViolation(input, contract) {
|
|
195
947
|
if (input.kind === "implement") {
|
|
196
|
-
if (input.toolName === "Bash") return PUBLISH_BASH.test(input.command ?? "") ? `${contract} forbids git commit, push and stash: the human commits` : void 0;
|
|
197
948
|
if (!input.worktree || !input.filePath) return void 0;
|
|
198
949
|
const path = absolute(input.filePath, input.cwd);
|
|
199
|
-
if (inside(path, input.worktree) ||
|
|
950
|
+
if (inside(path, input.worktree) || inScratch(path, input)) return void 0;
|
|
200
951
|
return `${contract} limits writes to its worktree ${input.worktree}`;
|
|
201
952
|
}
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
}
|
|
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);
|
|
207
959
|
if (input.toolName !== "Bash") return void 0;
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
if (
|
|
215
|
-
|
|
216
|
-
if (!violation || confinedToSandbox(input, sandbox)) return void 0;
|
|
217
|
-
return `${contract} limits writing commands to its sandbox ${sandbox}: ${violation} is not allowed here`;
|
|
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}`;
|
|
218
968
|
}
|
|
219
969
|
function kindOfAgentType(agentType) {
|
|
220
970
|
return /^rucher[\w-]*:(research|review)$/.exec(agentType ?? "")?.[1];
|
|
@@ -266,7 +1016,7 @@ function handleToolStart(carnet, payload) {
|
|
|
266
1016
|
if (payload.agent_id || payload.tool_name !== "AskUserQuestion") return;
|
|
267
1017
|
carnet.turn.wait(payload.session_id);
|
|
268
1018
|
}
|
|
269
|
-
function guardSubagentCall(carnet, payload,
|
|
1019
|
+
function guardSubagentCall(carnet, payload, scratchRoots) {
|
|
270
1020
|
if (!payload.agent_id || !payload.tool_name) return void 0;
|
|
271
1021
|
const agent = carnet.agents.byHostAgentId(payload.session_id, payload.agent_id);
|
|
272
1022
|
const kind = agent?.kind ?? kindOfAgentType(payload.agent_type);
|
|
@@ -279,7 +1029,7 @@ function guardSubagentCall(carnet, payload, scratchRoot) {
|
|
|
279
1029
|
cwd: payload.cwd,
|
|
280
1030
|
worktree: agent?.worktree,
|
|
281
1031
|
sandbox: agent?.sandbox,
|
|
282
|
-
|
|
1032
|
+
scratchRoots
|
|
283
1033
|
});
|
|
284
1034
|
}
|
|
285
1035
|
function guardMainLaunch(carnet, payload) {
|
|
@@ -340,22 +1090,6 @@ function writeStatusLine(carnet, sessionId, options = {}) {
|
|
|
340
1090
|
writeFileSync(temporary, line ? `${line}\n` : "");
|
|
341
1091
|
renameSync(temporary, path);
|
|
342
1092
|
}
|
|
343
|
-
|
|
344
|
-
function renderRunDirectory(workspace, options = {}) {
|
|
345
|
-
mkdirSync(workspace.runDirectory, { recursive: true });
|
|
346
|
-
mkdirSync(reportsDirectory(workspace), { recursive: true });
|
|
347
|
-
const result = {
|
|
348
|
-
runDirectory: workspace.runDirectory,
|
|
349
|
-
written: [],
|
|
350
|
-
removed: []
|
|
351
|
-
};
|
|
352
|
-
for (const id of options.host ? [options.host] : workspaceHosts(workspace)) {
|
|
353
|
-
const rendered = hostById(id).renderRunDirectory(workspace);
|
|
354
|
-
result.written.push(...rendered.written);
|
|
355
|
-
result.removed.push(...rendered.removed);
|
|
356
|
-
}
|
|
357
|
-
return result;
|
|
358
|
-
}
|
|
359
|
-
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, baseRules, buildStatusView, claudeCode, compactReminder, corePromptPath, createWorkspace, databasePath, defaultRunDirectory, definitionInstructions, deleteWorkspaceNotes, dropWorkspace, expandHome, 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, markdownCopy, memoryHalfLife, memoryMaxCharacters, mergeSettings, migrate, migrations, moveSession, openCarnet, openDatabase, openResolvedCarnet, openWorkspaceCarnet, outsideRucherContext, promptsDirectory, purgeDays, removeStaleCopies, removeWorkspaceRepo, renderAgentLine, renderMainLine, renderMemory, renderNoteLine, renderNotes, renderNotesSummary, renderRunDirectory, renderSections, renderStatus, renderStatusLine, renderTableLine, repoNameFor, repoPathFor, 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 };
|
|
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, 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 };
|
|
360
1094
|
|
|
361
1095
|
//# sourceMappingURL=index.mjs.map
|