@cogitator-ai/bridge 0.6.0 → 0.7.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.
Files changed (72) hide show
  1. package/README.md +43 -5
  2. package/dist/adapters/claude.d.ts +13 -0
  3. package/dist/adapters/claude.d.ts.map +1 -1
  4. package/dist/adapters/claude.js +11 -1
  5. package/dist/adapters/claude.js.map +1 -1
  6. package/dist/checks.d.ts +31 -0
  7. package/dist/checks.d.ts.map +1 -0
  8. package/dist/checks.js +202 -0
  9. package/dist/checks.js.map +1 -0
  10. package/dist/client.d.ts +7 -1
  11. package/dist/client.d.ts.map +1 -1
  12. package/dist/client.js +14 -0
  13. package/dist/client.js.map +1 -1
  14. package/dist/dispatcher.d.ts +118 -2
  15. package/dist/dispatcher.d.ts.map +1 -1
  16. package/dist/dispatcher.js +570 -11
  17. package/dist/dispatcher.js.map +1 -1
  18. package/dist/errors.d.ts +1 -1
  19. package/dist/errors.d.ts.map +1 -1
  20. package/dist/errors.js.map +1 -1
  21. package/dist/index.d.ts +3 -2
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +1 -0
  24. package/dist/index.js.map +1 -1
  25. package/dist/inputs.d.ts +89 -0
  26. package/dist/inputs.d.ts.map +1 -1
  27. package/dist/inputs.js +24 -0
  28. package/dist/inputs.js.map +1 -1
  29. package/dist/job-record.d.ts +41 -1
  30. package/dist/job-record.d.ts.map +1 -1
  31. package/dist/job-record.js +38 -1
  32. package/dist/job-record.js.map +1 -1
  33. package/dist/letters.d.ts +3 -1
  34. package/dist/letters.d.ts.map +1 -1
  35. package/dist/letters.js +38 -5
  36. package/dist/letters.js.map +1 -1
  37. package/dist/paths.d.ts +7 -0
  38. package/dist/paths.d.ts.map +1 -1
  39. package/dist/paths.js +9 -0
  40. package/dist/paths.js.map +1 -1
  41. package/dist/protocol.d.ts +3 -0
  42. package/dist/protocol.d.ts.map +1 -1
  43. package/dist/protocol.js +3 -0
  44. package/dist/protocol.js.map +1 -1
  45. package/dist/registry.d.ts +7 -2
  46. package/dist/registry.d.ts.map +1 -1
  47. package/dist/registry.js +8 -5
  48. package/dist/registry.js.map +1 -1
  49. package/dist/server.d.ts.map +1 -1
  50. package/dist/server.js +3 -0
  51. package/dist/server.js.map +1 -1
  52. package/dist/tools/guidance.d.ts.map +1 -1
  53. package/dist/tools/guidance.js +2 -0
  54. package/dist/tools/guidance.js.map +1 -1
  55. package/dist/tools/index.d.ts +1 -1
  56. package/dist/tools/index.js +1 -1
  57. package/dist/tools/tools.d.ts +1 -1
  58. package/dist/tools/tools.d.ts.map +1 -1
  59. package/dist/tools/tools.js +168 -4
  60. package/dist/tools/tools.js.map +1 -1
  61. package/dist/types.d.ts +90 -5
  62. package/dist/types.d.ts.map +1 -1
  63. package/dist/types.js +23 -2
  64. package/dist/types.js.map +1 -1
  65. package/dist/worktree.d.ts +131 -0
  66. package/dist/worktree.d.ts.map +1 -0
  67. package/dist/worktree.js +278 -0
  68. package/dist/worktree.js.map +1 -0
  69. package/fakes/claude.mjs +53 -3
  70. package/fakes/lib.mjs +24 -9
  71. package/fakes/mcp.mjs +3 -2
  72. package/package.json +4 -4
