@bevel-software/platform-core-backend 0.30.0 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/agent-guide/access-control.md +49 -4
  2. package/agent-guide/html-views.md +76 -2
  3. package/dist/core/catalog-revision.js +3 -3
  4. package/dist/core/create-core-server.d.ts.map +1 -1
  5. package/dist/core/create-core-server.js +2 -1
  6. package/dist/core/create-core-server.js.map +1 -1
  7. package/dist/core/create-core-services.d.ts.map +1 -1
  8. package/dist/core/create-core-services.js +4 -2
  9. package/dist/core/create-core-services.js.map +1 -1
  10. package/dist/modules/access/access-control.service.d.ts.map +1 -1
  11. package/dist/modules/access/access-control.service.js +1 -5
  12. package/dist/modules/access/access-control.service.js.map +1 -1
  13. package/dist/modules/audit/agent-audit.service.d.ts.map +1 -1
  14. package/dist/modules/audit/agent-audit.service.js +66 -6
  15. package/dist/modules/audit/agent-audit.service.js.map +1 -1
  16. package/dist/modules/audit/audit.contract.d.ts +52 -8
  17. package/dist/modules/audit/audit.contract.d.ts.map +1 -1
  18. package/dist/modules/audit/audit.contract.js +37 -1
  19. package/dist/modules/audit/audit.contract.js.map +1 -1
  20. package/dist/modules/audit/audit.routes.d.ts +1 -1
  21. package/dist/modules/audit/audit.routes.d.ts.map +1 -1
  22. package/dist/modules/audit/audit.routes.js +15 -13
  23. package/dist/modules/audit/audit.routes.js.map +1 -1
  24. package/dist/modules/audit/request-audit.d.ts +21 -10
  25. package/dist/modules/audit/request-audit.d.ts.map +1 -1
  26. package/dist/modules/audit/request-audit.js +26 -10
  27. package/dist/modules/audit/request-audit.js.map +1 -1
  28. package/dist/modules/database/core-schema.d.ts +22 -3
  29. package/dist/modules/database/core-schema.d.ts.map +1 -1
  30. package/dist/modules/database/core-schema.js +15 -6
  31. package/dist/modules/database/core-schema.js.map +1 -1
  32. package/dist/modules/kb-fs/index.d.ts +1 -0
  33. package/dist/modules/kb-fs/index.d.ts.map +1 -1
  34. package/dist/modules/kb-fs/index.js +1 -0
  35. package/dist/modules/kb-fs/index.js.map +1 -1
  36. package/dist/modules/kb-fs/locking-filesystem.d.ts.map +1 -1
  37. package/dist/modules/kb-fs/locking-filesystem.js +3 -12
  38. package/dist/modules/kb-fs/locking-filesystem.js.map +1 -1
  39. package/dist/modules/kb-fs/mutex.d.ts +11 -0
  40. package/dist/modules/kb-fs/mutex.d.ts.map +1 -1
  41. package/dist/modules/kb-fs/mutex.js +14 -0
  42. package/dist/modules/kb-fs/mutex.js.map +1 -1
  43. package/dist/modules/mcp/mcp-auth.middleware.d.ts +14 -0
  44. package/dist/modules/mcp/mcp-auth.middleware.d.ts.map +1 -1
  45. package/dist/modules/mcp/mcp-auth.middleware.js +4 -0
  46. package/dist/modules/mcp/mcp-auth.middleware.js.map +1 -1
  47. package/dist/modules/mcp/mcp.routes.d.ts +5 -0
  48. package/dist/modules/mcp/mcp.routes.d.ts.map +1 -1
  49. package/dist/modules/mcp/mcp.routes.js +67 -0
  50. package/dist/modules/mcp/mcp.routes.js.map +1 -1
  51. package/dist/modules/mcp/mcp.service.d.ts +107 -27
  52. package/dist/modules/mcp/mcp.service.d.ts.map +1 -1
  53. package/dist/modules/mcp/mcp.service.js +257 -50
  54. package/dist/modules/mcp/mcp.service.js.map +1 -1
  55. package/dist/modules/mcp/request-context.d.ts +25 -0
  56. package/dist/modules/mcp/request-context.d.ts.map +1 -0
  57. package/dist/modules/mcp/request-context.js +11 -0
  58. package/dist/modules/mcp/request-context.js.map +1 -0
  59. package/dist/modules/mcp/shared-definitions.d.ts +56 -0
  60. package/dist/modules/mcp/shared-definitions.d.ts.map +1 -0
  61. package/dist/modules/mcp/shared-definitions.js +117 -0
  62. package/dist/modules/mcp/shared-definitions.js.map +1 -0
  63. package/dist/modules/mcp/surface-cache.d.ts +70 -0
  64. package/dist/modules/mcp/surface-cache.d.ts.map +1 -0
  65. package/dist/modules/mcp/surface-cache.js +104 -0
  66. package/dist/modules/mcp/surface-cache.js.map +1 -0
  67. package/dist/modules/tool-helpers/tool-context.d.ts.map +1 -1
  68. package/dist/modules/tool-helpers/tool-context.js +33 -12
  69. package/dist/modules/tool-helpers/tool-context.js.map +1 -1
  70. package/dist/modules/tool-helpers/tool.contract.d.ts +8 -0
  71. package/dist/modules/tool-helpers/tool.contract.d.ts.map +1 -1
  72. package/dist/modules/tool-helpers/tool.contract.js.map +1 -1
  73. package/dist/modules/workflow/agent-tools/change-request-read.tools.d.ts.map +1 -1
  74. package/dist/modules/workflow/agent-tools/change-request-read.tools.js +3 -14
  75. package/dist/modules/workflow/agent-tools/change-request-read.tools.js.map +1 -1
  76. package/dist/modules/workflow/agent-tools/workflow.tools.d.ts +18 -1
  77. package/dist/modules/workflow/agent-tools/workflow.tools.d.ts.map +1 -1
  78. package/dist/modules/workflow/agent-tools/workflow.tools.js +453 -2
  79. package/dist/modules/workflow/agent-tools/workflow.tools.js.map +1 -1
  80. package/dist/modules/workflow/git/git.service.d.ts +113 -4
  81. package/dist/modules/workflow/git/git.service.d.ts.map +1 -1
  82. package/dist/modules/workflow/git/git.service.js +470 -106
  83. package/dist/modules/workflow/git/git.service.js.map +1 -1
  84. package/dist/modules/workflow/read-on-branch.d.ts +35 -0
  85. package/dist/modules/workflow/read-on-branch.d.ts.map +1 -0
  86. package/dist/modules/workflow/read-on-branch.js +58 -0
  87. package/dist/modules/workflow/read-on-branch.js.map +1 -0
  88. package/dist/modules/workflow/workflow.routes.d.ts.map +1 -1
  89. package/dist/modules/workflow/workflow.routes.js +22 -41
  90. package/dist/modules/workflow/workflow.routes.js.map +1 -1
  91. package/dist/modules/workflow/workflow.service.d.ts +48 -8
  92. package/dist/modules/workflow/workflow.service.d.ts.map +1 -1
  93. package/dist/modules/workflow/workflow.service.js +163 -16
  94. package/dist/modules/workflow/workflow.service.js.map +1 -1
  95. package/dist/modules/workspace/index.d.ts +2 -0
  96. package/dist/modules/workspace/index.d.ts.map +1 -1
  97. package/dist/modules/workspace/index.js +4 -0
  98. package/dist/modules/workspace/index.js.map +1 -1
  99. package/dist/shared/git.contract.d.ts +7 -0
  100. package/dist/shared/git.contract.d.ts.map +1 -1
  101. package/dist/shared/git.contract.js +9 -0
  102. package/dist/shared/git.contract.js.map +1 -1
  103. package/dist/shared/no-link-below.d.ts +10 -0
  104. package/dist/shared/no-link-below.d.ts.map +1 -0
  105. package/dist/shared/no-link-below.js +30 -0
  106. package/dist/shared/no-link-below.js.map +1 -0
  107. package/migrations/0018_agent_events_page.sql +11 -0
  108. package/migrations/meta/0018_snapshot.json +2429 -0
  109. package/migrations/meta/_journal.json +8 -1
  110. package/package.json +3 -3
  111. package/src/core/catalog-revision.ts +3 -3
  112. package/src/core/create-core-server.ts +2 -1
  113. package/src/core/create-core-services.ts +4 -2
  114. package/src/modules/access/access-control.service.ts +1 -6
  115. package/src/modules/agent-guide/__tests__/agent-guide.test.ts +22 -1
  116. package/src/modules/audit/__tests__/agent-audit.service.test.ts +78 -1
  117. package/src/modules/audit/__tests__/audit.routes.test.ts +43 -5
  118. package/src/modules/audit/agent-audit.service.ts +66 -6
  119. package/src/modules/audit/audit.contract.ts +62 -10
  120. package/src/modules/audit/audit.routes.ts +14 -12
  121. package/src/modules/audit/request-audit.ts +28 -13
  122. package/src/modules/database/core-schema.ts +15 -6
  123. package/src/modules/kb-fs/__tests__/mutex.canonical.test.ts +57 -0
  124. package/src/modules/kb-fs/index.ts +1 -0
  125. package/src/modules/kb-fs/locking-filesystem.ts +3 -12
  126. package/src/modules/kb-fs/mutex.ts +16 -0
  127. package/src/modules/mcp/__tests__/mcp-routes-harness.ts +7 -1
  128. package/src/modules/mcp/__tests__/mcp.routes.page.test.ts +115 -0
  129. package/src/modules/mcp/__tests__/mcp.surface-cache.test.ts +521 -0
  130. package/src/modules/mcp/__tests__/shared-definitions.test.ts +28 -0
  131. package/src/modules/mcp/__tests__/surface-cache.test.ts +127 -0
  132. package/src/modules/mcp/mcp-auth.middleware.ts +21 -0
  133. package/src/modules/mcp/mcp.routes.ts +68 -0
  134. package/src/modules/mcp/mcp.service.ts +315 -51
  135. package/src/modules/mcp/request-context.ts +34 -0
  136. package/src/modules/mcp/shared-definitions.ts +121 -0
  137. package/src/modules/mcp/surface-cache.ts +154 -0
  138. package/src/modules/tool-helpers/tool-context.ts +37 -18
  139. package/src/modules/tool-helpers/tool.contract.ts +8 -0
  140. package/src/modules/tool-registry/__tests__/own-tool-schemas.test.ts +1 -1
  141. package/src/modules/tool-registry/__tests__/tool-description-length.test.ts +1 -1
  142. package/src/modules/workflow/__tests__/workflow.routes.history-read-gate.test.ts +23 -12
  143. package/src/modules/workflow/__tests__/workflow.service.facade.test.ts +250 -4
  144. package/src/modules/workflow/agent-tools/__tests__/workflow.tools.test.ts +464 -4
  145. package/src/modules/workflow/agent-tools/change-request-read.tools.ts +4 -22
  146. package/src/modules/workflow/agent-tools/workflow.tools.ts +462 -1
  147. package/src/modules/workflow/git/__tests__/git.service.diffFileBetweenBranches.test.ts +76 -11
  148. package/src/modules/workflow/git/__tests__/git.service.mergeIntoBranch.test.ts +721 -0
  149. package/src/modules/workflow/git/git.service.ts +537 -106
  150. package/src/modules/workflow/read-on-branch.ts +79 -0
  151. package/src/modules/workflow/workflow.routes.ts +21 -39
  152. package/src/modules/workflow/workflow.service.ts +203 -16
  153. package/src/modules/workspace/index.ts +11 -0
  154. package/src/shared/__tests__/no-link-below.test.ts +45 -0
  155. package/src/shared/git.contract.ts +10 -0
  156. package/src/shared/no-link-below.ts +29 -0
