@mikode13/harness 11.0.0 → 11.1.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 (78) hide show
  1. package/README.md +138 -6
  2. package/dist/agent/domain/agent.d.ts +24 -3
  3. package/dist/agent/domain/agent.js.map +1 -1
  4. package/dist/agent/domain/approval.d.ts +20 -0
  5. package/dist/agent/domain/approval.js.map +1 -1
  6. package/dist/agent/domain/inbox.d.ts +42 -0
  7. package/dist/agent/domain/inbox.js +81 -0
  8. package/dist/agent/domain/inbox.js.map +1 -0
  9. package/dist/agent/domain/oneRunAtATime.d.ts +17 -0
  10. package/dist/agent/domain/oneRunAtATime.js +32 -0
  11. package/dist/agent/domain/oneRunAtATime.js.map +1 -0
  12. package/dist/agent/domain/runContext.d.ts +4 -0
  13. package/dist/agent/domain/runContext.js +5 -0
  14. package/dist/agent/domain/runContext.js.map +1 -1
  15. package/dist/agent/domain/session.d.ts +15 -0
  16. package/dist/agent/domain/session.js +80 -0
  17. package/dist/agent/domain/session.js.map +1 -0
  18. package/dist/engines/claude/infrastructure/model/claudeAgent.d.ts +6 -2
  19. package/dist/engines/claude/infrastructure/model/claudeAgent.js +20 -5
  20. package/dist/engines/claude/infrastructure/model/claudeAgent.js.map +1 -1
  21. package/dist/engines/codex/infrastructure/model/codexAgent.d.ts +5 -1
  22. package/dist/engines/codex/infrastructure/model/codexAgent.js +13 -2
  23. package/dist/engines/codex/infrastructure/model/codexAgent.js.map +1 -1
  24. package/dist/engines/domain/model/backgroundAgents.d.ts +5 -2
  25. package/dist/engines/domain/model/backgroundAgents.js +11 -3
  26. package/dist/engines/domain/model/backgroundAgents.js.map +1 -1
  27. package/dist/engines/domain/model/llmAgent.d.ts +5 -0
  28. package/dist/engines/domain/model/llmAgent.js +68 -10
  29. package/dist/engines/domain/model/llmAgent.js.map +1 -1
  30. package/dist/factory/infrastructure/agentLLMFactory.d.ts +18 -5
  31. package/dist/factory/infrastructure/agentLLMFactory.js +31 -8
  32. package/dist/factory/infrastructure/agentLLMFactory.js.map +1 -1
  33. package/dist/index.d.ts +5 -1
  34. package/dist/index.js +3 -0
  35. package/dist/index.js.map +1 -1
  36. package/dist/orchestration/domain/model/orchestratorAgent.d.ts +9 -1
  37. package/dist/orchestration/domain/model/orchestratorAgent.js +20 -3
  38. package/dist/orchestration/domain/model/orchestratorAgent.js.map +1 -1
  39. package/dist/recovery/domain/history.d.ts +10 -3
  40. package/dist/recovery/domain/history.js +1 -0
  41. package/dist/recovery/domain/history.js.map +1 -1
  42. package/dist/recovery/domain/recoveryStore.d.ts +14 -2
  43. package/dist/recovery/domain/recoveryStore.js.map +1 -1
  44. package/dist/recovery/infrastructure/fileRecoveryStore.d.ts +21 -2
  45. package/dist/recovery/infrastructure/fileRecoveryStore.js +58 -6
  46. package/dist/recovery/infrastructure/fileRecoveryStore.js.map +1 -1
  47. package/dist/recovery/infrastructure/folderClaims.d.ts +27 -0
  48. package/dist/recovery/infrastructure/folderClaims.js +124 -0
  49. package/dist/recovery/infrastructure/folderClaims.js.map +1 -0
  50. package/dist/shared/domain/session.d.ts +12 -0
  51. package/dist/shared/domain/session.js +2 -0
  52. package/dist/shared/domain/session.js.map +1 -0
  53. package/dist/tools/domain/preparedCall.d.ts +3 -1
  54. package/dist/tools/domain/preparedCall.js.map +1 -1
  55. package/dist/tools/infrastructure/commandTool.js +2 -0
  56. package/dist/tools/infrastructure/commandTool.js.map +1 -1
  57. package/dist/tools/infrastructure/exploreTool.js +1 -1
  58. package/dist/tools/infrastructure/exploreTool.js.map +1 -1
  59. package/dist/tools/infrastructure/fileTools.d.ts +2 -0
  60. package/dist/tools/infrastructure/fileTools.js +9 -1
  61. package/dist/tools/infrastructure/fileTools.js.map +1 -1
  62. package/dist/tools/infrastructure/removeWorktreeTool.d.ts +23 -0
  63. package/dist/tools/infrastructure/removeWorktreeTool.js +172 -0
  64. package/dist/tools/infrastructure/removeWorktreeTool.js.map +1 -0
  65. package/dist/tools/infrastructure/workspaceWrites.d.ts +4 -0
  66. package/dist/tools/infrastructure/workspaceWrites.js +30 -16
  67. package/dist/tools/infrastructure/workspaceWrites.js.map +1 -1
  68. package/dist/tools/infrastructure/worktrees.d.ts +49 -0
  69. package/dist/tools/infrastructure/worktrees.js +154 -0
  70. package/dist/tools/infrastructure/worktrees.js.map +1 -0
  71. package/dist/tools/infrastructure/writeSession.d.ts +5 -1
  72. package/dist/tools/infrastructure/writeSession.js +7 -3
  73. package/dist/tools/infrastructure/writeSession.js.map +1 -1
  74. package/dist/workflow/domain/workflow.d.ts +3 -0
  75. package/dist/workflow/domain/workflow.js.map +1 -1
  76. package/dist/workflow/domain/workflowRunner.js +8 -2
  77. package/dist/workflow/domain/workflowRunner.js.map +1 -1
  78. package/package.json +1 -1
