@bevel-software/platform-core-backend 0.25.0 → 0.26.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 (254) hide show
  1. package/agent-guide/access-control.md +234 -0
  2. package/agent-guide/conventions.md +27 -0
  3. package/agent-guide/directory-structure.md +145 -0
  4. package/agent-guide/finding-things.md +7 -0
  5. package/agent-guide/introduction.md +27 -0
  6. package/agent-guide/skills.md +47 -0
  7. package/agent-guide/tool-manuals.md +217 -0
  8. package/agent-guide/where-a-new-file-goes.md +36 -0
  9. package/dist/assets.d.ts +7 -0
  10. package/dist/assets.d.ts.map +1 -1
  11. package/dist/assets.js +9 -0
  12. package/dist/assets.js.map +1 -1
  13. package/dist/core/core-ports.d.ts +11 -0
  14. package/dist/core/core-ports.d.ts.map +1 -1
  15. package/dist/core/core-ports.js.map +1 -1
  16. package/dist/core/create-core-server.d.ts.map +1 -1
  17. package/dist/core/create-core-server.js +13 -2
  18. package/dist/core/create-core-server.js.map +1 -1
  19. package/dist/core/create-core-services.d.ts +9 -0
  20. package/dist/core/create-core-services.d.ts.map +1 -1
  21. package/dist/core/create-core-services.js +14 -4
  22. package/dist/core/create-core-services.js.map +1 -1
  23. package/dist/index.d.ts +1 -1
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +2 -2
  26. package/dist/index.js.map +1 -1
  27. package/dist/modules/access/access-control.interface.d.ts +9 -0
  28. package/dist/modules/access/access-control.interface.d.ts.map +1 -1
  29. package/dist/modules/access/access-control.service.d.ts +1 -0
  30. package/dist/modules/access/access-control.service.d.ts.map +1 -1
  31. package/dist/modules/access/access-control.service.js +16 -0
  32. package/dist/modules/access/access-control.service.js.map +1 -1
  33. package/dist/modules/agent-guide/agent-guide.d.ts +139 -0
  34. package/dist/modules/agent-guide/agent-guide.d.ts.map +1 -0
  35. package/dist/modules/agent-guide/agent-guide.js +191 -0
  36. package/dist/modules/agent-guide/agent-guide.js.map +1 -0
  37. package/dist/modules/agent-guide/agent-guide.tools.d.ts +24 -0
  38. package/dist/modules/agent-guide/agent-guide.tools.d.ts.map +1 -0
  39. package/dist/modules/agent-guide/agent-guide.tools.js +100 -0
  40. package/dist/modules/agent-guide/agent-guide.tools.js.map +1 -0
  41. package/dist/modules/agent-guide/index.d.ts +4 -0
  42. package/dist/modules/agent-guide/index.d.ts.map +1 -0
  43. package/dist/modules/agent-guide/index.js +4 -0
  44. package/dist/modules/agent-guide/index.js.map +1 -0
  45. package/dist/modules/agent-instructions/agent-instructions.routes.d.ts +3 -2
  46. package/dist/modules/agent-instructions/agent-instructions.routes.d.ts.map +1 -1
  47. package/dist/modules/agent-instructions/agent-instructions.routes.js +3 -2
  48. package/dist/modules/agent-instructions/agent-instructions.routes.js.map +1 -1
  49. package/dist/modules/agent-instructions/compose.d.ts +9 -6
  50. package/dist/modules/agent-instructions/compose.d.ts.map +1 -1
  51. package/dist/modules/agent-instructions/compose.js +9 -6
  52. package/dist/modules/agent-instructions/compose.js.map +1 -1
  53. package/dist/modules/agent-instructions/index.d.ts +1 -1
  54. package/dist/modules/agent-instructions/index.d.ts.map +1 -1
  55. package/dist/modules/agent-instructions/index.js +1 -1
  56. package/dist/modules/agent-instructions/index.js.map +1 -1
  57. package/dist/modules/agent-instructions/shared-file-rules.d.ts +10 -50
  58. package/dist/modules/agent-instructions/shared-file-rules.d.ts.map +1 -1
  59. package/dist/modules/agent-instructions/shared-file-rules.js +32 -85
  60. package/dist/modules/agent-instructions/shared-file-rules.js.map +1 -1
  61. package/dist/modules/mcp/mcp.service.d.ts +29 -2
  62. package/dist/modules/mcp/mcp.service.d.ts.map +1 -1
  63. package/dist/modules/mcp/mcp.service.js +113 -16
  64. package/dist/modules/mcp/mcp.service.js.map +1 -1
  65. package/dist/modules/mcp/tool-schema-guard.d.ts +105 -0
  66. package/dist/modules/mcp/tool-schema-guard.d.ts.map +1 -0
  67. package/dist/modules/mcp/tool-schema-guard.js +171 -0
  68. package/dist/modules/mcp/tool-schema-guard.js.map +1 -0
  69. package/dist/modules/plugins/plugins.tools.d.ts +36 -2
  70. package/dist/modules/plugins/plugins.tools.d.ts.map +1 -1
  71. package/dist/modules/plugins/plugins.tools.js +71 -14
  72. package/dist/modules/plugins/plugins.tools.js.map +1 -1
  73. package/dist/modules/settings/deployment-settings.service.d.ts +0 -7
  74. package/dist/modules/settings/deployment-settings.service.d.ts.map +1 -1
  75. package/dist/modules/settings/deployment-settings.service.js +14 -53
  76. package/dist/modules/settings/deployment-settings.service.js.map +1 -1
  77. package/dist/modules/settings/setup.routes.d.ts.map +1 -1
  78. package/dist/modules/settings/setup.routes.js +3 -6
  79. package/dist/modules/settings/setup.routes.js.map +1 -1
  80. package/dist/modules/skills/skills.tools.d.ts.map +1 -1
  81. package/dist/modules/skills/skills.tools.js +58 -16
  82. package/dist/modules/skills/skills.tools.js.map +1 -1
  83. package/dist/modules/tool-manuals/tool-manuals.contract.d.ts +23 -4
  84. package/dist/modules/tool-manuals/tool-manuals.contract.d.ts.map +1 -1
  85. package/dist/modules/tool-manuals/tool-manuals.contract.js.map +1 -1
  86. package/dist/modules/tool-manuals/tool-manuals.service.d.ts +4 -0
  87. package/dist/modules/tool-manuals/tool-manuals.service.d.ts.map +1 -1
  88. package/dist/modules/tool-manuals/tool-manuals.service.js +14 -0
  89. package/dist/modules/tool-manuals/tool-manuals.service.js.map +1 -1
  90. package/dist/modules/tool-manuals/tool-manuals.tools.d.ts +7 -0
  91. package/dist/modules/tool-manuals/tool-manuals.tools.d.ts.map +1 -1
  92. package/dist/modules/tool-manuals/tool-manuals.tools.js +66 -36
  93. package/dist/modules/tool-manuals/tool-manuals.tools.js.map +1 -1
  94. package/dist/modules/tool-registry/description-length.d.ts +14 -14
  95. package/dist/modules/tool-registry/description-length.d.ts.map +1 -1
  96. package/dist/modules/tool-registry/description-length.js +24 -26
  97. package/dist/modules/tool-registry/description-length.js.map +1 -1
  98. package/dist/modules/tool-registry/guide-first.d.ts +23 -0
  99. package/dist/modules/tool-registry/guide-first.d.ts.map +1 -0
  100. package/dist/modules/tool-registry/guide-first.js +32 -0
  101. package/dist/modules/tool-registry/guide-first.js.map +1 -0
  102. package/dist/modules/tool-registry/tool-registry.d.ts +6 -0
  103. package/dist/modules/tool-registry/tool-registry.d.ts.map +1 -1
  104. package/dist/modules/tool-registry/tool-registry.js +9 -2
  105. package/dist/modules/tool-registry/tool-registry.js.map +1 -1
  106. package/dist/modules/workflow/agent-tools/change-request-read-shape.d.ts +449 -0
  107. package/dist/modules/workflow/agent-tools/change-request-read-shape.d.ts.map +1 -0
  108. package/dist/modules/workflow/agent-tools/change-request-read-shape.js +481 -0
  109. package/dist/modules/workflow/agent-tools/change-request-read-shape.js.map +1 -0
  110. package/dist/modules/workflow/agent-tools/change-request-read.tools.d.ts +73 -0
  111. package/dist/modules/workflow/agent-tools/change-request-read.tools.d.ts.map +1 -0
  112. package/dist/modules/workflow/agent-tools/change-request-read.tools.js +582 -0
  113. package/dist/modules/workflow/agent-tools/change-request-read.tools.js.map +1 -0
  114. package/dist/modules/workflow/agent-tools/change-request-summary.d.ts +12 -1
  115. package/dist/modules/workflow/agent-tools/change-request-summary.d.ts.map +1 -1
  116. package/dist/modules/workflow/agent-tools/change-request-summary.js +5 -1
  117. package/dist/modules/workflow/agent-tools/change-request-summary.js.map +1 -1
  118. package/dist/modules/workflow/agent-tools/workflow.tools.d.ts.map +1 -1
  119. package/dist/modules/workflow/agent-tools/workflow.tools.js +9 -0
  120. package/dist/modules/workflow/agent-tools/workflow.tools.js.map +1 -1
  121. package/dist/modules/workflow/git/git.service.d.ts +210 -13
  122. package/dist/modules/workflow/git/git.service.d.ts.map +1 -1
  123. package/dist/modules/workflow/git/git.service.js +456 -91
  124. package/dist/modules/workflow/git/git.service.js.map +1 -1
  125. package/dist/modules/workflow/git/merge-commit.d.ts +73 -0
  126. package/dist/modules/workflow/git/merge-commit.d.ts.map +1 -0
  127. package/dist/modules/workflow/git/merge-commit.js +89 -0
  128. package/dist/modules/workflow/git/merge-commit.js.map +1 -0
  129. package/dist/modules/workflow/git/pull-request.service.d.ts +94 -1
  130. package/dist/modules/workflow/git/pull-request.service.d.ts.map +1 -1
  131. package/dist/modules/workflow/git/pull-request.service.js +332 -37
  132. package/dist/modules/workflow/git/pull-request.service.js.map +1 -1
  133. package/dist/modules/workflow/review-workflow/review-workflow.service.d.ts +35 -0
  134. package/dist/modules/workflow/review-workflow/review-workflow.service.d.ts.map +1 -1
  135. package/dist/modules/workflow/review-workflow/review-workflow.service.js +178 -12
  136. package/dist/modules/workflow/review-workflow/review-workflow.service.js.map +1 -1
  137. package/dist/modules/workflow/workflow.routes.d.ts +6 -2
  138. package/dist/modules/workflow/workflow.routes.d.ts.map +1 -1
  139. package/dist/modules/workflow/workflow.routes.js +7 -2
  140. package/dist/modules/workflow/workflow.routes.js.map +1 -1
  141. package/dist/modules/workflow/workflow.service.d.ts +4 -0
  142. package/dist/modules/workflow/workflow.service.d.ts.map +1 -1
  143. package/dist/modules/workflow/workflow.service.js +3 -0
  144. package/dist/modules/workflow/workflow.service.js.map +1 -1
  145. package/dist/modules/workspace/startup/kb-startup-runner.d.ts +70 -0
  146. package/dist/modules/workspace/startup/kb-startup-runner.d.ts.map +1 -1
  147. package/dist/modules/workspace/startup/kb-startup-runner.js +213 -20
  148. package/dist/modules/workspace/startup/kb-startup-runner.js.map +1 -1
  149. package/dist/modules/workspace/startup/steps/seed-tree.d.ts.map +1 -1
  150. package/dist/modules/workspace/startup/steps/seed-tree.js +22 -27
  151. package/dist/modules/workspace/startup/steps/seed-tree.js.map +1 -1
  152. package/dist/modules/workspace/startup/steps/template-files.step.d.ts +58 -52
  153. package/dist/modules/workspace/startup/steps/template-files.step.d.ts.map +1 -1
  154. package/dist/modules/workspace/startup/steps/template-files.step.js +209 -223
  155. package/dist/modules/workspace/startup/steps/template-files.step.js.map +1 -1
  156. package/dist/modules/workspace/startup/steps/template-source.d.ts +5 -3
  157. package/dist/modules/workspace/startup/steps/template-source.d.ts.map +1 -1
  158. package/dist/modules/workspace/startup/steps/template-source.js +5 -3
  159. package/dist/modules/workspace/startup/steps/template-source.js.map +1 -1
  160. package/dist/modules/workspace/workspace.tools.d.ts +10 -1
  161. package/dist/modules/workspace/workspace.tools.d.ts.map +1 -1
  162. package/dist/modules/workspace/workspace.tools.js +211 -18
  163. package/dist/modules/workspace/workspace.tools.js.map +1 -1
  164. package/dist/shared/domain-errors.d.ts +11 -0
  165. package/dist/shared/domain-errors.d.ts.map +1 -1
  166. package/dist/shared/domain-errors.js +14 -0
  167. package/dist/shared/domain-errors.js.map +1 -1
  168. package/dist/shared/hidden-tools.d.ts +44 -0
  169. package/dist/shared/hidden-tools.d.ts.map +1 -0
  170. package/dist/shared/hidden-tools.js +13 -0
  171. package/dist/shared/hidden-tools.js.map +1 -0
  172. package/kb-template/.bevelignore +0 -5
  173. package/package.json +4 -3
  174. package/src/__tests__/kb-layout-config.test.ts +10 -100
  175. package/src/__tests__/packaged-assets-ship.test.ts +54 -0
  176. package/src/assets.ts +10 -0
  177. package/src/core/core-ports.ts +11 -0
  178. package/src/core/create-core-server.ts +13 -2
  179. package/src/core/create-core-services.ts +28 -4
  180. package/src/index.ts +2 -2
  181. package/src/modules/access/__tests__/access-control.atref-batch.test.ts +58 -0
  182. package/src/modules/access/__tests__/access-control.platform-restore.test.ts +8 -7
  183. package/src/modules/access/__tests__/access-personal-plugin.test.ts +1 -18
  184. package/src/modules/access/access-control.interface.ts +15 -0
  185. package/src/modules/access/access-control.service.ts +21 -0
  186. package/src/modules/agent-guide/__tests__/agent-guide.test.ts +328 -0
  187. package/src/modules/agent-guide/__tests__/agent-guide.tools.test.ts +189 -0
  188. package/src/modules/agent-guide/agent-guide.tools.ts +122 -0
  189. package/src/modules/agent-guide/agent-guide.ts +291 -0
  190. package/src/modules/agent-guide/index.ts +21 -0
  191. package/src/modules/agent-instructions/__tests__/shared-file-rules.test.ts +28 -121
  192. package/src/modules/agent-instructions/agent-instructions.routes.ts +3 -2
  193. package/src/modules/agent-instructions/compose.ts +9 -6
  194. package/src/modules/agent-instructions/index.ts +0 -3
  195. package/src/modules/agent-instructions/shared-file-rules.ts +31 -93
  196. package/src/modules/mcp/__tests__/fake-downstream-mcp-server.ts +14 -3
  197. package/src/modules/mcp/__tests__/mcp.e2e.test.ts +250 -0
  198. package/src/modules/mcp/__tests__/mcp.service.test.ts +31 -23
  199. package/src/modules/mcp/__tests__/tool-schema-guard.test.ts +266 -0
  200. package/src/modules/mcp/mcp.service.ts +137 -19
  201. package/src/modules/mcp/tool-schema-guard.ts +196 -0
  202. package/src/modules/plugins/__tests__/plugins.tools.test.ts +154 -4
  203. package/src/modules/plugins/plugins.tools.ts +75 -15
  204. package/src/modules/settings/__tests__/deployment-settings.service.test.ts +26 -55
  205. package/src/modules/settings/deployment-settings.service.ts +13 -54
  206. package/src/modules/settings/setup.routes.ts +3 -6
  207. package/src/modules/skills/__tests__/skills.tools.description.test.ts +91 -0
  208. package/src/modules/skills/skills.tools.ts +62 -16
  209. package/src/modules/tool-manuals/__tests__/tool-manuals.detail.route.test.ts +57 -0
  210. package/src/modules/tool-manuals/__tests__/tool-manuals.tools.test.ts +73 -4
  211. package/src/modules/tool-manuals/tool-manuals.contract.ts +24 -4
  212. package/src/modules/tool-manuals/tool-manuals.service.ts +17 -0
  213. package/src/modules/tool-manuals/tool-manuals.tools.ts +74 -36
  214. package/src/modules/tool-registry/__tests__/own-tool-schemas.test.ts +160 -0
  215. package/src/modules/tool-registry/__tests__/tool-description-length.test.ts +61 -59
  216. package/src/modules/tool-registry/description-length.ts +24 -26
  217. package/src/modules/tool-registry/guide-first.ts +34 -0
  218. package/src/modules/tool-registry/tool-registry.ts +9 -2
  219. package/src/modules/workflow/__tests__/apply-failure.test.ts +6 -1
  220. package/src/modules/workflow/agent-tools/__tests__/change-request-read-shape.test.ts +705 -0
  221. package/src/modules/workflow/agent-tools/__tests__/change-request-read.tools.test.ts +1518 -0
  222. package/src/modules/workflow/agent-tools/__tests__/workflow.tools.test.ts +23 -2
  223. package/src/modules/workflow/agent-tools/change-request-read-shape.ts +712 -0
  224. package/src/modules/workflow/agent-tools/change-request-read.tools.ts +724 -0
  225. package/src/modules/workflow/agent-tools/change-request-summary.ts +5 -1
  226. package/src/modules/workflow/agent-tools/workflow.tools.ts +8 -0
  227. package/src/modules/workflow/git/__tests__/git.service.appliedChange.test.ts +285 -0
  228. package/src/modules/workflow/git/__tests__/git.service.changedFilesForPr.test.ts +124 -0
  229. package/src/modules/workflow/git/__tests__/git.service.mergeChangeRequest.test.ts +334 -0
  230. package/src/modules/workflow/git/__tests__/pull-request.service.list-fetch.test.ts +72 -2
  231. package/src/modules/workflow/git/__tests__/pull-request.service.placeholder.test.ts +24 -2
  232. package/src/modules/workflow/git/__tests__/pull-request.service.test.ts +620 -1
  233. package/src/modules/workflow/git/git.service.ts +537 -94
  234. package/src/modules/workflow/git/merge-commit.ts +88 -0
  235. package/src/modules/workflow/git/pull-request.service.ts +380 -54
  236. package/src/modules/workflow/review-workflow/__tests__/approval-states.test.ts +7 -1
  237. package/src/modules/workflow/review-workflow/__tests__/merge-records-own-commit.test.ts +407 -0
  238. package/src/modules/workflow/review-workflow/review-workflow.service.ts +189 -11
  239. package/src/modules/workflow/workflow.routes.ts +7 -2
  240. package/src/modules/workflow/workflow.service.ts +7 -0
  241. package/src/modules/workspace/__tests__/escape-sequences.routes.test.ts +4 -3
  242. package/src/modules/workspace/__tests__/workspace.routes.move-platform-files.test.ts +21 -10
  243. package/src/modules/workspace/__tests__/workspace.tools.agents-file.test.ts +33 -55
  244. package/src/modules/workspace/__tests__/workspace.tools.test.ts +255 -22
  245. package/src/modules/workspace/startup/__tests__/kb-startup-runner.test.ts +231 -1
  246. package/src/modules/workspace/startup/kb-startup-runner.ts +216 -19
  247. package/src/modules/workspace/startup/steps/__tests__/steps.test.ts +191 -489
  248. package/src/modules/workspace/startup/steps/seed-tree.ts +21 -27
  249. package/src/modules/workspace/startup/steps/template-files.step.ts +217 -249
  250. package/src/modules/workspace/startup/steps/template-source.ts +5 -3
  251. package/src/modules/workspace/workspace.tools.ts +226 -16
  252. package/src/shared/domain-errors.ts +15 -0
  253. package/src/shared/hidden-tools.ts +45 -0
  254. package/kb-template/AGENTS.md +0 -730