@@ -4,14 +4,17 @@ import { logger } from '../../../shared/logging.js';
4
4
  import { isFolderPlaceholder } from '@bevel-software/platform-shared';
5
5
  import { mergeCommitMessageNames } from './merge-commit.js';
6
6
  import { AccessDeniedError } from '../../access-model/access-errors.js';
7
- import { WorkspaceMutex } from '../../kb-fs/mutex.js';
7
+ import { WorkspaceIdMutex } from '../../kb-fs/index.js';
8
8
  import { isAbsence } from '../../../shared/fs.contract.js';
9
9
  import { assertInsideRepo } from '../../kb-fs/repo-path.js';
10
10
  import { cloneTrackingConfigArgs, SAFE_IMPLICIT_FETCH_ARGS } from '../../kb-fs/clone-config.js';
11
11
  import { readRefSha } from '../../kb-fs/index.js';
12
+ import { utf8Text } from '../../../shared/utf8-text.js';
13
+ import { lstatOrNull } from '../../../shared/rename-no-replace.js';
14
+ import { linkedAncestor } from '../../../shared/no-link-below.js';
12
15
  import { assertValidBranchName, assertValidRelativePath, isBranchAuthoredBy, isOwnSuggestionsBranch, } from '../../kb-fs/branch-name.js';
13
16
  import { AppliedChangeMismatchError, BranchAuthorshipError, BranchDeleteRefusedError, WorkflowDomainError, WorkflowValidationError, ProtectedBranchError, PullRebaseConflictError, RemoteBranchGoneError, VersionNotOnBranchError, isMissingRemoteBranchFailure, } from '../../../shared/domain-errors.js';
