@cirtium/acent-connect 1.3.2 → 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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "acent",
3
- "version": "1.3.2",
3
+ "version": "1.3.3",
4
4
  "description": "Recall past work, trace code changes, revisit decisions, and resume tasks with Acent.",
5
5
  "mcpServers": "./mcp-claude.json",
6
6
  "hooks": "./hooks/claude.json"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "acent",
3
- "version": "1.3.2",
3
+ "version": "1.3.3",
4
4
  "description": "Recall past work, trace code changes, revisit decisions, and resume tasks with Acent.",
5
5
  "skills": "./skills/",
6
6
  "mcpServers": "./mcp-codex.json",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "acent",
3
- "version": "1.3.2",
3
+ "version": "1.3.3",
4
4
  "description": "Recall past work, trace code changes, revisit decisions, and resume tasks with Acent.",
5
5
  "author": {
6
6
  "name": "Cirtium"
@@ -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,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" }
@@ -15,6 +15,7 @@ import { setTimeout as pause } from "node:timers/promises"
15
15
  import { lock } from "./acent-connect.mjs"
16
16
  import { bridgeChangeContributors } from "./bridge-capture.mjs"
17
17
  import { createBridgeFinalizer } from "./bridge-finalize.mjs"
18
+ import { checkProjectCodeReceipt, isProjectCodeReceipt } from "./bridge-project-permissions.mjs"
18
19
  import { createBridgeRetention } from "./bridge-retention.mjs"
19
20
  import { bridgeReviewResult } from "./bridge-review-result.mjs"
20
21
  import {
@@ -31,6 +32,7 @@ import {
31
32
  inspectBridgeChanges,
32
33
  mismatchedBridgePaths,
33
34
  pathsOverlap,
35
+ prepareBridgePatchRetry,
34
36
  projectSnapshot,
35
37
  projectFileVersions,
36
38
  withinPaths,
@@ -176,7 +178,7 @@ export const bridgeTools = [
176
178
  },
177
179
  dependsOn: idList,
178
180
  requestId: text(
179
- "Optional UUID reused for an exact retry of this request."
181
+ "Use the UUID returned by sharing approval. Reuse it for an exact retry."
180
182
  ),
181
183
  automatic: { type: "boolean" },
182
184
  },
@@ -201,10 +203,15 @@ export const bridgeTools = [
201
203
  ),
202
204
  toolSchema(
203
205
  "acent_bridge_integrate",
204
- "Check completed patches together against the current folder, or apply them after review. By default this only checks for overlap and local changes. Apply only within the user's authorized editing scope, then run integration tests.",
206
+ "Check completed patches or apply them after review. For overlap or changed source files, prepareRetry checks the patches in a private copy of the latest files and may return a new patch to review. It never applies the retry.",
205
207
  {
206
208
  ids: idList,
207
209
  apply: { type: "boolean" },
210
+ prepareRetry: {
211
+ type: "boolean",
212
+ description: "Prepare a new patch from the latest files. Use the returned retryId to read the patch and apply it separately after review.",
213
+ },
214
+ retryRevision: text("Revision returned by acent_bridge_status after reading a prepared retry. Required to apply that retry."),
208
215
  },
209
216
  ["ids"]
210
217
  ),
@@ -255,7 +262,7 @@ export const bridgeTools = [
255
262
  ],
256
263
  },
257
264
  id: text(
258
- "Stable UUID for this refinement, generated by the coordinating agent."
265
+ "Stable UUID for this refinement. Use the requestId returned by sharing approval when available."
259
266
  ),
260
267
  task: text("Original work and what to review."),
261
268
  acceptance: text("What the final code must do and how to verify it."),
@@ -309,6 +316,7 @@ export const bridgeInstructions = [
309
316
  "In the final answer after using Bridge, name any enabled or explicitly requested tools that could not participate because CLI authentication was required, even if other tools completed the work. Use loginRequiredTools from candidate selection and login_required from task or refinement status as evidence. If the tool later succeeds in the same request, report its final outcome instead. Do not infer sign-out from missing models or an unavailable tool. Point users to Set up in Acent Bridge when they need to sign in.",
310
317
  "Bridge runs four tasks per project folder as a baseline and expands to eight as needed; extra ready tasks queue and start as slots open. Track queued jobs using their existing IDs. Check several jobs together with acent_bridge_activity while doing independent work. If a delegate requests context, answer from the conversation or ask the user if their judgment is needed, then continue.",
311
318
  "Use acent_bridge_integrate to check and apply completed diffs. For substantive changes implemented in parallel, review the integrated result and run end-to-end checks while eligible independent reviewers look at the same integrated candidate. Give multiple reviewers complementary priorities, such as concurrency, interface behavior, or regressions. Keep the reviewed files stable while reviews and checks run. Apply findings and re-review and rerun affected checks if the candidate changes.",
319
+ "For an integration conflict, use prepareRetry on the original task IDs when offered. Inspect the returned retryId with acent_bridge_status, then pass its retryRevision to apply that patch alone. If a source patch conflicts with the latest files, reconcile the changes in one scoped task instead of forcing the old patch.",
312
320
  "For substantive authorized edits with a defined write scope, use acent_bridge_refine to run independent review, repair and re-review. Pass applied task IDs in dependsOn. Choose eligible model families and optionally set each reviewer's focus to a distinct priority. Set apply=true only within the user's authorized editing scope.",
313
321
  "At needs_checks, call verify with the current checkRevision and authorized test commands to run in the private staging workspace. For a pending verified patch, inspect and approve it with apply and checkRevision. Replace a failed reviewer with replace_reviewer and an eligible reviewer. Resolve context requests using acent_bridge_continue and then resume refinement status. For standalone review of integrated work, submit commands to acent_bridge_finalize and poll without commands until verification finishes. Use setupCommands if the private check copy needs project-specific preparation. Remain responsible for the final result.",
314
322
  "Include an Acent Bridge section in the first final answer after any Bridge run or requested independent review, including when a requested review could not run. Start with a bold Acent Bridge label and the observed status in the user's language. Follow it immediately with a Markdown table showing the agent or check and its execution model, the work it performed and its scope, the outcome, and the findings or evidence. Include the table even when only one delegate participated or its execution model is unknown. Name the coordinator and delegate separately for the checks each performed. For delegates, use actualModel as the host-reported model. For the coordinator, use the host's model metadata for that turn when available. When the execution model is unavailable, label any requested model as requested and mark the execution model unconfirmed. Keep model families separate from model names.",
@@ -824,6 +832,7 @@ export function createBridge({
824
832
  queueMode
825
833
  ) {
826
834
  const jobDir = join(projectDir, job.id)
835
+ const exactScopes = isProjectCodeReceipt(job.refinementId ?? job.id)
827
836
  const record = join(jobDir, "job.json")
828
837
  const baselineFile = join(jobDir, "baseline.json")
829
838
  const work = join(jobDir, "work")
@@ -861,6 +870,9 @@ export function createBridge({
861
870
  const prerequisites = []
862
871
  const dependencyPaths = new Set()
863
872
  const requestedScopes = delegateScopes(job)
873
+ const visible = (path) => exactScopes
874
+ ? requestedScopes.includes(path)
875
+ : withinPaths(path, requestedScopes)
864
876
  for (const id of job.dependsOn) {
865
877
  const dependency = await readJson(
866
878
  join(projectDir, id, "job.json"),
@@ -879,7 +891,7 @@ export function createBridge({
879
891
  const visiblePaths = changedPaths.filter(
880
892
  (path) =>
881
893
  delegateWorkspacePath(path) &&
882
- (!requestedScopes.length || withinPaths(path, requestedScopes))
894
+ (!requestedScopes.length || visible(path))
883
895
  )
884
896
  for (const path of visiblePaths) dependencyPaths.add(path)
885
897
  const paths = visiblePaths.join(", ").slice(0, 1200)
@@ -888,7 +900,7 @@ export function createBridge({
888
900
  !requestedScopes.length ||
889
901
  (earlierScopes.length > 0 &&
890
902
  earlierScopes.every((path) =>
891
- withinPaths(path, requestedScopes)
903
+ visible(path)
892
904
  ))
893
905
  const patch =
894
906
  visiblePaths.length === changedPaths.length &&
@@ -1008,7 +1020,7 @@ export function createBridge({
1008
1020
  if (abort.signal.aborted) throw abort.signal.reason
1009
1021
  const scopes = delegateScopes(job)
1010
1022
  if (!snapshot && reviewOnly(job.kind) && scopes.length)
1011
- job.reviewDiff = await bridgeReviewDiff(folder, scopes)
1023
+ job.reviewDiff = await bridgeReviewDiff(folder, scopes, undefined, undefined, { exactScopes })
1012
1024
  await projectSnapshot(
1013
1025
  snapshot?.work ?? folder,
1014
1026
  work,
@@ -1019,6 +1031,7 @@ export function createBridge({
1019
1031
  }),
1020
1032
  {
1021
1033
  scopes,
1034
+ exactScopes,
1022
1035
  trackSource:
1023
1036
  !snapshot && reviewOnly(job.kind) && Boolean(job.dependsOn?.length),
1024
1037
  }
@@ -1037,7 +1050,8 @@ export function createBridge({
1037
1050
  !prepare &&
1038
1051
  !(await checkDelegateWorkspace(
1039
1052
  work,
1040
- baseline.scopes ?? delegateScopes(job)
1053
+ baseline.scopes ?? delegateScopes(job),
1054
+ { exactScopes }
1041
1055
  ))
1042
1056
  const target = invalidWorkspace ? {} : await getTarget(job.tool, folder)
1043
1057
  const beforeAttempt = !prepare && !invalidWorkspace && !reviewOnly(job.kind)
@@ -1209,9 +1223,58 @@ export function createBridge({
1209
1223
  return { id: job.id, status: "running", tool: job.tool, model: job.model }
1210
1224
  }
1211
1225
 
1212
- async function integrate(folder, projectDir, coordination, ids, apply, captureEvidence) {
1213
- if (!safeIds(ids) || (apply !== undefined && typeof apply !== "boolean"))
1226
+ async function saveIntegrationRetry(folder, projectDir, records, patches) {
1227
+ const prepared = await prepareBridgePatchRetry(folder, records.map(({ id, job }, index) => ({
1228
+ id, changes: job.changes ?? [], patch: patches[index],
1229
+ })), join(projectDir, "previews"))
1230
+ if (prepared.status !== "prepared") {
1231
+ return prepared.status === "manual_review_required"
1232
+ ? { ...prepared, nextAction: "Review the source patches and current files together. Resolve the conflict in one new task before applying." }
1233
+ : prepared
1234
+ }
1235
+
1236
+ const sourceTaskIds = records.map(({ id }) => id)
1237
+ const digest = createHash("sha256").update(JSON.stringify([
1238
+ sourceTaskIds, prepared.versions, prepared.patch,
1239
+ ])).digest("hex")
1240
+ const retryId = `${digest.slice(0, 8)}-${digest.slice(8, 12)}-${digest.slice(12, 16)}-${digest.slice(16, 20)}-${digest.slice(20, 32)}`
1241
+ const directory = join(projectDir, retryId)
1242
+ const record = join(directory, "job.json")
1243
+ const paths = prepared.changes.map(({ path }) => path)
1244
+ if (!(await readJson(record, null))) {
1245
+ const contributors = records.map(({ job }) =>
1246
+ job.changeContributors ?? bridgeChangeContributors(job, job.changes ?? [])
1247
+ )
1248
+ await mkdir(directory, { recursive: true, mode: 0o700 })
1249
+ await writeFile(join(directory, "changes.patch"), prepared.patch, { mode: 0o600 })
1250
+ await writeJson(record, {
1251
+ id: retryId,
1252
+ kind: "implement",
1253
+ status: "completed",
1254
+ task: "Prepare integration retry from the latest files",
1255
+ summary: "Prepared a new patch for review. The original working copy was not modified.",
1256
+ paths,
1257
+ sourceTaskIds,
1258
+ retryRevision: randomUUID(),
1259
+ retryGuards: prepared.versions.filter(({ path }) => !paths.includes(path)),
1260
+ changes: prepared.changes,
1261
+ changeContributors: Object.fromEntries(paths.map((path) => [path,
1262
+ contributors.flatMap((byPath) => byPath[path] ?? []).slice(-8),
1263
+ ])),
1264
+ patchBytes: Buffer.byteLength(prepared.patch),
1265
+ history: [],
1266
+ finishedAt: Date.now(),
1267
+ })
1268
+ }
1269
+ return { status: "retry_prepared", retryId, sourceTaskIds, paths,
1270
+ nextAction: "Review the patch with acent_bridge_status, then apply only the retryId with its retryRevision if approved." }
1271
+ }
1272
+
1273
+ async function integrateOnce(folder, projectDir, coordination, { ids, apply, prepareRetry, retryRevision }, captureEvidence) {
1274
+ if (!safeIds(ids) || (apply !== undefined && typeof apply !== "boolean") ||
1275
+ (prepareRetry !== undefined && typeof prepareRetry !== "boolean"))
1214
1276
  throw new Error("Select one to eight completed Bridge task IDs.")
1277
+ if (apply && prepareRetry) throw new Error("Prepare and review the retry before applying it.")
1215
1278
  return withWorkspaceLock(coordination, async () => {
1216
1279
  const receiptPath = join(
1217
1280
  projectDir,
@@ -1250,9 +1313,19 @@ export function createBridge({
1250
1313
  status: job ? taskState(job) : "not_found",
1251
1314
  })),
1252
1315
  }
1316
+ const preparedRetry = records.find(({ job }) => job.sourceTaskIds)?.job
1317
+ if (preparedRetry && ids.length > 1)
1318
+ return { status: "retry_requires_separate_apply", retryId: preparedRetry.id }
1319
+ if (preparedRetry && apply && retryRevision !== preparedRetry.retryRevision)
1320
+ return { status: "retry_review_required", retryId: preparedRetry.id }
1253
1321
  const changes = records.flatMap(({ id, job }) =>
1254
1322
  (job.changes ?? []).map((change) => ({ ...change, id }))
1255
1323
  )
1324
+ const guards = records.flatMap(({ job }) => job.retryGuards ?? [])
1325
+ const guardConflicts = await mismatchedBridgePaths(folder, guards, "before")
1326
+ if (guardConflicts.length)
1327
+ return { status: "working_copy_changed", paths: guardConflicts,
1328
+ sourceTaskIds: preparedRetry?.sourceTaskIds }
1256
1329
  const overlaps = changes
1257
1330
  .filter((change, index) =>
1258
1331
  changes
@@ -1263,8 +1336,6 @@ export function createBridge({
1263
1336
  )
1264
1337
  )
1265
1338
  .map((change) => change.path)
1266
- if (overlaps.length)
1267
- return { status: "patch_overlap", paths: [...new Set(overlaps)] }
1268
1339
  const paths = changes.map((change) => change.path)
1269
1340
  const captureApplied = async (at) => {
1270
1341
  if (!captureEvidence) return
@@ -1312,15 +1383,23 @@ export function createBridge({
1312
1383
  )
1313
1384
  return { status: "working_copy_changed", paths }
1314
1385
  const conflicts = await mismatchedBridgePaths(folder, changes, "before")
1315
- if (conflicts.length)
1316
- return { status: "working_copy_changed", paths: conflicts }
1317
- if (
1318
- await leases(coordination).then((entries) =>
1319
- entries.some((item) => item.preparing)
1320
- )
1321
- )
1322
- return { status: "snapshot_in_progress" }
1323
-
1386
+ const retryable = receipt?.status !== "applying" && !preparedRetry
1387
+ const needsRetry = overlaps.length || conflicts.length
1388
+ if (needsRetry && (!prepareRetry || !retryable)) {
1389
+ return {
1390
+ status: overlaps.length ? "patch_overlap" : "working_copy_changed",
1391
+ paths: [...new Set(overlaps.length ? overlaps : conflicts)],
1392
+ ...(retryable && { nextAction: "Prepare a patch from the latest files with prepareRetry: true." }),
1393
+ ...(preparedRetry && { sourceTaskIds: preparedRetry.sourceTaskIds,
1394
+ nextAction: "Prepare another patch from the latest files using the original task IDs." }),
1395
+ }
1396
+ }
1397
+ const active = await leases(coordination)
1398
+ if (active.some(({ preparing }) => preparing)) return { status: "snapshot_in_progress" }
1399
+ const busy = [...paths, ...guards.map(({ path }) => path)].filter((path) => active.some((item) =>
1400
+ item.writes && (!item.paths.length || item.paths.some((scope) => pathsOverlap(scope, path)))
1401
+ ))
1402
+ if (busy.length) return { status: "scope_busy", paths: [...new Set(busy)] }
1324
1403
  const patches = await Promise.all(
1325
1404
  records.map(({ directory, job }) =>
1326
1405
  job.patchBytes
@@ -1328,12 +1407,15 @@ export function createBridge({
1328
1407
  : ""
1329
1408
  )
1330
1409
  )
1410
+ if (prepareRetry && needsRetry)
1411
+ return saveIntegrationRetry(folder, projectDir, records, patches)
1331
1412
  const patch = patches.filter(Boolean).join("\n")
1332
1413
  const result = await applyVersionedBridgePatch(
1333
1414
  folder,
1334
1415
  { patch, changes },
1335
1416
  {
1336
1417
  check: !apply,
1418
+ guards,
1337
1419
  previewRoot: join(projectDir, "previews"),
1338
1420
  beforeApply: () =>
1339
1421
  writeJson(receiptPath, { status: "applying", paths }),
@@ -1346,6 +1428,15 @@ export function createBridge({
1346
1428
  })
1347
1429
  }
1348
1430
 
1431
+ async function integrate(folder, projectDir, coordination, args, captureEvidence) {
1432
+ for (let retries = 0; ; retries++) {
1433
+ const result = await integrateOnce(folder, projectDir, coordination, args, captureEvidence)
1434
+ if (retries === 3 || !["snapshot_in_progress", "scope_busy"].includes(result.status))
1435
+ return result
1436
+ await pause(250 * (retries + 1))
1437
+ }
1438
+ }
1439
+
1349
1440
  return async function call(name, args, selectedFolder, loadSettings) {
1350
1441
  const worker = process.env.ACENT_BRIDGE_WORKER === "1"
1351
1442
  if (worker && (name === "acent_bridge_start" ||
@@ -1357,6 +1448,7 @@ export function createBridge({
1357
1448
  const folder = await realpath(selectedFolder)
1358
1449
  if (!(await stat(folder)).isDirectory())
1359
1450
  throw new Error("Bridge needs a project directory.")
1451
+ await checkProjectCodeReceipt(name, args, folder)
1360
1452
  const settings = await loadSettings(folder)
1361
1453
  if (
1362
1454
  !/^[a-f0-9]{64}$/.test(settings?.projectKey ?? "") ||
@@ -1479,7 +1571,7 @@ export function createBridge({
1479
1571
  })
1480
1572
  }
1481
1573
  if (name === "acent_bridge_integrate")
1482
- return integrate(folder, projectDir, coordination, args.ids, args.apply, settings.captureEvidence)
1574
+ return integrate(folder, projectDir, coordination, args, settings.captureEvidence)
1483
1575
  if (name === "acent_bridge_finalize") {
1484
1576
  const result = await finalize(folder, projectDir, coordination, args)
1485
1577
  if (settings.captureEvidence && result.checkedAt)
@@ -1649,6 +1741,8 @@ export function createBridge({
1649
1741
  findings,
1650
1742
  question,
1651
1743
  patchBytes,
1744
+ sourceTaskIds,
1745
+ retryRevision,
1652
1746
  lastRunTokens,
1653
1747
  lastRunErrorCode,
1654
1748
  remainingQuota,
@@ -1674,6 +1768,8 @@ export function createBridge({
1674
1768
  patch,
1675
1769
  patchPath,
1676
1770
  patchBytes,
1771
+ sourceTaskIds,
1772
+ retryRevision,
1677
1773
  violations,
1678
1774
  changedPaths: changes?.map((change) => change.path),
1679
1775
  lastRunTokens,
@@ -23,6 +23,7 @@ Use the Acent Bridge MCP tools in a session with one local project folder open.
23
23
  - Check multiple jobs together with `acent_bridge_activity`, or use `acent_bridge_status` for a patch or a full answer. While jobs run, continue independent work and avoid tight polling. If a delegate requests context, answer with the relevant evidence using `acent_bridge_continue`. Ask the user if their judgment is needed. Resume interrupted work from its existing copy or use `acent_bridge_cancel` to stop work that is no longer needed.
24
24
  - In the final answer, name any enabled or explicitly requested tool that could not participate because its CLI required authentication. Use `loginRequiredTools` from candidate selection or `login_required` from task or refinement status. Include the tool even if others completed the work, and use its final result if it later succeeded. Point the user to **Set up** in Acent Bridge. Report model catalog failures and other unavailable states with their own reasons.
25
25
  - Use `acent_bridge_integrate` to check completed patches together. Review them before applying. Start independent review after integration so all reviewers examine the same candidate, including the interfaces between changes. For substantive changes you are authorized to edit, start `acent_bridge_refine` with a UUID, the original task and constraints, the scoped files, a repair model, and one or more reviewers from distinct model families outside the original and repair families. Pass applied task IDs in `dependsOn`. For complex integrations, give eligible reviewers complementary priorities with `focus`, such as concurrency, cross-component behavior, or regressions. Review the integrated changes and run the coordinator's checks while Bridge reviewers work. Keep the reviewed files stable until the reports return. If fixes change the candidate, re-review and rerun the affected checks on the updated changes. For a read-only request, use the standalone review instead.
26
+ - Bridge briefly rechecks a busy workspace during integration. If the files changed or patches overlap, use `prepareRetry: true` on the original task IDs when offered, then read the returned `retryId` with `acent_bridge_status`. After review, apply that retry on its own with the returned `retryRevision`. If preparation reports `manual_review_required`, reconcile the current file and source patches in one scoped task.
26
27
  - Refinement supplies the original scoped Git diff and the cumulative repair diff to reviewers. It gathers independent findings and re-reviews repairs in a private staging workspace. Keep working on unrelated files while it runs. Check its status when results are needed. If a worker requests context, answer with `acent_bridge_continue` and then check refinement status. If a reviewer cannot run, call `replace_reviewer` with that review ID and an eligible replacement model. Completed reviews in that round stay in place.
27
28
  - At `needs_checks`, call the refinement's `verify` action with the current `checkRevision` and the authorized test executables and arguments. Bridge runs them in a private copy of the reviewed candidate. For a standalone review of integrated edits, submit `commands` to `acent_bridge_finalize` and poll without them. Both flows prepare dependencies in the private test copy. Bridge can install locked npm dependencies automatically, and `setupCommands` can supply the project's own preparation steps. Report verification after `verified`. If project files captured in the verification snapshot change, begin from the latest changes.
28
29
  - Use `apply: true` to apply scoped repairs after the stage passes review and tests. Otherwise inspect the verified patch and call `apply` with the current `checkRevision`. If the user stops verification or refinement, call its `cancel` action and confirm the final state. If promotion has already started, check what was applied. If findings remain after three repairs or require files outside the approved scope, report the blocker.
@@ -30,7 +31,8 @@ Use the Acent Bridge MCP tools in a session with one local project folder open.
30
31
  ## Approval before sharing data
31
32
 
32
33
  - Automatic delegation selects eligible tools. A direct request authorizes its stated destination and data. When a handoff needs additional data-sharing approval, call `acent_bridge_request_approval` before submitting it. Show all destination agents, the exact file or data scope, and the purpose using labels only. Include any context, diffs, and extra read access in the scope description without including their contents. Check again before a replacement or continuation that would share new data.
33
- - Proceed through the normal Bridge tool after explicit approval or a saved exact-scope approval. For a new task use the approval result’s requestId when calling acent_bridge_start. After an interrupted approval, reopen the same scope only when the user asks to resume. On `needs_user_input`, use the host's approval flow or ask once in the current chat if the host permits it. On decline, cancellation, or unavailable approval, continue locally. Follow all host approval requirements and never use the Bridge question to override or route around a host denial.
34
+ - Proceed through the normal Bridge tool after approval. Interactive Acent CLI install or update can save project code permission. Pass individual project-relative file paths to `acent_bridge_request_approval` to use that permission. When the result has `permissionScope: "project_code"`, use exactly those files across `paths` and `readPaths`. Keep any inline context within that project code scope. Request explicit approval for additional data, including raw logs and conversation content.
35
+ - Request approval once for destinations sharing the same scope and purpose. For a separate task per destination, set `requestId` to its `requestIdsByTarget` value. For a single task use `requestId`, and for refinement pass it as `id`. Keep the same purpose label for related handoffs with the same purpose. After an interrupted approval, reopen the same scope only when the user asks to resume. On `needs_user_input`, use the host's approval flow or ask once in the current chat if the host permits it. On decline, cancellation, or unavailable approval, continue locally. Follow all host approval requirements and never use the Bridge question to override or route around a host denial.
34
36
 
35
37
  ## Review when only the coordinator can access a source
36
38
 
@@ -2,7 +2,7 @@
2
2
  "$schema": "https://antigravity.google/schemas/v1/plugin.json",
3
3
  "name": "acent",
4
4
  "displayName": "Acent",
5
- "version": "1.3.2",
5
+ "version": "1.3.3",
6
6
  "description": "Recall past work, trace code changes, revisit decisions, and resume tasks with Acent.",
7
7
  "author": {
8
8
  "name": "Cirtium"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cirtium/acent-connect",
3
- "version": "1.3.2",
3
+ "version": "1.3.3",
4
4
  "type": "module",
5
5
  "description": "Install and connect the shared Acent coding-tool plugin",
6
6
  "repository": {
package/scripts/acent.mjs CHANGED
@@ -17,7 +17,7 @@ export { installationCommands } from "./install-plugin.mjs"
17
17
 
18
18
  const choose = () => chooseTool(tools)
19
19
 
20
- async function applyPlugin(tool, command, settings, folder, execute, dependencies) {
20
+ async function applyPlugin(tool, command, folder, execute, dependencies) {
21
21
  const installed = await (dependencies.install || installPlugin)(tool, {
22
22
  command,
23
23
  folder,
@@ -26,14 +26,14 @@ async function applyPlugin(tool, command, settings, folder, execute, dependencie
26
26
  const action = command === "update" ? "files and settings updated" : "files and settings prepared"
27
27
  console.error(`\nAcent ${installed.version} ${action} for ${tool}.\n`)
28
28
  console.error(installationGuidance(tool) + "\n")
29
- if (command === "install" || command === "update") {
30
- try {
31
- await (dependencies.offerPermission || offerBridgePermission)(tool)
32
- } catch (error) {
33
- console.error(`Bridge permission for ${tool} was not updated: ${error.message}`)
34
- }
29
+ }
30
+
31
+ async function offerPermission(hosts, folder, dependencies) {
32
+ try {
33
+ await (dependencies.offerPermission || offerBridgePermission)(hosts, { folder })
34
+ } catch (error) {
35
+ console.error(`Could not finish updating Bridge permissions: ${error.message}`)
35
36
  }
36
- return true
37
37
  }
38
38
 
39
39
  async function applyAll(command, settings, execute, dependencies) {
@@ -42,23 +42,22 @@ async function applyAll(command, settings, execute, dependencies) {
42
42
  throw new Error("Choose an existing directory.")
43
43
  const updating = command === "update"
44
44
  const failures = []
45
- let completed = 0
45
+ const completed = []
46
46
  for (const tool of tools) {
47
47
  try {
48
48
  if (updating && !(await (dependencies.isManaged || isManagedInstallation)(tool))) continue
49
- const applied = await applyPlugin(
50
- tool, command, { skipUnavailable: !updating }, folder, execute, dependencies
51
- )
52
- if (applied) completed++
49
+ await applyPlugin(tool, command, folder, execute, dependencies)
50
+ completed.push(tool)
53
51
  } catch (error) {
54
52
  failures.push(`${tool}: ${error.message}`)
55
53
  }
56
54
  }
55
+ if (completed.length) await offerPermission(completed, folder, dependencies)
57
56
  if (failures.length)
58
57
  throw new Error(`Acent could not ${command} for every tool:\n${failures.join("\n")}`)
59
- if (!completed && !updating)
58
+ if (!completed.length && !updating)
60
59
  throw new Error("No plugins were installed.")
61
- if (!completed) console.error("No Acent plugins installed by this CLI were found.")
60
+ if (!completed.length) console.error("No Acent plugins installed by this CLI were found.")
62
61
  }
63
62
 
64
63
  export async function main(
@@ -127,8 +126,9 @@ export async function main(
127
126
  if (!(await stat(config.folder)).isDirectory())
128
127
  throw new Error("Open an existing project folder before connecting.")
129
128
  if (["connect", "install", "update"].includes(command))
130
- await applyPlugin(tool, command, settings, config.folder, execute, dependencies)
131
- if (!["install", "update"].includes(command)) await connect(adapterArgs)
129
+ await applyPlugin(tool, command, config.folder, execute, dependencies)
130
+ if (["install", "update"].includes(command)) await offerPermission(tool, config.folder, dependencies)
131
+ else await connect(adapterArgs)
132
132
  }
133
133
  if (
134
134
  process.argv[1] &&
@@ -1,6 +1,8 @@
1
1
  import { homedir } from "node:os"
2
2
  import { join } from "node:path"
3
3
  import { createInterface } from "node:readline/promises"
4
+ import { bridgeTargets } from "../acent/scripts/bridge-runners.mjs"
5
+ import { bridgeProject, newProjectCodeGrant } from "../acent/scripts/bridge-project-permissions.mjs"
4
6
  import { editSettings } from "./local-registration.mjs"
5
7
 
6
8
  const bridgeTool = "acent_bridge_start"
@@ -13,13 +15,7 @@ function addRule(object, key, rule) {
13
15
  return true
14
16
  }
15
17
 
16
- export async function offerBridgePermission(tool, {
17
- home = homedir(),
18
- input = process.stdin,
19
- output = process.stderr,
20
- ask,
21
- } = {}) {
22
- if (!ask && !input.isTTY) return
18
+ async function allowHost(tool, home, confirm) {
23
19
  const codex = tool === "Codex"
24
20
  const claude = tool === "Claude Code"
25
21
  const cursor = tool === "Cursor"
@@ -45,6 +41,27 @@ export async function offerBridgePermission(tool, {
45
41
  ? `mcp__plugin_acent_acent__${bridgeTool}`
46
42
  : `mcp(acent/${bridgeTool})`)
47
43
  }
44
+ let decision
45
+ await editSettings(path, codex, async data => {
46
+ if (!change(data)) return false
47
+ const allowed = await confirm()
48
+ decision = allowed ? "allowed" : "skipped"
49
+ return allowed
50
+ })
51
+ return decision
52
+ }
53
+
54
+ export async function offerBridgePermission(tool, {
55
+ folder,
56
+ home = homedir(),
57
+ input = process.stdin,
58
+ output = process.stderr,
59
+ ask,
60
+ } = {}) {
61
+ if (!ask && !input.isTTY) return
62
+ const hosts = Array.isArray(tool) ? tool : [tool]
63
+ if (!hosts.length) return
64
+ const hostLabel = host => host === "Antigravity" ? "Antigravity CLI" : host
48
65
  const select = ask ?? (async question => {
49
66
  const prompt = createInterface({ input, output })
50
67
  try {
@@ -54,15 +71,35 @@ export async function offerBridgePermission(tool, {
54
71
  }
55
72
  })
56
73
  const decisionPath = join(home, ".local", "share", "acent", "bridge-host-permissions.json")
74
+ const project = await bridgeProject(folder, home)
57
75
  await editSettings(decisionPath, false, async decisions => {
58
- if (decisions[tool] !== undefined) return false
59
- await editSettings(path, codex, async data => {
60
- if (!change(data)) return false
61
- const host = tool === "Antigravity" ? "Antigravity CLI" : tool
62
- const allowed = await select(`Always allow Acent Bridge to start in ${host} across projects? [y/N] `)
63
- decisions[tool] = allowed ? "allowed" : "skipped"
64
- return allowed
65
- })
66
- return decisions[tool] !== undefined
76
+ let combined
77
+ if (project) {
78
+ await editSettings(project.path, false, async grant => {
79
+ if (grant.status !== undefined) return false
80
+ const destinations = bridgeTargets.map(hostLabel).join(", ")
81
+ const installedHosts = hosts.map(hostLabel).join(", ")
82
+ combined = await select([
83
+ "Allow Acent Bridge to start without a tool prompt where host policy permits?",
84
+ `Host tool permission across projects: ${installedHosts}`,
85
+ `Project code sharing: ${JSON.stringify(project.root)}`,
86
+ `Destinations for this project's scoped files: ${destinations}`,
87
+ "Allow future code handoffs for implementation, review, and diagnosis in this project.",
88
+ "Other data and broader file scopes still need approval. [y/N] ",
89
+ ].join("\n"))
90
+ Object.assign(grant, combined ? newProjectCodeGrant() : { status: "skipped" })
91
+ })
92
+ }
93
+ let changed = false
94
+ for (const host of hosts) {
95
+ if (decisions[host] !== undefined && !(combined && decisions[host] === "skipped")) continue
96
+ const decision = await allowHost(host, home, () => combined ?? select(
97
+ `Always allow Acent Bridge to start in ${hostLabel(host)} across projects? [y/N] `
98
+ ))
99
+ if (!decision) continue
100
+ decisions[host] = decision
101
+ changed = true
102
+ }
103
+ return changed
67
104
  })
68
105
  }