@@ -0,0 +1,172 @@
1
+ import { lstat, realpath } from 'node:fs/promises';
2
+ import { join, resolve, sep } from 'node:path';
3
+ import { z } from 'zod';
4
+ import { WorkspaceBusyError } from '#src/recovery/domain/recoveryStore';
5
+ import { FolderClaims } from '#src/recovery/infrastructure/folderClaims';
6
+ import { definePreparingTool } from "./defineTool.js";
7
+ import { git, listWorktrees } from "./worktrees.js";
8
+ function within(path, folder) {
9
+ return path === folder || path.startsWith(`${folder}${sep}`);
10
+ }
11
+ /**
12
+ * The paths `git status --porcelain -z` names, each with its two-letter code. A rename or copy
13
+ * names its source after it, which is skipped.
14
+ */
15
+ function statusEntries(status) {
16
+ const fields = status.split('\0');
17
+ const entries = [];
18
+ for (let index = 0; index < fields.length; index++) {
19
+ const field = fields[index] ?? '';
20
+ if (field.length < 4)
21
+ continue;
22
+ const code = field.slice(0, 2);
23
+ entries.push({ code, path: field.slice(3) });
24
+ if (code.startsWith('R') || code.startsWith('C'))
25
+ index++;
26
+ }
27
+ return entries;
28
+ }
29
+ async function gitOutput(args, cwd, signal) {
30
+ const { stdout, stderr, exitCode } = await git(args, cwd, signal);
31
+ if (exitCode !== 0) {
32
+ throw new Error(`git could not tell what removing ${cwd} would lose, so nothing was removed: ${stderr.trim()}`);
33
+ }
34
+ return stdout;
35
+ }
36
+ /**
37
+ * What removing the worktree at `path` would lose, and a fingerprint of all it rests on: its
38
+ * HEAD, its branch, the commits at risk, and each file `git status` names, by size and time of
39
+ * change. Throws when
40
+ * any of it cannot be read, since a removal must never be asked about with less than it loses.
41
+ */
42
+ async function inspect(path, branch, signal) {
43
+ const head = (await gitOutput(['rev-parse', '--verify', 'HEAD'], path, signal)).trim();
44
+ const changed = statusEntries(await gitOutput(['status', '--porcelain=v1', '-z', '--untracked-files=all'], path, signal));
45
+ // A folder `.gitignore` excludes whole is named once, however much it holds.
46
+ const ignored = statusEntries(await gitOutput(['status', '--porcelain=v1', '-z', '--untracked-files=normal', '--ignored=matching'], path, signal)).filter(({ code }) => code === '!!');
47
+ // The commits only a detached HEAD holds, which are lost with it.
48
+ const atRisk = [];
49
+ if (branch === undefined) {
50
+ const listed = (await gitOutput(['rev-list', 'HEAD', '--not', '--branches', '--tags', '--remotes'], path, signal))
51
+ .split('\n')
52
+ .filter(line => line !== '');
53
+ if (!listed.every(line => /^[0-9a-f]{40,64}$/.test(line))) {
54
+ throw new Error(`git could not list the commits only ${path} holds, so nothing was removed: it answered "${listed.join(' ')}".`);
55
+ }
56
+ atRisk.push(...listed);
57
+ }
58
+ const files = await Promise.all([...changed, ...ignored].map(async ({ code, path: file }) => {
59
+ const stats = await lstat(join(path, file)).catch(() => undefined);
60
+ return `${code} ${file} ${String(stats?.size)} ${String(stats?.mtimeMs)}`;
61
+ }));
62
+ return {
63
+ removal: {
64
+ path,
65
+ ...(branch === undefined ? {} : { branch }),
66
+ uncommitted: changed.length,
67
+ ignored: ignored.length,
68
+ commitsOnlyHere: atRisk.length,
69
+ },
70
+ fingerprint: JSON.stringify([head, branch ?? null, atRisk, files.sort()]),
71
+ };
72
+ }
73
+ /**
74
+ * The worktree of this repository at `target`, checked as removable: not the main folder, not
75
+ * one the agent works in, and not locked. Throws a message for the model otherwise.
76
+ */
77
+ async function removableWorktree(target, { base, roots }, signal) {
78
+ const worktrees = await listWorktrees(base, signal);
79
+ const [main] = worktrees;
80
+ if (main?.path === target) {
81
+ throw new Error(`${target} is the repository's main folder, not a worktree. Only a worktree can be removed.`);
82
+ }
83
+ const worktree = worktrees.find(listed => listed.path === target);
84
+ if (!worktree) {
85
+ const others = worktrees.slice(1).map(listed => listed.path);
86
+ throw new Error(`${target} is not a worktree of this repository. Its worktrees: ${others.join(', ') || 'none'}.`);
87
+ }
88
+ const own = await Promise.all(
89
+ // From the working directory, as the workspace reads them.
90
+ roots.map(root => realpath(resolve(root.path)).catch(() => resolve(root.path))));
91
+ if (own.some(root => within(root, target) || within(target, root))) {
92
+ throw new Error(`You work in ${target}, so it cannot be removed from this run.`);
93
+ }
94
+ if (worktree.locked) {
95
+ throw new Error(`${target} is locked. The user must unlock it to remove it.`);
96
+ }
97
+ return worktree;
98
+ }
99
+ /**
100
+ * `removeWorktree`: removes a git worktree of the repository the first root is in, its folder
101
+ * and every file in it, never its branch, which keeps its commits. Each call is `destructive`,
102
+ * so it is asked about, and the request names what is lost: changes no commit has, files
103
+ * `.gitignore` excludes, and with a detached HEAD the commits no branch, tag or remote holds. It
104
+ * refuses the repository's main folder, a worktree the agent works in, which holds one of its
105
+ * roots or lies inside one, and a locked one.
106
+ *
107
+ * Once approved it claims the worktree (`FolderClaims`), so no run that may write in it starts,
108
+ * and removes nothing while one works; it checks again that nothing it rests on changed while
109
+ * the user was asked, and otherwise removes nothing, so the model calls it again to have the
110
+ * user asked anew. A folder `.gitignore` excludes whole is checked as a folder, never looked
111
+ * into, and its result tells the model so.
112
+ */
113
+ export function createRemoveWorktreeTool({ base, roots, stateDirectory, }) {
114
+ return definePreparingTool({
115
+ name: 'removeWorktree',
116
+ description: 'Removes a git worktree of this repository: its folder and every file in it, committed or not. Its branch stays, with its commits. Only when the user asks for it.',
117
+ input: z.object({
118
+ path: z
119
+ .string()
120
+ .describe('The folder of the worktree, absolute or relative to the first root.'),
121
+ }),
122
+ summarize: ({ path }) => path,
123
+ prepare: async ({ path }, signal) => {
124
+ const asked = resolve(base, path);
125
+ const target = await realpath(asked).catch(() => {
126
+ throw new Error(`There is no folder at ${asked}.`);
127
+ });
128
+ const worktree = await removableWorktree(target, { base, roots }, signal);
129
+ const { removal, fingerprint } = await inspect(target, worktree.branch, signal);
130
+ return {
131
+ risk: 'destructive',
132
+ worktree: removal,
133
+ run: async (runSignal) => {
134
+ let release;
135
+ try {
136
+ release = await new FolderClaims(stateDirectory).claimRemoval(target);
137
+ }
138
+ catch (error) {
139
+ if (!(error instanceof WorkspaceBusyError))
140
+ throw error;
141
+ throw new Error(`A run, or a move through a history, may write in ${target}, so nothing was removed. The harness removes no worktree a run may write in; tell the user, and try again once it ends.`, { cause: error });
142
+ }
143
+ try {
144
+ const now = await removableWorktree(target, { base, roots }, runSignal);
145
+ const current = await inspect(target, now.branch, runSignal);
146
+ if (current.fingerprint !== fingerprint) {
147
+ throw new Error(`${target} changed since the user was asked, so nothing was removed. Call removeWorktree again to have them asked with what it holds now.`);
148
+ }
149
+ // Forced: what it holds unsaved is what the user approved losing.
150
+ const removed = await git(['worktree', 'remove', '--force', '--', target], base, runSignal);
151
+ if (removed.exitCode !== 0) {
152
+ throw new Error(`git could not remove ${target}: ${removed.stderr.trim()}`);
153
+ }
154
+ }
155
+ finally {
156
+ await release();
157
+ }
158
+ const done = `Removed the worktree at ${target}.`;
159
+ const kept = removal.branch === undefined
160
+ ? ''
161
+ : ` Its branch ${removal.branch} stays, with its commits.`;
162
+ // Told to the model, which may have to mention it: an ignored folder went unchecked.
163
+ const ignored = removal.ignored === 0
164
+ ? ''
165
+ : ` It held ${String(removal.ignored)} ${removal.ignored === 1 ? 'path' : 'paths'} .gitignore excludes, removed whole without looking into them, so anything written in them while the user was asked went too.`;
166
+ return `${done}${kept}${ignored}`;
167
+ },
168
+ };
169
+ },
170
+ });
171
+ }
172
+ //# sourceMappingURL=removeWorktreeTool.js.map
@@ -0,0 +1 @@
1
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B,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;wBAC7E,CAAC;oBACF,CAAC;4BAAS,CAAC;wBACV,MAAM,OAAO,EAAE,CAAC;oBACjB,CAAC;oBACD,MAAM,IAAI,GAAG,2BAA2B,MAAM,GAAG,CAAC;oBAClD,MAAM,IAAI,GACT,OAAO,CAAC,MAAM,KAAK,SAAS;wBAC3B,CAAC,CAAC,EAAE;wBACJ,CAAC,CAAC,eAAe,OAAO,CAAC,MAAM,2BAA2B,CAAC;oBAC7D,qFAAqF;oBACrF,MAAM,OAAO,GACZ,OAAO,CAAC,OAAO,KAAK,CAAC;wBACpB,CAAC,CAAC,EAAE;wBACJ,CAAC,CAAC,YAAY,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,OAAO,CAAC,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,+HAA+H,CAAC;oBACnN,OAAO,GAAG,IAAI,GAAG,IAAI,GAAG,OAAO,EAAE,CAAC;gBACnC,CAAC;aACD,CAAC;QACH,CAAC;KACD,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { lstat, realpath } from 'node:fs/promises';\nimport { join, resolve, sep } from 'node:path';\nimport { z } from 'zod';\nimport type { WorktreeRemoval } from '#src/agent/domain/approval';\nimport { WorkspaceBusyError } from '#src/recovery/domain/recoveryStore';\nimport { FolderClaims } from '#src/recovery/infrastructure/folderClaims';\nimport type { WorkspaceRoot } from '../domain/accessPolicy.ts';\nimport type { PreparingTool } from '../domain/preparedCall.ts';\nimport { definePreparingTool } from './defineTool.ts';\nimport { git, listWorktrees } from './worktrees.ts';\n\nfunction within(path: string, folder: string): boolean {\n\treturn path === folder || path.startsWith(`${folder}${sep}`);\n}\n\n/**\n * The paths `git status --porcelain -z` names, each with its two-letter code. A rename or copy\n * names its source after it, which is skipped.\n */\nfunction statusEntries(status: string): { code: string; path: string }[] {\n\tconst fields = status.split('\\0');\n\tconst entries: { code: string; path: string }[] = [];\n\tfor (let index = 0; index < fields.length; index++) {\n\t\tconst field = fields[index] ?? '';\n\t\tif (field.length < 4) continue;\n\t\tconst code = field.slice(0, 2);\n\t\tentries.push({ code, path: field.slice(3) });\n\t\tif (code.startsWith('R') || code.startsWith('C')) index++;\n\t}\n\treturn entries;\n}\n\nasync function gitOutput(args: string[], cwd: string, signal: AbortSignal): Promise<string> {\n\tconst { stdout, stderr, exitCode } = await git(args, cwd, signal);\n\tif (exitCode !== 0) {\n\t\tthrow new Error(\n\t\t\t`git could not tell what removing ${cwd} would lose, so nothing was removed: ${stderr.trim()}`,\n\t\t);\n\t}\n\treturn stdout;\n}\n\n/**\n * What removing the worktree at `path` would lose, and a fingerprint of all it rests on: its\n * HEAD, its branch, the commits at risk, and each file `git status` names, by size and time of\n * change. Throws when\n * any of it cannot be read, since a removal must never be asked about with less than it loses.\n */\nasync function inspect(\n\tpath: string,\n\tbranch: string | undefined,\n\tsignal: AbortSignal,\n): Promise<{ removal: WorktreeRemoval; fingerprint: string }> {\n\tconst head = (await gitOutput(['rev-parse', '--verify', 'HEAD'], path, signal)).trim();\n\tconst changed = statusEntries(\n\t\tawait gitOutput(['status', '--porcelain=v1', '-z', '--untracked-files=all'], path, signal),\n\t);\n\t// A folder `.gitignore` excludes whole is named once, however much it holds.\n\tconst ignored = statusEntries(\n\t\tawait gitOutput(\n\t\t\t['status', '--porcelain=v1', '-z', '--untracked-files=normal', '--ignored=matching'],\n\t\t\tpath,\n\t\t\tsignal,\n\t\t),\n\t).filter(({ code }) => code === '!!');\n\t// The commits only a detached HEAD holds, which are lost with it.\n\tconst atRisk: string[] = [];\n\tif (branch === undefined) {\n\t\tconst listed = (\n\t\t\tawait gitOutput(\n\t\t\t\t['rev-list', 'HEAD', '--not', '--branches', '--tags', '--remotes'],\n\t\t\t\tpath,\n\t\t\t\tsignal,\n\t\t\t)\n\t\t)\n\t\t\t.split('\\n')\n\t\t\t.filter(line => line !== '');\n\t\tif (!listed.every(line => /^[0-9a-f]{40,64}$/.test(line))) {\n\t\t\tthrow new Error(\n\t\t\t\t`git could not list the commits only ${path} holds, so nothing was removed: it answered \"${listed.join(' ')}\".`,\n\t\t\t);\n\t\t}\n\t\tatRisk.push(...listed);\n\t}\n\tconst files = await Promise.all(\n\t\t[...changed, ...ignored].map(async ({ code, path: file }) => {\n\t\t\tconst stats = await lstat(join(path, file)).catch(() => undefined);\n\t\t\treturn `${code} ${file} ${String(stats?.size)} ${String(stats?.mtimeMs)}`;\n\t\t}),\n\t);\n\treturn {\n\t\tremoval: {\n\t\t\tpath,\n\t\t\t...(branch === undefined ? {} : { branch }),\n\t\t\tuncommitted: changed.length,\n\t\t\tignored: ignored.length,\n\t\t\tcommitsOnlyHere: atRisk.length,\n\t\t},\n\t\tfingerprint: JSON.stringify([head, branch ?? null, atRisk, files.sort()]),\n\t};\n}\n\n/**\n * The worktree of this repository at `target`, checked as removable: not the main folder, not\n * one the agent works in, and not locked. Throws a message for the model otherwise.\n */\nasync function removableWorktree(\n\ttarget: string,\n\t{ base, roots }: { base: string; roots: readonly WorkspaceRoot[] },\n\tsignal: AbortSignal,\n) {\n\tconst worktrees = await listWorktrees(base, signal);\n\tconst [main] = worktrees;\n\tif (main?.path === target) {\n\t\tthrow new Error(\n\t\t\t`${target} is the repository's main folder, not a worktree. Only a worktree can be removed.`,\n\t\t);\n\t}\n\tconst worktree = worktrees.find(listed => listed.path === target);\n\tif (!worktree) {\n\t\tconst others = worktrees.slice(1).map(listed => listed.path);\n\t\tthrow new Error(\n\t\t\t`${target} is not a worktree of this repository. Its worktrees: ${others.join(', ') || 'none'}.`,\n\t\t);\n\t}\n\tconst own = await Promise.all(\n\t\t// From the working directory, as the workspace reads them.\n\t\troots.map(root => realpath(resolve(root.path)).catch(() => resolve(root.path))),\n\t);\n\tif (own.some(root => within(root, target) || within(target, root))) {\n\t\tthrow new Error(`You work in ${target}, so it cannot be removed from this run.`);\n\t}\n\tif (worktree.locked) {\n\t\tthrow new Error(`${target} is locked. The user must unlock it to remove it.`);\n\t}\n\treturn worktree;\n}\n\n/**\n * `removeWorktree`: removes a git worktree of the repository the first root is in, its folder\n * and every file in it, never its branch, which keeps its commits. Each call is `destructive`,\n * so it is asked about, and the request names what is lost: changes no commit has, files\n * `.gitignore` excludes, and with a detached HEAD the commits no branch, tag or remote holds. It\n * refuses the repository's main folder, a worktree the agent works in, which holds one of its\n * roots or lies inside one, and a locked one.\n *\n * Once approved it claims the worktree (`FolderClaims`), so no run that may write in it starts,\n * and removes nothing while one works; it checks again that nothing it rests on changed while\n * the user was asked, and otherwise removes nothing, so the model calls it again to have the\n * user asked anew. A folder `.gitignore` excludes whole is checked as a folder, never looked\n * into, and its result tells the model so.\n */\nexport function createRemoveWorktreeTool({\n\tbase,\n\troots,\n\tstateDirectory,\n}: {\n\t/** The real path of the first root. */\n\tbase: string;\n\troots: readonly WorkspaceRoot[];\n\t/** Where the histories are kept, as a real path: their runs' claims are there. */\n\tstateDirectory: string;\n}): PreparingTool {\n\treturn definePreparingTool({\n\t\tname: 'removeWorktree',\n\t\tdescription:\n\t\t\t'Removes a git worktree of this repository: its folder and every file in it, committed or not. Its branch stays, with its commits. Only when the user asks for it.',\n\t\tinput: z.object({\n\t\t\tpath: z\n\t\t\t\t.string()\n\t\t\t\t.describe('The folder of the worktree, absolute or relative to the first root.'),\n\t\t}),\n\t\tsummarize: ({ path }) => path,\n\t\tprepare: async ({ path }, signal) => {\n\t\t\tconst asked = resolve(base, path);\n\t\t\tconst target = await realpath(asked).catch(() => {\n\t\t\t\tthrow new Error(`There is no folder at ${asked}.`);\n\t\t\t});\n\t\t\tconst worktree = await removableWorktree(target, { base, roots }, signal);\n\t\t\tconst { removal, fingerprint } = await inspect(target, worktree.branch, signal);\n\t\t\treturn {\n\t\t\t\trisk: 'destructive',\n\t\t\t\tworktree: removal,\n\t\t\t\trun: async runSignal => {\n\t\t\t\t\tlet release: () => Promise<void>;\n\t\t\t\t\ttry {\n\t\t\t\t\t\trelease = await new FolderClaims(stateDirectory).claimRemoval(target);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (!(error instanceof WorkspaceBusyError)) throw error;\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`A run, or a move through a history, may write in ${target}, so nothing was removed. The harness removes no worktree a run may write in; tell the user, and try again once it ends.`,\n\t\t\t\t\t\t\t{ cause: error },\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst now = await removableWorktree(target, { base, roots }, runSignal);\n\t\t\t\t\t\tconst current = await inspect(target, now.branch, runSignal);\n\t\t\t\t\t\tif (current.fingerprint !== fingerprint) {\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t`${target} changed since the user was asked, so nothing was removed. Call removeWorktree again to have them asked with what it holds now.`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Forced: what it holds unsaved is what the user approved losing.\n\t\t\t\t\t\tconst removed = await git(\n\t\t\t\t\t\t\t['worktree', 'remove', '--force', '--', target],\n\t\t\t\t\t\t\tbase,\n\t\t\t\t\t\t\trunSignal,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (removed.exitCode !== 0) {\n\t\t\t\t\t\t\tthrow new Error(`git could not remove ${target}: ${removed.stderr.trim()}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tawait release();\n\t\t\t\t\t}\n\t\t\t\t\tconst done = `Removed the worktree at ${target}.`;\n\t\t\t\t\tconst kept =\n\t\t\t\t\t\tremoval.branch === undefined\n\t\t\t\t\t\t\t? ''\n\t\t\t\t\t\t\t: ` Its branch ${removal.branch} stays, with its commits.`;\n\t\t\t\t\t// Told to the model, which may have to mention it: an ignored folder went unchecked.\n\t\t\t\t\tconst ignored =\n\t\t\t\t\t\tremoval.ignored === 0\n\t\t\t\t\t\t\t? ''\n\t\t\t\t\t\t\t: ` It held ${String(removal.ignored)} ${removal.ignored === 1 ? 'path' : 'paths'} .gitignore excludes, removed whole without looking into them, so anything written in them while the user was asked went too.`;\n\t\t\t\t\treturn `${done}${kept}${ignored}`;\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t});\n}\n"]}
@@ -25,6 +25,10 @@ export declare class WorkspaceWrites {
25
25
  * Everything this run writes to this history, its commands' changes included, from any set of
26
26
  * tools. Created on its first write, and registered before anything is awaited, so two tools
27
27
  * asking at once get the same one.
28
+ *
29
+ * @throws {EditRefusedError} for a set of tools that may write outside the folders of the set
30
+ * that started the session: the run claims those alone, so a worktree removed meanwhile could
31
+ * lose what it writes there.
28
32
  */
29
33
  sessionFor(context: RunContext): WriteSession;
30
34
  }
@@ -1,9 +1,14 @@
1
+ import { sep } from 'node:path';
2
+ import { EditRefusedError } from "../domain/fileEdits.js";
1
3
  import { FileEditor } from "./fileEditor.js";
2
4
  import { WriteSession } from "./writeSession.js";
3
5
  // One session per run and history on disk, whichever set of tools asks for it: two sets built
4
6
  // apart over one workspace, such as two stages of a workflow, record one run. Each keeps its own
5
7
  // policy. Kept by the run's context, so nothing here outlives a run.
6
8
  const sessions = new WeakMap();
9
+ function within(path, folder) {
10
+ return path === folder || path.startsWith(`${folder}${sep}`);
11
+ }
7
12
  /**
8
13
  * The writing side of a workspace, shared by every write tool built over it: one policy and
9
14
  * one recovery store. Every set of tools over the same history shares the run's `WriteSession`,
@@ -27,6 +32,10 @@ export class WorkspaceWrites {
27
32
  * Everything this run writes to this history, its commands' changes included, from any set of
28
33
  * tools. Created on its first write, and registered before anything is awaited, so two tools
29
34
  * asking at once get the same one.
35
+ *
36
+ * @throws {EditRefusedError} for a set of tools that may write outside the folders of the set
37
+ * that started the session: the run claims those alone, so a worktree removed meanwhile could
38
+ * lose what it writes there.
30
39
  */
31
40
  sessionFor(context) {
32
41
  let ofRun = sessions.get(context);
@@ -34,23 +43,28 @@ export class WorkspaceWrites {
34
43
  ofRun = new Map();
35
44
  sessions.set(context, ofRun);
36
45
  }
37
- let session = ofRun.get(this.store.workspaceId);
38
- if (!session) {
39
- const created = new WriteSession({
40
- store: this.store,
41
- // So every turn of the run, in every role, can be tied to what it wrote.
42
- onStart: runId => {
43
- context.historyRun.runId = runId;
44
- },
45
- // A run that changed nothing is not in the history, so its turns wrote nothing.
46
- onDiscard: () => {
47
- delete context.historyRun.runId;
48
- },
49
- });
50
- context.onFinish(end => created.finish(end));
51
- ofRun.set(this.store.workspaceId, created);
52
- session = created;
46
+ const started = ofRun.get(this.store.workspaceId);
47
+ if (started) {
48
+ const outside = this.store.writeFolders.filter(folder => !started.folders.some(claimed => within(folder, claimed)));
49
+ if (outside.length > 0) {
50
+ throw new EditRefusedError(`This run already writes to this workspace's history with tools that may write only in ${started.folders.join(', ')}; tools that may also write in ${outside.join(', ')} cannot join it, so nothing was changed. It is a limit of the harness: in one run, every set of tools that writes to a history may write only where the first one may. Tell the user.`);
51
+ }
52
+ return started.session;
53
53
  }
54
+ const session = new WriteSession({
55
+ store: this.store,
56
+ session: context.session,
57
+ // So every turn of the run, in every role, can be tied to what it wrote.
58
+ onStart: runId => {
59
+ context.historyRun.runId = runId;
60
+ },
61
+ // A run that changed nothing is not in the history, so its turns wrote nothing.
62
+ onDiscard: () => {
63
+ delete context.historyRun.runId;
64
+ },
65
+ });
66
+ context.onFinish(end => session.finish(end));
67
+ ofRun.set(this.store.workspaceId, { session, folders: this.store.writeFolders });
54
68
  return session;
55
69
  }
56
70
  }
@@ -1 +1 @@
1
- {"version":3,"file":"workspaceWrites.js","sourceRoot":"","sources":["../../../src/tools/infrastructure/workspaceWrites.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAE7C,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEjD,8FAA8F;AAC9F,iGAAiG;AACjG,qEAAqE;AACrE,MAAM,QAAQ,GAAG,IAAI,OAAO,EAAyC,CAAC;AAEtE;;;;GAIG;AACH,MAA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OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;YAC7C,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC;YAC3C,OAAO,GAAG,OAAO,CAAC;QACnB,CAAC;QACD,OAAO,OAAO,CAAC;IAChB,CAAC;CACD","sourcesContent":["import type { RunContext } from '#src/agent/domain/runContext';\nimport type { RecoveryStore } from '#src/recovery/domain/recoveryStore';\nimport type { AccessPolicy } from '../domain/accessPolicy.ts';\nimport { FileEditor } from './fileEditor.ts';\nimport type { FileFormatter } from './fileFormatter.ts';\nimport { WriteSession } from './writeSession.ts';\n\n// One session per run and history on disk, whichever set of tools asks for it: two sets built\n// apart over one workspace, such as two stages of a workflow, record one run. Each keeps its own\n// policy. Kept by the run's context, so nothing here outlives a run.\nconst sessions = new WeakMap<RunContext, Map<string, WriteSession>>();\n\n/**\n * The writing side of a workspace, shared by every write tool built over it: one policy and\n * one recovery store. Every set of tools over the same history shares the run's `WriteSession`,\n * ended with that run.\n */\nexport class WorkspaceWrites {\n\t/** What the edit tools run on each file they create or change, when the consumer gave one. */\n\treadonly formatter: FileFormatter | undefined;\n\tprivate readonly policy: AccessPolicy;\n\tprivate readonly store: RecoveryStore;\n\n\tconstructor({\n\t\tpolicy,\n\t\tstore,\n\t\tformatter,\n\t}: {\n\t\tpolicy: AccessPolicy;\n\t\tstore: RecoveryStore;\n\t\tformatter?: FileFormatter;\n\t}) {\n\t\tthis.policy = policy;\n\t\tthis.store = store;\n\t\tthis.formatter = formatter;\n\t}\n\n\t/** An editor over this run's session, under this set of tools' policy. */\n\teditorFor(context: RunContext): FileEditor {\n\t\treturn new FileEditor({ policy: this.policy, session: this.sessionFor(context) });\n\t}\n\n\t/**\n\t * Everything this run writes to this history, its commands' changes included, from any set of\n\t * tools. Created on its first write, and registered before anything is awaited, so two tools\n\t * asking at once get the same one.\n\t */\n\tsessionFor(context: RunContext): WriteSession {\n\t\tlet ofRun = sessions.get(context);\n\t\tif (!ofRun) {\n\t\t\tofRun = new Map();\n\t\t\tsessions.set(context, ofRun);\n\t\t}\n\t\tlet session = ofRun.get(this.store.workspaceId);\n\t\tif (!session) {\n\t\t\tconst created = new WriteSession({\n\t\t\t\tstore: this.store,\n\t\t\t\t// So every turn of the run, in every role, can be tied to what it wrote.\n\t\t\t\tonStart: runId => {\n\t\t\t\t\tcontext.historyRun.runId = runId;\n\t\t\t\t},\n\t\t\t\t// A run that changed nothing is not in the history, so its turns wrote nothing.\n\t\t\t\tonDiscard: () => {\n\t\t\t\t\tdelete context.historyRun.runId;\n\t\t\t\t},\n\t\t\t});\n\t\t\tcontext.onFinish(end => created.finish(end));\n\t\t\tofRun.set(this.store.workspaceId, created);\n\t\t\tsession = created;\n\t\t}\n\t\treturn session;\n\t}\n}\n"]}
1
+ {"version":3,"file":"workspaceWrites.js","sourceRoot":"","sources":["../../../src/tools/infrastructure/workspaceWrites.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAChC,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAE7C,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEjD,8FAA8F;AAC9F,iGAAiG;AACjG,qEAAqE;AACrE,MAAM,QAAQ,GAAG,IAAI,OAAO,EAGzB,CAAC;AAEJ,SAAS,MAAM,CAAC,IAAY,EAAE,MAAc;IAC3C,OAAO,IAAI,KAAK,MAAM,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,MAAM,GAAG,GAAG,EAAE,CAAC,CAAC;AAC9D,CAAC;AAED;;;;GAIG;AACH,MAAM,OAAO,eAAe;IAC3B,8FAA8F;IACrF,SAAS,CAA4B;IAC7B,MAAM,CAAe;IACrB,KAAK,CAAgB;IAEtC,YAAY,EACX,MAAM,EACN,KAAK,EACL,SAAS,GAKT;QACA,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;YAChC,KAAK,EAAE,IAAI,CAAC,KAAK;YACjB,OAAO,EAAE,OAAO,CAAC,OAAO;YACxB,yEAAyE;YACzE,OAAO,EAAE,KAAK,CAAC,EAAE;gBAChB,OAAO,CAAC,UAAU,CAAC,KAAK,GAAG,KAAK,CAAC;YAClC,CAAC;YACD,gFAAgF;YAChF,SAAS,EAAE,GAAG,EAAE;gBACf,OAAO,OAAO,CAAC,UAAU,CAAC,KAAK,CAAC;YACjC,CAAC;SACD,CAAC,CAAC;QACH,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;QAC7C,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,WAAW,EAAE,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,KAAK,CAAC,YAAY,EAAE,CAAC,CAAC;QACjF,OAAO,OAAO,CAAC;IAChB,CAAC;CACD","sourcesContent":["import type { RunContext } from '#src/agent/domain/runContext';\nimport type { RecoveryStore } from '#src/recovery/domain/recoveryStore';\nimport type { AccessPolicy } from '../domain/accessPolicy.ts';\nimport { sep } from 'node:path';\nimport { EditRefusedError } from '../domain/fileEdits.ts';\nimport { FileEditor } from './fileEditor.ts';\nimport type { FileFormatter } from './fileFormatter.ts';\nimport { WriteSession } from './writeSession.ts';\n\n// One session per run and history on disk, whichever set of tools asks for it: two sets built\n// apart over one workspace, such as two stages of a workflow, record one run. Each keeps its own\n// policy. Kept by the run's context, so nothing here outlives a run.\nconst sessions = new WeakMap<\n\tRunContext,\n\tMap<string, { session: WriteSession; folders: readonly string[] }>\n>();\n\nfunction within(path: string, folder: string): boolean {\n\treturn path === folder || path.startsWith(`${folder}${sep}`);\n}\n\n/**\n * The writing side of a workspace, shared by every write tool built over it: one policy and\n * one recovery store. Every set of tools over the same history shares the run's `WriteSession`,\n * ended with that run.\n */\nexport class WorkspaceWrites {\n\t/** What the edit tools run on each file they create or change, when the consumer gave one. */\n\treadonly formatter: FileFormatter | undefined;\n\tprivate readonly policy: AccessPolicy;\n\tprivate readonly store: RecoveryStore;\n\n\tconstructor({\n\t\tpolicy,\n\t\tstore,\n\t\tformatter,\n\t}: {\n\t\tpolicy: AccessPolicy;\n\t\tstore: RecoveryStore;\n\t\tformatter?: FileFormatter;\n\t}) {\n\t\tthis.policy = policy;\n\t\tthis.store = store;\n\t\tthis.formatter = formatter;\n\t}\n\n\t/** An editor over this run's session, under this set of tools' policy. */\n\teditorFor(context: RunContext): FileEditor {\n\t\treturn new FileEditor({ policy: this.policy, session: this.sessionFor(context) });\n\t}\n\n\t/**\n\t * Everything this run writes to this history, its commands' changes included, from any set of\n\t * tools. Created on its first write, and registered before anything is awaited, so two tools\n\t * asking at once get the same one.\n\t *\n\t * @throws {EditRefusedError} for a set of tools that may write outside the folders of the set\n\t * that started the session: the run claims those alone, so a worktree removed meanwhile could\n\t * lose what it writes there.\n\t */\n\tsessionFor(context: RunContext): WriteSession {\n\t\tlet ofRun = sessions.get(context);\n\t\tif (!ofRun) {\n\t\t\tofRun = new Map();\n\t\t\tsessions.set(context, ofRun);\n\t\t}\n\t\tconst started = ofRun.get(this.store.workspaceId);\n\t\tif (started) {\n\t\t\tconst outside = this.store.writeFolders.filter(\n\t\t\t\tfolder => !started.folders.some(claimed => within(folder, claimed)),\n\t\t\t);\n\t\t\tif (outside.length > 0) {\n\t\t\t\tthrow new EditRefusedError(\n\t\t\t\t\t`This run already writes to this workspace's history with tools that may write only in ${started.folders.join(', ')}; tools that may also write in ${outside.join(', ')} cannot join it, so nothing was changed. It is a limit of the harness: in one run, every set of tools that writes to a history may write only where the first one may. Tell the user.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn started.session;\n\t\t}\n\t\tconst session = new WriteSession({\n\t\t\tstore: this.store,\n\t\t\tsession: context.session,\n\t\t\t// So every turn of the run, in every role, can be tied to what it wrote.\n\t\t\tonStart: runId => {\n\t\t\t\tcontext.historyRun.runId = runId;\n\t\t\t},\n\t\t\t// A run that changed nothing is not in the history, so its turns wrote nothing.\n\t\t\tonDiscard: () => {\n\t\t\t\tdelete context.historyRun.runId;\n\t\t\t},\n\t\t});\n\t\tcontext.onFinish(end => session.finish(end));\n\t\tofRun.set(this.store.workspaceId, { session, folders: this.store.writeFolders });\n\t\treturn session;\n\t}\n}\n"]}
@@ -0,0 +1,49 @@
1
+ /** Runs git in `cwd`, its output unaffected by the user's colour settings. */
2
+ export declare function git(args: string[], cwd: string, signal?: AbortSignal): Promise<import("./runProcess.ts").ProcessResult>;
3
+ /**
4
+ * Whether `git version` names a git new enough for worktrees: `git version 2.39.3 (Apple
5
+ * Git-146)` is, `git version 2.34.1` is not. An answer it cannot read is not.
6
+ */
7
+ export declare function supportsWorktrees(versionOutput: string): boolean;
8
+ /** One worktree of a repository, as `git worktree list` gives it. */
9
+ export interface ListedWorktree {
10
+ /** Its folder, as a real path. */
11
+ path: string;
12
+ /** The branch it has checked out; absent when its HEAD is detached. */
13
+ branch?: string;
14
+ locked: boolean;
15
+ }
16
+ /**
17
+ * Every worktree of the repository `cwd` belongs to, the main folder first.
18
+ *
19
+ * @throws {Error} when git is older than 2.36, or `cwd` is in no git repository.
20
+ */
21
+ export declare function listWorktrees(cwd: string, signal?: AbortSignal): Promise<ListedWorktree[]>;
22
+ /**
23
+ * Creates a git worktree of `repository` on a new branch, `branch`, started at `from`, so an
24
+ * agent can work there apart from other runs on the same repository: it is a folder of its own,
25
+ * with a history of runs of its own. Give its `path` as an agent's root.
26
+ *
27
+ * Without `path`, it goes in a folder beside the repository's main folder, named after it:
28
+ * `../<repository>-worktrees/<branch>`, any `/` in the branch made a `-`. A relative `path` is
29
+ * from the working directory. The harness never removes it; the user does, or an agent given
30
+ * `removeWorktree` when the user asks it to.
31
+ *
32
+ * @throws {UnrecoverableError} when git is older than 2.36, `repository` is in no git
33
+ * repository, `branch` is not a valid new branch or already exists, `from` names no commit, or
34
+ * the folder already exists and is not empty. A failure leaves no branch or folder it made
35
+ * behind.
36
+ */
37
+ export declare function createWorktree({ repository, branch, from, path, }: {
38
+ /** A folder of the repository: its main folder, or one of its worktrees. */
39
+ repository: string;
40
+ /** The new branch the worktree checks out. */
41
+ branch: string;
42
+ /** The revision the branch starts at, such as `main` or a commit. */
43
+ from: string;
44
+ /** Where the worktree goes. */
45
+ path?: string;
46
+ }): Promise<{
47
+ path: string;
48
+ branch: string;
49
+ }>;
@@ -0,0 +1,154 @@
1
+ import { mkdir, readdir, realpath, rmdir } from 'node:fs/promises';
2
+ import { basename, dirname, join, resolve } from 'node:path';
3
+ import { UnrecoverableError } from '#src/shared/domain/errors';
4
+ import { runProcess } from "./runProcess.js";
5
+ // Never cancelled: creating a worktree is short, and the consumer waits for it.
6
+ const uncancelled = new AbortController().signal;
7
+ /** Runs git in `cwd`, its output unaffected by the user's colour settings. */
8
+ export function git(args, cwd, signal = uncancelled) {
9
+ return runProcess('git', ['-c', 'color.ui=never', ...args], { cwd, signal });
10
+ }
11
+ function firstLine(text) {
12
+ return text.trim().split('\n')[0] ?? '';
13
+ }
14
+ // The first git whose `worktree list` takes `-z`, without which a path holding a newline is
15
+ // misread.
16
+ const oldestGit = [2, 36];
17
+ /**
18
+ * Whether `git version` names a git new enough for worktrees: `git version 2.39.3 (Apple
19
+ * Git-146)` is, `git version 2.34.1` is not. An answer it cannot read is not.
20
+ */
21
+ export function supportsWorktrees(versionOutput) {
22
+ const match = /^git version (\d+)\.(\d+)/.exec(versionOutput.trim());
23
+ if (!match)
24
+ return false;
25
+ const [major, minor] = [Number(match[1]), Number(match[2])];
26
+ return major > oldestGit[0] || (major === oldestGit[0] && minor >= oldestGit[1]);
27
+ }
28
+ /** Throws, naming the version found, unless this machine's git is new enough for worktrees. */
29
+ async function checkGit(cwd, signal) {
30
+ const { stdout, stderr, exitCode } = await git(['version'], cwd, signal);
31
+ if (exitCode !== 0)
32
+ throw new Error(`git could not be run: ${firstLine(stderr)}`);
33
+ if (!supportsWorktrees(stdout)) {
34
+ throw new Error(`worktrees need git ${oldestGit.join('.')} or later, and this machine has ${firstLine(stdout) || 'an unknown version'}`);
35
+ }
36
+ }
37
+ /**
38
+ * Every worktree of the repository `cwd` belongs to, the main folder first.
39
+ *
40
+ * @throws {Error} when git is older than 2.36, or `cwd` is in no git repository.
41
+ */
42
+ export async function listWorktrees(cwd, signal) {
43
+ await checkGit(cwd, signal);
44
+ const { stdout, stderr, exitCode } = await git(['worktree', 'list', '--porcelain', '-z'], cwd, signal);
45
+ if (exitCode !== 0)
46
+ throw new Error(`git could not list the worktrees: ${firstLine(stderr)}`);
47
+ const worktrees = [];
48
+ let current;
49
+ // One attribute per NUL-terminated field, and an empty field between worktrees.
50
+ for (const field of stdout.split('\0')) {
51
+ if (field.startsWith('worktree ')) {
52
+ current = { path: field.slice('worktree '.length), locked: false };
53
+ worktrees.push(current);
54
+ }
55
+ else if (current && field.startsWith('branch refs/heads/')) {
56
+ current.branch = field.slice('branch refs/heads/'.length);
57
+ }
58
+ else if (current && (field === 'locked' || field.startsWith('locked '))) {
59
+ current.locked = true;
60
+ }
61
+ }
62
+ // git prints the paths it was given; a link in one must not hide a match.
63
+ return Promise.all(worktrees.map(async (worktree) => ({
64
+ ...worktree,
65
+ path: await realpath(worktree.path).catch(() => worktree.path),
66
+ })));
67
+ }
68
+ /**
69
+ * Removes the branch this call made, once its worktree could not be added: only while it still
70
+ * points at `sha`, which `update-ref` checks as it deletes, and no worktree has it.
71
+ */
72
+ async function removeOwnBranch(cwd, branch, sha) {
73
+ const worktrees = await listWorktrees(cwd).catch(() => undefined);
74
+ if (!worktrees?.every(worktree => worktree.branch !== branch))
75
+ return;
76
+ await git(['update-ref', '-d', `refs/heads/${branch}`, sha], cwd);
77
+ }
78
+ function failed(what, cause) {
79
+ return new UnrecoverableError(`The worktree could not be created: ${what}`, { cause });
80
+ }
81
+ /**
82
+ * Creates a git worktree of `repository` on a new branch, `branch`, started at `from`, so an
83
+ * agent can work there apart from other runs on the same repository: it is a folder of its own,
84
+ * with a history of runs of its own. Give its `path` as an agent's root.
85
+ *
86
+ * Without `path`, it goes in a folder beside the repository's main folder, named after it:
87
+ * `../<repository>-worktrees/<branch>`, any `/` in the branch made a `-`. A relative `path` is
88
+ * from the working directory. The harness never removes it; the user does, or an agent given
89
+ * `removeWorktree` when the user asks it to.
90
+ *
91
+ * @throws {UnrecoverableError} when git is older than 2.36, `repository` is in no git
92
+ * repository, `branch` is not a valid new branch or already exists, `from` names no commit, or
93
+ * the folder already exists and is not empty. A failure leaves no branch or folder it made
94
+ * behind.
95
+ */
96
+ export async function createWorktree({ repository, branch, from, path, }) {
97
+ const cwd = resolve(repository);
98
+ // First: an older git could make the branch and then fail to list the worktrees.
99
+ await checkGit(cwd).catch((error) => {
100
+ throw failed(error instanceof Error ? error.message : String(error), 'Update git.');
101
+ });
102
+ const valid = await git(['check-ref-format', '--branch', branch], cwd);
103
+ if (valid.exitCode !== 0) {
104
+ throw failed(`"${branch}" is not a valid branch name`, firstLine(valid.stderr) || 'git refused it.');
105
+ }
106
+ // Resolved first, so a revision that starts with a dash can never be read as an option.
107
+ const commit = await git(['rev-parse', '--verify', '--quiet', '--end-of-options', `${from}^{commit}`], cwd);
108
+ if (commit.exitCode !== 0) {
109
+ throw failed(`"${from}" names no commit`, firstLine(commit.stderr) || 'git found no such revision.');
110
+ }
111
+ const sha = commit.stdout.trim();
112
+ const ref = `refs/heads/${branch}`;
113
+ if ((await git(['show-ref', '--verify', '--quiet', ref], cwd)).exitCode === 0) {
114
+ throw failed(`the branch "${branch}" already exists`, 'Name a new branch.');
115
+ }
116
+ let target;
117
+ if (path === undefined) {
118
+ const [main] = await listWorktrees(cwd).catch((error) => {
119
+ // git's own words: no repository is one cause among others.
120
+ throw failed(error instanceof Error ? error.message : String(error), `In ${cwd}.`);
121
+ });
122
+ if (!main)
123
+ throw failed(`${cwd} is in no git repository`, 'git listed no worktree.');
124
+ target = join(dirname(main.path), `${basename(main.path)}-worktrees`, branch.replaceAll('/', '-'));
125
+ }
126
+ else {
127
+ target = resolve(path);
128
+ }
129
+ // git takes an empty folder, but would create the branch before refusing a full one.
130
+ const held = await readdir(target).catch((error) => error.code === 'ENOENT' ? [] : undefined);
131
+ if (held === undefined || held.length > 0) {
132
+ throw failed(`${target} already exists`, 'Give the worktree a folder that does not.');
133
+ }
134
+ // The first folder this call made, if any, which it removes again should git fail.
135
+ const made = path === undefined ? await mkdir(dirname(target), { recursive: true }) : undefined;
136
+ const removeMade = async () => {
137
+ if (made !== undefined)
138
+ await rmdir(made).catch(() => undefined);
139
+ };
140
+ // Made apart and first: git refuses a branch that exists, so the one made here is this call's.
141
+ const created = await git(['branch', '--no-track', branch, sha], cwd);
142
+ if (created.exitCode !== 0) {
143
+ await removeMade();
144
+ throw failed(`the branch "${branch}" could not be made`, firstLine(created.stderr));
145
+ }
146
+ const added = await git(['worktree', 'add', '--', target, branch], cwd);
147
+ if (added.exitCode !== 0) {
148
+ await removeOwnBranch(cwd, branch, sha);
149
+ await removeMade();
150
+ throw failed('git refused it', firstLine(added.stderr));
151
+ }
152
+ return { path: await realpath(target), branch };
153
+ }
154
+ //# sourceMappingURL=worktrees.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worktrees.js","sourceRoot":"","sources":["../../../src/tools/infrastructure/worktrees.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAC;AACnE,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC7D,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAE7C,gFAAgF;AAChF,MAAM,WAAW,GAAG,IAAI,eAAe,EAAE,CAAC,MAAM,CAAC;AAEjD,8EAA8E;AAC9E,MAAM,UAAU,GAAG,CAAC,IAAc,EAAE,GAAW,EAAE,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C;IAChG,MAAM,UAAU,GAAG,KAAK,IAAI,EAAE;QAC7B,IAAI,IAAI,KAAK,SAAS;YAAE,MAAM,KAAK,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;IAClE,CAAC,CAAC;IAEF,+FAA+F;IAC/F,MAAM,OAAO,GAAG,MAAM,GAAG,CAAC,CAAC,QAAQ,EAAE,YAAY,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC;IACtE,IAAI,OAAO,CAAC,QAAQ,KAAK,CAAC,EAAE,CAAC;QAC5B,MAAM,UAAU,EAAE,CAAC;QACnB,MAAM,MAAM,CAAC,eAAe,MAAM,qBAAqB,EAAE,SAAS,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC;IACrF,CAAC;IACD,MAAM,KAAK,GAAG,MAAM,GAAG,CAAC,CAAC,UAAU,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,GAAG,CAAC,CAAC;IACxE,IAAI,KAAK,CAAC,QAAQ,KAAK,CAAC,EAAE,CAAC;QAC1B,MAAM,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,CAAC,CAAC;QACxC,MAAM,UAAU,EAAE,CAAC;QACnB,MAAM,MAAM,CAAC,gBAAgB,EAAE,SAAS,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC;IACzD,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;AACjD,CAAC","sourcesContent":["import { mkdir, readdir, realpath, rmdir } from 'node:fs/promises';\nimport { basename, dirname, join, resolve } from 'node:path';\nimport { UnrecoverableError } from '#src/shared/domain/errors';\nimport { runProcess } from './runProcess.ts';\n\n// Never cancelled: creating a worktree is short, and the consumer waits for it.\nconst uncancelled = new AbortController().signal;\n\n/** Runs git in `cwd`, its output unaffected by the user's colour settings. */\nexport function git(args: string[], cwd: string, signal: AbortSignal = uncancelled) {\n\treturn runProcess('git', ['-c', 'color.ui=never', ...args], { cwd, signal });\n}\n\nfunction firstLine(text: string): string {\n\treturn text.trim().split('\\n')[0] ?? '';\n}\n\n// The first git whose `worktree list` takes `-z`, without which a path holding a newline is\n// misread.\nconst oldestGit = [2, 36] as const;\n\n/**\n * Whether `git version` names a git new enough for worktrees: `git version 2.39.3 (Apple\n * Git-146)` is, `git version 2.34.1` is not. An answer it cannot read is not.\n */\nexport function supportsWorktrees(versionOutput: string): boolean {\n\tconst match = /^git version (\\d+)\\.(\\d+)/.exec(versionOutput.trim());\n\tif (!match) return false;\n\tconst [major, minor] = [Number(match[1]), Number(match[2])];\n\treturn major > oldestGit[0] || (major === oldestGit[0] && minor >= oldestGit[1]);\n}\n\n/** Throws, naming the version found, unless this machine's git is new enough for worktrees. */\nasync function checkGit(cwd: string, signal?: AbortSignal): Promise<void> {\n\tconst { stdout, stderr, exitCode } = await git(['version'], cwd, signal);\n\tif (exitCode !== 0) throw new Error(`git could not be run: ${firstLine(stderr)}`);\n\tif (!supportsWorktrees(stdout)) {\n\t\tthrow new Error(\n\t\t\t`worktrees need git ${oldestGit.join('.')} or later, and this machine has ${firstLine(stdout) || 'an unknown version'}`,\n\t\t);\n\t}\n}\n\n/** One worktree of a repository, as `git worktree list` gives it. */\nexport interface ListedWorktree {\n\t/** Its folder, as a real path. */\n\tpath: string;\n\t/** The branch it has checked out; absent when its HEAD is detached. */\n\tbranch?: string;\n\tlocked: boolean;\n}\n\n/**\n * Every worktree of the repository `cwd` belongs to, the main folder first.\n *\n * @throws {Error} when git is older than 2.36, or `cwd` is in no git repository.\n */\nexport async function listWorktrees(cwd: string, signal?: AbortSignal): Promise<ListedWorktree[]> {\n\tawait checkGit(cwd, signal);\n\tconst { stdout, stderr, exitCode } = await git(\n\t\t['worktree', 'list', '--porcelain', '-z'],\n\t\tcwd,\n\t\tsignal,\n\t);\n\tif (exitCode !== 0) throw new Error(`git could not list the worktrees: ${firstLine(stderr)}`);\n\tconst worktrees: ListedWorktree[] = [];\n\tlet current: ListedWorktree | undefined;\n\t// One attribute per NUL-terminated field, and an empty field between worktrees.\n\tfor (const field of stdout.split('\\0')) {\n\t\tif (field.startsWith('worktree ')) {\n\t\t\tcurrent = { path: field.slice('worktree '.length), locked: false };\n\t\t\tworktrees.push(current);\n\t\t} else if (current && field.startsWith('branch refs/heads/')) {\n\t\t\tcurrent.branch = field.slice('branch refs/heads/'.length);\n\t\t} else if (current && (field === 'locked' || field.startsWith('locked '))) {\n\t\t\tcurrent.locked = true;\n\t\t}\n\t}\n\t// git prints the paths it was given; a link in one must not hide a match.\n\treturn Promise.all(\n\t\tworktrees.map(async worktree => ({\n\t\t\t...worktree,\n\t\t\tpath: await realpath(worktree.path).catch(() => worktree.path),\n\t\t})),\n\t);\n}\n\n/**\n * Removes the branch this call made, once its worktree could not be added: only while it still\n * points at `sha`, which `update-ref` checks as it deletes, and no worktree has it.\n */\nasync function removeOwnBranch(cwd: string, branch: string, sha: string): Promise<void> {\n\tconst worktrees = await listWorktrees(cwd).catch(() => undefined);\n\tif (!worktrees?.every(worktree => worktree.branch !== branch)) return;\n\tawait git(['update-ref', '-d', `refs/heads/${branch}`, sha], cwd);\n}\n\nfunction failed(what: string, cause: string): UnrecoverableError {\n\treturn new UnrecoverableError(`The worktree could not be created: ${what}`, { cause });\n}\n\n/**\n * Creates a git worktree of `repository` on a new branch, `branch`, started at `from`, so an\n * agent can work there apart from other runs on the same repository: it is a folder of its own,\n * with a history of runs of its own. Give its `path` as an agent's root.\n *\n * Without `path`, it goes in a folder beside the repository's main folder, named after it:\n * `../<repository>-worktrees/<branch>`, any `/` in the branch made a `-`. A relative `path` is\n * from the working directory. The harness never removes it; the user does, or an agent given\n * `removeWorktree` when the user asks it to.\n *\n * @throws {UnrecoverableError} when git is older than 2.36, `repository` is in no git\n * repository, `branch` is not a valid new branch or already exists, `from` names no commit, or\n * the folder already exists and is not empty. A failure leaves no branch or folder it made\n * behind.\n */\nexport async function createWorktree({\n\trepository,\n\tbranch,\n\tfrom,\n\tpath,\n}: {\n\t/** A folder of the repository: its main folder, or one of its worktrees. */\n\trepository: string;\n\t/** The new branch the worktree checks out. */\n\tbranch: string;\n\t/** The revision the branch starts at, such as `main` or a commit. */\n\tfrom: string;\n\t/** Where the worktree goes. */\n\tpath?: string;\n}): Promise<{ path: string; branch: string }> {\n\tconst cwd = resolve(repository);\n\t// First: an older git could make the branch and then fail to list the worktrees.\n\tawait checkGit(cwd).catch((error: unknown) => {\n\t\tthrow failed(error instanceof Error ? error.message : String(error), 'Update git.');\n\t});\n\tconst valid = await git(['check-ref-format', '--branch', branch], cwd);\n\tif (valid.exitCode !== 0) {\n\t\tthrow failed(\n\t\t\t`\"${branch}\" is not a valid branch name`,\n\t\t\tfirstLine(valid.stderr) || 'git refused it.',\n\t\t);\n\t}\n\t// Resolved first, so a revision that starts with a dash can never be read as an option.\n\tconst commit = await git(\n\t\t['rev-parse', '--verify', '--quiet', '--end-of-options', `${from}^{commit}`],\n\t\tcwd,\n\t);\n\tif (commit.exitCode !== 0) {\n\t\tthrow failed(\n\t\t\t`\"${from}\" names no commit`,\n\t\t\tfirstLine(commit.stderr) || 'git found no such revision.',\n\t\t);\n\t}\n\n\tconst sha = commit.stdout.trim();\n\tconst ref = `refs/heads/${branch}`;\n\tif ((await git(['show-ref', '--verify', '--quiet', ref], cwd)).exitCode === 0) {\n\t\tthrow failed(`the branch \"${branch}\" already exists`, 'Name a new branch.');\n\t}\n\n\tlet target: string;\n\tif (path === undefined) {\n\t\tconst [main] = await listWorktrees(cwd).catch((error: unknown) => {\n\t\t\t// git's own words: no repository is one cause among others.\n\t\t\tthrow failed(error instanceof Error ? error.message : String(error), `In ${cwd}.`);\n\t\t});\n\t\tif (!main) throw failed(`${cwd} is in no git repository`, 'git listed no worktree.');\n\t\ttarget = join(\n\t\t\tdirname(main.path),\n\t\t\t`${basename(main.path)}-worktrees`,\n\t\t\tbranch.replaceAll('/', '-'),\n\t\t);\n\t} else {\n\t\ttarget = resolve(path);\n\t}\n\t// git takes an empty folder, but would create the branch before refusing a full one.\n\tconst held = await readdir(target).catch((error: unknown) =>\n\t\t(error as NodeJS.ErrnoException).code === 'ENOENT' ? [] : undefined,\n\t);\n\tif (held === undefined || held.length > 0) {\n\t\tthrow failed(`${target} already exists`, 'Give the worktree a folder that does not.');\n\t}\n\t// The first folder this call made, if any, which it removes again should git fail.\n\tconst made = path === undefined ? await mkdir(dirname(target), { recursive: true }) : undefined;\n\tconst removeMade = async () => {\n\t\tif (made !== undefined) await rmdir(made).catch(() => undefined);\n\t};\n\n\t// Made apart and first: git refuses a branch that exists, so the one made here is this call's.\n\tconst created = await git(['branch', '--no-track', branch, sha], cwd);\n\tif (created.exitCode !== 0) {\n\t\tawait removeMade();\n\t\tthrow failed(`the branch \"${branch}\" could not be made`, firstLine(created.stderr));\n\t}\n\tconst added = await git(['worktree', 'add', '--', target, branch], cwd);\n\tif (added.exitCode !== 0) {\n\t\tawait removeOwnBranch(cwd, branch, sha);\n\t\tawait removeMade();\n\t\tthrow failed('git refused it', firstLine(added.stderr));\n\t}\n\treturn { path: await realpath(target), branch };\n}\n"]}
@@ -1,3 +1,4 @@
1
+ import type { Session } from '#src/shared/domain/session';
1
2
  import { type RecoveryStore, type RunJournal, type RunStatus } from '#src/recovery/domain/recoveryStore';
2
3
  /**
3
4
  * Everything one top-level run writes, across all its roles and rounds. Its journal starts on
@@ -10,17 +11,20 @@ export declare class WriteSession {
10
11
  private readonly maxChanges;
11
12
  private readonly onStart;
12
13
  private readonly onDiscard;
14
+ private readonly session;
13
15
  private journal;
14
16
  private changes;
15
17
  private stopped;
16
18
  private writing;
17
- constructor({ store, maxChanges, onStart, onDiscard, }: {
19
+ constructor({ store, maxChanges, onStart, onDiscard, session, }: {
18
20
  store: RecoveryStore;
19
21
  maxChanges?: number;
20
22
  /** Told the run's id once its journal has started, before its first change is recorded. */
21
23
  onStart?: (runId: string) => void;
22
24
  /** Told when the run ended having changed nothing, so the history no longer has it. */
23
25
  onDiscard?: () => void;
26
+ /** The session the run belongs to, recorded with it. */
27
+ session?: Session;
24
28
  });
25
29
  /** The journal for one more change, counted against the run's limit. */
26
30
  journalForChange(): Promise<RunJournal>;
@@ -13,16 +13,18 @@ export class WriteSession {
13
13
  maxChanges;
14
14
  onStart;
15
15
  onDiscard;
16
+ session;
16
17
  journal;
17
18
  changes = 0;
18
19
  stopped;
19
20
  // The end of the last write waiting or running, which the next one starts after.
20
21
  writing = Promise.resolve();
21
- constructor({ store, maxChanges = defaultMaxChanges, onStart, onDiscard, }) {
22
+ constructor({ store, maxChanges = defaultMaxChanges, onStart, onDiscard, session, }) {
22
23
  this.store = store;
23
24
  this.maxChanges = maxChanges;
24
25
  this.onStart = onStart;
25
26
  this.onDiscard = onDiscard;
27
+ this.session = session;
26
28
  }
27
29
  /** The journal for one more change, counted against the run's limit. */
28
30
  async journalForChange() {
@@ -31,7 +33,9 @@ export class WriteSession {
31
33
  if (this.changes >= this.maxChanges) {
32
34
  throw new EditRefusedError(`This run has made ${String(this.maxChanges)} changes, the most one run may make`);
33
35
  }
34
- this.journal ??= this.store.startRun().then(started => {
36
+ this.journal ??= this.store
37
+ .startRun(this.session ? { session: this.session } : {})
38
+ .then(started => {
35
39
  this.onStart?.(started.runId);
36
40
  return started;
37
41
  });
@@ -43,7 +47,7 @@ export class WriteSession {
43
47
  // A failed start is not kept, so the next change tries again.
44
48
  this.journal = undefined;
45
49
  if (error instanceof WorkspaceBusyError) {
46
- throw new EditRefusedError('Another run, or a move through its history, holds this workspace, so nothing was changed', {
50
+ throw new EditRefusedError('Another run, a move through its history, or the removal of its worktree holds this workspace, so nothing was changed. The harness lets one run at a time write to a workspace; tell the user, who can wait for it to end or give this chat a worktree of its own.', {
47
51
  cause: error,
48
52
  });
49
53
  }