@@ -2,8 +2,11 @@ import fs from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { logger } from '../../../shared/logging.js';
4
4
  import type {
5
+ AppliedChangeRef,
6
+ AppliedMergeResult,
5
7
  AuthUser,
6
8
  BranchInfo,
9
+ ChangedPathPair,
7
10
  CommitAttribution,
8
11
  IGitService,
9
12
  RemoteSyncPullResult,
@@ -13,6 +16,7 @@ import type {
13
16
  WorkingTreeStatus,
14
17
  } from '@bevel-software/platform-shared';
15
18
  import { isFolderPlaceholder } from '@bevel-software/platform-shared';
19
+ import { mergeCommitMessageNames } from './merge-commit.js';
16
20
  import type { WorkspaceService } from '../../workspace/workspace.service.js';
17
21
  import type { WorkflowHooks, CommitValidationContext } from '../workflow-hooks.js';
18
22
  import type { IAccessControl } from '../../access/access-control.interface.js';
@@ -29,6 +33,7 @@ import {
29
33
  } from '../../kb-fs/branch-name.js';
30
34
  import type { KbContext } from '../../../shared/kb-context.js';
31
35
  import {
36
+ AppliedChangeMismatchError,
32
37
  BranchAuthorshipError,
33
38
  WorkflowDomainError,
34
39
  WorkflowValidationError,
@@ -1442,7 +1447,9 @@ export class GitService implements IGitService {
1442
1447
  * the new base and re-merge on top of it. Conflicts are deterministic — they
1443
1448
  * return immediately (no retry) so the caller can route into resolution.
1444
1449
  *
1445
- * Returns the merge commit SHA, or the conflicting paths.
1450
+ * Returns the state the target is left at (`sha`) together with the merge
1451
+ * commit this change request owns (`mergeCommit`, null when there is none), or
1452
+ * the conflicting paths.
1446
1453
  */
1447
1454
  async mergeChangeRequest(
1448
1455
  baseWorkspaceId: string,
@@ -1477,11 +1484,33 @@ export class GitService implements IGitService {
1477
1484
  * instead of falling back to the stale one.
1478
1485
  */
1479
1486
  authorize?: (target: { sha: string; changedPaths: string[] }) => Promise<void>;
1487
+ /**
1488
+ * The change request this merge applies, when it is one (the agent
1489
+ * `merge_branch` path merges no request and leaves it unset).
1490
+ *
1491
+ * It is what lets the "nothing to merge" case tell apart a request that
1492
+ * never had anything to land from one whose merge commit an EARLIER
1493
+ * attempt already pushed — see {@link ownMergeCommitOn}. Without it the
1494
+ * second is indistinguishable from the first, and finalizing it would
1495
+ * forget the only commit its files can be read from.
1496
+ */
1497
+ appliedChangeNumber?: number;
1498
+ /** The request's stored title, so a merge commit in the old message format is recognised too. */
1499
+ appliedChangeTitle?: string;
1480
1500
  } = {},
1481
- ): Promise<{ kind: 'merged'; sha: string } | { kind: 'conflicts'; paths: string[] }> {
1501
+ ): Promise<AppliedMergeResult> {
1482
1502
  assertValidBranchName(sourceBranch);
1483
1503
  assertValidBranchName(targetBranch);
1484
1504
  assertValidAuthor(user);
1505
+ // The same single-line rule `commit` applies, and for a sharper reason here:
1506
+ // `git commit -m` takes the first PARAGRAPH of this string as the subject, so
1507
+ // a blank line inside it would silently push everything after the break into
1508
+ // the body — including the `(#N)` an applied request is read back by.
1509
+ // `mergeCommitSubject` already flattens the title it builds from; this is the
1510
+ // guard that keeps any other caller from reintroducing the break.
1511
+ if (/\n\s*\n/.test(commit.subject)) {
1512
+ throw new WorkflowValidationError('merge commit subject must be a single paragraph');
1513
+ }
1485
1514
  const MAX_ATTEMPTS = 3;
1486
1515
  return this.mutex.run(baseWorkspaceId, async () => {
1487
1516
  const cwd = await this.repoDir(baseWorkspaceId);
@@ -1561,13 +1590,29 @@ export class GitService implements IGitService {
1561
1590
  );
1562
1591
  }
1563
1592
 
1564
- // Nothing staged ⇒ base already contains source (empty CR). The base tip
1565
- // is the "merged" state; report it without an empty commit.
1593
+ // Nothing staged ⇒ the target already contains the source. The target tip
1594
+ // is the "merged" state; report it without an empty commit — but NOT as
1595
+ // this request's own merge commit. It is whatever landed on the target
1596
+ // last, usually another request's merge commit, and a reader that took it
1597
+ // for this request's would answer with that other request's files under
1598
+ // this number (cubic P1 on #347).
1599
+ //
1600
+ // There are two ways to arrive here, and they differ in exactly one
1601
+ // thing: whether this request has a merge commit on the target already.
1602
+ // An EMPTY request never had anything to land and has none. A request
1603
+ // whose previous attempt pushed its merge commit and then failed to
1604
+ // finalize the row (a transient database fault between the push and the
1605
+ // update) has one, and it is the only place its file list survives — so
1606
+ // it is looked for rather than assumed absent (cubic P2 on #347).
1566
1607
  const { stdout: staged } = await this.git(cwd, ['diff', '--cached', '--name-only']);
1567
1608
  if (staged.trim() === '') {
1568
1609
  const { stdout: sha } = await this.git(cwd, ['rev-parse', 'HEAD']);
1569
1610
  await this.git(cwd, ['merge', '--abort']).catch(() => undefined);
1570
- return { kind: 'merged' as const, sha: sha.trim() };
1611
+ const own =
1612
+ opts.appliedChangeNumber === undefined
1613
+ ? null
1614
+ : await this.ownMergeCommitOn(cwd, `origin/${targetBranch}`, opts.appliedChangeNumber, opts.appliedChangeTitle);
1615
+ return { kind: 'merged' as const, sha: sha.trim(), mergeCommit: own };
1571
1616
  }
1572
1617
 
1573
1618
  await this.git(cwd, [
@@ -1581,7 +1626,8 @@ export class GitService implements IGitService {
1581
1626
  try {
1582
1627
  await this.git(cwd, ['push', 'origin', `HEAD:refs/heads/${targetBranch}`]);
1583
1628
  this.accessControl?.invalidate(baseWorkspaceId);
1584
- return { kind: 'merged' as const, sha: sha.trim() };
1629
+ // A commit of this request's own, with the subject the reader verifies.
1630
+ return { kind: 'merged' as const, sha: sha.trim(), mergeCommit: sha.trim() };
1585
1631
  } catch (err) {
1586
1632
  const msg = err instanceof Error ? err.message : String(err);
1587
1633
  // Base moved under us — reset to the new tip and re-merge next loop.
@@ -1597,6 +1643,112 @@ export class GitService implements IGitService {
1597
1643
  });
1598
1644
  }
1599
1645
 
1646
+ /**
1647
+ * The merge commit change request `number` OWNS on `targetBranch`, or null when
1648
+ * the target carries none. Asks the published target only — no source branch,
1649
+ * no working tree, nothing merged, nothing written.
1650
+ *
1651
+ * This is the same question {@link mergeChangeRequest} answers for itself when
1652
+ * it finds nothing to merge, asked WITHOUT attempting a merge at all. The
1653
+ * merge path cannot be the only way to ask it: a request whose merge commit
1654
+ * was pushed by an attempt that then failed to record the row has an empty
1655
+ * diff against the target, so the approval gate refuses the retry ("no file
1656
+ * changes to approve") BEFORE any merge runs, and the recovery inside the
1657
+ * merge never gets its turn (cubic P2 on #347). The gate asks here instead.
1658
+ *
1659
+ * The target ref is refreshed first, because the attempt that pushed the
1660
+ * commit may have run in another process or another clone — and a fetch that
1661
+ * FAILS answers null without looking, which is the only safe answer: what the
1662
+ * caller does with a commit is record it as this request's published state, so
1663
+ * a decision taken on a stale tracking ref could finalize a request with a
1664
+ * commit the published branch no longer carries, and a clone that has no
1665
+ * tracking ref at all would turn the gate's clean refusal into a git error
1666
+ * (cubic P1 on #347). No authority, no answer; the caller then refuses exactly
1667
+ * as it did before this method existed.
1668
+ */
1669
+ async appliedMergeCommitOnTarget(
1670
+ baseWorkspaceId: string,
1671
+ targetBranch: string,
1672
+ number: number,
1673
+ title?: string,
1674
+ ): Promise<string | null> {
1675
+ assertValidBranchName(targetBranch);
1676
+ const cwd = await this.repoDir(baseWorkspaceId);
1677
+ // The fetch runs outside the workspace mutex, the way the implicit and
1678
+ // per-request fetches do (see `fetchLocks`, `fetchPrRefs`): it writes only
1679
+ // `refs/remotes/origin/*` and new objects, never HEAD, the index or the
1680
+ // working tree, so nothing it does needs serializing against a checkout or
1681
+ // a commit, and holding the mutex through a network round trip would park
1682
+ // every other git op behind the origin. (`mergeChangeRequest` fetches under
1683
+ // the mutex for a reason this method lacks: its fetch is one step of a
1684
+ // merge whose working tree must not move between the fetch and the push.)
1685
+ // The read that follows is a local one, and takes the mutex like
1686
+ // `appliedChangeShas` does.
1687
+ const refreshed = await this.git(cwd, [
1688
+ 'fetch', '--no-write-fetch-head', 'origin',
1689
+ `+refs/heads/${targetBranch}:refs/remotes/origin/${targetBranch}`,
1690
+ ]).then(() => true, () => false);
1691
+ if (!refreshed) {
1692
+ log.warn(
1693
+ `could not refresh "${targetBranch}" to look for change request #${number}'s merge commit, ` +
1694
+ 'so it is reported as owning none.',
1695
+ );
1696
+ return null;
1697
+ }
1698
+ return this.mutex.run(baseWorkspaceId, () => this.ownMergeCommitOn(cwd, `origin/${targetBranch}`, number, title));
1699
+ }
1700
+
1701
+ /**
1702
+ * The newest merge commit reachable from `targetRef` that is change request
1703
+ * `number`'s OWN, or null if the target carries none.
1704
+ *
1705
+ * Asked when a merge finds nothing to merge, to tell "this request never had
1706
+ * anything to land" apart from "a previous attempt already landed it". The
1707
+ * second happens when the push succeeded and the row update did not — the
1708
+ * merge commit is on the target, and if this attempt then records no sha the
1709
+ * request becomes permanently fileless, readable by its author alone, with the
1710
+ * commit that holds its files still sitting there unreferenced (cubic P2 on
1711
+ * #347).
1712
+ *
1713
+ * The two conditions are the reader's own (`appliedChangeShas`): a merge
1714
+ * commit, whose subject names this number. Deciding it here with the same
1715
+ * predicate means the writer records only what the reader will accept. The
1716
+ * walk is bounded by `--grep` (the number, as a fixed string), which is the
1717
+ * whole of the target's history for commits mentioning the number — and not
1718
+ * by a count: a fixed count of newer merges once hid a stuck request's commit
1719
+ * from the probe on a busy target, and a request that could no longer be
1720
+ * finalized is worse than a log walk. The message check then confirms a
1721
+ * body-only mention is not the request's own. Never on an ordinary merge:
1722
+ * the two callers are the empty-merge case here and
1723
+ * {@link appliedMergeCommitOnTarget}, which the approval gate asks before it
1724
+ * refuses a retry that has nothing left to merge.
1725
+ *
1726
+ * `title` lets the old message format be recognised — see
1727
+ * {@link mergeCommitMessageNames}.
1728
+ */
1729
+ private async ownMergeCommitOn(
1730
+ cwd: string,
1731
+ targetRef: string,
1732
+ number: number,
1733
+ title?: string,
1734
+ ): Promise<string | null> {
1735
+ // The whole message per commit. Records are NUL-separated (`-z`), the one
1736
+ // byte a commit message cannot hold, and the sha is the record's first
1737
+ // line: nothing a title may contain can split a record or a line early.
1738
+ const { stdout } = await this.git(cwd, [
1739
+ 'log', '-z', '--merges', '--fixed-strings', `--grep=(#${number})`,
1740
+ '--format=%H%n%B', targetRef,
1741
+ ]);
1742
+ for (const record of stdout.split('\0')) {
1743
+ const newline = record.indexOf('\n');
1744
+ const sha = (newline === -1 ? record : record.slice(0, newline)).trim();
1745
+ if (!/^[0-9a-f]{40,64}$/.test(sha)) continue;
1746
+ const message = newline === -1 ? '' : record.slice(newline + 1);
1747
+ if (mergeCommitMessageNames(message, number, title)) return sha;
1748
+ }
1749
+ return null;
1750
+ }
1751
+
1600
1752
  /** Conflicted paths from a half-done merge, parsed from porcelain status. */
1601
1753
  private async conflictedPaths(cwd: string): Promise<string[]> {
1602
1754
  const { stdout } = await this.git(cwd, ['status', '--porcelain=v1']);
@@ -2557,73 +2709,265 @@ export class GitService implements IGitService {
2557
2709
  return this.mutex.run(workspaceId, async () => {
2558
2710
  const baseRef = opts.at ? opts.at.baseSha : await this.resolvePublishedBranchRef(cwd, baseBranch);
2559
2711
  const headRef = opts.at ? opts.at.headSha : await this.resolvePublishedBranchRef(cwd, headBranch);
2560
- const range = `${baseRef}...${headRef}`; // three-dot = changes on head since merge-base
2712
+ // three-dot = changes on head since merge-base
2713
+ return this.prFilesForRange(cwd, `${baseRef}...${headRef}`, patchCap);
2714
+ });
2715
+ }
2561
2716
 
2562
- const [{ stdout: nameStatusOut }, { stdout: numstatOut }] = await Promise.all([
2563
- this.git(cwd, ['diff', '-M', '-z', '--name-status', range]),
2564
- this.git(cwd, ['diff', '-M', '-z', '--numstat', range]),
2565
- ]);
2566
- let statuses = parseNameStatusZ(nameStatusOut);
2567
- let counts = parseNumstatZ(numstatOut);
2568
- // roles.yaml can NEVER change through a merge — `preserveBaseRolesYaml`
2569
- // restores the base copy onto the source branch before every merge — so
2570
- // listing it as "changed" claims something the merge will not do, and
2571
- // (worse) makes its approval a requirement for a change that cannot
2572
- // land. Filter it from the review surface entirely; the neutralisation
2573
- // reads the raw refs itself and is unaffected. Both lists are filtered
2574
- // IN STEP so the index-zip below stays aligned.
2575
- // The empty-folder placeholder is filtered the same way: it is never
2576
- // content, so it is not a file to review or approve. It still merges
2577
- // with the rest, and `changedPathsForPr` keeps it, so a request that
2578
- // only creates a folder is not mistaken for an empty one and closed.
2579
- // An empty file deleted as its folder gets the (equally empty)
2580
- // placeholder reads to `-M` as a RENAME onto it; the real side of such
2581
- // a pair is first made the plain removal (or addition) it is, so
2582
- // dropping the placeholder never drops the file with it.
2583
- statuses = statuses.map(withoutPlaceholderRename);
2584
- if (statuses.some((s) => s.path === 'roles.yaml' || isFolderPlaceholder(s.path))) {
2585
- const keep = statuses.map((s) => s.path !== 'roles.yaml' && !isFolderPlaceholder(s.path));
2586
- statuses = statuses.filter((_, i) => keep[i]);
2587
- if (counts.length === keep.length) counts = counts.filter((_, i) => keep[i]);
2588
- }
2717
+ /**
2718
+ * The changed-file list over one already-decided diff `range`, with the
2719
+ * statuses, the +/- counts and up to `patchCap` patches — everything
2720
+ * `changedFilesForPr` does once it knows which two commits it is comparing.
2721
+ *
2722
+ * Separated from the ref resolution because a change request has a second
2723
+ * diff that means exactly the same thing and resolves nothing: the one a
2724
+ * MERGE COMMIT holds, read against its first parent. Both must filter
2725
+ * `roles.yaml` and the folder placeholder the same way and zip the two
2726
+ * `--name-status` / `--numstat` lists by the same index, or a merged request
2727
+ * would answer a different file list from the one it answered while open.
2728
+ *
2729
+ * The caller holds the workspace reservation; this takes none.
2730
+ */
2731
+ private async prFilesForRange(
2732
+ cwd: string,
2733
+ range: string,
2734
+ patchCap: number,
2735
+ ): Promise<PullRequestFile[]> {
2736
+ const [{ stdout: nameStatusOut }, { stdout: numstatOut }] = await Promise.all([
2737
+ this.git(cwd, ['diff', '-M', '-z', '--name-status', range]),
2738
+ this.git(cwd, ['diff', '-M', '-z', '--numstat', range]),
2739
+ ]);
2740
+ let statuses = parseNameStatusZ(nameStatusOut);
2741
+ let counts = parseNumstatZ(numstatOut);
2742
+ // roles.yaml can NEVER change through a merge — `preserveBaseRolesYaml`
2743
+ // restores the base copy onto the source branch before every merge — so
2744
+ // listing it as "changed" claims something the merge will not do, and
2745
+ // (worse) makes its approval a requirement for a change that cannot
2746
+ // land. Filter it from the review surface entirely; the neutralisation
2747
+ // reads the raw refs itself and is unaffected. Both lists are filtered
2748
+ // IN STEP so the index-zip below stays aligned.
2749
+ // The empty-folder placeholder is filtered the same way: it is never
2750
+ // content, so it is not a file to review or approve. It still merges
2751
+ // with the rest, and `changedPathsForPr` keeps it, so a request that
2752
+ // only creates a folder is not mistaken for an empty one and closed.
2753
+ // An empty file deleted as its folder gets the (equally empty)
2754
+ // placeholder reads to `-M` as a RENAME onto it; the real side of such
2755
+ // a pair is first made the plain removal (or addition) it is, so
2756
+ // dropping the placeholder never drops the file with it.
2757
+ statuses = statuses.map(withoutPlaceholderRename);
2758
+ if (statuses.some((s) => s.path === 'roles.yaml' || isFolderPlaceholder(s.path))) {
2759
+ const keep = statuses.map((s) => s.path !== 'roles.yaml' && !isFolderPlaceholder(s.path));
2760
+ statuses = statuses.filter((_, i) => keep[i]);
2761
+ if (counts.length === keep.length) counts = counts.filter((_, i) => keep[i]);
2762
+ }
2589
2763
 
2590
- // `--name-status` and `--numstat` enumerate the same files in the same
2591
- // order (same `-M` over the same range), so we zip by index. If the two
2592
- // ever disagree in length, the index alignment is unsafe — fall back to
2593
- // zeroed counts (statuses/paths stay correct) rather than pin the wrong
2594
- // +/- to a file.
2595
- const aligned = counts.length === statuses.length;
2596
- if (!aligned) {
2597
- crLog.warn(
2598
- `diff name-status/numstat length mismatch (${statuses.length} vs ${counts.length}) ` +
2599
- `for ${range} — reporting file list without +/- counts`,
2600
- );
2601
- }
2764
+ // `--name-status` and `--numstat` enumerate the same files in the same
2765
+ // order (same `-M` over the same range), so we zip by index. If the two
2766
+ // ever disagree in length, the index alignment is unsafe — fall back to
2767
+ // zeroed counts (statuses/paths stay correct) rather than pin the wrong
2768
+ // +/- to a file.
2769
+ const aligned = counts.length === statuses.length;
2770
+ if (!aligned) {
2771
+ crLog.warn(
2772
+ `diff name-status/numstat length mismatch (${statuses.length} vs ${counts.length}) ` +
2773
+ `for ${range} — reporting file list without +/- counts`,
2774
+ );
2775
+ }
2602
2776
 
2603
- const files: PullRequestFile[] = statuses.map((s, i) => {
2604
- const c = (aligned ? counts[i] : undefined) ?? { additions: 0, deletions: 0, isBinary: false };
2605
- return {
2606
- path: s.path,
2607
- previousPath: s.previousPath,
2608
- status: s.status,
2609
- additions: c.additions,
2610
- deletions: c.deletions,
2611
- patch: undefined,
2612
- isBinary: c.isBinary,
2613
- sha: '',
2614
- rawUrl: '',
2615
- };
2616
- });
2777
+ const files: PullRequestFile[] = statuses.map((s, i) => {
2778
+ const c = (aligned ? counts[i] : undefined) ?? { additions: 0, deletions: 0, isBinary: false };
2779
+ return {
2780
+ path: s.path,
2781
+ previousPath: s.previousPath,
2782
+ status: s.status,
2783
+ additions: c.additions,
2784
+ deletions: c.deletions,
2785
+ patch: undefined,
2786
+ isBinary: c.isBinary,
2787
+ sha: '',
2788
+ rawUrl: '',
2789
+ };
2790
+ });
2791
+
2792
+ // Generate per-file patches for the first `patchCap` non-binary files.
2793
+ let generated = 0;
2794
+ for (const f of files) {
2795
+ if (generated >= patchCap) break;
2796
+ if (f.isBinary) continue;
2797
+ f.patch = await this.filePatchForPr(cwd, range, f);
2798
+ generated += 1;
2799
+ }
2800
+ return files;
2801
+ }
2617
2802
 
2618
- // Generate per-file patches for the first `patchCap` non-binary files.
2619
- let generated = 0;
2620
- for (const f of files) {
2621
- if (generated >= patchCap) break;
2622
- if (f.isBinary) continue;
2623
- f.patch = await this.filePatchForPr(cwd, range, f);
2624
- generated += 1;
2803
+ /**
2804
+ * The FIRST PARENT of a commit, resolved — the other end of the diff one
2805
+ * commit introduced, and the check that this clone holds the commit at all.
2806
+ *
2807
+ * This is how an applied change request is read back. Its source branch is
2808
+ * retired, so there are no two branch refs left to diff; what is left is the
2809
+ * merge commit the row records, whose first parent is the target as it stood
2810
+ * before the merge and whose tree is the target with the change in it. The
2811
+ * diff between the two is precisely what the request applied — and it is
2812
+ * immutable, which the branch pair never was.
2813
+ *
2814
+ * First-parent and TWO dots, both deliberately. A three-dot diff would be
2815
+ * read from the merge base of the two parents, i.e. it would re-report the
2816
+ * source branch's whole history rather than what landed. `^1` is the target
2817
+ * side for a merge commit, and for a squashed or fast-forwarded commit it is
2818
+ * simply the commit before — the same answer either way.
2819
+ *
2820
+ * Throws `WorkflowValidationError` whenever the recorded commit cannot be
2821
+ * PROVEN to be this request's own merge commit — see
2822
+ * {@link appliedChangeShas}. Every caller reads that as "the file set could
2823
+ * not be resolved" and falls back to its own fail-closed answer, which is what
2824
+ * a clone that has not fetched the merge yet must get: no files, never
2825
+ * somebody else's.
2826
+ */
2827
+ private async appliedEnds(
2828
+ cwd: string,
2829
+ applied: AppliedChangeRef,
2830
+ ): Promise<{ baseSha: string; headSha: string }> {
2831
+ const { mergeSha, number } = applied;
2832
+ if (!/^[0-9a-f]{40,64}$/.test(mergeSha)) {
2833
+ throw new WorkflowValidationError(`invalid commit sha: ${mergeSha}`);
2834
+ }
2835
+ const revParse = async (rev: string): Promise<string | null> => {
2836
+ try {
2837
+ // One question, both answers: `--verify --quiet` prints what it resolved
2838
+ // and exits 1 if there is nothing to resolve.
2839
+ const { stdout } = await this.git(cwd, ['rev-parse', '--verify', '--quiet', rev]);
2840
+ return stdout.trim();
2841
+ } catch (err) {
2842
+ // Exit 1 under --quiet is git's own "no such object": this clone does
2843
+ // not have the commit, or the commit has no such parent. Anything else
2844
+ // (a deadline, a broken repository) is the caller's to see.
2845
+ if (err instanceof GitRunError && !err.timedOut && err.exitCode === 1) return null;
2846
+ throw err;
2625
2847
  }
2626
- return files;
2848
+ };
2849
+ // Two refusals, told apart for the caller's sake. A commit this clone does
2850
+ // NOT HOLD is a passing state — the next fetch may bring it — and is
2851
+ // reported as plain validation failure, to be asked again. A commit the
2852
+ // clone holds that is NOT THIS REQUEST'S merge commit (no second parent,
2853
+ // or a message that does not name the request) never becomes it, and is
2854
+ // reported as a mismatch the caller may remember.
2855
+ if (!(await revParse(`${mergeSha}^{commit}`))) {
2856
+ throw new WorkflowValidationError(
2857
+ `commit ${mergeSha} is not in this clone, so change request #${number} cannot be read from it yet`,
2858
+ );
2859
+ }
2860
+ // The SECOND parent first, because its absence is the whole P1: a merge
2861
+ // `--no-ff` always has one, and a commit that does not is not a merge this
2862
+ // request made.
2863
+ const headSha = await revParse(`${mergeSha}^2^{commit}`);
2864
+ if (!headSha) {
2865
+ throw new AppliedChangeMismatchError(
2866
+ `commit ${mergeSha} is not a merge commit, so it cannot be change request #${number}'s`,
2867
+ );
2868
+ }
2869
+ const baseSha = await revParse(`${mergeSha}^1^{commit}`);
2870
+ if (!baseSha) {
2871
+ throw new AppliedChangeMismatchError(`no first parent for commit ${mergeSha}`);
2872
+ }
2873
+ const { stdout: message } = await this.git(cwd, ['log', '-1', '--format=%B', mergeSha]);
2874
+ if (!mergeCommitMessageNames(message, number, applied.title)) {
2875
+ throw new AppliedChangeMismatchError(
2876
+ `commit ${mergeSha} is not the merge commit of change request #${number}`,
2877
+ );
2878
+ }
2879
+ return { baseSha, headSha };
2880
+ }
2881
+
2882
+ /**
2883
+ * The two commits an APPLIED change request spanned, recovered from the merge
2884
+ * commit its row records: the target as it stood before the merge (`^1`) and
2885
+ * the source tip that was merged (`^2`).
2886
+ *
2887
+ * These are what the detail of a merged request reports as its `baseSha` and
2888
+ * `headSha`, and the `headSha` matters beyond being informative: an approval
2889
+ * row stores the source head it was given against, and the detail calls an
2890
+ * approval stale when that sha is not the detail's `headSha`. Answering the
2891
+ * merge commit itself there would report every approval a merged request ever
2892
+ * collected as stale, and every file of it as unapproved — the opposite of
2893
+ * what happened.
2894
+ *
2895
+ * ## Why the commit is VERIFIED rather than taken
2896
+ *
2897
+ * `merged_sha` is not reliably a commit this request created. When the target
2898
+ * already contains the source there is nothing to merge, so
2899
+ * `mergeChangeRequest` writes no commit and reports the TARGET TIP as the
2900
+ * merged state — and in a deployment that lands everything through change
2901
+ * requests, that tip is usually ANOTHER request's merge commit. Reading "the
2902
+ * recorded commit's own change" then answers with somebody else's files under
2903
+ * this request's number: the request looks like it changed files it never
2904
+ * touched, and becomes visible to whoever may read THOSE (cubic P1 on #347).
2905
+ *
2906
+ * So three things must hold, and all three are cheap:
2907
+ *
2908
+ * 1. the commit is in this clone,
2909
+ * 2. it has a SECOND parent — `mergeChangeRequest` merges `--no-ff`, so
2910
+ * every merge commit it writes has one, and a commit that has none was
2911
+ * not written by a merge,
2912
+ * 3. its subject names THIS request — see `merge-commit.ts`.
2913
+ *
2914
+ * Anything else fails closed: no files, so author-only, rather than a file
2915
+ * list that belongs to another change. The write side no longer records a
2916
+ * no-op merge's sha at all, so for rows written from now on all three hold by
2917
+ * construction; the verification is what protects the rows written before it.
2918
+ */
2919
+ async appliedChangeShas(
2920
+ workspaceId: string,
2921
+ applied: AppliedChangeRef,
2922
+ ): Promise<{ baseSha: string; headSha: string }> {
2923
+ const cwd = await this.repoDir(workspaceId);
2924
+ return this.mutex.run(workspaceId, async () => this.appliedEnds(cwd, applied));
2925
+ }
2926
+
2927
+ /**
2928
+ * The changed-file list an APPLIED change request landed, read from its merge
2929
+ * commit against that commit's first parent, and shaped the way
2930
+ * `changedFilesForPr` shapes a branch pair — how an applied request is read
2931
+ * back, since its source branch is retired and the merge commit is what is
2932
+ * left of it.
2933
+ *
2934
+ * TWO dots, from the first parent. A three-dot diff would be read from the
2935
+ * merge base of the merge commit's two parents, i.e. it would re-report the
2936
+ * source branch's whole history instead of what landed on the target.
2937
+ *
2938
+ * Verified, not assumed — see {@link appliedChangeShas}. No fetch: the commit
2939
+ * is in this clone or this rejects.
2940
+ */
2941
+ async changedFilesOfAppliedChange(
2942
+ workspaceId: string,
2943
+ applied: AppliedChangeRef,
2944
+ opts: { patchCap?: number } = {},
2945
+ ): Promise<PullRequestFile[]> {
2946
+ const cwd = await this.repoDir(workspaceId);
2947
+ return this.mutex.run(workspaceId, async () => {
2948
+ const { baseSha } = await this.appliedEnds(cwd, applied);
2949
+ return this.prFilesForRange(cwd, `${baseSha}..${applied.mergeSha}`, opts.patchCap ?? 400);
2950
+ });
2951
+ }
2952
+
2953
+ /**
2954
+ * The same applied change as the two path views a change-request SUMMARY needs
2955
+ * — the flat touched-path list and the rename-aware pairs — out of one
2956
+ * `git diff`, exactly as {@link changedPathsAndPairsForPr} does for a branch
2957
+ * pair. Same verification and same no-fetch contract.
2958
+ */
2959
+ async changedPathsAndPairsOfAppliedChange(
2960
+ workspaceId: string,
2961
+ applied: AppliedChangeRef,
2962
+ ): Promise<{ paths: string[]; pairs: ChangedPathPair[] }> {
2963
+ const cwd = await this.repoDir(workspaceId);
2964
+ return this.mutex.run(workspaceId, async () => {
2965
+ const { baseSha } = await this.appliedEnds(cwd, applied);
2966
+ const entries = await this.prChangedEntriesForRange(
2967
+ cwd,
2968
+ `${baseSha}..${applied.mergeSha}`,
2969
+ );
2970
+ return { paths: flattenChangedPaths(entries, {}), pairs: changedPathPairs(entries) };
2627
2971
  });
2628
2972
  }
2629
2973
 
@@ -2702,32 +3046,70 @@ export class GitService implements IGitService {
2702
3046
  headRef: string,
2703
3047
  opts: { forAccessCheck?: boolean } = {},
2704
3048
  ): Promise<string[]> {
2705
- const { stdout } = await this.git(cwd, [
2706
- 'diff', '-M', '-z', '--name-status', `${baseRef}...${headRef}`,
2707
- ]);
2708
- // Deduped: both sides of a rename can collide with another entry's path.
2709
- return [
2710
- ...new Set(
2711
- parseNameStatusZ(stdout)
2712
- // A rename onto or off the placeholder is a real file removed or
2713
- // added (see `withoutPlaceholderRename`): both of its paths are
2714
- // touched, or filtering the placeholder would lose the file.
2715
- //
2716
- // Authorizing the change needs both sides of EVERY rename, not just
2717
- // the placeholder's: git reports a rename under its new name alone,
2718
- // and the old name is a path the change deletes.
2719
- .flatMap((s) =>
2720
- s.previousPath &&
2721
- (opts.forAccessCheck || isFolderPlaceholder(s.path) || isFolderPlaceholder(s.previousPath))
2722
- ? [s.previousPath, s.path]
2723
- : [s.path],
2724
- )
2725
- // Same rule as `changedFilesForPr`: a roles.yaml change never
2726
- // survives a merge, so it is not a touched path for routing or
2727
- // summaries either.
2728
- .filter((p) => opts.forAccessCheck || p !== 'roles.yaml'),
2729
- ),
2730
- ];
3049
+ return flattenChangedPaths(await this.prChangedEntriesAt(cwd, baseRef, headRef), opts);
3050
+ }
3051
+
3052
+ /**
3053
+ * The same diff, left as parsed ENTRIES: each changed file with the path it
3054
+ * came from when git detected a rename.
3055
+ *
3056
+ * The flat path list cannot express that pairing, and a caller deciding what
3057
+ * someone may READ needs it. A file renamed out of a folder the caller cannot
3058
+ * open is readable under neither of its names — the diff of a rename shows
3059
+ * the old side's content — and a flat list that offers both paths unlabelled
3060
+ * cannot say which new file the closed old path belongs to. `forAccessCheck`
3061
+ * solves the write side of this by taking the union; a read gate needs the
3062
+ * pairing itself.
3063
+ */
3064
+ private async prChangedEntriesAt(
3065
+ cwd: string,
3066
+ baseRef: string,
3067
+ headRef: string,
3068
+ ): Promise<NameStatusEntry[]> {
3069
+ return this.prChangedEntriesForRange(cwd, `${baseRef}...${headRef}`);
3070
+ }
3071
+
3072
+ /**
3073
+ * The same parsed entries over an already-decided `range`, so a merge
3074
+ * commit's own diff ({@link firstParentRange}) is read by the same parser as a
3075
+ * change request's branch pair.
3076
+ */
3077
+ private async prChangedEntriesForRange(
3078
+ cwd: string,
3079
+ range: string,
3080
+ ): Promise<NameStatusEntry[]> {
3081
+ const { stdout } = await this.git(cwd, ['diff', '-M', '-z', '--name-status', range]);
3082
+ return parseNameStatusZ(stdout);
3083
+ }
3084
+
3085
+ /**
3086
+ * One diff, both views of it: the flat touched-path list every existing
3087
+ * caller reads, and the rename-aware pairs a read gate needs. The change-
3088
+ * request summary builder wants both, and must not pay for two `git diff`s
3089
+ * to get them — it is on the list path that is polled every 60s.
3090
+ */
3091
+ async changedPathsAndPairsForPr(
3092
+ workspaceId: string,
3093
+ baseBranch: string,
3094
+ headBranch: string,
3095
+ opts: { fetch?: boolean } = {},
3096
+ ): Promise<{ paths: string[]; pairs: ChangedPathPair[] }> {
3097
+ assertValidBranchName(baseBranch);
3098
+ assertValidBranchName(headBranch);
3099
+ const cwd = await this.repoDir(workspaceId);
3100
+ // Same ref pinning and the same fetch skip as `changedPathsForPr`, for the
3101
+ // same reasons spelled out there.
3102
+ const pinned =
3103
+ opts.fetch === false ? await this.publishedPrCommits(cwd, baseBranch, headBranch) : null;
3104
+ if (!pinned) {
3105
+ await this.fetchPrRefs(cwd, baseBranch, headBranch);
3106
+ }
3107
+ return this.mutex.run(workspaceId, async () => {
3108
+ const baseRef = pinned ? pinned.base : await this.resolvePublishedBranchRef(cwd, baseBranch);
3109
+ const headRef = pinned ? pinned.head : await this.resolvePublishedBranchRef(cwd, headBranch);
3110
+ const entries = await this.prChangedEntriesAt(cwd, baseRef, headRef);
3111
+ return { paths: flattenChangedPaths(entries, {}), pairs: changedPathPairs(entries) };
3112
+ });
2731
3113
  }
2732
3114
 
2733
3115
  /**
@@ -3616,6 +3998,67 @@ interface NameStatusEntry {
3616
3998
  * Parse `git diff -M -z --name-status` output. NUL-separated tokens: each record
3617
3999
  * is `<statusLetter>\0<path>`, or for a rename/copy `<Rxxx|Cxxx>\0<old>\0<new>`.
3618
4000
  */
4001
+ /**
4002
+ * The flat touched-path list of a parsed `--name-status` diff. Lifted out of
4003
+ * `prChangedPathsAt` unchanged, so the pair-returning reader can share one
4004
+ * diff with it rather than running a second.
4005
+ */
4006
+ function flattenChangedPaths(
4007
+ entries: NameStatusEntry[],
4008
+ opts: { forAccessCheck?: boolean } = {},
4009
+ ): string[] {
4010
+ // Deduped: both sides of a rename can collide with another entry's path.
4011
+ return [
4012
+ ...new Set(
4013
+ entries
4014
+ // A rename onto or off the placeholder is a real file removed or
4015
+ // added (see `withoutPlaceholderRename`): both of its paths are
4016
+ // touched, or filtering the placeholder would lose the file.
4017
+ //
4018
+ // Authorizing the change needs both sides of EVERY rename, not just
4019
+ // the placeholder's: git reports a rename under its new name alone,
4020
+ // and the old name is a path the change deletes.
4021
+ .flatMap((s) =>
4022
+ s.previousPath &&
4023
+ (opts.forAccessCheck || isFolderPlaceholder(s.path) || isFolderPlaceholder(s.previousPath))
4024
+ ? [s.previousPath, s.path]
4025
+ : [s.path],
4026
+ )
4027
+ // Same rule as `changedFilesForPr`: a roles.yaml change never
4028
+ // survives a merge, so it is not a touched path for routing or
4029
+ // summaries either.
4030
+ .filter((p) => opts.forAccessCheck || p !== 'roles.yaml'),
4031
+ ),
4032
+ ];
4033
+ }
4034
+
4035
+ /**
4036
+ * The changed files of a diff as read-gate pairs: every file the request
4037
+ * proposes, carrying the path it was renamed from when it has one.
4038
+ *
4039
+ * Normalised and filtered EXACTLY as `changedFilesForPr` does it, through the
4040
+ * same `withoutPlaceholderRename` and the same two drops — because this is the
4041
+ * file set a change-request LIST decides visibility over and that one is the
4042
+ * file set its DETAIL decides over, and the two answering differently is how a
4043
+ * list comes to advertise a request its own detail refuses (or to hide one the
4044
+ * detail serves). Any future change to one filter belongs in both.
4045
+ */
4046
+ function changedPathPairs(entries: NameStatusEntry[]): ChangedPathPair[] {
4047
+ const byPath = new Map<string, ChangedPathPair>();
4048
+ for (const raw of entries) {
4049
+ // A rename between a real file and the placeholder is a removal or an
4050
+ // addition of the real side; after this, the placeholder filter below
4051
+ // cannot take the file with it.
4052
+ const entry = withoutPlaceholderRename(raw);
4053
+ if (isFolderPlaceholder(entry.path) || entry.path === 'roles.yaml') continue;
4054
+ byPath.set(entry.path, {
4055
+ path: entry.path,
4056
+ ...(entry.previousPath ? { previousPath: entry.previousPath } : {}),
4057
+ });
4058
+ }
4059
+ return [...byPath.values()];
4060
+ }
4061
+
3619
4062
  export function parseNameStatusZ(out: string): NameStatusEntry[] {
3620
4063
  const tokens = out.split('\0');
3621
4064
  const entries: NameStatusEntry[] = [];