@cirtium/acent-connect 1.3.0 → 1.3.3

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.
@@ -2,6 +2,7 @@ import { createHash, randomUUID } from "node:crypto"
2
2
  import { mkdir, readFile, realpath, rename, rm, writeFile } from "node:fs/promises"
3
3
  import { homedir } from "node:os"
4
4
  import { join } from "node:path"
5
+ import { projectCodeGrant, projectCodeReceipt } from "./bridge-project-permissions.mjs"
5
6
  import { bridgeTargets } from "./bridge-runners.mjs"
6
7
  import { supportsForm } from "./clarification.mjs"
7
8
 
@@ -9,10 +10,11 @@ const scopeLimit = 128
9
10
  const itemLimit = 300
10
11
  const purposeLimit = 500
11
12
  const choices = ["Allow once", "Continue locally"]
13
+ const inFlightApprovals = new Map()
12
14
 
13
15
  export const bridgeApprovalTool = {
14
16
  name: "acent_bridge_request_approval",
15
- description: "Ask for scoped permission before a Bridge handoff that needs user approval. Pass only the external agent names, file paths or names of data categories, and a brief purpose. Never include file contents, diffs, secrets, or raw logs. This tool only asks the user and does not launch a delegate or override host policy.",
17
+ description: "Resolve sharing permission for destinations receiving the same scope. Use exact project-relative file paths for project code permission, or data category labels for explicit approval. Keep the same purpose label on retries. Never include file contents, diffs, secrets, or raw logs. This tool does not launch a delegate or override host policy.",
16
18
  inputSchema: {
17
19
  type: "object",
18
20
  properties: {
@@ -47,17 +49,50 @@ export async function requestBridgeApproval(input, capabilities, protocol, reque
47
49
  throw new Error("Provide the Bridge destinations, data scope, and purpose using brief labels only.")
48
50
  }
49
51
 
50
- // Match only this project, exact destinations, and exact scope and purpose labels.
51
- const choicesForProject = project ? ["Allow once", "Always allow this scope", "Continue locally"] : choices
52
- const store = project ? await approvalStore(project, { targets, scope, purpose }) : undefined
52
+ const grant = await projectCodeGrant(project?.folder, targets, scope, project?.home)
53
+ if (grant) {
54
+ const requestId = projectCodeReceipt(grant, targets, scope)
55
+ return {
56
+ status: "approved_always", permissionScope: "project_code", targets, scope, purpose, requestId,
57
+ requestIdsByTarget: Object.fromEntries(targets.map(target => [
58
+ target, targets.length === 1 ? requestId : projectCodeReceipt(grant, [target], scope),
59
+ ])),
60
+ nextAction: "Use exactly these files across paths and readPaths. Use requestIdsByTarget for separate tasks, or requestId as the refinement ID for this group. Keep context within the approved project code scope and honor host policy.",
61
+ }
62
+ }
63
+
64
+ const store = project ? await approvalStore(project, input) : undefined
65
+ if (!store) return askForApproval(input, capabilities, protocol, request)
66
+ const pending = inFlightApprovals.get(store.key)
67
+ if (pending) return pending
68
+ const approval = askForApproval(input, capabilities, protocol, request, store)
69
+ inFlightApprovals.set(store.key, approval)
70
+ try {
71
+ return await approval
72
+ } finally {
73
+ inFlightApprovals.delete(store.key)
74
+ }
75
+ }
76
+
77
+ function taskRequestIds(requestId, targets) {
78
+ return Object.fromEntries(targets.map((target) => {
79
+ if (targets.length === 1) return [target, requestId]
80
+ const token = createHash("sha256").update(JSON.stringify([requestId, target])).digest("hex")
81
+ return [target, `${token.slice(0, 8)}-${token.slice(8, 12)}-8${token.slice(13, 16)}-8${token.slice(17, 20)}-${token.slice(20, 32)}`]
82
+ }))
83
+ }
84
+
85
+ async function askForApproval({ targets, scope, purpose }, capabilities, protocol, request, store) {
86
+ const choicesForProject = store ? ["Allow once", "Always allow this scope", "Continue locally"] : choices
53
87
  const saved = await store?.readGrant()
54
88
  const pending = await store?.readPending()
55
89
  const requestId = pending?.requestId ?? randomUUID()
56
- const proceed = status => ({
57
- status, targets, scope, purpose, requestId,
58
- nextAction: "Submit only the approved handoff through the normal Bridge tool. Use requestId when starting the task so retries cannot start duplicates. Honor any host approval requirements.",
90
+ const proceed = (status, id = requestId) => ({
91
+ status, targets, scope, purpose, requestId: id,
92
+ requestIdsByTarget: taskRequestIds(id, targets),
93
+ nextAction: "Submit only the approved handoff through the normal Bridge tool. Use requestIdsByTarget for separate tasks covered by this approval. Keep the same purpose and scope for related retries. Honor any host approval requirements.",
59
94
  })
60
- if (saved?.status === "approved_always") return { ...proceed("approved_always"), requestId: randomUUID() }
95
+ if (saved?.status === "approved_always") return proceed("approved_always", randomUUID())
61
96
 
62
97
  const question = [
63
98
  "Allow Acent Bridge to share the following with the selected coding agents?",
@@ -117,7 +152,10 @@ export async function requestBridgeApproval(input, capabilities, protocol, reque
117
152
 
118
153
  async function approvalStore({ folder, directory = join(homedir(), ".local", "share", "acent", "bridge-approvals") }, { targets, scope, purpose }) {
119
154
  const project = await realpath(folder)
120
- const key = createHash("sha256").update(JSON.stringify([project, [...targets].sort(), [...scope].sort(), purpose])).digest("hex")
155
+ const keyFor = (destinations) => createHash("sha256")
156
+ .update(JSON.stringify([project, [...destinations].sort(), [...scope].sort(), purpose]))
157
+ .digest("hex")
158
+ const key = keyFor(targets)
121
159
  const grant = join(directory, key + ".grant.json")
122
160
  const pending = join(directory, key + ".pending.json")
123
161
  const read = path => readFile(path, "utf8").then(JSON.parse).catch(error => {
@@ -125,7 +163,28 @@ async function approvalStore({ folder, directory = join(homedir(), ".local", "sh
125
163
  throw error
126
164
  })
127
165
  return {
128
- readGrant: () => read(grant),
166
+ key: grant,
167
+ async readGrant() {
168
+ const exact = await read(grant)
169
+ if (exact?.status === "approved_always") return exact
170
+
171
+ // Distributing the same approved material across tasks does not add destinations.
172
+ // Consult only grants for the same project, file labels and stated purpose.
173
+ const requested = new Set(targets)
174
+ const destinationSets = []
175
+ for (let mask = 1; mask < 2 ** bridgeTargets.length; mask++) {
176
+ const destinations = bridgeTargets.filter((_, index) => (mask & (1 << index)) !== 0)
177
+ if (destinations.some((destination) => requested.has(destination)))
178
+ destinationSets.push(destinations)
179
+ }
180
+ const approved = await Promise.all(destinationSets.map(async (destinations) => {
181
+ const path = join(directory, keyFor(destinations) + ".grant.json")
182
+ if (path === grant) return []
183
+ return (await read(path))?.status === "approved_always" ? destinations : []
184
+ }))
185
+ const covered = new Set(approved.flat())
186
+ return targets.every((target) => covered.has(target)) ? { status: "approved_always" } : undefined
187
+ },
129
188
  readPending: () => read(pending),
130
189
  async clearPending(requestId) {
131
190
  const current = await read(pending)
@@ -0,0 +1,119 @@
1
+ import { createHash } from "node:crypto"
2
+ import { mkdir, readFile, rm, stat, unlink } from "node:fs/promises"
3
+ import { join } from "node:path"
4
+ import { atomicJson, boundConfig, configDirectory, request } from "./acent-connect.mjs"
5
+ import { isCodexGeneratedPrompt } from "./codex-capture.mjs"
6
+
7
+ const guidance = "Acent Bridge: for feature work, bug fixes, or behavioral verification, call acent_bridge_settings before investigating or editing. If automatic delegation is enabled, check candidates early and start an independent task within the approved sharing scope. If no review can run, report the reason before finishing. Honor a user request to work directly."
8
+ const reminder = "Acent Bridge: this turn edited the project with automatic delegation enabled, and no candidate check or delegation was observed. Before finishing, check the Bridge settings and eligible candidates and arrange an independent check if applicable. For small styling or copy edits, a user opt-out, unavailable candidates, or pending sharing approval, finish directly and report the applicable reason."
9
+ const edits = /^(?:apply_patch|Edit|MultiEdit|Write|NotebookEdit|write_to_file|replace_file_content|multi_replace_file_content|str_replace|str_replace_editor)$/i
10
+ const bridgeTool = /^(?:(?:mcp__acent(?:_acent)?__|mcp_acent_acent_|MCP:)?acent_bridge_)(?:candidates|start|refine|request_approval)$/
11
+
12
+ export function isBridgeContinuation(payload) {
13
+ return ["UserPromptSubmit", "beforeSubmitPrompt"].includes(payload.hook_event_name) &&
14
+ payload.prompt === reminder
15
+ }
16
+
17
+ function observedTool(payload, tool, event) {
18
+ if (tool !== "Antigravity") {
19
+ if (event === "afterMCPExecution") {
20
+ return ["acent", "acent-acent", "acent_acent"].includes(payload.mcp_server_name)
21
+ ? payload.tool_name : undefined
22
+ }
23
+ return payload.tool_name
24
+ }
25
+ const { name, args } = payload.toolCall ?? {}
26
+ if (name === "call_mcp_tool" && args?.ServerName === "acent_acent") {
27
+ if (args.ToolName === "acent_workspace") return args.Arguments?.tool
28
+ return args.ToolName
29
+ }
30
+ if (name === "mcp_acent_acent_acent_workspace") return args?.tool
31
+ return name
32
+ }
33
+
34
+ function nativeContext(tool, event, payload) {
35
+ const model = payload.model ?? payload.model_name ?? payload.modelName
36
+ const modelKnown = typeof model === "string" && /^[\w][\w.:/-]{0,159}$/.test(model) &&
37
+ !/^(?:auto|default|unknown)$/i.test(model)
38
+ const context = modelKnown
39
+ ? guidance + " Use the host-reported model ID " + model + " as currentModel for independent review or diagnosis."
40
+ : guidance
41
+ if (tool === "Cursor") return { additional_context: context }
42
+ if (tool === "Antigravity") return { injectSteps: [{ ephemeralMessage: context }] }
43
+ return { hookSpecificOutput: { hookEventName: event, additionalContext: context } }
44
+ }
45
+
46
+ function nativeReminder(tool) {
47
+ if (tool === "Cursor") return { followup_message: reminder }
48
+ return { decision: tool === "Antigravity" ? "continue" : "block", reason: reminder }
49
+ }
50
+
51
+ async function automaticSetting(config, credentials) {
52
+ // The hook must not contend with capture for refresh-token rotation.
53
+ if (typeof credentials?.access_token !== "string" ||
54
+ !Number.isFinite(credentials.expiresAt) || credentials.expiresAt <= Date.now() + 30_000) return null
55
+ const settings = await request(config, "/api/external/bridge", {
56
+ headers: { Authorization: "Bearer " + credentials.access_token },
57
+ signal: AbortSignal.timeout(750),
58
+ }).catch(() => null)
59
+ return typeof settings?.automatic === "boolean" ? settings.automatic : null
60
+ }
61
+
62
+ export async function bridgeLifecycle({ tool, folder, session, payload, args, event }) {
63
+ if (process.env.ACENT_BRIDGE_WORKER === "1" || !folder || !session) return
64
+ const cursor = tool === "Cursor"
65
+ const antigravity = tool === "Antigravity"
66
+ const prompt = event === "UserPromptSubmit" || event === "beforeSubmitPrompt" ||
67
+ (event === "PreInvocation" && payload.invocationNum === 0)
68
+ const sessionStart = cursor && event === "sessionStart"
69
+ const stop = event === "Stop" || event === "stop"
70
+ const observed = event === "PostToolUse" || event === "postToolUse" || event === "afterMCPExecution"
71
+ const name = observed ? observedTool(payload, tool, event) ?? "" : ""
72
+ const attempted = bridgeTool.test(name)
73
+ const edited = event === "afterFileEdit" || edits.test(name)
74
+ if (!prompt && !sessionStart && !stop && !attempted && !edited) return
75
+
76
+ const config = await boundConfig(["flush", ...args, "--folder", folder])
77
+ if (config.general) return
78
+ const directory = configDirectory(config)
79
+ const credentialsPath = join(directory, "credentials.json")
80
+ if (!(await stat(credentialsPath).catch(() => null))?.isFile()) return
81
+ const stateDir = join(directory, "bridge-turns")
82
+ const key = createHash("sha256").update(JSON.stringify([
83
+ session, tool === "Codex" ? payload.turn_id ?? null : null,
84
+ ])).digest("hex")
85
+ const file = join(stateDir, key + ".json")
86
+ const editsFile = file + ".edited"
87
+ const attemptsFile = file + ".attempted"
88
+ const removeState = () => Promise.all([file, editsFile, attemptsFile].map(path => rm(path, { force: true })))
89
+ if (sessionStart) return nativeContext(tool, event, payload)
90
+
91
+ if (prompt) {
92
+ if (isBridgeContinuation(payload) || (tool === "Codex" && isCodexGeneratedPrompt(payload.prompt))) return
93
+ const credentials = await readFile(credentialsPath, "utf8").then(JSON.parse)
94
+ const automatic = await automaticSetting(config, credentials)
95
+ await mkdir(stateDir, { mode: 0o700, recursive: true })
96
+ await removeState()
97
+ if (automatic === true) await atomicJson(file, { at: Date.now() })
98
+ if (!cursor && automatic !== false) return nativeContext(tool, event, payload)
99
+ return
100
+ }
101
+
102
+ const state = await readFile(file, "utf8").then(JSON.parse).catch(() => null)
103
+ if (!state || Date.now() - state.at > 24 * 60 * 60 * 1000) {
104
+ if (stop && state) await removeState()
105
+ return
106
+ }
107
+ if (attempted || edited) {
108
+ await atomicJson(attempted ? attemptsFile : editsFile, true)
109
+ return
110
+ }
111
+ if (antigravity && !payload.fullyIdle) return
112
+ const [hasEdits, hasAttempt] = await Promise.all([editsFile, attemptsFile].map(path => stat(path).catch(() => null)))
113
+ // Only the first completion hook can claim the check for this turn.
114
+ if (!(await unlink(file).then(() => true).catch(() => false))) return
115
+ await Promise.all([editsFile, attemptsFile].map(path => rm(path, { force: true })))
116
+ if (payload.stop_hook_active || (cursor && (payload.status !== "completed" || payload.loop_count > 0)) ||
117
+ (antigravity && payload.terminationReason !== "model_stop")) return
118
+ if (hasEdits && !hasAttempt) return nativeReminder(tool)
119
+ }
@@ -0,0 +1,80 @@
1
+ import { createHash, createHmac, randomBytes } from "node:crypto"
2
+ import { lstat, readFile, realpath } from "node:fs/promises"
3
+ import { homedir } from "node:os"
4
+ import { basename, extname, join } from "node:path"
5
+ import { bridgeTargets } from "./bridge-runners.mjs"
6
+ import { delegateWorkspacePath, git } from "./bridge-workspace.mjs"
7
+
8
+ const sourceExtension = /^(?:[cm]?js|[cm]?ts|jsx|tsx|vue|svelte|py|rb|rs|go|java|kt|swift|c|cc|cpp|h|hpp|cs|php|exs?|lua|sh|fish|css|scss|html|sql|md|mdx)$/i
9
+ const privateSegment = /(?:^|[._-])(?:secrets?|credentials?|tokens?|logs?|dumps?|attachments?)(?:$|[._-])/i
10
+ const receiptPattern = /^ace7([a-f0-9]{4})-([a-f0-9]{4})-8([a-f0-9]{3})-([a-f0-9]{4})-([a-f0-9]{12})$/
11
+ export const isProjectCodeReceipt = id => typeof id === "string" && receiptPattern.test(id)
12
+
13
+ export async function bridgeProject(folder, home = homedir()) {
14
+ if (!folder) return
15
+ try {
16
+ const workspace = await realpath(folder)
17
+ const root = await realpath((await git(workspace, ["rev-parse", "--show-toplevel"])).trimEnd())
18
+ const key = createHash("sha256").update(root).digest("hex")
19
+ return { workspace, root, path: join(home, ".local", "share", "acent", "bridge-project-permissions", key + ".json") }
20
+ } catch {
21
+ // Bridge sharing consent is available only in Git projects.
22
+ }
23
+ }
24
+
25
+ export function newProjectCodeGrant() {
26
+ return { status: "approved", targets: [...bridgeTargets], key: randomBytes(32).toString("hex") }
27
+ }
28
+
29
+ function codeFile(path) {
30
+ return delegateWorkspacePath(path) &&
31
+ path.split("/").every(part => !part.startsWith(".") && !privateSegment.test(part)) &&
32
+ (sourceExtension.test(extname(path).slice(1)) ||
33
+ /^(?:Dockerfile|Makefile|package(?:-lock)?\.json|tsconfig(?:\.[\w-]+)?\.json)$/.test(basename(path)))
34
+ }
35
+
36
+ export async function projectCodeGrant(folder, targets, scope, home) {
37
+ if (!targets.length || !scope.length || !scope.every(codeFile)) return
38
+ const project = await bridgeProject(folder, home)
39
+ if (!project) return
40
+ try {
41
+ const grant = JSON.parse(await readFile(project.path, "utf8"))
42
+ if (grant.status !== "approved" || !/^[a-f0-9]{64}$/.test(grant.key) ||
43
+ !Array.isArray(grant.targets) || !targets.every(target => grant.targets.includes(target))) return
44
+ const files = new Set((await git(project.workspace, [
45
+ "--literal-pathspecs", "ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", ...scope,
46
+ ])).split("\0"))
47
+ const eligible = await Promise.all(scope.map(async path => {
48
+ if (!files.has(path)) return false
49
+ const full = join(project.workspace, path)
50
+ return (await lstat(full)).isFile() && await realpath(full) === full
51
+ }))
52
+ if (eligible.every(Boolean)) return { ...project, key: grant.key }
53
+ } catch {
54
+ // An unavailable grant or file falls back to explicit approval.
55
+ }
56
+ }
57
+
58
+ export function projectCodeReceipt(grant, targets, scope, nonce = randomBytes(6).toString("hex").slice(0, 11)) {
59
+ const signature = createHmac("sha256", grant.key)
60
+ .update(JSON.stringify([grant.workspace, [...new Set(targets)].sort(), [...new Set(scope)].sort(), nonce]))
61
+ .digest("hex")
62
+ return `ace7${nonce.slice(0, 4)}-${nonce.slice(4, 8)}-8${nonce.slice(8)}-${signature.slice(0, 4)}-${signature.slice(4, 16)}`
63
+ }
64
+
65
+ export async function checkProjectCodeReceipt(name, args, folder, home) {
66
+ const refining = name === "acent_bridge_refine" && args.action === "start"
67
+ if (!refining && name !== "acent_bridge_start") return
68
+ const id = refining ? args.id : args.requestId
69
+ const receipt = typeof id === "string" && receiptPattern.exec(id)
70
+ if (!receipt) return
71
+ const { paths = [], readPaths = [] } = args
72
+ if (!Array.isArray(paths) || !Array.isArray(readPaths) || (refining && !Array.isArray(args.reviewers)))
73
+ throw new Error("Provide the approved Bridge files and destinations.")
74
+ const scope = [...paths, ...readPaths]
75
+ const targets = refining ? [args.repair?.tool, ...args.reviewers.map(reviewer => reviewer?.tool)] : [args.tool]
76
+ const grant = await projectCodeGrant(folder, targets, scope, home)
77
+ const nonce = receipt.slice(1, 4).join("")
78
+ if (!grant || projectCodeReceipt(grant, targets, scope, nonce) !== id)
79
+ throw new Error("The Bridge handoff changed its approved files, project, or destinations. Request approval for the new scope.")
80
+ }
@@ -2,6 +2,7 @@ import { createHash, randomUUID } from "node:crypto"
2
2
  import { mkdir } from "node:fs/promises"
3
3
  import { join } from "node:path"
4
4
  import { setTimeout } from "node:timers"
5
+ import { isProjectCodeReceipt } from "./bridge-project-permissions.mjs"
5
6
  import { modelFamily } from "./bridge-runners.mjs"
6
7
  import { bridgeReviewResult } from "./bridge-review-result.mjs"
7
8
  import {
@@ -504,7 +505,9 @@ export function createBridgeRefinement({
504
505
  return false
505
506
  }
506
507
 
507
- const originalDiff = await bridgeReviewDiff(folder, cycle.input.paths)
508
+ const originalDiff = await bridgeReviewDiff(folder, cycle.input.paths, undefined, undefined, {
509
+ exactScopes: isProjectCodeReceipt(cycle.id),
510
+ })
508
511
  const source = await prepareStage(stageDir)
509
512
  if (
510
513
  stale(
@@ -708,7 +711,8 @@ export function createBridgeRefinement({
708
711
  work,
709
712
  cycle.input.paths,
710
713
  cycle.originalHead,
711
- cycle.stage.head
714
+ cycle.stage.head,
715
+ { exactScopes: isProjectCodeReceipt(cycle.id) }
712
716
  )
713
717
  cycle.repairsApplied++
714
718
  cycle.appliedModel = job.actualModel ?? job.model
@@ -189,14 +189,15 @@ export function appliedBridgeChanges(jobs) {
189
189
  return [...latest.values()]
190
190
  }
191
191
 
192
- export async function bridgeReviewDiff(folder, scopes, from, to) {
192
+ export async function bridgeReviewDiff(folder, scopes, from, to, { exactScopes = false } = {}) {
193
193
  const head =
194
194
  from ??
195
195
  (await git(folder, ["rev-parse", "--verify", "HEAD"])
196
196
  .then((value) => value.trim())
197
197
  .catch(() => null))
198
198
  const relevant = (path) =>
199
- delegateWorkspacePath(path) && (!scopes.length || withinPaths(path, scopes))
199
+ delegateWorkspacePath(path) &&
200
+ (exactScopes ? scopes.includes(path) : !scopes.length || withinPaths(path, scopes))
200
201
  const untracked = !from
201
202
  ? (head
202
203
  ? (
@@ -265,7 +266,7 @@ export async function projectSnapshot(
265
266
  folder,
266
267
  work,
267
268
  saveBaseline,
268
- { scopes, trackSource = false } = {}
269
+ { scopes, trackSource = false, exactScopes = false } = {}
269
270
  ) {
270
271
  const paths = await projectFiles(folder)
271
272
  const baseline = Object.create(null)
@@ -274,7 +275,8 @@ export async function projectSnapshot(
274
275
  let fileCount = 0
275
276
  await mkdir(work, { recursive: true, mode: 0o700 })
276
277
  for (const path of paths) {
277
- if (scopes && (!delegateWorkspacePath(path) || !withinPaths(path, scopes))) {
278
+ if (scopes && (!delegateWorkspacePath(path) ||
279
+ !(exactScopes ? scopes.includes(path) : withinPaths(path, scopes)))) {
278
280
  if (sourceFiles) {
279
281
  const version = await fileVersion(folder, path)
280
282
  if (version && version !== "unsupported") sourceFiles[path] = version
@@ -311,7 +313,7 @@ export async function projectSnapshot(
311
313
  })
312
314
  }
313
315
 
314
- export async function checkDelegateWorkspace(work, scopes) {
316
+ export async function checkDelegateWorkspace(work, scopes, { exactScopes = false } = {}) {
315
317
  const directory = await lstat(work).catch((error) => {
316
318
  if (error.code === "ENOENT" || error.code === "ENOTDIR") return null
317
319
  throw error
@@ -327,7 +329,7 @@ export async function checkDelegateWorkspace(work, scopes) {
327
329
  info &&
328
330
  (!info.isFile() ||
329
331
  !delegateWorkspacePath(path) ||
330
- (scopes && !withinPaths(path, scopes)) ||
332
+ (scopes && !(exactScopes ? scopes.includes(path) : withinPaths(path, scopes))) ||
331
333
  (await realpath(file)) !== file)
332
334
  )
333
335
  return false
@@ -493,10 +495,94 @@ function applyBridgePatch(folder, patch, metadata) {
493
495
  )
494
496
  }
495
497
 
498
+ async function hasUniqueRetryContext(work, patch, changes) {
499
+ // The recorded path order is also the order of the --no-renames diff chunks.
500
+ const chunks = patch.split(/(?=^diff --git )/m)
501
+ if (chunks.length !== changes.length) return false
502
+ for (const [index, { path, before, after }] of changes.entries()) {
503
+ if (await fileVersion(work, path) === before) continue
504
+ if (before === null || after === null) return false
505
+ const file = await readFile(join(work, path), "utf8")
506
+ const current = "\n" + file + (file.endsWith("\n") ? "" : "\n")
507
+ const hunks = chunks[index].split(/^@@ [^\n]*\n/m).slice(1)
508
+ if (!hunks.length) return false // Binary and mode-only patches have no text preimage.
509
+ for (const hunk of hunks) {
510
+ const oldLines = hunk.split("\n")
511
+ .filter((line) => line.startsWith(" ") || line.startsWith("-"))
512
+ .map((line) => line.slice(1))
513
+ const context = "\n" + oldLines.join("\n") + "\n"
514
+ const first = current.indexOf(context)
515
+ if (!oldLines.length || first < 0 || current.indexOf(context, first + 1) !== -1)
516
+ return false
517
+ }
518
+ }
519
+ return true
520
+ }
521
+
522
+ export async function prepareBridgePatchRetry(folder, records, previewRoot) {
523
+ const paths = [...new Set(records.flatMap(({ changes }) => changes.map(({ path }) => path)))].sort()
524
+ if (paths.some((path, index) => !delegateWorkspacePath(path) ||
525
+ paths.slice(0, index).some((other) => pathsOverlap(path, other))))
526
+ return { status: "manual_review_required", paths }
527
+
528
+ await mkdir(previewRoot, { recursive: true, mode: 0o700 })
529
+ const preview = await realpath(await mkdtemp(join(previewRoot, "acent-retry-")))
530
+ try {
531
+ const versions = await Promise.all(paths.map(async (path) => ({
532
+ path, before: await fileVersion(folder, path),
533
+ })))
534
+ const unsupported = versions.filter(({ before }) => before === "unsupported").map(({ path }) => path)
535
+ if (unsupported.length) return { status: "manual_review_required", paths: unsupported }
536
+
537
+ let baseline
538
+ await projectSnapshot(folder, preview, (snapshot) => { baseline = snapshot }, { scopes: paths })
539
+ const drift = await mismatchedBridgePaths(preview, versions, "before")
540
+ if (drift.length) return { status: "working_copy_changed", paths: drift }
541
+ let previous = baseline
542
+ const metadata = join(preview, ".git")
543
+ const sourceVersions = new Map()
544
+ for (const { id, patch, changes } of records) {
545
+ // Two jobs from different versions of one file might overwrite each other
546
+ // even when their patches apply in sequence. Let a reviewer reconcile them.
547
+ const differentBases = changes.filter(({ path, before }) =>
548
+ sourceVersions.has(path) && sourceVersions.get(path) !== before
549
+ )
550
+ if (differentBases.length)
551
+ return { status: "manual_review_required", taskId: id,
552
+ paths: differentBases.map(({ path }) => path) }
553
+ for (const { path, before } of changes) sourceVersions.set(path, before)
554
+ if (!changes.length || !(await mismatchedBridgePaths(preview, changes)).length) continue
555
+ const allowed = new Set(changes.map(({ path }) => path))
556
+ try {
557
+ if (!patch || !(await hasUniqueRetryContext(preview, patch, changes)))
558
+ return { status: "manual_review_required", taskId: id, paths: [...allowed] }
559
+ // Git requires matching context. Do not force overlap or write conflict markers.
560
+ await applyBridgePatch(preview, patch, metadata)
561
+ const step = await inspectBridgeChanges(preview, previous, [...allowed])
562
+ if (step.violations.length || step.changes.some(({ path }) => !allowed.has(path)))
563
+ throw new Error("Source patch changed an unexpected path.")
564
+ previous = await checkpointBridgeWorkspace(preview)
565
+ } catch {
566
+ return { status: "manual_review_required", taskId: id, paths: [...allowed] }
567
+ }
568
+ }
569
+ const currentDrift = await mismatchedBridgePaths(folder, versions, "before")
570
+ if (currentDrift.length) return { status: "working_copy_changed", paths: currentDrift }
571
+ const result = await inspectBridgeChanges(preview, baseline, paths)
572
+ if (result.violations.length || result.changes.some(({ path }) => !paths.includes(path)))
573
+ return { status: "manual_review_required", paths }
574
+ return result.changes.length
575
+ ? { status: "prepared", changes: result.changes, patch: result.patch, versions }
576
+ : { status: "no_changes", paths }
577
+ } finally {
578
+ await rm(preview, { recursive: true, force: true })
579
+ }
580
+ }
581
+
496
582
  export async function applyVersionedBridgePatch(
497
583
  folder,
498
584
  { patch, changes },
499
- { check = false, beforeApply, previewRoot = tmpdir() } = {}
585
+ { check = false, beforeApply, guards = [], previewRoot = tmpdir() } = {}
500
586
  ) {
501
587
  if (!changes.length) return { status: "applied" }
502
588
  if (changes.some(({ path }) => !workspacePath(path)))
@@ -555,11 +641,14 @@ export async function applyVersionedBridgePatch(
555
641
  if (check) return { status: "ready_to_apply" }
556
642
  if (beforeApply && (await beforeApply()) === false)
557
643
  return { status: "cancelled" }
558
- const lateConflicts = await mismatchedBridgePaths(folder, changes, "before")
644
+ const lateConflicts = await mismatchedBridgePaths(folder, [...changes, ...guards], "before")
559
645
  if (lateConflicts.length)
560
646
  return { status: "working_copy_changed", paths: lateConflicts }
561
647
  await applyBridgePatch(folder, patch, metadata)
562
- const drift = await mismatchedBridgePaths(folder, changes)
648
+ const drift = [
649
+ ...await mismatchedBridgePaths(folder, changes),
650
+ ...await mismatchedBridgePaths(folder, guards, "before"),
651
+ ]
563
652
  return drift.length
564
653
  ? { status: "working_copy_changed", paths: drift }
565
654
  : { status: "applied" }