@@ -0,0 +1,278 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { existsSync } from 'node:fs';
3
+ import { mkdir, rm, writeFile } from 'node:fs/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import { isAbsolute, join, relative, sep } from 'node:path';
6
+ import { runCommand } from './adapters/exec.js';
7
+ import { JOB_WORKTREES_DIR, canonicalPath, isInside } from './paths.js';
8
+ export { JOB_WORKTREES_DIR };
9
+ /** Where the work of a worktree nobody took or dropped is kept when the worktree goes. */
10
+ export const DISCARDED_REFS = 'refs/cogitator/discarded';
11
+ const GIT_TIMEOUT_MS = 120_000;
12
+ /** The id git reads as "no commit": the old value of a ref that must not exist yet. */
13
+ const NO_COMMIT = '0'.repeat(40);
14
+ /** Who a snapshot is by when the repository names nobody. */
15
+ const FALLBACK_IDENTITY = {
16
+ GIT_AUTHOR_NAME: 'cogitator bridge',
17
+ GIT_AUTHOR_EMAIL: 'bridge@localhost',
18
+ GIT_COMMITTER_NAME: 'cogitator bridge',
19
+ GIT_COMMITTER_EMAIL: 'bridge@localhost',
20
+ };
21
+ /** A git command that did not do what it was run for. */
22
+ export class GitError extends Error {
23
+ args;
24
+ code;
25
+ said;
26
+ constructor(args, code, said) {
27
+ super(`git ${args[0] ?? ''} failed: ${said || `exit code ${code ?? 'none'}`}`);
28
+ this.args = args;
29
+ this.code = code;
30
+ this.said = said;
31
+ this.name = 'GitError';
32
+ }
33
+ }
34
+ async function git(cwd, args, options = {}) {
35
+ const result = await runCommand('git', args, {
36
+ cwd,
37
+ timeoutMs: GIT_TIMEOUT_MS,
38
+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0', ...options.env },
39
+ ...(options.input !== undefined && { input: options.input }),
40
+ });
41
+ if (result.code === null || !(options.accept ?? [0]).includes(result.code)) {
42
+ throw new GitError(args, result.code, (result.stderr.trim() || result.stdout.trim()).trim());
43
+ }
44
+ return { code: result.code, stdout: result.stdout };
45
+ }
46
+ async function gitText(cwd, args, options) {
47
+ return (await git(cwd, args, options)).stdout.trim();
48
+ }
49
+ function slug(text) {
50
+ let out = '';
51
+ for (const char of text.toLowerCase()) {
52
+ if (/[a-z0-9]/.test(char))
53
+ out += char;
54
+ else if (out !== '' && !out.endsWith('-'))
55
+ out += '-';
56
+ if (out.length >= 32)
57
+ break;
58
+ }
59
+ return out.replace(/-+$/, '');
60
+ }
61
+ /**
62
+ * Makes the git worktree of a job: `.cogitator/worktrees/job-<number>-<title>` under the main
63
+ * checkout of the project, on a branch `cogitator/job-<number>-<title>`, off the commit the
64
+ * checkout of `from` is at. History is shared with the project and only the working files are
65
+ * new, so what that checkout has not committed is not there, and neither is anything git
66
+ * ignores, such as installed dependencies and build output.
67
+ *
68
+ * @throws GitError when `from` is in no git repository, or the repository has no commit yet
69
+ */
70
+ export async function addJobWorktree(options) {
71
+ const from = canonicalPath(options.from);
72
+ const top = canonicalPath(await gitText(from, ['rev-parse', '--show-toplevel']));
73
+ const base = await gitText(from, ['rev-parse', '--verify', 'HEAD^{commit}']);
74
+ const dir = join(canonicalPath(options.project), JOB_WORKTREES_DIR);
75
+ await mkdir(dir, { recursive: true });
76
+ const ignore = join(dir, '.gitignore');
77
+ if (!existsSync(ignore))
78
+ await writeFile(ignore, '*\n');
79
+ const named = slug(options.title);
80
+ const folder = `job-${options.number}${named ? `-${named}` : ''}`;
81
+ const path = join(dir, folder);
82
+ const branch = `cogitator/${folder}`;
83
+ await git(options.project, ['worktree', 'add', '-b', branch, path, base]);
84
+ const inside = relative(top, from);
85
+ const cwd = inside !== '' && isInside(top, from) && existsSync(join(path, inside))
86
+ ? join(path, inside)
87
+ : path;
88
+ return { path, branch, base, cwd };
89
+ }
90
+ const KINDS = { A: 'added', D: 'deleted' };
91
+ /**
92
+ * Reads what a worktree changed since `base`: its commits, what it has not committed and the
93
+ * files it added, without what git ignores. Nothing of the worktree is touched: the files are
94
+ * staged in an index of their own, not the worktree's, so an agent that cannot commit (a Codex
95
+ * thread in its sandbox cannot) and one that did are read the same way.
96
+ */
97
+ export async function changesOf(worktree, base) {
98
+ const index = join(tmpdir(), `cogitator-bridge-index-${randomUUID()}`);
99
+ const env = { GIT_INDEX_FILE: index };
100
+ try {
101
+ const head = await gitText(worktree, ['rev-parse', '--verify', 'HEAD^{commit}']);
102
+ await git(worktree, ['read-tree', head], { env });
103
+ await git(worktree, ['add', '-A', '.'], { env });
104
+ const tree = await gitText(worktree, ['write-tree'], { env });
105
+ const [numstat, names, commits] = await Promise.all([
106
+ git(worktree, ['diff', '--numstat', '-z', '--no-renames', base, tree]),
107
+ git(worktree, ['diff', '--name-status', '-z', '--no-renames', base, tree]),
108
+ gitText(worktree, ['rev-list', '--count', `${base}..${head}`]),
109
+ ]);
110
+ const kinds = new Map();
111
+ const named = names.stdout.split('\0');
112
+ for (let at = 0; at + 1 < named.length; at += 2) {
113
+ kinds.set(named[at + 1], KINDS[named[at][0]] ?? 'modified');
114
+ }
115
+ const files = [];
116
+ let insertions = 0;
117
+ let deletions = 0;
118
+ for (const entry of numstat.stdout.split('\0')) {
119
+ if (entry === '')
120
+ continue;
121
+ const [added, removed, ...rest] = entry.split('\t');
122
+ const path = rest.join('\t');
123
+ const file = { path, kind: kinds.get(path) ?? 'modified' };
124
+ if (added !== '-') {
125
+ file.insertions = Number(added);
126
+ file.deletions = Number(removed);
127
+ insertions += file.insertions;
128
+ deletions += file.deletions;
129
+ }
130
+ files.push(file);
131
+ }
132
+ return { files, insertions, deletions, commits: Number(commits), head, tree };
133
+ }
134
+ finally {
135
+ await rm(index, { force: true });
136
+ await rm(`${index}.lock`, { force: true });
137
+ }
138
+ }
139
+ const DEFAULT_PATCH_CHARS = 200_000;
140
+ /** The changes of a worktree as a patch, cut at `maxChars`. */
141
+ export async function patchOf(worktree, base, tree, options = {}) {
142
+ const max = options.maxChars ?? DEFAULT_PATCH_CHARS;
143
+ const { stdout } = await git(worktree, [
144
+ 'diff',
145
+ '--no-renames',
146
+ '--no-ext-diff',
147
+ base,
148
+ tree,
149
+ '--',
150
+ ...(options.paths ?? []),
151
+ ]);
152
+ return stdout.length > max
153
+ ? { patch: stdout.slice(0, max), truncated: true }
154
+ : { patch: stdout, truncated: false };
155
+ }
156
+ /**
157
+ * The commit that holds everything a worktree has: its own last commit when nothing is left
158
+ * uncommitted, else a new commit on top of it with `message`. The new commit is on no branch and
159
+ * the worktree is not touched.
160
+ */
161
+ export async function snapshotOf(worktree, changes, message) {
162
+ const committed = await gitText(worktree, ['rev-parse', `${changes.head}^{tree}`]);
163
+ if (committed === changes.tree)
164
+ return changes.head;
165
+ const [name, email] = await Promise.all(['user.name', 'user.email'].map((key) => gitText(worktree, ['config', '--get', key], { accept: [0, 1] })));
166
+ return gitText(worktree, ['commit-tree', changes.tree, '-p', changes.head, '-F', '-'], {
167
+ input: message,
168
+ ...((!name || !email) && { env: FALLBACK_IDENTITY }),
169
+ });
170
+ }
171
+ /**
172
+ * The files a merge of `commit` into what `target` is at would leave in conflict, none when it
173
+ * merges cleanly. Nothing of `target` is touched: git works the merge out without a checkout.
174
+ *
175
+ * @throws GitError on a git older than 2.38, which cannot
176
+ */
177
+ export async function conflictsOf(target, commit) {
178
+ const { code, stdout } = await git(target, ['merge-tree', '--write-tree', '--name-only', '--no-messages', '-z', 'HEAD', commit], { accept: [0, 1] });
179
+ if (code === 0)
180
+ return [];
181
+ return stdout
182
+ .split('\0')
183
+ .slice(1)
184
+ .filter((path) => path !== '');
185
+ }
186
+ /** What git is in the middle of in a checkout, by the file or folder it keeps for it. */
187
+ const IN_PROGRESS = [
188
+ ['MERGE_HEAD', 'a merge'],
189
+ ['CHERRY_PICK_HEAD', 'a cherry-pick'],
190
+ ['REVERT_HEAD', 'a revert'],
191
+ ['rebase-merge', 'a rebase'],
192
+ ['rebase-apply', 'a rebase'],
193
+ ];
194
+ /**
195
+ * Why nothing can be brought into the checkout `target` right now, undefined when it can: git
196
+ * is in the middle of something there, or changes are staged. Bringing work in stages it, so
197
+ * what was staged before could not be told from it afterwards, and git would refuse anyway.
198
+ */
199
+ export async function busyWith(target) {
200
+ for (const [name, what] of IN_PROGRESS) {
201
+ const path = await gitText(target, ['rev-parse', '--git-path', name]);
202
+ if (existsSync(isAbsolute(path) ? path : join(target, path))) {
203
+ return `${what} is in progress there`;
204
+ }
205
+ }
206
+ const { code } = await git(target, ['diff', '--cached', '--quiet'], { accept: [0, 1] });
207
+ return code === 0 ? undefined : 'changes are staged there';
208
+ }
209
+ /**
210
+ * Brings the changes of `commit` into the checkout `target` as one change that is staged and not
211
+ * committed (`git merge --squash`): the commit, with its message and the hooks of the project,
212
+ * is for whoever works there. Only for a checkout `busyWith` finds free: nothing is staged
213
+ * there, so when git gives up half way, taking back what the merge staged takes back nothing
214
+ * else, and what is changed there and not staged stays as it is.
215
+ *
216
+ * @throws GitError when the checkout is not free, or git refuses, as it does when files the
217
+ * merge changes have changes of their own in `target`. The checkout is then as it was
218
+ */
219
+ export async function squashInto(target, commit) {
220
+ const busy = await busyWith(target);
221
+ if (busy)
222
+ throw new GitError(['merge'], null, busy);
223
+ try {
224
+ await git(target, ['merge', '--squash', '--no-commit', commit]);
225
+ }
226
+ catch (error) {
227
+ await git(target, ['reset', '--merge'], { accept: [0, 1, 128] }).catch(() => undefined);
228
+ throw error;
229
+ }
230
+ }
231
+ /** Whether `ancestor` is `commit` or one of the commits it grew from. */
232
+ export async function isAncestor(folder, ancestor, commit) {
233
+ const { code } = await git(folder, ['merge-base', '--is-ancestor', ancestor, commit], {
234
+ accept: [0, 1],
235
+ });
236
+ return code === 0;
237
+ }
238
+ /**
239
+ * Points `ref` (a branch as `refs/heads/<name>`, or any other ref) at `commit`. With `fresh` the
240
+ * ref must not be there yet.
241
+ *
242
+ * @throws GitError when a `fresh` ref exists already
243
+ */
244
+ export async function pointRef(project, ref, commit, options = {}) {
245
+ await git(project, ['update-ref', ref, commit, ...(options.fresh ? [NO_COMMIT] : [])]);
246
+ }
247
+ /**
248
+ * Removes the worktree of a job with everything in it, and its branch when one is named. When
249
+ * its folder is gone already, as after someone removed it by hand, git is told to forget the
250
+ * worktrees whose folders are missing, which is the only way it has to forget one.
251
+ */
252
+ export async function removeJobWorktree(project, path, branch) {
253
+ if (existsSync(path))
254
+ await git(project, ['worktree', 'remove', '--force', path]);
255
+ else
256
+ await git(project, ['worktree', 'prune']);
257
+ if (branch)
258
+ await git(project, ['branch', '-D', branch], { accept: [0, 1] });
259
+ }
260
+ /** The commit a branch is at, undefined when there is no such branch. */
261
+ export async function branchTip(project, branch) {
262
+ const { code, stdout } = await git(project, ['rev-parse', '--verify', '--quiet', `refs/heads/${branch}^{commit}`], { accept: [0, 1] });
263
+ return code === 0 ? stdout.trim() : undefined;
264
+ }
265
+ /** The top folder of the checkout `folder` is in, undefined when it is in no git repository. */
266
+ export async function checkoutOf(folder) {
267
+ try {
268
+ return canonicalPath(await gitText(folder, ['rev-parse', '--show-toplevel']));
269
+ }
270
+ catch {
271
+ return undefined;
272
+ }
273
+ }
274
+ /** A path of a changed file as a letter shows it, with `/` whatever the platform. */
275
+ export function shownPath(path) {
276
+ return sep === '/' ? path : path.split(sep).join('/');
277
+ }
278
+ //# sourceMappingURL=worktree.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worktree.js","sourceRoot":"","sources":["../src/worktree.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,KAAK,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACxD,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAC5D,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,iBAAiB,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAExE,OAAO,EAAE,iBAAiB,EAAE,CAAC;AAE7B,0FAA0F;AAC1F,MAAM,CAAC,MAAM,cAAc,GAAG,0BAA0B,CAAC;AAEzD,MAAM,cAAc,GAAG,OAAO,CAAC;AAE/B,uFAAuF;AACvF,MAAM,SAAS,GAAG,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;AAEjC,6DAA6D;AAC7D,MAAM,iBAAiB,GAAG;IACxB,eAAe,EAAE,kBAAkB;IACnC,gBAAgB,EAAE,kBAAkB;IACpC,kBAAkB,EAAE,kBAAkB;IACtC,mBAAmB,EAAE,kBAAkB;CACxC,CAAC;AAEF,yDAAyD;AACzD,MAAM,OAAO,QAAS,SAAQ,KAAK;IAEtB;IACA;IACA;IAHX,YACW,IAAuB,EACvB,IAAmB,EACnB,IAAY;QAErB,KAAK,CAAC,OAAO,IAAI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IAAI,EAAE,MAAM,EAAE,GAAG,MAAM,GAAG,CAChC,OAAO,EACP,CAAC,WAAW,EAAE,UAAU,EAAE,SAAS,EAAE,cAAc,MAAM,WAAW,CAAC,EACrE,EAAE,MAAM,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,CACnB,CAAC;IACF,OAAO,IAAI,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;AAChD,CAAC;AAED,gGAAgG;AAChG,MAAM,CAAC,KAAK,UAAU,UAAU,CAAC,MAAc;IAC7C,IAAI,CAAC;QACH,OAAO,aAAa,CAAC,MAAM,OAAO,CAAC,MAAM,EAAE,CAAC,WAAW,EAAE,iBAAiB,CAAC,CAAC,CAAC,CAAC;IAChF,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC;AAED,qFAAqF;AACrF,MAAM,UAAU,SAAS,CAAC,IAAY;IACpC,OAAO,GAAG,KAAK,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACxD,CAAC"}
package/fakes/claude.mjs CHANGED
@@ -11,9 +11,10 @@
11
11
  * `mcp__<server>__<tool>` run, and one may replace the arguments (`updatedInput`). A background
