shapewall 0.2.4 → 0.3.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/CHANGELOG.md +36 -0
- package/README.md +35 -1
- package/dist/agent/package-lock.json +2 -2
- package/dist/client/assets/BoardChat-CupOxioV.js +27 -0
- package/dist/client/assets/{BuzzDialog-CZdwIQLF.js → BuzzDialog-Ds7Thpfe.js} +1 -1
- package/dist/client/assets/ChecksPanel-BqrS02Ih.js +1 -0
- package/dist/client/assets/History-CQG3NQOC.js +1 -0
- package/dist/client/assets/{LocalSettings-B5gtfKEl.js → LocalSettings-CSNMhNyV.js} +1 -1
- package/dist/client/assets/{Management-BxEUZAmI.js → Management-CJVNAqAW.js} +1 -1
- package/dist/client/assets/QuickConnect-B-4pUgXH.js +1 -0
- package/dist/client/assets/{ShareDialog-CdVAreaw.js → ShareDialog-BouvNraR.js} +2 -2
- package/dist/client/assets/{app-update-dialog-BONq9YFp.js → app-update-dialog-rhaw0MRk.js} +1 -1
- package/dist/client/assets/{circle-x-BmT6vHKl.js → circle-x-PRxj7kPi.js} +1 -1
- package/dist/client/assets/index-CXtuJi1K.css +2 -0
- package/dist/client/assets/index-DKOCIQiq.js +37 -0
- package/dist/client/assets/{refresh-cw-ugt3cWKH.js → refresh-cw-aeOBDuGQ.js} +1 -1
- package/dist/client/assets/{square-_KG6tM5A.js → shield-check-DuPBJ6H_.js} +1 -1
- package/dist/client/assets/ui-Cg4TTrec.js +41 -0
- package/dist/client/build-info.json +1 -1
- package/dist/client/index.html +3 -3
- package/dist/client/sw.js +2 -2
- package/dist/console/assets/LocalAccountsApp-DOKZI6Lt.js +1 -0
- package/dist/console/assets/LocalConsole-DXzldLW9.js +1 -0
- package/dist/console/assets/{app-update-dialog-o4QY_jL9.js → app-update-dialog-CrqIMEwN.js} +1 -1
- package/dist/console/assets/console-76WovHlh.js +55 -0
- package/dist/console/assets/console-Fp4k9iyx.css +2 -0
- package/dist/console/build-info.json +1 -1
- package/dist/console/console.html +2 -2
- package/docs/agent-hardening.md +19 -0
- package/docs/agent-workflow.md +33 -0
- package/docs/agents.md +112 -0
- package/docs/config.md +41 -0
- package/docs/deployment.md +3 -0
- package/docs/hosted.md +10 -0
- package/docs/pull-requests.md +192 -0
- package/package.json +2 -1
- package/src/agent/backends/acp.js +23 -6
- package/src/agent/batch-fixes.js +45 -0
- package/src/agent/batch-queue.js +204 -0
- package/src/agent/branch-mode.js +753 -0
- package/src/agent/config.js +6 -0
- package/src/agent/fix-prompt.js +5 -0
- package/src/agent/routes.js +850 -185
- package/src/agent/run.js +8 -1
- package/src/agent/settings-routes.js +69 -1
- package/src/agent/starter/worktree.js +254 -25
- package/src/agent/threads.js +2 -7
- package/src/agent/tools.js +51 -0
- package/src/agent/user-settings.js +33 -2
- package/src/ci/capture.js +103 -0
- package/src/ci/compare.js +267 -0
- package/src/ci/github.js +307 -0
- package/src/ci/images.js +76 -0
- package/src/ci/settings.js +211 -0
- package/src/ci/start.js +148 -0
- package/src/ci/summary.js +262 -0
- package/src/ci/workflow.js +238 -0
- package/src/cli/args.js +24 -1
- package/src/cli/ci.js +229 -0
- package/src/cli/help.js +23 -1
- package/src/cli/init.js +33 -1
- package/src/cli.js +6 -2
- package/src/comment-drawing.js +161 -0
- package/src/comment-fields.js +51 -0
- package/src/comment-media.js +528 -0
- package/src/config.js +7 -0
- package/src/doctor.js +23 -0
- package/src/export.js +8 -0
- package/src/feedback.js +89 -12
- package/src/github.js +3 -3
- package/src/hosted/admin.js +36 -4
- package/src/hosted/app.js +5 -0
- package/src/hosted/board-routes.js +63 -7
- package/src/hosted/clean-worker.js +22 -4
- package/src/hosted/cleaner.js +4 -1
- package/src/hosted/comment-files.js +200 -0
- package/src/hosted/comments.js +68 -15
- package/src/hosted/db.js +32 -0
- package/src/hosted/guest-view.js +9 -0
- package/src/hosted/import.js +213 -18
- package/src/hosted/operator.js +3 -1
- package/src/hosted/projects.js +3 -2
- package/src/hosted/push.js +6 -3
- package/src/hosted/retention.js +18 -0
- package/src/hosted/tenancy.js +1 -0
- package/src/hosted/token-api.js +110 -9
- package/src/image-sniff.js +11 -0
- package/src/mcp.js +48 -3
- package/src/remote/remote-mcp.js +2 -2
- package/src/remote/remote.js +6 -2
- package/src/remote/share.js +77 -7
- package/src/server/app.js +18 -1
- package/src/store.js +119 -33
- package/src/watch.js +4 -0
- package/dist/client/assets/BoardChat-C0a3DDjv.js +0 -28
- package/dist/client/assets/ChecksPanel-BHWgwJWO.js +0 -1
- package/dist/client/assets/History-C01qLFpP.js +0 -1
- package/dist/client/assets/QuickConnect-BzTM3UNO.js +0 -1
- package/dist/client/assets/index-C1IsGdGs.js +0 -29
- package/dist/client/assets/index-DnsWelgZ.css +0 -2
- package/dist/client/assets/ui-BAGBTB_P.js +0 -41
- package/dist/console/assets/LocalAccountsApp-DtfTDbQg.js +0 -1
- package/dist/console/assets/LocalConsole-BPpsxDq_.js +0 -1
- package/dist/console/assets/console-DeOji9Zv.css +0 -2
- package/dist/console/assets/console-MvFrlUCC.js +0 -51
|
@@ -0,0 +1,753 @@
|
|
|
1
|
+
// Agent branch mode: a coding agent connected over ACP (Claude Code, Codex,
|
|
2
|
+
// goose) makes its changes in a separate checkout on a new branch, never in
|
|
3
|
+
// the person's working checkout. Off by default.
|
|
4
|
+
//
|
|
5
|
+
// It reuses the starter agent's git side (starter/worktree.js) and its rules:
|
|
6
|
+
//
|
|
7
|
+
// - the checkout is a plain copy of HEAD with no .git in it, written by
|
|
8
|
+
// Shapewall from the blobs (no git checkout, so no smudge filter runs), in
|
|
9
|
+
// <project>/.shapewall/agent-worktrees/<run id>. Nothing the agent writes
|
|
10
|
+
// there can point git anywhere, and `GIT_CEILING_DIRECTORIES` stops git
|
|
11
|
+
// commands the agent runs from finding the project's own repository;
|
|
12
|
+
// - the agent's work is committed by Shapewall at the end of the turn by
|
|
13
|
+
// reading the files itself and writing blobs with hash-object --no-filters
|
|
14
|
+
// (no filter, attribute or hook runs; .gitattributes and .gitmodules keep
|
|
15
|
+
// their base version; symlinks out of the checkout are refused), on a new
|
|
16
|
+
// branch made with update-ref only if it does not exist;
|
|
17
|
+
// - every git call runs with hooks, fsmonitor and signing off and the system
|
|
18
|
+
// config ignored (SAFE_GIT_FLAGS), and git's environment scrubbed; on the
|
|
19
|
+
// person's checkout every configured filter, merge and diff driver is
|
|
20
|
+
// overridden with an empty command (inertDriverFlags);
|
|
21
|
+
// - the agent's commit leaves out what the base commit's ignore rules ignore,
|
|
22
|
+
// whatever the agent did to .gitignore.
|
|
23
|
+
//
|
|
24
|
+
// Apply brings the branch into the person's checkout: only when it is clean,
|
|
25
|
+
// on a branch, with no merge or rebase in progress, and the agent's branch
|
|
26
|
+
// still points at the agent's commit. A fast-forward when possible, else a
|
|
27
|
+
// merge that `git merge-tree` checked first: on a conflict nothing changes.
|
|
28
|
+
// It is refused, changing nothing, when it would write over a file Git does
|
|
29
|
+
// not track (an ignored .env) or touch a file a Git filter handles (LFS);
|
|
30
|
+
// Undo has the same check. Submodules are never recursed into, and nothing
|
|
31
|
+
// is stashed.
|
|
32
|
+
//
|
|
33
|
+
// The branch name comes from the comment text, sanitized to [a-z0-9-] and
|
|
34
|
+
// never starting with "-"; commits are passed by their id, never by a name a
|
|
35
|
+
// person or a model chose. The worktree folder is fixed under the project's
|
|
36
|
+
// .shapewall folder: the config's outputDir cannot move it, and a symlinked
|
|
37
|
+
// .shapewall or agent-worktrees folder is refused.
|
|
38
|
+
|
|
39
|
+
import fs from 'node:fs'
|
|
40
|
+
import path from 'node:path'
|
|
41
|
+
import {
|
|
42
|
+
createWorktree,
|
|
43
|
+
commitWorktree,
|
|
44
|
+
filterNames,
|
|
45
|
+
git,
|
|
46
|
+
inertDriverFlags,
|
|
47
|
+
newRunId,
|
|
48
|
+
processAlive,
|
|
49
|
+
removeWorktree,
|
|
50
|
+
sweepWorkRoot,
|
|
51
|
+
RUN_DIR_RE,
|
|
52
|
+
} from './starter/worktree.js'
|
|
53
|
+
import { userAgentEntry } from './user-settings.js'
|
|
54
|
+
import { THREAD_RE } from './thread-history.js'
|
|
55
|
+
|
|
56
|
+
export const BRANCH_MODE_VAR = 'SHAPEWALL_AGENT_BRANCH_MODE'
|
|
57
|
+
export const BRANCH_PREFIX_VAR = 'SHAPEWALL_AGENT_BRANCH_PREFIX'
|
|
58
|
+
export const DEFAULT_BRANCH_PREFIX = 'shapewall/'
|
|
59
|
+
export const WORKTREES_DIR = path.join('.shapewall', 'agent-worktrees')
|
|
60
|
+
export const FALLBACK_AUTHOR = { name: 'Shapewall agent', email: 'agent@shapewall.invalid' }
|
|
61
|
+
const PREFIX_MAX = 40
|
|
62
|
+
// Segments of letters, digits, "_" and "-" (each starting with a letter or a
|
|
63
|
+
// digit) joined by "/", with or without a trailing "/". No dots at all (no
|
|
64
|
+
// "..", no ".lock"), no spaces, nothing git would read as an option.
|
|
65
|
+
const PREFIX_RE = /^[A-Za-z0-9][A-Za-z0-9_-]*(?:\/[A-Za-z0-9][A-Za-z0-9_-]*)*\/?$/
|
|
66
|
+
const BRANCH_RE = /^[A-Za-z0-9][A-Za-z0-9_-]*(?:\/[A-Za-z0-9][A-Za-z0-9_-]*)*$/
|
|
67
|
+
const BRANCH_MAX = 120
|
|
68
|
+
const SHA_RE = /^[0-9a-f]{40}([0-9a-f]{24})?$/
|
|
69
|
+
const BOARD_ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/
|
|
70
|
+
const MESSAGE_ID_RE = /^msg_[a-z0-9]{1,40}$/
|
|
71
|
+
const PROTECTED = new Set(['main', 'master', 'trunk', 'develop', 'production', 'staging', 'release', 'head'])
|
|
72
|
+
const IN_PROGRESS = [
|
|
73
|
+
['MERGE_HEAD', 'merge'],
|
|
74
|
+
['rebase-merge', 'rebase'],
|
|
75
|
+
['rebase-apply', 'rebase'],
|
|
76
|
+
['CHERRY_PICK_HEAD', 'cherry-pick'],
|
|
77
|
+
['REVERT_HEAD', 'revert'],
|
|
78
|
+
]
|
|
79
|
+
// For git on the person's checkout (Apply, revert): no submodule recursion,
|
|
80
|
+
// no autostash, no automatic gc or maintenance started from here.
|
|
81
|
+
const CHECKOUT_FLAGS = [
|
|
82
|
+
'-c',
|
|
83
|
+
'submodule.recurse=false',
|
|
84
|
+
'-c',
|
|
85
|
+
'merge.autoStash=false',
|
|
86
|
+
'-c',
|
|
87
|
+
'gc.auto=0',
|
|
88
|
+
'-c',
|
|
89
|
+
'maintenance.auto=false',
|
|
90
|
+
'-c',
|
|
91
|
+
'merge.verifySignatures=false',
|
|
92
|
+
]
|
|
93
|
+
|
|
94
|
+
export class BranchError extends Error {
|
|
95
|
+
constructor(code, message, status = 409) {
|
|
96
|
+
super(message)
|
|
97
|
+
this.code = code
|
|
98
|
+
this.status = status
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const isObject = (value) => Boolean(value) && typeof value === 'object' && !Array.isArray(value)
|
|
103
|
+
|
|
104
|
+
// A prefix as given, or null when it is not one Shapewall accepts.
|
|
105
|
+
export function cleanBranchPrefix(value) {
|
|
106
|
+
if (typeof value !== 'string') return null
|
|
107
|
+
const prefix = value.trim()
|
|
108
|
+
if (!prefix || prefix.length > PREFIX_MAX || !PREFIX_RE.test(prefix)) return null
|
|
109
|
+
return prefix
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const envFlag = (value) => {
|
|
113
|
+
const text = String(value ?? '')
|
|
114
|
+
.trim()
|
|
115
|
+
.toLowerCase()
|
|
116
|
+
if (['1', 'true', 'on', 'yes'].includes(text)) return true
|
|
117
|
+
if (['0', 'false', 'off', 'no'].includes(text)) return false
|
|
118
|
+
return null
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// `agent.branchMode` (true or false) and `agent.branchPrefix` in
|
|
122
|
+
// shapewall.config.json. Pushes one message per problem.
|
|
123
|
+
export function validateBranchConfig(raw, problems) {
|
|
124
|
+
const out = {}
|
|
125
|
+
if (!isObject(raw)) return out
|
|
126
|
+
if (raw.branchMode !== undefined) {
|
|
127
|
+
if (typeof raw.branchMode !== 'boolean') problems.push('agent.branchMode: true or false')
|
|
128
|
+
else out.branchMode = raw.branchMode
|
|
129
|
+
}
|
|
130
|
+
if (raw.branchPrefix !== undefined) {
|
|
131
|
+
const prefix = cleanBranchPrefix(raw.branchPrefix)
|
|
132
|
+
if (!prefix)
|
|
133
|
+
problems.push(`agent.branchPrefix: letters, digits, "-", "_" and "/", at most ${PREFIX_MAX} characters, such as "shapewall/"`)
|
|
134
|
+
else out.branchPrefix = prefix
|
|
135
|
+
}
|
|
136
|
+
return out
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Whether the agent works on a branch here, and the branch prefix. The
|
|
140
|
+
// environment wins, then Settings (agents.json), then the config.
|
|
141
|
+
// { enabled, prefix, sources: { enabled, prefix } } (env | settings | config | null)
|
|
142
|
+
export function branchModeSettings(config, env = process.env) {
|
|
143
|
+
const repo = config.agent || {}
|
|
144
|
+
const saved = config.dir ? userAgentEntry(config.dir, env).entry || {} : {}
|
|
145
|
+
const fromEnv = envFlag(env[BRANCH_MODE_VAR])
|
|
146
|
+
let enabled = false
|
|
147
|
+
let enabledSource = null
|
|
148
|
+
if (fromEnv !== null) [enabled, enabledSource] = [fromEnv, 'env']
|
|
149
|
+
else if (typeof saved.branchMode === 'boolean') [enabled, enabledSource] = [saved.branchMode, 'settings']
|
|
150
|
+
else if (typeof repo.branchMode === 'boolean') [enabled, enabledSource] = [repo.branchMode, 'config']
|
|
151
|
+
let prefix = DEFAULT_BRANCH_PREFIX
|
|
152
|
+
let prefixSource = null
|
|
153
|
+
const envPrefix = cleanBranchPrefix(env[BRANCH_PREFIX_VAR])
|
|
154
|
+
if (envPrefix) [prefix, prefixSource] = [envPrefix, 'env']
|
|
155
|
+
else if (cleanBranchPrefix(saved.branchPrefix)) [prefix, prefixSource] = [saved.branchPrefix, 'settings']
|
|
156
|
+
else if (cleanBranchPrefix(repo.branchPrefix)) [prefix, prefixSource] = [repo.branchPrefix, 'config']
|
|
157
|
+
return { enabled, prefix, sources: { enabled: enabledSource, prefix: prefixSource } }
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// The first line of `text` as a short [a-z0-9-] name, "fix" when nothing is left.
|
|
161
|
+
export function slugOf(text, max = 32) {
|
|
162
|
+
const slug = String(text || '')
|
|
163
|
+
.split('\n')[0]
|
|
164
|
+
.normalize('NFKD')
|
|
165
|
+
.replace(/\p{M}+/gu, '')
|
|
166
|
+
.toLowerCase()
|
|
167
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
168
|
+
.replace(/^-+/, '')
|
|
169
|
+
.slice(0, max)
|
|
170
|
+
.replace(/-+$/, '')
|
|
171
|
+
return slug || 'fix'
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export function validBranchName(name) {
|
|
175
|
+
if (typeof name !== 'string' || name.length > BRANCH_MAX || !BRANCH_RE.test(name)) return false
|
|
176
|
+
const parts = name.toLowerCase().split('/')
|
|
177
|
+
return !PROTECTED.has(name.toLowerCase()) && !PROTECTED.has(parts.at(-1))
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// <prefix>comment-<n>-<slug> for a comment, <prefix>chat-<thread>-<n> for a chat.
|
|
181
|
+
export function agentBranchName({ prefix = DEFAULT_BRANCH_PREFIX, kind, commentId = null, threadId = 'board', n = 1, text = '' }) {
|
|
182
|
+
const clean = cleanBranchPrefix(prefix)
|
|
183
|
+
if (!clean) throw new BranchError('bad_prefix', 'The branch prefix is not valid.', 400)
|
|
184
|
+
const count = Number.isSafeInteger(Number(n)) && Number(n) > 0 ? Number(n) : 1
|
|
185
|
+
let tail
|
|
186
|
+
if (kind === 'comment') {
|
|
187
|
+
if (!Number.isSafeInteger(commentId) || commentId <= 0)
|
|
188
|
+
throw new BranchError('bad_branch', 'A comment branch needs the comment number.', 400)
|
|
189
|
+
tail = `comment-${commentId}-${slugOf(text)}`
|
|
190
|
+
} else {
|
|
191
|
+
const thread = String(threadId || 'board')
|
|
192
|
+
.replace(/^chat-/, '')
|
|
193
|
+
.replace(/[^a-z0-9]/g, '')
|
|
194
|
+
.slice(0, 16)
|
|
195
|
+
tail = `chat-${thread || 'board'}-${count}`
|
|
196
|
+
}
|
|
197
|
+
const name = `${clean}${tail}`
|
|
198
|
+
if (!validBranchName(name)) throw new BranchError('bad_branch', `refusing branch name "${name.slice(0, 80)}"`, 400)
|
|
199
|
+
return name
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// The folder the worktrees go in: <project>/.shapewall/agent-worktrees, both
|
|
203
|
+
// real folders (never a symlink). `create`: make them (0700) when missing.
|
|
204
|
+
export function agentWorktreeRoot(config, { create = false } = {}) {
|
|
205
|
+
const project = fs.realpathSync(config.dir)
|
|
206
|
+
const store = path.join(project, '.shapewall')
|
|
207
|
+
const root = path.join(store, 'agent-worktrees')
|
|
208
|
+
for (const dir of [store, root]) {
|
|
209
|
+
let stat
|
|
210
|
+
try {
|
|
211
|
+
stat = fs.lstatSync(dir)
|
|
212
|
+
} catch (error) {
|
|
213
|
+
if (error.code !== 'ENOENT') throw error
|
|
214
|
+
if (!create) return root
|
|
215
|
+
fs.mkdirSync(dir, { mode: 0o700 })
|
|
216
|
+
stat = fs.lstatSync(dir)
|
|
217
|
+
}
|
|
218
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) {
|
|
219
|
+
throw new BranchError(
|
|
220
|
+
'bad_worktree_root',
|
|
221
|
+
`${path.relative(project, dir)} is not a plain folder, so the agent cannot work on a branch here. Remove it, or turn off "Agent works on a branch".`,
|
|
222
|
+
)
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
if (fs.realpathSync(root) !== root) throw new BranchError('bad_worktree_root', 'The agent worktree folder resolves outside the project.')
|
|
226
|
+
return root
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const metaFile = (root, id) => path.join(root, `${id}.json`)
|
|
230
|
+
|
|
231
|
+
// A stored record, checked field by field (the folder is the person's, but
|
|
232
|
+
// anything that ends up in a git command is checked again here).
|
|
233
|
+
function cleanMeta(raw, id) {
|
|
234
|
+
if (!isObject(raw) || raw.id !== id || !RUN_DIR_RE.test(id)) return null
|
|
235
|
+
if (!validBranchName(raw.branch) || !SHA_RE.test(String(raw.base || ''))) return null
|
|
236
|
+
if (raw.commit !== null && raw.commit !== undefined && !SHA_RE.test(String(raw.commit))) return null
|
|
237
|
+
if (!BOARD_ID_RE.test(String(raw.boardId || '')) || !THREAD_RE.test(String(raw.threadId || ''))) return null
|
|
238
|
+
// The project's folder inside the checkout: plain relative segments only.
|
|
239
|
+
const sub =
|
|
240
|
+
typeof raw.sub === 'string' &&
|
|
241
|
+
raw.sub &&
|
|
242
|
+
raw.sub.length <= 500 &&
|
|
243
|
+
raw.sub.split('/').every((part) => part && part !== '.' && part !== '..' && !part.includes('\\') && !part.includes('\0'))
|
|
244
|
+
? raw.sub
|
|
245
|
+
: null
|
|
246
|
+
return {
|
|
247
|
+
version: 1,
|
|
248
|
+
id,
|
|
249
|
+
branch: raw.branch,
|
|
250
|
+
base: raw.base,
|
|
251
|
+
commit: raw.commit || null,
|
|
252
|
+
sub,
|
|
253
|
+
boardId: raw.boardId,
|
|
254
|
+
threadId: raw.threadId,
|
|
255
|
+
commentId: Number.isSafeInteger(raw.commentId) && raw.commentId > 0 ? raw.commentId : null,
|
|
256
|
+
messageId: MESSAGE_ID_RE.test(String(raw.messageId || '')) ? raw.messageId : null,
|
|
257
|
+
kind: raw.kind === 'comment' ? 'comment' : 'chat',
|
|
258
|
+
files: Number.isSafeInteger(raw.files) && raw.files >= 0 ? raw.files : 0,
|
|
259
|
+
createdAt: typeof raw.createdAt === 'string' ? raw.createdAt.slice(0, 40) : null,
|
|
260
|
+
committedAt: typeof raw.committedAt === 'string' ? raw.committedAt.slice(0, 40) : null,
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
export function writeMeta(root, meta) {
|
|
265
|
+
const file = metaFile(root, meta.id)
|
|
266
|
+
const temp = `${file}.${process.pid}.tmp`
|
|
267
|
+
fs.writeFileSync(temp, `${JSON.stringify(meta, null, 2)}\n`, { mode: 0o600 })
|
|
268
|
+
fs.renameSync(temp, file)
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
export function readMeta(config, id) {
|
|
272
|
+
if (!RUN_DIR_RE.test(String(id || ''))) return null
|
|
273
|
+
let root
|
|
274
|
+
try {
|
|
275
|
+
root = agentWorktreeRoot(config)
|
|
276
|
+
} catch {
|
|
277
|
+
return null
|
|
278
|
+
}
|
|
279
|
+
try {
|
|
280
|
+
return cleanMeta(JSON.parse(fs.readFileSync(metaFile(root, id), 'utf8')), id)
|
|
281
|
+
} catch {
|
|
282
|
+
return null
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function readAllMeta(root) {
|
|
287
|
+
let names
|
|
288
|
+
try {
|
|
289
|
+
names = fs.readdirSync(root)
|
|
290
|
+
} catch {
|
|
291
|
+
return []
|
|
292
|
+
}
|
|
293
|
+
const out = []
|
|
294
|
+
for (const name of names) {
|
|
295
|
+
if (!name.endsWith('.json')) continue
|
|
296
|
+
const id = name.slice(0, -5)
|
|
297
|
+
if (!RUN_DIR_RE.test(id)) continue
|
|
298
|
+
try {
|
|
299
|
+
const meta = cleanMeta(JSON.parse(fs.readFileSync(path.join(root, name), 'utf8')), id)
|
|
300
|
+
if (meta) out.push(meta)
|
|
301
|
+
} catch {
|
|
302
|
+
/* a record being written or broken: skipped */
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
return out.sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)))
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// The project's repository: { top, gitDir, head, branch } or a BranchError
|
|
309
|
+
// saying why the agent cannot work on a branch here.
|
|
310
|
+
export async function checkRepo(config) {
|
|
311
|
+
const run = (args) => git(args, { cwd: config.dir, timeoutMs: 20000 })
|
|
312
|
+
let top
|
|
313
|
+
try {
|
|
314
|
+
top = (await run(['rev-parse', '--show-toplevel'])).trim()
|
|
315
|
+
} catch {
|
|
316
|
+
top = ''
|
|
317
|
+
}
|
|
318
|
+
if (!top)
|
|
319
|
+
throw new BranchError(
|
|
320
|
+
'not_a_repo',
|
|
321
|
+
'This project is not a Git repository, so the agent cannot work on a branch. Run git init and commit, or turn off "Agent works on a branch".',
|
|
322
|
+
)
|
|
323
|
+
const head = (await run(['rev-parse', '--verify', '-q', 'HEAD^{commit}']).catch(() => '')).trim()
|
|
324
|
+
if (!SHA_RE.test(head))
|
|
325
|
+
throw new BranchError(
|
|
326
|
+
'unborn_head',
|
|
327
|
+
'This repository has no commit yet, so there is nothing to branch from. Make a first commit, then try again.',
|
|
328
|
+
)
|
|
329
|
+
const gitDir = (await run(['rev-parse', '--absolute-git-dir'])).trim()
|
|
330
|
+
for (const [marker, what] of IN_PROGRESS) {
|
|
331
|
+
if (fs.existsSync(path.join(gitDir, marker)))
|
|
332
|
+
throw new BranchError('git_busy', `A ${what} is in progress in this repository. Finish or abort it first, then try again.`)
|
|
333
|
+
}
|
|
334
|
+
const branch = (await run(['symbolic-ref', '-q', '--short', 'HEAD']).catch(() => '')).trim() || null
|
|
335
|
+
return { top, gitDir, head, branch }
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
// The Git filters (['lfs']) the attributes of HEAD and $GIT_DIR/info/attributes
|
|
339
|
+
// name. Branch mode runs none of them: the agent's checkout holds those files
|
|
340
|
+
// as stored (an LFS pointer file), and Apply refuses a change to one. [] when
|
|
341
|
+
// it cannot tell (not a repository yet).
|
|
342
|
+
export async function repoFilters(config) {
|
|
343
|
+
try {
|
|
344
|
+
const repo = await checkRepo(config)
|
|
345
|
+
return await filterNames({ gitDir: repo.gitDir, cwd: repo.top, commit: repo.head })
|
|
346
|
+
} catch {
|
|
347
|
+
return []
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
async function refTip(config, branch) {
|
|
352
|
+
if (!validBranchName(branch)) return null
|
|
353
|
+
const out = await git(['rev-parse', '--verify', '-q', `refs/heads/${branch}`], { cwd: config.dir, timeoutMs: 20000 }).catch(() => '')
|
|
354
|
+
return SHA_RE.test(out.trim()) ? out.trim() : null
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
// The author of the agent's commit: the repository's user.name and
|
|
358
|
+
// user.email (its own config and the person's global one), else Shapewall's.
|
|
359
|
+
export async function repoAuthor(cwd) {
|
|
360
|
+
const read = async (key) =>
|
|
361
|
+
(await git(['config', '--get', key], { cwd, timeoutMs: 10000 }).catch(() => ''))
|
|
362
|
+
.trim()
|
|
363
|
+
// eslint-disable-next-line no-control-regex
|
|
364
|
+
.replace(/[\u0000-\u001f<>]/g, '')
|
|
365
|
+
.slice(0, 200)
|
|
366
|
+
const name = await read('user.name')
|
|
367
|
+
const email = await read('user.email')
|
|
368
|
+
return name && email ? { name, email, configured: true } : { ...FALLBACK_AUTHOR, configured: false }
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
// A new worktree for one agent turn, on a branch that does not exist yet
|
|
372
|
+
// (made when the turn's work is committed). -> { tree, meta, root }
|
|
373
|
+
export async function createAgentBranch(
|
|
374
|
+
config,
|
|
375
|
+
{ prefix = DEFAULT_BRANCH_PREFIX, kind, boardId, threadId, commentId = null, text = '', n = 1, now = new Date() },
|
|
376
|
+
) {
|
|
377
|
+
const repo = await checkRepo(config)
|
|
378
|
+
const root = agentWorktreeRoot(config, { create: true })
|
|
379
|
+
const first = agentBranchName({ prefix, kind, commentId, threadId, n, text })
|
|
380
|
+
const taken = new Set(readAllMeta(root).map((item) => item.branch))
|
|
381
|
+
let branch = first
|
|
382
|
+
for (let count = 2; taken.has(branch) || (await refTip(config, branch)); count += 1) {
|
|
383
|
+
if (count > 50) throw new BranchError('branch_taken', `Too many branches named ${first} already exist.`)
|
|
384
|
+
branch = `${first}-${count}`
|
|
385
|
+
}
|
|
386
|
+
const runId = newRunId(now)
|
|
387
|
+
const tree = await createWorktree({ projectDir: config.dir, root, runId, branch, base: repo.head })
|
|
388
|
+
const meta = {
|
|
389
|
+
version: 1,
|
|
390
|
+
id: runId,
|
|
391
|
+
branch,
|
|
392
|
+
base: tree.base,
|
|
393
|
+
commit: null,
|
|
394
|
+
sub: path.relative(tree.dir, tree.projectDir).split(path.sep).filter(Boolean).join('/') || null,
|
|
395
|
+
boardId,
|
|
396
|
+
threadId,
|
|
397
|
+
commentId,
|
|
398
|
+
messageId: null,
|
|
399
|
+
kind: kind === 'comment' ? 'comment' : 'chat',
|
|
400
|
+
files: 0,
|
|
401
|
+
createdAt: now.toISOString(),
|
|
402
|
+
committedAt: null,
|
|
403
|
+
}
|
|
404
|
+
writeMeta(root, meta)
|
|
405
|
+
return { tree, meta, root }
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
// Commits what the agent changed in the worktree on its new branch, as the
|
|
409
|
+
// repository's author. Symlinks that leave the checkout are refused (the
|
|
410
|
+
// branch is taken back). -> commitWorktree's result
|
|
411
|
+
export async function commitAgentBranch(config, { tree, meta, root, message }) {
|
|
412
|
+
const author = await repoAuthor(tree.repo)
|
|
413
|
+
// The project's own store, should the checkout hold one (it is ignored as a rule).
|
|
414
|
+
const sub = path.relative(tree.dir, tree.projectDir).split(path.sep).filter(Boolean)
|
|
415
|
+
const exclude = [[...sub, '.shapewall'].join('/')]
|
|
416
|
+
const result = await commitWorktree({ tree, message, exclude, author: { name: author.name, email: author.email } })
|
|
417
|
+
if (result.committed && result.links?.length) {
|
|
418
|
+
await git(['--git-dir', tree.gitDir, 'update-ref', '-d', `refs/heads/${meta.branch}`, result.commit], { cwd: tree.repo }).catch(
|
|
419
|
+
() => {},
|
|
420
|
+
)
|
|
421
|
+
throw new BranchError(
|
|
422
|
+
'symlink_out',
|
|
423
|
+
`The agent made symlinks that point outside the project (${result.links.slice(0, 5).join(', ')}), so nothing was committed.`,
|
|
424
|
+
)
|
|
425
|
+
}
|
|
426
|
+
if (result.committed) {
|
|
427
|
+
Object.assign(meta, { commit: result.commit, files: result.files.length, committedAt: new Date().toISOString() })
|
|
428
|
+
writeMeta(root, meta)
|
|
429
|
+
}
|
|
430
|
+
return result
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
// The worktree, its record and (when it still points at the agent's commit)
|
|
434
|
+
// its branch. -> { branchDeleted, branchMoved }
|
|
435
|
+
export async function discardAgentBranch(config, meta) {
|
|
436
|
+
const root = agentWorktreeRoot(config)
|
|
437
|
+
let branchDeleted = false
|
|
438
|
+
let branchMoved = false
|
|
439
|
+
if (meta.commit) {
|
|
440
|
+
const tip = await refTip(config, meta.branch)
|
|
441
|
+
if (tip === meta.commit) {
|
|
442
|
+
await git(['update-ref', '-m', 'shapewall: discard agent branch', '-d', `refs/heads/${meta.branch}`, meta.commit], {
|
|
443
|
+
cwd: config.dir,
|
|
444
|
+
timeoutMs: 20000,
|
|
445
|
+
})
|
|
446
|
+
branchDeleted = true
|
|
447
|
+
} else if (tip) branchMoved = true
|
|
448
|
+
}
|
|
449
|
+
await removeWorktree({ tree: { dir: path.join(root, meta.id), root, runId: meta.id } })
|
|
450
|
+
fs.rmSync(metaFile(root, meta.id), { force: true })
|
|
451
|
+
return { branchDeleted, branchMoved }
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// Git on the person's checkout, with its git dir and work tree named, and
|
|
455
|
+
// every configured filter, merge and diff driver overridden with an empty
|
|
456
|
+
// command (inertDriverFlags): Apply, Undo and the checks before them run no
|
|
457
|
+
// program from the repository's or the person's config.
|
|
458
|
+
async function onCheckout(repo) {
|
|
459
|
+
const inert = await inertDriverFlags({ gitDir: repo.gitDir, cwd: repo.top })
|
|
460
|
+
return (args, options = {}) =>
|
|
461
|
+
git(['--git-dir', repo.gitDir, '--work-tree', repo.top, ...CHECKOUT_FLAGS, ...inert, ...args], {
|
|
462
|
+
cwd: repo.top,
|
|
463
|
+
timeoutMs: 120000,
|
|
464
|
+
...options,
|
|
465
|
+
})
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
// What git sees in the person's checkout: HEAD plus each changed or
|
|
469
|
+
// untracked (not ignored) file with its size and time. Compared before and
|
|
470
|
+
// after a branch-mode turn to warn when something wrote to the checkout.
|
|
471
|
+
// null when it cannot tell (then no warning).
|
|
472
|
+
export async function checkoutSignature(config) {
|
|
473
|
+
try {
|
|
474
|
+
const repo = await checkRepo(config)
|
|
475
|
+
const status = await (
|
|
476
|
+
await onCheckout(repo)
|
|
477
|
+
)(['--no-optional-locks', 'status', '--porcelain=v1', '-z', '--untracked-files=all', '--ignore-submodules=all']).catch(() => null)
|
|
478
|
+
if (status === null) return null
|
|
479
|
+
const parts = status.split('\0')
|
|
480
|
+
const files = []
|
|
481
|
+
for (let i = 0; i < parts.length; i++) {
|
|
482
|
+
const entry = parts[i]
|
|
483
|
+
if (entry.length < 4) continue
|
|
484
|
+
files.push(entry.slice(3))
|
|
485
|
+
if (entry[0] === 'R' || entry[0] === 'C') i++
|
|
486
|
+
}
|
|
487
|
+
const stamps = files.sort().map((file) => {
|
|
488
|
+
try {
|
|
489
|
+
const stat = fs.lstatSync(path.join(repo.top, file), { bigint: true })
|
|
490
|
+
return `${file}:${stat.size}:${stat.mtimeNs}`
|
|
491
|
+
} catch {
|
|
492
|
+
return `${file}:gone`
|
|
493
|
+
}
|
|
494
|
+
})
|
|
495
|
+
return [repo.head || '', ...stamps].join('\n')
|
|
496
|
+
} catch {
|
|
497
|
+
return null
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
async function assertClean(run) {
|
|
502
|
+
const status = await run(['status', '--porcelain=v1', '-z', '--untracked-files=no', '--ignore-submodules=all'])
|
|
503
|
+
if (status.replace(/\0/g, '').trim())
|
|
504
|
+
throw new BranchError(
|
|
505
|
+
'checkout_dirty',
|
|
506
|
+
'Your checkout has uncommitted changes to tracked files. Commit or stash them, then apply. Nothing was changed.',
|
|
507
|
+
)
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
const listOf = (files) => `${files.slice(0, 5).join(', ')}${files.length > 5 ? ` and ${files.length - 5} more` : ''}`
|
|
511
|
+
|
|
512
|
+
// The paths that going from the tree `from` (HEAD) to the tree `to` writes,
|
|
513
|
+
// after checking that none of them would land on a file Git does not track:
|
|
514
|
+
// an untracked or ignored file (.env) at a path the change adds, or an
|
|
515
|
+
// untracked file or symlink where it needs a folder. Git itself overwrites
|
|
516
|
+
// ignored files without asking. -> { written, blocked }
|
|
517
|
+
export async function overwriteCheck(run, repo, from, to) {
|
|
518
|
+
const tracked = new Set((await run(['ls-tree', '-r', '-z', '--name-only', '--full-tree', from])).split('\0').filter(Boolean))
|
|
519
|
+
const parts = (await run(['diff-tree', '-r', '-z', '--no-renames', '--name-status', from, to])).split('\0')
|
|
520
|
+
const written = []
|
|
521
|
+
const blocked = new Set()
|
|
522
|
+
const exists = (rel) => {
|
|
523
|
+
try {
|
|
524
|
+
return fs.lstatSync(path.join(repo.top, rel))
|
|
525
|
+
} catch {
|
|
526
|
+
return null
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
for (let index = 0; index + 1 < parts.length; index += 2) {
|
|
530
|
+
const [status, rel] = [parts[index], parts[index + 1]]
|
|
531
|
+
if (!status || !rel || status === 'D') continue
|
|
532
|
+
written.push(rel)
|
|
533
|
+
if (!tracked.has(rel) && exists(rel)) blocked.add(rel)
|
|
534
|
+
const dirs = rel.split('/').slice(0, -1)
|
|
535
|
+
for (let depth = 1; depth <= dirs.length; depth += 1) {
|
|
536
|
+
const dir = dirs.slice(0, depth).join('/')
|
|
537
|
+
if (tracked.has(dir)) break
|
|
538
|
+
const stat = exists(dir)
|
|
539
|
+
if (!stat) break
|
|
540
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) {
|
|
541
|
+
blocked.add(dir)
|
|
542
|
+
break
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
return { written, blocked: [...blocked].sort() }
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
// The written paths a Git filter (such as Git LFS) handles, by the
|
|
550
|
+
// attributes of `source` and $GIT_DIR/info/attributes. Shapewall runs no
|
|
551
|
+
// filter, so it does not bring such files in. -> [{ path, filter }]
|
|
552
|
+
async function filteredPaths(run, source, files) {
|
|
553
|
+
if (!files.length) return []
|
|
554
|
+
const input = `${files.join('\0')}\0`
|
|
555
|
+
let out = await run(['check-attr', '-z', '--stdin', `--source=${source}`, 'filter'], { input, status: true })
|
|
556
|
+
if (out.code !== 0) out = await run(['check-attr', '-z', '--stdin', 'filter'], { input, status: true })
|
|
557
|
+
if (out.code !== 0) throw new BranchError('apply_failed', `Git could not read the attributes: ${out.stderr.trim().slice(0, 200)}`)
|
|
558
|
+
const parts = out.stdout.split('\0')
|
|
559
|
+
const found = []
|
|
560
|
+
for (let index = 0; index + 2 < parts.length; index += 3) {
|
|
561
|
+
const value = parts[index + 2]
|
|
562
|
+
if (value && value !== 'unspecified' && value !== 'unset') found.push({ path: parts[index], filter: value })
|
|
563
|
+
}
|
|
564
|
+
return found
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
async function assertWritable(run, repo, from, to, { code, what, branch }) {
|
|
568
|
+
const { written, blocked } = await overwriteCheck(run, repo, from, to)
|
|
569
|
+
if (blocked.length)
|
|
570
|
+
throw new BranchError(
|
|
571
|
+
code,
|
|
572
|
+
`${what} would overwrite files in your checkout that Git does not track: ${listOf(blocked)}. Nothing was changed. Move them out of the way, or ${branch ? `merge ${branch}` : 'do it'} yourself with Git.`,
|
|
573
|
+
)
|
|
574
|
+
const filtered = await filteredPaths(run, from, written)
|
|
575
|
+
if (filtered.length)
|
|
576
|
+
throw new BranchError(
|
|
577
|
+
code,
|
|
578
|
+
`${what} touches files that a Git filter handles (${listOf(filtered.map((item) => item.path))}, filter ${[...new Set(filtered.map((item) => item.filter))].join(', ')}). Shapewall runs no Git filters, such as Git LFS, so nothing was changed. ${branch ? `Merge ${branch}` : 'Do it'} yourself with Git.`,
|
|
579
|
+
)
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
// Who makes a merge or revert commit: the repository's identity, or
|
|
583
|
+
// Shapewall's when the repository has none (git would stop and ask).
|
|
584
|
+
async function identityEnv(repo) {
|
|
585
|
+
const author = await repoAuthor(repo.top)
|
|
586
|
+
if (author.configured) return {}
|
|
587
|
+
return {
|
|
588
|
+
GIT_AUTHOR_NAME: author.name,
|
|
589
|
+
GIT_AUTHOR_EMAIL: author.email,
|
|
590
|
+
GIT_COMMITTER_NAME: author.name,
|
|
591
|
+
GIT_COMMITTER_EMAIL: author.email,
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
// Brings the agent's branch into the current branch of the person's
|
|
596
|
+
// checkout. Nothing changes unless every check passes; a conflict changes
|
|
597
|
+
// nothing. -> { mode: 'fast-forward' | 'merge', before, after, branch }
|
|
598
|
+
export async function applyAgentBranch(config, meta, { message = null } = {}) {
|
|
599
|
+
if (!meta?.commit) throw new BranchError('nothing_to_apply', 'The agent made no commit on this branch.')
|
|
600
|
+
const repo = await checkRepo(config)
|
|
601
|
+
if (!repo.branch)
|
|
602
|
+
throw new BranchError(
|
|
603
|
+
'detached_head',
|
|
604
|
+
'Your checkout is not on a branch (detached HEAD). Check out a branch, then apply. Nothing was changed.',
|
|
605
|
+
)
|
|
606
|
+
const tip = await refTip(config, meta.branch)
|
|
607
|
+
if (tip !== meta.commit)
|
|
608
|
+
throw new BranchError(
|
|
609
|
+
'branch_moved',
|
|
610
|
+
`The branch ${meta.branch} ${tip ? 'has moved since the agent committed' : 'is gone'}, so Shapewall does not apply it. Merge it yourself with Git.`,
|
|
611
|
+
)
|
|
612
|
+
const run = await onCheckout(repo)
|
|
613
|
+
await assertClean(run)
|
|
614
|
+
const before = repo.head
|
|
615
|
+
const ancestor = await run(['merge-base', '--is-ancestor', before, meta.commit], { status: true })
|
|
616
|
+
let mode
|
|
617
|
+
if (before === meta.commit) throw new BranchError('already_applied', 'Your checkout already has this change.')
|
|
618
|
+
if (ancestor.code === 0) {
|
|
619
|
+
await assertWritable(run, repo, before, meta.commit, { code: 'apply_overwrite', what: 'Apply', branch: meta.branch })
|
|
620
|
+
await run(['merge', '--ff-only', '--no-autostash', '--no-stat', '--no-verify', meta.commit])
|
|
621
|
+
mode = 'fast-forward'
|
|
622
|
+
} else {
|
|
623
|
+
// Checked without touching the checkout: on a conflict, nothing changes.
|
|
624
|
+
const tried = await run(['merge-tree', '--write-tree', '--name-only', '--no-messages', before, meta.commit], { status: true })
|
|
625
|
+
if (tried.code === 1) {
|
|
626
|
+
const files = tried.stdout.split('\n').slice(1).filter(Boolean).slice(0, 8)
|
|
627
|
+
throw new BranchError(
|
|
628
|
+
'apply_conflict',
|
|
629
|
+
`The agent's branch conflicts with your checkout${files.length ? ` in ${files.join(', ')}` : ''}. Nothing was changed. Merge ${meta.branch} yourself with Git, or discard it.`,
|
|
630
|
+
)
|
|
631
|
+
}
|
|
632
|
+
if (tried.code !== 0) throw new BranchError('apply_failed', `Git could not check the merge: ${tried.stderr.trim().slice(0, 200)}`)
|
|
633
|
+
const merged = tried.stdout.split('\n')[0].trim()
|
|
634
|
+
if (!SHA_RE.test(merged)) throw new BranchError('apply_failed', 'Git could not check the merge.')
|
|
635
|
+
await assertWritable(run, repo, before, merged, { code: 'apply_overwrite', what: 'Apply', branch: meta.branch })
|
|
636
|
+
const env = { ...process.env, ...(await identityEnv(repo)) }
|
|
637
|
+
try {
|
|
638
|
+
await run(
|
|
639
|
+
[
|
|
640
|
+
'merge',
|
|
641
|
+
'--no-ff',
|
|
642
|
+
'--no-edit',
|
|
643
|
+
'--no-autostash',
|
|
644
|
+
'--no-stat',
|
|
645
|
+
'--no-verify',
|
|
646
|
+
'-m',
|
|
647
|
+
message || `Apply ${meta.branch}`,
|
|
648
|
+
meta.commit,
|
|
649
|
+
],
|
|
650
|
+
{ env },
|
|
651
|
+
)
|
|
652
|
+
} catch (error) {
|
|
653
|
+
await run(['merge', '--abort']).catch(() => {})
|
|
654
|
+
throw new BranchError('apply_failed', `The merge did not go through, so it was taken back: ${error.message.slice(0, 200)}`)
|
|
655
|
+
}
|
|
656
|
+
mode = 'merge'
|
|
657
|
+
}
|
|
658
|
+
const after = (await run(['rev-parse', '--verify', 'HEAD'])).trim()
|
|
659
|
+
await discardAgentBranch(config, meta).catch(() => {})
|
|
660
|
+
return { mode, before, after, branch: repo.branch }
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
// Undo after Apply: new commits that revert what Apply brought in, only
|
|
664
|
+
// while the checkout is clean and its branch still ends at what Apply made.
|
|
665
|
+
export async function revertAppliedBranch(config, applied) {
|
|
666
|
+
if (!applied || !SHA_RE.test(String(applied.before || '')) || !SHA_RE.test(String(applied.after || '')))
|
|
667
|
+
throw new BranchError('undo_unavailable', 'This change cannot be undone here.')
|
|
668
|
+
const repo = await checkRepo(config)
|
|
669
|
+
if (repo.branch !== applied.branch || repo.head !== applied.after)
|
|
670
|
+
throw new BranchError(
|
|
671
|
+
'undo_conflict',
|
|
672
|
+
`Your branch moved on since the agent's change was applied, so it was left as it is. Revert ${applied.after.slice(0, 7)} with Git.`,
|
|
673
|
+
)
|
|
674
|
+
const run = await onCheckout(repo)
|
|
675
|
+
await assertClean(run).catch(() => {
|
|
676
|
+
throw new BranchError('undo_conflict', 'Your checkout has uncommitted changes, so nothing was undone. Commit or stash them first.')
|
|
677
|
+
})
|
|
678
|
+
// Undo brings back the tree from before Apply: the same check for what it writes.
|
|
679
|
+
await assertWritable(run, repo, applied.after, applied.before, { code: 'undo_conflict', what: 'Undo', branch: null })
|
|
680
|
+
const env = { ...process.env, ...(await identityEnv(repo)) }
|
|
681
|
+
try {
|
|
682
|
+
if (applied.mode === 'merge') await run(['revert', '--no-edit', '-m', '1', applied.after], { env })
|
|
683
|
+
else await run(['revert', '--no-edit', `${applied.before}..${applied.after}`], { env })
|
|
684
|
+
} catch (error) {
|
|
685
|
+
await run(['revert', '--abort']).catch(() => {})
|
|
686
|
+
throw new BranchError('undo_conflict', `The revert did not go through, so nothing was undone: ${error.message.slice(0, 200)}`)
|
|
687
|
+
}
|
|
688
|
+
return { head: (await run(['rev-parse', '--verify', 'HEAD'])).trim() }
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
// The agent's branches waiting here: [{ ...meta, state, worktree }] with
|
|
692
|
+
// state ready (the branch is the agent's commit), moved, gone, or pending
|
|
693
|
+
// (a turn still working, nothing committed yet).
|
|
694
|
+
export async function listAgentBranches(config) {
|
|
695
|
+
let root
|
|
696
|
+
try {
|
|
697
|
+
root = agentWorktreeRoot(config)
|
|
698
|
+
} catch {
|
|
699
|
+
return []
|
|
700
|
+
}
|
|
701
|
+
const out = []
|
|
702
|
+
for (const meta of readAllMeta(root)) {
|
|
703
|
+
const tip = meta.commit ? await refTip(config, meta.branch) : null
|
|
704
|
+
const state = !meta.commit ? 'pending' : tip === meta.commit ? 'ready' : tip ? 'moved' : 'gone'
|
|
705
|
+
out.push({ ...meta, state, worktree: fs.existsSync(path.join(root, meta.id)) })
|
|
706
|
+
}
|
|
707
|
+
return out
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
// What dead turns left: worktrees whose server process is gone, with the
|
|
711
|
+
// starter's rules (sweepWorkRoot). A worktree whose commit is not in HEAD yet
|
|
712
|
+
// is never removed. Records whose worktree and branch are both gone go too.
|
|
713
|
+
export async function sweepAgentBranches(config, { isAlive = processAlive, now = Date.now() } = {}) {
|
|
714
|
+
let root
|
|
715
|
+
try {
|
|
716
|
+
root = agentWorktreeRoot(config)
|
|
717
|
+
} catch {
|
|
718
|
+
return []
|
|
719
|
+
}
|
|
720
|
+
if (!fs.existsSync(root)) return []
|
|
721
|
+
const metas = readAllMeta(root)
|
|
722
|
+
const keep = new Set()
|
|
723
|
+
const head = (await git(['rev-parse', '--verify', '-q', 'HEAD'], { cwd: config.dir, timeoutMs: 20000 }).catch(() => '')).trim()
|
|
724
|
+
for (const meta of metas) {
|
|
725
|
+
if (!meta.commit) continue
|
|
726
|
+
const tip = await refTip(config, meta.branch)
|
|
727
|
+
if (tip !== meta.commit) continue
|
|
728
|
+
const applied =
|
|
729
|
+
SHA_RE.test(head) &&
|
|
730
|
+
(
|
|
731
|
+
await git(['merge-base', '--is-ancestor', meta.commit, head], { cwd: config.dir, status: true, timeoutMs: 20000 }).catch(() => ({
|
|
732
|
+
code: 1,
|
|
733
|
+
}))
|
|
734
|
+
).code === 0
|
|
735
|
+
if (!applied) keep.add(meta.id)
|
|
736
|
+
}
|
|
737
|
+
const removed = sweepWorkRoot(root, { isAlive, now, keep: (id) => keep.has(id) })
|
|
738
|
+
for (const id of removed) fs.rmSync(metaFile(root, id), { force: true })
|
|
739
|
+
// A record without its folder and without an unapplied commit is nothing to keep.
|
|
740
|
+
for (const meta of metas) {
|
|
741
|
+
if (keep.has(meta.id) || removed.includes(meta.id) || fs.existsSync(path.join(root, meta.id))) continue
|
|
742
|
+
fs.rmSync(metaFile(root, meta.id), { force: true })
|
|
743
|
+
removed.push(meta.id)
|
|
744
|
+
}
|
|
745
|
+
return removed
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
// The environment an agent working in a worktree under `worktreesRoot` gets
|
|
749
|
+
// on top of its own: git run there finds no repository above the worktree
|
|
750
|
+
// (in particular not the project's own, which holds .shapewall).
|
|
751
|
+
export function worktreeAgentEnv(worktreesRoot) {
|
|
752
|
+
return { GIT_CEILING_DIRECTORIES: worktreesRoot }
|
|
753
|
+
}
|