14
- import { GitRunError, assertOneSpecPerLine, isGitTimeout, redactGitToken, } from '../../../shared/git.contract.js';
17
+ import { GitRunError, assertOneSpecPerLine, redactGitToken, } from '../../../shared/git.contract.js';
15
18
  import { NodeGitRunner } from './node-git-runner.js';
16
19
  import { printable } from '../../../shared/printable.js';
17
20
  import { sanitizeError } from '../sanitize-error.js';
@@ -270,7 +273,11 @@ export class GitService {
270
273
  * replaced). No hooks registered = no commit-time validation, which is
271
274
  * safe because validation is advisory and never blocks a commit.
272
275
  */
273
- hooks, kb, mutex = new WorkspaceMutex(), accessControl = null,
276
+ hooks, kb,
277
+ // Keyed by the CANONICAL workspace id: a route's Express-decoded `:id`
278
+ // (`alice/feature`) and a tool's `alice%2Ffeature` name one clone, and
279
+ // must take one reservation.
280
+ mutex = new WorkspaceIdMutex(), accessControl = null,
274
281
  /**
275
282
  * How git is actually run — see `shared/git.contract.ts`. The composition
276
283
  * root passes the one runner, carrying the deployment's configured
@@ -849,18 +856,19 @@ export class GitService {
849
856
  const sha = /^[0-9a-f]{4,64}$/i;
850
857
  if (!sha.test(ancestor) || !sha.test(descendant))
851
858
  throw new Error('isAncestor takes commit ids');
852
- return this.mutex.run(workspaceId, async () => {
853
- const cwd = await this.repoDir(workspaceId);
854
- try {
855
- await this.git(cwd, ['merge-base', '--is-ancestor', ancestor, descendant]);
856
- return true;
857
- }
858
- catch (err) {
859
- if (err instanceof GitRunError && !err.timedOut && err.exitCode === 1)
860
- return false;
861
- throw err;
862
- }
863
- });
859
+ return this.mutex.run(workspaceId, async () => this.isAncestorUnlocked(await this.repoDir(workspaceId), ancestor, descendant));
860
+ }
861
+ /** `isAncestor`'s body, for a caller that already holds the workspace's reservation. */
862
+ async isAncestorUnlocked(cwd, ancestor, descendant) {
863
+ try {
864
+ await this.git(cwd, ['merge-base', '--is-ancestor', ancestor, descendant]);
865
+ return true;
866
+ }
867
+ catch (err) {
868
+ if (err instanceof GitRunError && !err.timedOut && err.exitCode === 1)
869
+ return false;
870
+ throw err;
871
+ }
864
872
  }