12
12
  * session calls only the tools its settings allow: nobody sits there to be asked.
13
13
  */
14
+ import { spawnSync } from 'node:child_process';
14
15
  import { randomUUID } from 'node:crypto';
15
- import { existsSync, readFileSync, rmSync } from 'node:fs';
16
- import { dirname, join, resolve } from 'node:path';
16
+ import { existsSync, readFileSync, rmSync, statSync } from 'node:fs';
17
+ import { dirname, join, relative, resolve } from 'node:path';
17
18
  import { fileURLToPath } from 'node:url';
18
19
  import {
19
20
  CliError,
@@ -22,6 +23,7 @@ import {
22
23
  abandonWork,
23
24
  awaitJson,
24
25
  boundLife,
26
+ canonical,
25
27
  enqueue,
26
28
  flag,
27
29
  isAlive,
@@ -399,7 +401,7 @@ function sessionServers(record) {
399
401
 
400
402
  /** The settings a session goes by: `--settings` and the two settings files of its project */
401
403
  function settingsOf(record) {
402
- const project = join(record.cwd, '.claude');
404
+ const project = join(record.projectDir ?? record.cwd, '.claude');
403
405
  const sources = [
404
406
  () => record.settings && readSettingsOption(record.settings, record.cwd),
405
407
  () => readJson(join(project, 'settings.json')),
@@ -498,6 +500,54 @@ function ruleCovers(rule, toolName, input) {
498
500
  * are told (Claude Code takes about six seconds).
499
501
  */
500
502
  async function leaveFor(session, toolName, input) {
503
+ const moved = toolName === 'Edit' ? isolate(session, input.file_path) : undefined;
504
+ const leave = await decideLeave(
505
+ session,
506
+ toolName,
507
+ moved ? { ...input, file_path: moved.file } : input
508
+ );
509
+ return moved ? { ...leave, ...moved } : leave;
510
+ }
511
+
512
+ function gitSays(cwd, args) {
513
+ const result = spawnSync('git', args, { cwd, encoding: 'utf8' });
514
+ return result.status === 0 ? result.stdout.trim() : undefined;
515
+ }
516
+
517
+ /**
518
+ * Moves a background session into a git worktree of its own before its first edit. Claude Code
519
+ * refuses the edit and has the model enter a worktree, which comes to the same for a model that
520
+ * does as it is told: `.claude/worktrees/<name>` under the top of the repository, on a branch
521
+ * `worktree-<name>`. Not when its settings say `worktree.bgIsolation: "none"`, not outside a git
522
+ * repository, and not when it is in a linked worktree already. The settings of the project it
523
+ * was started in stay the ones it reads.
524
+ * @returns {{ cwd: string, file: string } | undefined} where the session is now and which file
525
+ * the edit means there, undefined for a session that stays where it is
526
+ */
527
+ function isolate(session, file) {
528
+ const { record, files } = session;
529
+ if (record.kind !== 'background') return undefined;
530
+ if (settingsOf(record).some((settings) => settings.worktree?.bgIsolation === 'none')) {
531
+ return undefined;
532
+ }
533
+ const top = gitSays(record.cwd, ['rev-parse', '--show-toplevel']);
534
+ const isMain = top !== undefined && statSync(join(top, '.git')).isDirectory();
535
+ if (!isMain) return undefined;
536
+ const name = `session-${record.id}`;
537
+ const path = join(top, '.claude', 'worktrees', name);
538
+ if (gitSays(top, ['worktree', 'add', '-b', `worktree-${name}`, path, 'HEAD']) === undefined) {
539
+ throw new Error(`fake claude could not make the worktree ${path}`);
540
+ }
541
+ const into = (place) =>
542
+ isWithin(place, top) ? join(path, relative(canonical(top), canonical(place))) : place;
543
+ const started = record.cwd;
544
+ record.projectDir = started;
545
+ record.cwd = into(started);
546
+ patchJson(files.record, { cwd: record.cwd, projectDir: started });
547
+ return { cwd: record.cwd, file: into(file) };
548
+ }
549
+
550
+ async function decideLeave(session, toolName, input) {
501
551
  const { record, files } = session;
502
552
  const mode = record.permissionMode ?? 'default';
503
553
  const refused = (message) => ({ allowed: false, message });
package/fakes/lib.mjs CHANGED
@@ -549,26 +549,37 @@ async function runWithLeave(command, cwd, env, askLeave) {
549
549
  * An `edit:` directive: a file the session's own edit tool changes, by adding a line to it,
550
550
  * which the session needs leave for the way its harness decides. It is in the turn as a command
551
551
  * `edit <path>`, refused or done. A harness that imitates no edit tool of its own fails it.
552
+ * A harness may move the session before it edits, as Claude Code moves a background session
553
+ * into a worktree of its own: the leave then says where the session is now (`cwd`) and which
554
+ * file the edit means there (`file`).
552
555
  * @param {string} path as the model wrote it, relative to the folder of the session or absolute
553
556
  * @param {LeaveAsker | undefined} askLeave
554
- * @returns {Promise<CommandRun>}
557
+ * @returns {Promise<CommandRun & { movedTo?: string }>}
555
558
  */
556
559
  async function editWithLeave(path, cwd, askLeave) {
557
- const file = resolve(cwd, path);
558
560
  const command = `edit ${path}`;
559
561
  if (!askLeave) {
560
562
  return { command, code: 1, stdout: '', stderr: 'this stand-in has no edit tool of its own' };
561
563
  }
562
- const leave = await askLeave({ tool: 'Edit', input: { file_path: file } });
564
+ const leave = await askLeave({ tool: 'Edit', input: { file_path: resolve(cwd, path) } });
565
+ const moved = leave.cwd !== undefined && { movedTo: leave.cwd };
563
566
  if (!leave.allowed) {
564
- return { command, code: null, stdout: '', stderr: leave.message ?? 'denied', denied: true };
567
+ return {
568
+ command,
569
+ code: null,
570
+ stdout: '',
571
+ stderr: leave.message ?? 'denied',
572
+ denied: true,
573
+ ...moved,
574
+ };
565
575
  }
576
+ const file = leave.file ?? resolve(cwd, path);
566
577
  try {
567
578
  mkdirSync(dirname(file), { recursive: true });
568
579
  appendFileSync(file, 'edited\n');
569
- return { command, code: 0, stdout: '', stderr: '' };
580
+ return { command, code: 0, stdout: '', stderr: '', ...moved };
570
581
  } catch (error) {
571
- return { command, code: 1, stdout: '', stderr: error.message };
582
+ return { command, code: 1, stdout: '', stderr: error.message, ...moved };
572
583
  }
573
584
  }
574
585
 
@@ -586,16 +597,20 @@ async function editWithLeave(path, cwd, askLeave) {
586
597
  * @param {LeaveAsker} [turn.askLeave] how the session gets leave for a call of its own tools
587
598
  * @returns {Promise<TurnOutcome>}
588
599
  */
589
- export async function performTurn({ input, cwd, env, callTool, askLeave }) {
600
+ export async function performTurn({ input, cwd: startedIn, env, callTool, askLeave }) {
590
601
  const at = new Date().toISOString();
591
602
  const ran = [];
592
603
  const tools = [];
593
604
  let answer = 'ok';
605
+ let cwd = startedIn;
594
606
  for (const { kind, value } of directives(input)) {
595
607
  if (kind === 'run') ran.push(await runCommand(value, cwd, env));
596
608
  else if (kind === 'bash') ran.push(await runWithLeave(value, cwd, env, askLeave));
597
- else if (kind === 'edit') ran.push(await editWithLeave(value, cwd, askLeave));
598
- else if (kind === 'tool') tools.push(await runTool(value, callTool));
609
+ else if (kind === 'edit') {
610
+ const { movedTo, ...run } = await editWithLeave(value, cwd, askLeave);
611
+ if (movedTo !== undefined) cwd = movedTo;
612
+ ran.push(run);
613
+ } else if (kind === 'tool') tools.push(await runTool(value, callTool));
599
614
  else if (kind === 'sleep') await sleep(Number(value));
600
615
  else answer = value;
601
616
  }
package/fakes/mcp.mjs CHANGED
@@ -6,8 +6,9 @@ import { spawn } from 'node:child_process';
6
6
  import { createInterface } from 'node:readline';
7
7
 
8
8
  /**
9
- * A server of tools is a process that loads the whole runtime before it answers its first
10
- * request: on a busy CI runner that took over fifteen seconds, so a request waits a minute
9
+ * A server of tools is a process that starts for the request: on a busy CI runner its first
10
+ * answer took over fifteen seconds while it still loaded the whole runtime, so a request waits
11
+ * a minute
11
12
  */
12
13
  const REQUEST_TIMEOUT_MS = 60_000;
13
14
  const PROTOCOL_VERSION = '2025-06-18';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cogitator-ai/bridge",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Agent bridge for Cogitator: Claude Code, Codex and other agents hand each other jobs, ask questions and report back, each in its own window (experimental)",
5
5
  "keywords": [
6
6
  "cogitator",
@@ -52,8 +52,8 @@
52
52
  "zod": "^4.6.6"
53
53
  },
54
54
  "devDependencies": {
55
- "@cogitator-ai/core": "0.78.1",
56
- "@cogitator-ai/mcp": "19.11.0",
55
+ "@cogitator-ai/core": "0.79.0",
56
+ "@cogitator-ai/mcp": "19.12.0",
57
57
  "@types/better-sqlite3": "^9.6.0",
58
58
  "@types/node": "^22.20.4",
59
59
  "better-sqlite3": "^13.0.3",
@@ -61,7 +61,7 @@
61
61
  "vitest": "^5.0.3"
62
62
  },
63
63
  "peerDependencies": {
64
- "@cogitator-ai/core": ">=0.78.1",
64
+ "@cogitator-ai/core": ">=0.79.0",
65
65
  "better-sqlite3": "^11.0.0 || ^12.0.0 || ^13.0.0"
66
66
  },
67
67
  "peerDependenciesMeta": {