865
873
  /**
866
874
  * True iff the given ref (e.g. `refs/heads/foo`, `refs/remotes/origin/foo`)
@@ -1283,8 +1291,20 @@ export class GitService {
1283
1291
  // stamped after the push instead, as one short write made as the
1284
1292
  // repository's administrator (see `git`).
1285
1293
  await this.git(cwd, ['push', 'origin', branch]);
1286
- await this.git(cwd, ['config', '--replace-all', `branch.${branch}.remote`, 'origin']);
1287
- await this.git(cwd, ['config', '--replace-all', `branch.${branch}.merge`, `refs/heads/${branch}`]);
1294
+ // The stamp is maintenance after a push that LANDED: a config the
1295
+ // repository's administrator could not write just now (a lock held by
1296
+ // another worktree's stamp) does not make the branch unpublished, and
1297
+ // reporting it as a refused push would hand a published commit to
1298
+ // recovery. Logged; the next push stamps it.
1299
+ try {
1300
+ await this.git(cwd, ['config', '--replace-all', `branch.${branch}.remote`, 'origin']);
1301
+ await this.git(cwd, ['config', '--replace-all', `branch.${branch}.merge`, `refs/heads/${branch}`]);
1302
+ }
1303
+ catch (err) {
1304
+ log.warn(`"${branch}" is pushed; its tracking config could not be stamped after the push:`, {
1305
+ detail: redactGitToken(err instanceof Error ? err.message : String(err), this.credentials.token()),
1306
+ });
1307
+ }
1288
1308
  }
1289
1309
  }
1290
1310
  // `forcePush` method removed. The workflow layer no longer auto-force-pushes
@@ -1319,73 +1339,375 @@ export class GitService {
1319
1339
  assertValidBranchName(sourceBranch);
1320
1340
  assertValidBranchName(targetBranch);
1321
1341
  assertValidAuthor(user);
1342
+ // The one merge protocol (`mergeRefIntoCheckout`), asked for what the
1343
+ // auto-merge needs: no resolutions, the conflicted paths alone, no
1344
+ // publish. Under the per-branch workspace model the workspace IS the
1345
+ // source branch, so the checked-out guard is not asked for; nor is the
1346
+ // dirty-tree one — save=share keeps the tree clean before an auto-merge,
1347
+ // and a dirty one is an upstream bug `statusInternal` already logs.
1322
1348
  return this.mutex.run(workspaceId, async () => {
1323
- const cwd = await this.repoDir(workspaceId);
1324
- // Under the per-branch workspace model, the workspace's identity is
1325
- // the source branch — the legacy "current branch must equal sourceBranch"
1326
- // guard was an artifact of the single-workspace-many-branches model and
1327
- // is no longer needed. The legacy dirty-tree refusal is also gone:
1328
- // save=share guarantees the tree is clean before any auto-merge runs,
1329
- // and the only way it could be dirty now is an upstream bug, which
1330
- // `statusInternal` already logs server-side.
1331
- // Refresh the target ref so we merge against the latest published
1332
- // state. Failing the fetch here is non-recoverable for this
1333
- // operation: a stale `origin/<target>` would let us silently miss
1334
- // conflicts the next push would surface, and the whole point of
1335
- // `mergeFromOrigin` is to surface those conflicts now. Propagate
1336
- // the error so the auto-merge aborts cleanly instead of producing
1337
- // a merge based on a stale ref. Explicit destination refspec for the
1338
- // same reason as `mergeChangeRequest`: a bare `fetch origin <branch>`
1339
- // updates `origin/<branch>` only as far as `remote.origin.fetch` allows,
1340
- // and a drifted refspec would hand this merge the stale ref it is
1341
- // explicitly trying to avoid.
1342
- await this.git(cwd, [
1343
- 'fetch', '--no-write-fetch-head', 'origin',
1344
- `+refs/heads/${targetBranch}:refs/remotes/origin/${targetBranch}`,
1345
- ]);
1346
- // `--no-commit --no-ff` so we control the commit (need to override
1347
- // author) and so we never sneak a fast-forward past the merge-commit
1348
- // explanation gate.
1349
- let mergeStdout = '';
1350
- try {
1351
- const r = await this.git(cwd, [
1352
- 'merge', '--no-commit', '--no-ff', `origin/${targetBranch}`,
1353
- ]);
1354
- mergeStdout = r.stdout;
1349
+ const outcome = await this.mergeRefIntoCheckout(workspaceId, await this.repoDir(workspaceId), sourceBranch, targetBranch, user, {
1350
+ subject: `Refresh ${sourceBranch} from ${targetBranch}`,
1351
+ body: `Workflow auto-merge: incorporates the latest ${targetBranch} into ${sourceBranch} ` +
1352
+ `as part of opening or refreshing a change request. ` +
1353
+ `Conflicts (if any) would have been surfaced to the caller before this commit landed; ` +
1354
+ `none were detected, so the merge applied cleanly.`,
1355
+ resolutions: new Map(),
1356
+ guardCheckout: false,
1357
+ describeConflicts: false,
1358
+ });
1359
+ if (outcome.kind === 'conflicts')
1360
+ return { kind: 'conflicts', paths: outcome.unresolved };
1361
+ return { kind: 'clean', alreadyUpToDate: outcome.kind === 'nothing-to-merge' };
1362
+ });
1363
+ }
1364
+ /** The most of one side of a conflicted file that travels in an answer; past it the side is read by the caller instead. */
1365
+ static CONFLICT_SIDE_MAX_CHARS = 200_000;
1366
+ async mergeIntoBranch(workspaceId, branch, fromBranch, user, opts) {
1367
+ assertValidBranchName(branch);
1368
+ assertValidBranchName(fromBranch);
1369
+ assertValidAuthor(user);
1370
+ if (/\n\s*\n/.test(opts.subject)) {
1371
+ throw new WorkflowValidationError('merge commit subject must be a single paragraph');
1372
+ }
1373
+ // Every resolution names a repository path; which of them are conflicted
1374
+ // is only known inside the merge, where they are matched exactly.
1375
+ const resolutions = new Map();
1376
+ // A resolution writes a file on the branch: it is somebody's to
1377
+ // authorize, and a caller that brings none writes nothing (closed).
1378
+ if ((opts.resolutions?.length ?? 0) > 0 && typeof opts.authorizeResolutions !== 'function') {
1379
+ throw new Error('mergeIntoBranch: resolutions need an `authorizeResolutions` to be asked inside the merge');
1380
+ }
1381
+ for (const r of opts.resolutions ?? []) {
1382
+ assertValidRelativePath(r.path);
1383
+ const p = this.stripRepoPrefix(r.path);
1384
+ const ways = [r.content !== undefined, r.choose !== undefined].filter(Boolean).length;
1385
+ if (ways !== 1) {
1386
+ throw new WorkflowValidationError(`resolution for "${p}": give either \`content\` or \`choose\`, not ${ways === 0 ? 'neither' : 'both'}`);
1355
1387
  }
1356
- catch (err) {
1357
- // Conflict or other failure. Disambiguate via the shared porcelain parse.
1358
- const conflictPaths = await this.conflictedPaths(cwd);
1359
- // Always attempt to abort so a partial merge doesn't poison the tree.
1360
- try {
1361
- await this.git(cwd, ['merge', '--abort']);
1388
+ if (r.choose !== undefined && !['ours', 'theirs', 'delete'].includes(r.choose)) {
1389
+ throw new WorkflowValidationError(`resolution for "${p}": \`choose\` is \`ours\`, \`theirs\` or \`delete\``);
1390
+ }
1391
+ if (resolutions.has(p))
1392
+ throw new WorkflowValidationError(`"${p}" is resolved twice`);
1393
+ resolutions.set(p, { ...r, path: p });
1394
+ }
1395
+ return this.mutex.run(workspaceId, async () => this.mergeRefIntoCheckout(workspaceId, await this.repoDir(workspaceId), branch, fromBranch, user, {
1396
+ subject: opts.subject,
1397
+ body: opts.body,
1398
+ resolutions,
1399
+ guardCheckout: true,
1400
+ describeConflicts: true,
1401
+ publish: opts.publish,
1402
+ authorizeResolutions: opts.authorizeResolutions,
1403
+ }));
1404
+ }
1405
+ /**
1406
+ * THE merge of `origin/<fromBranch>` into the checkout at `cwd` — what
1407
+ * `mergeFromOrigin` (the change-request auto-merge) and `mergeIntoBranch`
1408
+ * (the agent's update) both run. The caller holds the workspace's
1409
+ * reservation. `--no-commit --no-ff`, so the commit is authored as `user`
1410
+ * and the record of what was merged is never fast-forwarded past.
1411
+ *
1412
+ * The checkout is never left mid-merge, whatever happens: every exit after
1413
+ * `git merge` has started — a conflict described, a resolution refused or
1414
+ * failed, a commit or a publish that failed — runs `merge --abort` first,
1415
+ * and an abort that itself fails is reported, never swallowed, because a
1416
+ * checkout stuck in a merge is what breaks the commit worker and every
1417
+ * later operation on the branch.
1418
+ *
1419
+ * `publish` runs over the merge commit inside this same reservation, so no
1420
+ * save or sync can land between the commit and its push; it is the
1421
+ * caller's push policy (the workflow's `pushWithRecovery`: one replay onto
1422
+ * the moved branch with the merge kept, `--rebase-merges`, then the typed
1423
+ * hand-off) over this checkout's own unlocked moves.
1424
+ */
1425
+ async mergeRefIntoCheckout(workspaceId, cwd, branch, fromBranch, user, opts) {
1426
+ const theirsRef = `refs/remotes/origin/${fromBranch}`;
1427
+ if (opts.guardCheckout) {
1428
+ const checkedOut = await this.currentBranch(cwd);
1429
+ if (checkedOut !== branch) {
1430
+ throw new WorkflowValidationError(`the workspace is on "${checkedOut}", not on "${branch}"`);
1431
+ }
1432
+ // A merge rewrites tracked files. Edits still on their way to a commit
1433
+ // (a save the worker has not landed) would be swept into the merge
1434
+ // commit under this user's name, or lost under the merge's version.
1435
+ const { stdout: dirty } = await this.git(cwd, ['status', '--porcelain=v1', '-z']);
1436
+ if (parsePorcelainZ(dirty).length > 0) {
1437
+ throw new WorkflowDomainError(`"${branch}" has edits that are not committed yet. Try again once they are saved.`, 409, { kind: 'branch-busy', branch });
1438
+ }
1439
+ }
1440
+ // `git merge`/`git commit` need a committer identity (see `mergeChangeRequest`).
1441
+ await this.git(cwd, ['config', 'user.name', BOT_NAME]);
1442
+ await this.git(cwd, ['config', 'user.email', BOT_EMAIL]);
1443
+ // The published tip, explicitly: a bare `fetch origin <branch>` updates
1444
+ // the tracking ref only as far as `remote.origin.fetch` allows, and a
1445
+ // stale ref would hide exactly the conflicts this merge exists to surface.
1446
+ await this.git(cwd, ['fetch', '--no-write-fetch-head', 'origin', `+refs/heads/${fromBranch}:${theirsRef}`]);
1447
+ const ours = (await this.git(cwd, ['rev-parse', 'HEAD'])).stdout.trim();
1448
+ // The COMMIT the merge is of, from here on — never the ref it was read
1449
+ // from: the repository's refs are shared by every worktree and moved by
1450
+ // every fetch (the timer's sync, another workspace's merge), so what is
1451
+ // authorized, merged, described and recorded is this one sha.
1452
+ const theirs = (await this.git(cwd, ['rev-parse', theirsRef])).stdout.trim();
1453
+ // Resolutions are authorized here, on the clean checkout at `ours` with
1454
+ // `theirs` fetched, before the merge changes a single file. Which of
1455
+ // them are conflicted is matched after the merge; a stray one is refused.
1456
+ if (opts.resolutions.size > 0 && opts.authorizeResolutions)
1457
+ await opts.authorizeResolutions({ ours, theirs });
1458
+ // A merge with nothing to settle leaves no resolution a place to go: one
1459
+ // supplied anyway names a path that is not conflicted, and is refused as
1460
+ // such rather than dropped on the floor behind a published merge.
1461
+ const noConflictsFor = () => new WorkflowValidationError(`nothing conflicted, so nothing is resolved here: ${[...opts.resolutions.keys()].join(', ')}.`, { kind: 'not-conflicted', paths: [...opts.resolutions.keys()] });
1462
+ // Nothing to merge is a question of ANCESTRY, not of content: a source
1463
+ // the branch already reaches is merged; one it does not reach is merged
1464
+ // in even when the two trees are identical, so the branch records that
1465
+ // it holds the source's history and stops reading as behind it.
1466
+ if (await this.isAncestorUnlocked(cwd, theirs, ours)) {
1467
+ if (opts.resolutions.size > 0)
1468
+ throw noConflictsFor();
1469
+ return { kind: 'nothing-to-merge', sha: ours, from: fromBranch };
1470
+ }
1471
+ try {
1472
+ await this.git(cwd, ['merge', '--no-commit', '--no-ff', theirs]);
1473
+ }
1474
+ catch (err) {
1475
+ // A conflict, or another failure: either way the merge may be on disk
1476
+ // from here on, and every exit below undoes it.
1477
+ return this.settleMerge(cwd, async () => {
1478
+ const conflicted = await this.conflictedPaths(cwd);
1479
+ if (conflicted.length === 0) {
1480
+ throw new Error(`git merge failed without detectable conflicts: ${redactGitToken(err instanceof Error ? err.message : String(err), this.credentials.token())}`);
1362
1481
  }
1363
- catch {
1364
- // Already aborted (no MERGE_HEAD) — fine.
1482
+ const stray = [...opts.resolutions.keys()].filter((p) => !conflicted.includes(p));
1483
+ if (stray.length > 0) {
1484
+ // Only a conflicted path is written by a resolution: anything else
1485
+ // is an ordinary write, which goes through the file tools and their
1486
+ // locks. Refused whole, before any resolution is applied — naming
1487
+ // the caller's own paths only, never the conflicted set (which the
1488
+ // caller is told of, cut to what they may read, by the answer).
1489
+ throw new WorkflowValidationError(`not conflicted, so not resolved here: ${stray.join(', ')}.`, { kind: 'not-conflicted', paths: stray });
1490
+ }
1491
+ const unresolved = conflicted.filter((p) => !opts.resolutions.has(p));
1492
+ if (unresolved.length > 0) {
1493
+ // Described while the merge is on disk — the three stages and the
1494
+ // marked-up working copy exist only then — and undone (by
1495
+ // `settleMerge`) before the answer leaves the reservation.
1496
+ const mergeBase = await this.git(cwd, ['merge-base', ours, theirs])
1497
+ .then((r) => r.stdout.trim() || null)
1498
+ .catch(() => null);
1499
+ const files = [];
1500
+ if (opts.describeConflicts)
1501
+ for (const p of conflicted)
1502
+ files.push(await this.describeConflict(cwd, p));
1503
+ return { done: false, outcome: { kind: 'conflicts', from: fromBranch, mergeBase, ours, theirs, files, unresolved } };
1365
1504
  }
1366
- if (conflictPaths.length === 0)
1505
+ for (const p of conflicted)
1506
+ await this.applyResolution(cwd, opts.resolutions.get(p));
1507
+ const still = await this.conflictedPaths(cwd);
1508
+ if (still.length > 0)
1509
+ throw new Error(`still conflicted after the resolutions were applied: ${still.join(', ')}`);
1510
+ return {
1511
+ done: true,
1512
+ outcome: await this.commitMerge(workspaceId, cwd, branch, fromBranch, user, opts, conflicted),
1513
+ };
1514
+ });
1515
+ }
1516
+ // A clean merge: committed whatever it staged — an empty diff (the two
1517
+ // sides made the same change) is still the source's history joined.
1518
+ return this.settleMerge(cwd, async () => {
1519
+ if (opts.resolutions.size > 0)
1520
+ throw noConflictsFor();
1521
+ return { done: true, outcome: await this.commitMerge(workspaceId, cwd, branch, fromBranch, user, opts, []) };
1522
+ });
1523
+ }
1524
+ /**
1525
+ * Run `work` while a merge may be on disk, and leave none: an answer with
1526
+ * `done: false` (a conflict described, nothing to merge) is aborted before
1527
+ * it is returned, and a failure anywhere in `work` is aborted before it is
1528
+ * rethrown. A commit that landed (`done: true`) needs no abort. An abort
1529
+ * that fails while a merge is still in progress is the one thing never
1530
+ * swallowed: it is reported with the failure it followed.
1531
+ */
1532
+ async settleMerge(cwd, work) {
1533
+ let result;
1534
+ try {
1535
+ result = await work();
1536
+ }
1537
+ catch (err) {
1538
+ await this.abortMerge(cwd, err);
1539
+ throw err;
1540
+ }
1541
+ if (!result.done)
1542
+ await this.abortMerge(cwd);
1543
+ return result.outcome;
1544
+ }
1545
+ /**
1546
+ * `git merge --abort`, and proof that nothing is left: a failed abort with
1547
+ * no `MERGE_HEAD` is the benign "no merge to abort"; one that leaves
1548
+ * `MERGE_HEAD` behind is thrown (wrapping `after`, the failure that led
1549
+ * here, when there is one), because the checkout is now stuck.
1550
+ */
1551
+ async abortMerge(cwd, after) {
1552
+ try {
1553
+ await this.git(cwd, ['merge', '--abort']);
1554
+ return;
1555
+ }
1556
+ catch (abortErr) {
1557
+ const merging = await this.refExists(cwd, 'MERGE_HEAD').catch(() => true);
1558
+ if (!merging)
1559
+ return;
1560
+ const detail = redactGitToken(abortErr instanceof Error ? abortErr.message : String(abortErr), this.credentials.token());
1561
+ log.error(`a merge in ${cwd} could not be undone; the checkout is left mid-merge:`, { detail });
1562
+ const lead = after === undefined ? 'the merge could not be undone' : `${after instanceof Error ? after.message : String(after)}; and the merge could not be undone`;
1563
+ throw new Error(`${lead}: ${detail}`, { cause: after ?? abortErr });
1564
+ }
1565
+ }
1566
+ /** The merge commit, as `user`, and its publish when asked for. The caller settles a failure. */
1567
+ async commitMerge(workspaceId, cwd, branch, fromBranch, user, opts, resolvedPaths) {
1568
+ await this.git(cwd, ['commit', `--author=${user.name} <${user.email}>`, '-m', opts.subject, '-m', opts.body]);
1569
+ this.accessControl?.invalidate(workspaceId);
1570
+ // The publish runs here, inside the reservation the merge was made in,
1571
+ // over this checkout's own push and pull-rebase (the merge kept as a
1572
+ // merge) — the caller's policy, the git layer's moves. Whatever it
1573
+ // throws leaves the merge commit on the branch locally; a replay that
1574
+ // conflicts aborts itself (`rebaseOntoRemote`), so the checkout is clean.
1575
+ if (opts.publish) {
1576
+ await opts.publish({
1577
+ push: () => this.pushUnlocked(workspaceId, cwd, user),
1578
+ pullRebase: () => this.pullUnlocked(workspaceId, cwd, { preserveMerges: true }),
1579
+ });
1580
+ }
1581
+ // Read AFTER the publish: a push the host rejected is retried with the
1582
+ // local commits replayed onto the moved branch, which gives the merge
1583
+ // commit a new id — the one that is now the published tip.
1584
+ const sha = (await this.git(cwd, ['rev-parse', 'HEAD'])).stdout.trim();
1585
+ return { kind: 'merged', sha, from: fromBranch, resolvedPaths };
1586
+ }
1587
+ /**
1588
+ * One conflicted path as the merge on disk has it: the three index stages
1589
+ * (base, ours, theirs) and the working copy with git's markers. A side that
1590
+ * is not there (a delete on that side) is null; one that is not text or too
1591
+ * large to carry is left out and marked, for the caller to read at the
1592
+ * commit instead. Read while the merge is on disk — the stages exist only
1593
+ * then.
1594
+ */
1595
+ async describeConflict(cwd, repoRelativePath) {
1596
+ const truncated = [];
1597
+ const side = async (name, stage) => {
1598
+ let bytes;
1599
+ try {
1600
+ bytes = (await this.gitRunner.run(cwd, ['show', `:${stage}:${repoRelativePath}`], { encoding: 'buffer' })).stdout;
1601
+ }
1602
+ catch (err) {
1603
+ // ONLY a stage git says is not there is a side that has no file (that
1604
+ // side deleted it; the base never had it). Anything else — a deadline,
1605
+ // a repository failure — is not "deleted", and reporting it as such
1606
+ // would have a resolver drop a file over a hiccup.
1607
+ const msg = err.stderr ?? (err instanceof Error ? err.message : String(err));
1608
+ if (/is in the index, but not at stage|does not exist in|exists on disk, but not in|invalid object name/i.test(msg))
1609
+ return null;
1610
+ throw err;
1611
+ }
1612
+ return this.carriedText(bytes, () => truncated.push(name));
1613
+ };
1614
+ const base = await side('base', 1);
1615
+ const ours = await side('ours', 2);
1616
+ const theirs = await side('theirs', 3);
1617
+ let merged = null;
1618
+ // The working copy is read from disk, so it is read only where that
1619
+ // stays inside the checkout: a link (the path itself, or a folder on
1620
+ // the way to it) is never followed — the side is left out instead.
1621
+ const file = path.join(cwd, repoRelativePath);
1622
+ const leaf = await lstatOrNull(file);
1623
+ if (leaf?.isSymbolicLink() || (await linkedAncestor(cwd, path.dirname(file))) !== null) {
1624
+ truncated.push('merged');
1625
+ }
1626
+ else {
1627
+ try {
1628
+ merged = this.carriedText(await fs.readFile(file), () => truncated.push('merged'));
1629
+ }
1630
+ catch (err) {
1631
+ if (!isAbsence(err))
1367
1632
  throw err;
1368
- return { kind: 'conflicts', paths: conflictPaths };
1369
- }
1370
- // No conflicts. Detect "already up to date" — git prints that exact
1371
- // phrase and stages nothing. Otherwise the merge is staged and waiting
1372
- // for the commit we now author as `user`.
1373
- if (/Already up to date/i.test(mergeStdout)) {
1374
- return { kind: 'clean', alreadyUpToDate: true };
1375
- }
1376
- const subject = `Refresh ${sourceBranch} from ${targetBranch}`;
1377
- const body = `Workflow auto-merge: incorporates the latest ${targetBranch} into ${sourceBranch} ` +
1378
- `as part of opening or refreshing a change request. ` +
1379
- `Conflicts (if any) would have been surfaced to the caller before this commit landed; ` +
1380
- `none were detected, so the merge applied cleanly.`;
1381
- await this.git(cwd, [
1382
- 'commit',
1383
- `--author=${user.name} <${user.email}>`,
1384
- '-m', subject,
1385
- '-m', body,
1386
- ]);
1387
- this.accessControl?.invalidate(workspaceId);
1388
- return { kind: 'clean', alreadyUpToDate: false };
1633
+ }
1634
+ }
1635
+ return { path: repoRelativePath, base, ours, theirs, merged, ...(truncated.length > 0 ? { truncated } : {}) };
1636
+ }
1637
+ /**
1638
+ * `bytes` as text when they are text by the one rule every reader applies
1639
+ * (`utf8Text`: no NUL, valid UTF-8, BOM kept) and small enough to carry;
1640
+ * else null, and `left` is told.
1641
+ */
1642
+ carriedText(bytes, left) {
1643
+ const text = bytes.length > GitService.CONFLICT_SIDE_MAX_CHARS ? null : utf8Text(bytes);
1644
+ if (text === null)
1645
+ left();
1646
+ return text;
1647
+ }
1648
+ /**
1649
+ * Settle one conflicted path on disk and in the index, as the resolution
1650
+ * says. `r.path` is one the merge itself listed as conflicted (matched
1651
+ * exactly by the caller), so it is a path git owns inside the checkout.
1652
+ * A side kept whole is restored by git from its index stage, byte for
1653
+ * byte — never through a text decoding — so a binary file survives it.
1654
+ */
1655
+ async applyResolution(cwd, r) {
1656
+ const file = path.join(cwd, r.path);
1657
+ // Written and removed where that stays inside the checkout: a folder on
1658
+ // the way that is a link is refused, and a path that is itself a link is
1659
+ // replaced as a path (the link removed first), never written through.
1660
+ if ((await linkedAncestor(cwd, path.dirname(file))) !== null) {
1661
+ throw new WorkflowValidationError(`"${r.path}" is reached through a link, so it is not resolved here`);
1662
+ }
1663
+ if (r.content !== undefined) {
1664
+ if ((await lstatOrNull(file))?.isSymbolicLink())
1665
+ await fs.unlink(file);
1666
+ await fs.mkdir(path.dirname(file), { recursive: true });
1667
+ await fs.writeFile(file, r.content, 'utf-8');
1668
+ await this.git(cwd, ['add', '--', r.path]);
1669
+ return;
1670
+ }
1671
+ if (r.choose === 'delete') {
1672
+ // `rm` removes a link itself, never what it points at.
1673
+ await fs.rm(file, { force: true });
1674
+ await this.git(cwd, ['add', '-A', '--', r.path]);
1675
+ return;
1676
+ }
1677
+ // `ours`/`theirs`: git checks that side's stage out as it is. A side with
1678
+ // no stage (deleted there) is "does not have our/their version": the
1679
+ // file goes.
1680
+ try {
1681
+ await this.git(cwd, ['checkout', r.choose === 'ours' ? '--ours' : '--theirs', '--', r.path]);
1682
+ }
1683
+ catch (err) {
1684
+ const msg = err instanceof Error ? err.message : String(err);
1685
+ if (!/does not have (our|their) version/i.test(msg))
1686
+ throw err;
1687
+ await fs.rm(file, { force: true });
1688
+ }
1689
+ await this.git(cwd, ['add', '-A', '--', r.path]);
1690
+ }
1691
+ async readFileAtBranch(workspaceId, relativePath, branch, authorize) {
1692
+ assertValidRelativePath(relativePath);
1693
+ assertValidBranchName(branch);
1694
+ const repoRelativePath = this.stripRepoPrefix(relativePath);
1695
+ return this.mutex.run(workspaceId, async () => {
1696
+ const cwd = await this.repoDir(workspaceId);
1697
+ // The PUBLISHED tip: what the branch's own workspace holds and has not
1698
+ // shared is nobody else's to read, so `origin/<branch>` comes first and
1699
+ // the local head serves only a branch origin does not have.
1700
+ const { ref, sha } = await this.resolvePublishedBranch(cwd, branch);
1701
+ // The caller's verdict, at every commit the branch resolves to here
1702
+ // (the served one first), BEFORE anything is said about the path at
1703
+ // it: a refusal that names what the path is (a folder) is an answer
1704
+ // about content the caller may not read.
1705
+ if (authorize)
1706
+ await authorize(await this.branchCommits(cwd, branch, sha));
1707
+ // Per file, as every history read: a folder's content at a commit is
1708
+ // every child's, which the per-file gate never checked.
1709
+ await this.assertNotTreeAtRef(cwd, sha, repoRelativePath, relativePath);
1710
+ return { sha, ref, content: await this.readFileAtRef(workspaceId, sha, repoRelativePath) };
1389
1711
  });
1390
1712
  }
1391
1713
  /**
@@ -1766,17 +2088,25 @@ export class GitService {
1766
2088
  const { stdout } = await this.git(cwd, ['ls-remote', '--heads', 'origin']);
1767
2089
  return stdout.trim().length > 0;
1768
2090
  }
1769
- /** `git rev-parse --verify` that answers null for a rev that does not resolve (an unborn HEAD). */
2091
+ /**
2092
+ * `git rev-parse --verify --quiet`: the commit `rev` names, or null when
2093
+ * the rev is ABSENT (an unborn HEAD, a ref nobody made) — and nothing
2094
+ * else. Git says "absent" with exit 1 and an empty stderr; a lookup that
2095
+ * fails any other way (a corrupt repository, a deadline) throws, because
2096
+ * every caller reads null as a fact about the repository — "unborn",
2097
+ * "no such tip", "nothing to authorize at" — and a failure dressed as that
2098
+ * fact would make a sync reset an unborn clone or a verdict list lose a
2099
+ * commit.
2100
+ */
1770
2101
  async revParseOrNull(cwd, rev) {
1771
2102
  try {
1772
2103
  const { stdout } = await this.git(cwd, ['rev-parse', '--verify', '--quiet', rev]);
1773
2104
  return stdout.trim() || null;
1774
2105
  }
1775
2106
  catch (err) {
1776
- // Null is "no such rev"; a deadline is not that answer (see GitRunError).
1777
- if (isGitTimeout(err))
1778
- throw err;
1779
- return null;
2107
+ if (err instanceof GitRunError && !err.timedOut && err.exitCode === 1 && (err.stderr ?? '').trim() === '')
2108
+ return null;
2109
+ throw err;
1780
2110
  }
1781
2111
  }
1782
2112
  /**
@@ -1973,23 +2303,24 @@ export class GitService {
1973
2303
  });
1974
2304
  }
1975
2305
  async pull(workspaceId, opts = {}) {
1976
- return this.mutex.run(workspaceId, async () => {
1977
- const cwd = await this.repoDir(workspaceId);
1978
- const branch = await this.checkedOutBranch(cwd);
1979
- // For `treeChanged` (see IGitService.pull): TREE ids, not commit ids —
1980
- // a pull that lands only content-identical commits (an empty commit)
1981
- // must not read as a content change. Tolerant of an unborn HEAD (a
1982
- // clone of an empty upstream): "" before + a tree after correctly
1983
- // reads as changed, "" both sides as not.
1984
- const treeBefore = (await this.revParseOrNull(cwd, 'HEAD^{tree}')) ?? '';
1985
- // Refresh WITHOUT `git pull`, and without touching `FETCH_HEAD` — see
1986
- // `refreshRemoteBranchRef` for why both halves are load-bearing.
1987
- const remoteRef = await this.refreshRemoteBranchRef(cwd, branch);
1988
- await this.rebaseOntoRemote(cwd, branch, remoteRef, opts);
1989
- this.accessControl?.invalidate(workspaceId);
1990
- const treeAfter = (await this.revParseOrNull(cwd, 'HEAD^{tree}')) ?? '';
1991
- return { treeChanged: treeAfter !== treeBefore };
1992
- });
2306
+ return this.mutex.run(workspaceId, async () => this.pullUnlocked(workspaceId, await this.repoDir(workspaceId), opts));
2307
+ }
2308
+ /** `pull`'s body, for a caller that already holds the workspace's reservation. */
2309
+ async pullUnlocked(workspaceId, cwd, opts = {}) {
2310
+ const branch = await this.checkedOutBranch(cwd);
2311
+ // For `treeChanged` (see IGitService.pull): TREE ids, not commit ids —
2312
+ // a pull that lands only content-identical commits (an empty commit)
2313
+ // must not read as a content change. Tolerant of an unborn HEAD (a
2314
+ // clone of an empty upstream): "" before + a tree after correctly
2315
+ // reads as changed, "" both sides as not.
2316
+ const treeBefore = (await this.revParseOrNull(cwd, 'HEAD^{tree}')) ?? '';
2317
+ // Refresh WITHOUT `git pull`, and without touching `FETCH_HEAD` — see
2318
+ // `refreshRemoteBranchRef` for why both halves are load-bearing.
2319
+ const remoteRef = await this.refreshRemoteBranchRef(cwd, branch);
2320
+ await this.rebaseOntoRemote(cwd, branch, remoteRef, opts);
2321
+ this.accessControl?.invalidate(workspaceId);
2322
+ const treeAfter = (await this.revParseOrNull(cwd, 'HEAD^{tree}')) ?? '';
2323
+ return { treeChanged: treeAfter !== treeBefore };
1993
2324
  }
1994
2325
  /**
1995
2326
  * Does the checked-out branch carry commits its remote-tracking ref
@@ -2414,7 +2745,7 @@ export class GitService {
2414
2745
  return { baseline, current };
2415
2746
  });
2416
2747
  }
2417
- async diffFileBetweenBranches(workspaceId, relativePath, fromBranch, toBranch) {
2748
+ async diffFileBetweenBranches(workspaceId, relativePath, fromBranch, toBranch, authorize) {
2418
2749
  assertValidRelativePath(relativePath);
2419
2750
  assertValidBranchName(fromBranch);
2420
2751
  assertValidBranchName(toBranch);
@@ -2424,8 +2755,21 @@ export class GitService {
2424
2755
  const repoRelativePath = this.stripRepoPrefix(relativePath);
2425
2756
  return this.mutex.run(workspaceId, async () => {
2426
2757
  const cwd = await this.repoDir(workspaceId);
2427
- const fromRef = await this.resolveBranchRef(cwd, fromBranch);
2428
- const toRef = await this.resolveBranchRef(cwd, toBranch);
2758
+ // Each side's COMMIT, read once here and diffed from here on: what the
2759
+ // caller authorizes the answer at. The ref is a name a fetch may move.
2760
+ const fromRef = (await this.git(cwd, ['rev-parse', await this.resolveBranchRef(cwd, fromBranch)])).stdout.trim();
2761
+ const toRef = (await this.git(cwd, ['rev-parse', await this.resolveBranchRef(cwd, toBranch)])).stdout.trim();
2762
+ const pinned = (diff) => ({ diff, from: fromRef, to: toRef });
2763
+ // The caller's verdict at every commit each side resolves to here (the
2764
+ // served one first) BEFORE anything is said about the path at either:
2765
+ // a refusal that names what the path is there (a folder) is an answer
2766
+ // about content the caller may not read.
2767
+ if (authorize) {
2768
+ await authorize({
2769
+ from: await this.branchCommits(cwd, fromBranch, fromRef),
2770
+ to: await this.branchCommits(cwd, toBranch, toRef),
2771
+ });
2772
+ }
2429
2773
  await this.assertNotTreeAtRef(cwd, fromRef, repoRelativePath, relativePath);
2430
2774
  await this.assertNotTreeAtRef(cwd, toRef, repoRelativePath, relativePath);
2431
2775
  // When one side is the currently-checked-out branch, diff against the
@@ -2443,7 +2787,7 @@ export class GitService {
2443
2787
  // same pattern diffFileWorking uses for HEAD-vs-working-tree.
2444
2788
  if (isToCurrent !== isFromCurrent &&
2445
2789
  (await this.isPathUntracked(cwd, repoRelativePath))) {
2446
- return synthesizeUntrackedSideDiff(cwd, repoRelativePath, isToCurrent ? 'added' : 'removed');
2790
+ return pinned(await synthesizeUntrackedSideDiff(cwd, repoRelativePath, isToCurrent ? 'added' : 'removed'));
2447
2791
  }
2448
2792
  const args = ['diff', '--no-color'];
2449
2793
  if (isToCurrent && !isFromCurrent) {
@@ -2467,7 +2811,7 @@ export class GitService {
2467
2811
  args.push('--', repoRelativePath);
2468
2812
  try {
2469
2813
  const { stdout } = await this.git(cwd, args);
2470
- return stdout;
2814
+ return pinned(stdout);
2471
2815
  }
2472
2816
  catch (err) {
2473
2817
  const msg = err instanceof Error ? err.message : String(err);
@@ -3260,6 +3604,26 @@ export class GitService {
3260
3604
  }
3261
3605
  throw new WorkflowValidationError(`unknown branch: ${branch}`);
3262
3606
  }
3607
+ /**
3608
+ * Every commit `branch` resolves to in this repository — its local head
3609
+ * and its published tip (`origin/<branch>`), whichever resolve, deduped,
3610
+ * `served` first. What a caller's read verdict is asked at: content of
3611
+ * another branch is served from one of them, and a grant at the served one
3612
+ * must not outrun a denial at the other (a draft's unshared commits may
3613
+ * carry rules its published tip does not, and the other way round) — the
3614
+ * rule the compare route always applied to both refs, pinned to commits.
3615
+ */
3616
+ async branchCommits(cwd, branch, served) {
3617
+ const commits = [served];
3618
+ for (const ref of [`refs/heads/${branch}`, `refs/remotes/origin/${branch}`]) {
3619
+ // Null is ABSENT and nothing else (`revParseOrNull`): a lookup that
3620
+ // fails otherwise throws, so this list never quietly loses a commit.
3621
+ const sha = await this.revParseOrNull(cwd, ref);
3622
+ if (sha && !commits.includes(sha))
3623
+ commits.push(sha);
3624
+ }
3625
+ return commits;
3626
+ }
3263
3627
  /**
3264
3628
  * Resolve a branch name to a concrete ref the local clone knows about.
3265
3629
  * Tries the local head first, falls back to the matching remote-tracking