@bevel-software/platform-core-backend 0.21.0 → 0.22.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 (177) hide show
  1. package/dist/core/create-core-server.d.ts.map +1 -1
  2. package/dist/core/create-core-server.js +32 -2
  3. package/dist/core/create-core-server.js.map +1 -1
  4. package/dist/core/create-core-services.d.ts +13 -1
  5. package/dist/core/create-core-services.d.ts.map +1 -1
  6. package/dist/core/create-core-services.js +51 -5
  7. package/dist/core/create-core-services.js.map +1 -1
  8. package/dist/modules/access/access-requests.contract.d.ts +75 -0
  9. package/dist/modules/access/access-requests.contract.d.ts.map +1 -0
  10. package/dist/modules/access/access-requests.contract.js +20 -0
  11. package/dist/modules/access/access-requests.contract.js.map +1 -0
  12. package/dist/modules/access/access-requests.routes.d.ts +35 -0
  13. package/dist/modules/access/access-requests.routes.d.ts.map +1 -0
  14. package/dist/modules/access/access-requests.routes.js +237 -0
  15. package/dist/modules/access/access-requests.routes.js.map +1 -0
  16. package/dist/modules/access/access-requests.service.d.ts +123 -0
  17. package/dist/modules/access/access-requests.service.d.ts.map +1 -0
  18. package/dist/modules/access/access-requests.service.js +337 -0
  19. package/dist/modules/access/access-requests.service.js.map +1 -0
  20. package/dist/modules/access-model/access-grammar.d.ts +12 -0
  21. package/dist/modules/access-model/access-grammar.d.ts.map +1 -1
  22. package/dist/modules/access-model/access-grammar.js +24 -0
  23. package/dist/modules/access-model/access-grammar.js.map +1 -1
  24. package/dist/modules/auth/auth.service.d.ts +26 -1
  25. package/dist/modules/auth/auth.service.d.ts.map +1 -1
  26. package/dist/modules/auth/auth.service.js +11 -2
  27. package/dist/modules/auth/auth.service.js.map +1 -1
  28. package/dist/modules/github-app/github-app.client.d.ts +101 -0
  29. package/dist/modules/github-app/github-app.client.d.ts.map +1 -0
  30. package/dist/modules/github-app/github-app.client.js +222 -0
  31. package/dist/modules/github-app/github-app.client.js.map +1 -0
  32. package/dist/modules/github-app/github-app.connection.d.ts +102 -0
  33. package/dist/modules/github-app/github-app.connection.d.ts.map +1 -0
  34. package/dist/modules/github-app/github-app.connection.js +185 -0
  35. package/dist/modules/github-app/github-app.connection.js.map +1 -0
  36. package/dist/modules/github-app/github-app.routes.d.ts +59 -0
  37. package/dist/modules/github-app/github-app.routes.d.ts.map +1 -0
  38. package/dist/modules/github-app/github-app.routes.js +323 -0
  39. package/dist/modules/github-app/github-app.routes.js.map +1 -0
  40. package/dist/modules/github-app/index.d.ts +4 -0
  41. package/dist/modules/github-app/index.d.ts.map +1 -0
  42. package/dist/modules/github-app/index.js +4 -0
  43. package/dist/modules/github-app/index.js.map +1 -0
  44. package/dist/modules/kb-fs/remote-url.d.ts +22 -0
  45. package/dist/modules/kb-fs/remote-url.d.ts.map +1 -0
  46. package/dist/modules/kb-fs/remote-url.js +35 -0
  47. package/dist/modules/kb-fs/remote-url.js.map +1 -0
  48. package/dist/modules/plugins/join-proposals.d.ts +17 -5
  49. package/dist/modules/plugins/join-proposals.d.ts.map +1 -1
  50. package/dist/modules/plugins/join-proposals.js +76 -22
  51. package/dist/modules/plugins/join-proposals.js.map +1 -1
  52. package/dist/modules/plugins/join-requests.service.d.ts +111 -18
  53. package/dist/modules/plugins/join-requests.service.d.ts.map +1 -1
  54. package/dist/modules/plugins/join-requests.service.js +173 -29
  55. package/dist/modules/plugins/join-requests.service.js.map +1 -1
  56. package/dist/modules/plugins/plugins.routes.d.ts.map +1 -1
  57. package/dist/modules/plugins/plugins.routes.js +3 -2
  58. package/dist/modules/plugins/plugins.routes.js.map +1 -1
  59. package/dist/modules/settings/deployment-settings.service.d.ts +22 -1
  60. package/dist/modules/settings/deployment-settings.service.d.ts.map +1 -1
  61. package/dist/modules/settings/deployment-settings.service.js +93 -4
  62. package/dist/modules/settings/deployment-settings.service.js.map +1 -1
  63. package/dist/modules/settings/managed-repository.d.ts +43 -0
  64. package/dist/modules/settings/managed-repository.d.ts.map +1 -0
  65. package/dist/modules/settings/managed-repository.js +60 -0
  66. package/dist/modules/settings/managed-repository.js.map +1 -0
  67. package/dist/modules/settings/repository-source.d.ts +128 -0
  68. package/dist/modules/settings/repository-source.d.ts.map +1 -0
  69. package/dist/modules/settings/repository-source.js +150 -0
  70. package/dist/modules/settings/repository-source.js.map +1 -0
  71. package/dist/modules/settings/setup.routes.d.ts +27 -4
  72. package/dist/modules/settings/setup.routes.d.ts.map +1 -1
  73. package/dist/modules/settings/setup.routes.js +187 -13
  74. package/dist/modules/settings/setup.routes.js.map +1 -1
  75. package/dist/modules/skills/skill-access-requests.routes.d.ts +6 -8
  76. package/dist/modules/skills/skill-access-requests.routes.d.ts.map +1 -1
  77. package/dist/modules/skills/skill-access-requests.routes.js +24 -63
  78. package/dist/modules/skills/skill-access-requests.routes.js.map +1 -1
  79. package/dist/modules/tool-helpers/tool-context.d.ts.map +1 -1
  80. package/dist/modules/tool-helpers/tool-context.js +15 -0
  81. package/dist/modules/tool-helpers/tool-context.js.map +1 -1
  82. package/dist/modules/workflow/agent-tools/workflow.tools.d.ts.map +1 -1
  83. package/dist/modules/workflow/agent-tools/workflow.tools.js +38 -2
  84. package/dist/modules/workflow/agent-tools/workflow.tools.js.map +1 -1
  85. package/dist/modules/workflow/git/git.service.d.ts +3 -1
  86. package/dist/modules/workflow/git/git.service.d.ts.map +1 -1
  87. package/dist/modules/workflow/git/git.service.js +17 -4
  88. package/dist/modules/workflow/git/git.service.js.map +1 -1
  89. package/dist/modules/workflow/git/node-git-runner.d.ts.map +1 -1
  90. package/dist/modules/workflow/git/node-git-runner.js +5 -0
  91. package/dist/modules/workflow/git/node-git-runner.js.map +1 -1
  92. package/dist/modules/workflow/git/pull-request.service.d.ts +45 -0
  93. package/dist/modules/workflow/git/pull-request.service.d.ts.map +1 -1
  94. package/dist/modules/workflow/git/pull-request.service.js +99 -0
  95. package/dist/modules/workflow/git/pull-request.service.js.map +1 -1
  96. package/dist/modules/workflow/workflow.routes.d.ts.map +1 -1
  97. package/dist/modules/workflow/workflow.routes.js +3 -1
  98. package/dist/modules/workflow/workflow.routes.js.map +1 -1
  99. package/dist/modules/workflow/workflow.service.d.ts +34 -7
  100. package/dist/modules/workflow/workflow.service.d.ts.map +1 -1
  101. package/dist/modules/workflow/workflow.service.js +148 -48
  102. package/dist/modules/workflow/workflow.service.js.map +1 -1
  103. package/dist/modules/workspace/startup/kb-startup-runner.d.ts +66 -0
  104. package/dist/modules/workspace/startup/kb-startup-runner.d.ts.map +1 -1
  105. package/dist/modules/workspace/startup/kb-startup-runner.js +148 -0
  106. package/dist/modules/workspace/startup/kb-startup-runner.js.map +1 -1
  107. package/dist/modules/workspace/workspace.service.d.ts.map +1 -1
  108. package/dist/modules/workspace/workspace.service.js +17 -1
  109. package/dist/modules/workspace/workspace.service.js.map +1 -1
  110. package/dist/modules/workspace/workspace.tools.d.ts.map +1 -1
  111. package/dist/modules/workspace/workspace.tools.js +28 -2
  112. package/dist/modules/workspace/workspace.tools.js.map +1 -1
  113. package/dist/shared/domain-errors.d.ts +39 -0
  114. package/dist/shared/domain-errors.d.ts.map +1 -1
  115. package/dist/shared/domain-errors.js +55 -0
  116. package/dist/shared/domain-errors.js.map +1 -1
  117. package/dist/shared/git.contract.d.ts +10 -0
  118. package/dist/shared/git.contract.d.ts.map +1 -1
  119. package/dist/shared/git.contract.js.map +1 -1
  120. package/package.json +3 -3
  121. package/src/core/create-core-server.ts +37 -1
  122. package/src/core/create-core-services.ts +65 -8
  123. package/src/modules/access/__tests__/access-requests.recut.test.ts +134 -0
  124. package/src/modules/access/__tests__/access-requests.routes.test.ts +610 -0
  125. package/src/modules/access/access-requests.contract.ts +93 -0
  126. package/src/modules/access/access-requests.routes.ts +286 -0
  127. package/src/modules/access/access-requests.service.ts +420 -0
  128. package/src/modules/access-model/access-grammar.ts +22 -0
  129. package/src/modules/auth/__tests__/auth.service.test.ts +38 -0
  130. package/src/modules/auth/auth.service.ts +28 -1
  131. package/src/modules/github-app/__tests__/github-app.test.ts +848 -0
  132. package/src/modules/github-app/github-app.client.ts +268 -0
  133. package/src/modules/github-app/github-app.connection.ts +204 -0
  134. package/src/modules/github-app/github-app.routes.ts +359 -0
  135. package/src/modules/github-app/index.ts +19 -0
  136. package/src/modules/kb-fs/__tests__/remote-url.test.ts +38 -0
  137. package/src/modules/kb-fs/remote-url.ts +35 -0
  138. package/src/modules/plugins/__tests__/join-proposals.test.ts +100 -19
  139. package/src/modules/plugins/__tests__/join-requests.service.test.ts +27 -11
  140. package/src/modules/plugins/__tests__/join-requests.settlement.test.ts +371 -0
  141. package/src/modules/plugins/__tests__/plugins.routes.test.ts +1 -1
  142. package/src/modules/plugins/join-proposals.ts +87 -19
  143. package/src/modules/plugins/join-requests.service.ts +199 -39
  144. package/src/modules/plugins/plugins.routes.ts +3 -2
  145. package/src/modules/settings/__tests__/repository-source.test.ts +191 -0
  146. package/src/modules/settings/__tests__/setup.routes.git-mode.test.ts +353 -0
  147. package/src/modules/settings/__tests__/setup.routes.github-app.test.ts +282 -0
  148. package/src/modules/settings/__tests__/setup.routes.managed-phase.test.ts +233 -0
  149. package/src/modules/settings/deployment-settings.service.ts +109 -3
  150. package/src/modules/settings/managed-repository.ts +68 -0
  151. package/src/modules/settings/repository-source.ts +197 -0
  152. package/src/modules/settings/setup.routes.ts +214 -10
  153. package/src/modules/skills/__tests__/skill-access-requests.routes.test.ts +5 -1
  154. package/src/modules/skills/skill-access-requests.routes.ts +25 -75
  155. package/src/modules/tool-helpers/tool-context.ts +15 -0
  156. package/src/modules/workflow/__tests__/apply-failure.test.ts +9 -1
  157. package/src/modules/workflow/__tests__/workflow.service.facade.test.ts +159 -8
  158. package/src/modules/workflow/__tests__/workflow.service.update-from-target.test.ts +146 -40
  159. package/src/modules/workflow/agent-tools/__tests__/workflow.tools.test.ts +141 -1
  160. package/src/modules/workflow/agent-tools/workflow.tools.ts +49 -3
  161. package/src/modules/workflow/git/__tests__/git.service.pull.test.ts +121 -0
  162. package/src/modules/workflow/git/__tests__/pull-request.service.getPrDetail.test.ts +145 -2
  163. package/src/modules/workflow/git/__tests__/pull-request.service.viewer-can-delete.test.ts +166 -0
  164. package/src/modules/workflow/git/git.service.ts +25 -4
  165. package/src/modules/workflow/git/node-git-runner.ts +6 -0
  166. package/src/modules/workflow/git/pull-request.service.ts +119 -0
  167. package/src/modules/workflow/workflow.routes.ts +3 -1
  168. package/src/modules/workflow/workflow.service.ts +170 -52
  169. package/src/modules/workspace/__tests__/workspace.service.unknown-branch.test.ts +43 -0
  170. package/src/modules/workspace/__tests__/workspace.tools.branch-errors.test.ts +233 -7
  171. package/src/modules/workspace/__tests__/workspace.tools.test.ts +35 -3
  172. package/src/modules/workspace/startup/__tests__/kb-startup-runner.test.ts +211 -0
  173. package/src/modules/workspace/startup/kb-startup-runner.ts +159 -0
  174. package/src/modules/workspace/workspace.service.ts +17 -1
  175. package/src/modules/workspace/workspace.tools.ts +35 -0
  176. package/src/shared/domain-errors.ts +58 -0
  177. package/src/shared/git.contract.ts +10 -0
@@ -9,6 +9,13 @@ import { logger } from '../../shared/logging.js';
9
9
 
10
10
  const log = logger('plugins');
11
11
  import type { KbContext } from '../../shared/kb-context.js';
12
+ import type { IAccessControl } from '../access/access-control.interface.js';
13
+ import {
14
+ rulesFileFor,
15
+ type AccessRequestTarget,
16
+ type IAccessRequestLifecycle,
17
+ } from '../access/access-requests.contract.js';
18
+ import type { Verb } from '../access-model/access-grammar.js';
12
19
  import { pendingProposals, type JoinProposal } from './join-proposals.js';
13
20
 
14
21
  /** One open join change request, with what it still proposes. */
@@ -22,57 +29,185 @@ export interface JoinRequest {
22
29
  }
23
30
 
24
31
  /**
25
- * Join requests as PROPOSALS, and the reconciliation that retires them.
32
+ * Access requests as PROPOSALS, and the reconciliation that retires them.
26
33
  *
27
34
  * The lifecycle has no state of its own — it is derived, every time, from two
28
- * copies of one file:
35
+ * copies of one file (a folder's `access.md`, or a file's own frontmatter):
29
36
  *
30
- * open the branch's `access.md` grants something the default's does not
37
+ * open the branch proposes something the person does not already hold
31
38
  * settled it does not
32
39
  *
33
- * so "approve" is not an operation on the request at all. A manager grants a
40
+ * so "approve" is not an operation on the request at all. An editor grants a
34
41
  * principal through the ordinary access path (the same lock + commit every
35
42
  * other access edit uses, gated the same way), the default branch gains that
36
- * entry, and the proposal stops being pending because the diff no longer
37
- * contains it. When the last one goes, the change request has nothing left to
38
- * say and is rejected, its branch deleted.
43
+ * entry, and the proposal stops being pending.
44
+ *
45
+ * "Does not already hold" is stronger than "is not in the file", and
46
+ * deliberately so: Owner covers Can edit, a parent folder's grant covers this
47
+ * one, and a role or group carries access without naming anybody. Each of
48
+ * those would leave a proposal nobody can usefully accept — accepting writes
49
+ * a grant that changes nothing — and the request would sit open forever. See
50
+ * {@link JoinRequestsService.unmetProposals}.
39
51
  *
40
- * That reconciliation runs LAZILY on every listing as well as on demand, so a
41
- * grant made anywhere — this banner, the Manage-access dialog, a hand edit —
42
- * settles the request that asked for it. Nothing has to remember to.
52
+ * That reconciliation runs LAZILY on every listing as well as on demand, so
53
+ * access gained anywhere — this banner, the Manage access dialog, a hand
54
+ * edit, a role someone joined — settles the request that asked for it.
55
+ * Nothing has to remember to.
43
56
  */
44
- export class JoinRequestsService {
57
+ export class JoinRequestsService implements IAccessRequestLifecycle {
45
58
  constructor(
46
59
  private readonly workspaceService: WorkspaceService,
47
60
  private readonly workflow: IWorkflowService,
48
61
  private readonly kb: Pick<KbContext, 'defaultBranch' | 'defaultWorkspaceId'>,
62
+ /**
63
+ * Read-only, and asked one question only: does this person already hold
64
+ * this verb on the item, on the DEFAULT branch? See {@link unmetProposals}.
65
+ */
66
+ private readonly accessControl: Pick<
67
+ IAccessControl,
68
+ 'canRead' | 'canWrite' | 'canOwner' | 'canDownload'
69
+ >,
49
70
  ) {}
50
71
 
51
72
  /**
52
- * Open join requests for `plugin`, each carrying only its still-pending
53
- * proposals. Requests with none left are reconciled away (rejected, branch
54
- * deleted) and omitted.
73
+ * What `branch` still proposes for `target`, minus everything the person it
74
+ * names already holds — or NULL when the branch's own copy could not be read
75
+ * at all.
76
+ *
77
+ * That distinction is the whole point of the return type. "The branch says
78
+ * nothing" is NOT "the branch proposes nothing", and the two arrive as the
79
+ * same empty diff: `pendingProposals` reads an unreadable file as carrying
80
+ * no grants (fail-closed, which is right for deciding what to SHOW). Used as
81
+ * the settle test it is fail-open in the one direction that cannot be taken
82
+ * back — it closes a request nobody answered.
83
+ *
84
+ * And unreadable is the normal case for a few seconds. These reads go
85
+ * through `origin/<branch>` in the DEFAULT branch's clone, whose fetch is
86
+ * throttled; a request opened moments ago names a ref that clone has not
87
+ * heard of. So a miss is retried behind a FORCED fetch before it is believed,
88
+ * and if it still misses the caller is told nothing rather than something
89
+ * false.
90
+ */
91
+ async proposalsOn(
92
+ branch: string,
93
+ target: AccessRequestTarget,
94
+ opts: { fresh?: boolean } = {},
95
+ ): Promise<JoinProposal[] | null> {
96
+ const rulesPath = rulesFileFor(target);
97
+ await this.refresh({ force: opts.fresh });
98
+ let branchText = await this.readAt(branch, rulesPath);
99
+ if (branchText === null && !opts.fresh) {
100
+ await this.refresh({ force: true });
101
+ branchText = await this.readAt(branch, rulesPath);
102
+ }
103
+ if (branchText === null) return null;
104
+ // `kind` picks the grammar: a folder's rules are block lists in an
105
+ // access.md body, a file's are its own frontmatter, where one grant is
106
+ // written as a scalar. Reading one with the other's grammar yields no
107
+ // grants, which reads as a finished request.
108
+ const proposals = pendingProposals(
109
+ branchText,
110
+ await this.readAt(this.kb.defaultBranch, rulesPath),
111
+ rulesPath,
112
+ target.kind,
113
+ );
114
+ // Unreadable rules on the branch: say nothing rather than "nothing left".
115
+ if (proposals === null) return null;
116
+ return this.unmetProposals(proposals, target);
117
+ }
118
+
119
+ /**
120
+ * Drop every proposal the live workspace has already ANSWERED, however it
121
+ * was answered.
122
+ *
123
+ * The file diff alone cannot see this. A request asking for `write` is
124
+ * satisfied by an `owner:` line, by a grant on a parent folder, or by a role
125
+ * or group the person has since joined — none of which put their email into
126
+ * this file, so the diff keeps reporting a proposal nobody can usefully
127
+ * accept (accepting writes a grant that changes nothing, and the request
128
+ * never retires). Asking the resolver the question the dialog's own grant
129
+ * would have to satisfy closes those requests instead of stranding them.
55
130
  *
56
- * `actor` is who the reconciliation acts as — a manager of the plugin, since
131
+ * A proposal naming a ROLE keeps the literal rule: "does this role hold the
132
+ * verb here" is not a question the per-person resolver answers, and a role
133
+ * proposal is answered by the live rules carrying it.
134
+ */
135
+ private async unmetProposals(
136
+ proposals: JoinProposal[],
137
+ target: AccessRequestTarget,
138
+ ): Promise<JoinProposal[]> {
139
+ const out: JoinProposal[] = [];
140
+ for (const proposal of proposals) {
141
+ if (proposal.principal.kind !== 'user') {
142
+ out.push(proposal);
143
+ continue;
144
+ }
145
+ if (await this.holds(proposal.principal.email, proposal.verb, target.path)) continue;
146
+ out.push(proposal);
147
+ }
148
+ return out;
149
+ }
150
+
151
+ /**
152
+ * Does `email` hold `verb` on the ITEM, on the default branch? The verb
153
+ * folds are the resolver's own (owner covers write, write covers read), so
154
+ * this asks exactly what an accepted grant would have to achieve.
155
+ *
156
+ * Best-effort in ONE direction: a resolver that fails answers "no", which
157
+ * leaves the request open. A failure must never close somebody's request for
158
+ * them.
159
+ */
160
+ private async holds(email: string, verb: Verb, itemPath: string): Promise<boolean> {
161
+ const wsId = this.kb.defaultWorkspaceId();
162
+ try {
163
+ switch (verb) {
164
+ case 'owner':
165
+ return await this.accessControl.canOwner(wsId, email, itemPath);
166
+ case 'write':
167
+ return await this.accessControl.canWrite(wsId, email, itemPath);
168
+ case 'download':
169
+ return await this.accessControl.canDownload(wsId, email, itemPath);
170
+ default:
171
+ return await this.accessControl.canRead(wsId, email, itemPath);
172
+ }
173
+ } catch (err) {
174
+ log.warn(
175
+ `could not resolve ${verb} on "${itemPath}" for a request: ${
176
+ err instanceof Error ? err.message : String(err)
177
+ }`,
178
+ );
179
+ return false;
180
+ }
181
+ }
182
+
183
+ /**
184
+ * Open requests for one item, each carrying only what it still proposes.
185
+ * Requests with nothing left are reconciled away (rejected, branch deleted)
186
+ * and omitted.
187
+ *
188
+ * `key` is what named the branch (`joinBranchFor`) — a plugin's name for a
189
+ * Subscribe request, the item's own path for everything the Manage access
190
+ * dialog opens. `target` is the item whose rules those proposals edit; the
191
+ * two differ only for plugins, whose folder is not their name.
192
+ *
193
+ * `actor` is who the reconciliation acts as — an editor of the item, since
57
194
  * rejecting a change request requires write on everything it touches.
58
195
  */
59
196
  async list(
60
- plugin: string,
61
- folder: string,
197
+ key: string,
198
+ target: AccessRequestTarget,
62
199
  crs: ChangeRequest[],
63
200
  actor: AuthUser,
64
201
  ): Promise<JoinRequest[]> {
65
- await this.refresh();
66
- const accessPath = `${folder}/access.md`;
67
- const baseText = await this.readAt(this.kb.defaultBranch, accessPath);
68
202
  const out: JoinRequest[] = [];
69
203
  for (const cr of crs) {
70
- if (cr.state !== 'open' || !isJoinBranchFor(cr.branch, plugin)) continue;
71
- const proposals = pendingProposals(
72
- await this.readAt(cr.branch, accessPath),
73
- baseText,
74
- accessPath,
75
- );
204
+ if (cr.state !== 'open' || !isJoinBranchFor(cr.branch, key)) continue;
205
+ const proposals = await this.confirmedProposals(cr.branch, target);
206
+ // Unreadable: leave it exactly as it is. There is nothing to offer an
207
+ // editor and nothing that says it is finished, and closing it on a read
208
+ // that failed would end somebody's request for them. It stays in Change
209
+ // requests for you, where it can still be answered by hand.
210
+ if (proposals === null) continue;
76
211
  if (proposals.length === 0) {
77
212
  await this.settle(cr, actor);
78
213
  continue;
@@ -94,24 +229,46 @@ export class JoinRequestsService {
94
229
  * same round-trip instead of waiting for the next listing.
95
230
  */
96
231
  async reconcile(
97
- plugin: string,
98
- folder: string,
232
+ key: string,
233
+ target: AccessRequestTarget,
99
234
  cr: ChangeRequest,
100
235
  actor: AuthUser,
101
236
  ): Promise<boolean> {
102
- if (cr.state !== 'open' || !isJoinBranchFor(cr.branch, plugin)) return false;
103
- await this.refresh();
104
- const accessPath = `${folder}/access.md`;
105
- const proposals = pendingProposals(
106
- await this.readAt(cr.branch, accessPath),
107
- await this.readAt(this.kb.defaultBranch, accessPath),
108
- accessPath,
109
- );
110
- if (proposals.length > 0) return false;
237
+ if (cr.state !== 'open' || !isJoinBranchFor(cr.branch, key)) return false;
238
+ const proposals = await this.confirmedProposals(cr.branch, target);
239
+ // Same rule as the listing: only a branch that was READ and, on a fresh
240
+ // read, proposes nothing is finished.
241
+ if (proposals === null || proposals.length > 0) return false;
111
242
  await this.settle(cr, actor);
112
243
  return true;
113
244
  }
114
245
 
246
+ /**
247
+ * What the branch proposes, with an EMPTY answer confirmed against freshly
248
+ * fetched refs before anyone acts on it. Null keeps its meaning: nothing
249
+ * could be read, so nothing can be said.
250
+ *
251
+ * The confirmation is there because an empty answer is the terminal one.
252
+ * These reads go through `origin/<branch>` in the default branch's clone,
253
+ * and that clone's fetch is throttled — so a branch whose remote-tracking
254
+ * ref is a few seconds old answers with the commit BEFORE the proposal was
255
+ * pushed. That is a file identical to live, which is an empty diff, which
256
+ * reads as "every grant has landed". A request nobody answered is then
257
+ * closed, its branch deleted, and the person told it was not accepted.
258
+ *
259
+ * One extra fetch, on the one path that cannot be undone — and when that
260
+ * fetch turns up a proposal after all, it is the answer, not a discarded
261
+ * second opinion.
262
+ */
263
+ private async confirmedProposals(
264
+ branch: string,
265
+ target: AccessRequestTarget,
266
+ ): Promise<JoinProposal[] | null> {
267
+ const first = await this.proposalsOn(branch, target);
268
+ if (first === null || first.length > 0) return first;
269
+ return this.proposalsOn(branch, target, { fresh: true });
270
+ }
271
+
115
272
  /**
116
273
  * Close a request whose proposals have all landed, and delete its branch.
117
274
  *
@@ -180,10 +337,13 @@ export class JoinRequestsService {
180
337
  * Refresh remote-tracking refs before reading them. Throttled inside, and
181
338
  * best-effort: a request pushed seconds ago is worth one fetch, but a fetch
182
339
  * failure must degrade to "read what we have" rather than empty the list.
340
+ *
341
+ * `force` skips the throttle — for the one caller that has already missed
342
+ * and must not mistake a stale ref list for an answer.
183
343
  */
184
- private async refresh(): Promise<void> {
344
+ private async refresh(opts: { force?: boolean } = {}): Promise<void> {
185
345
  await this.workspaceService
186
- .ensureRemotesFetched(this.kb.defaultWorkspaceId())
346
+ .ensureRemotesFetched(this.kb.defaultWorkspaceId(), opts)
187
347
  .catch(() => undefined);
188
348
  }
189
349
  }
@@ -19,6 +19,7 @@ import { PluginProvisionError, type PluginProvisionService } from './plugin-prov
19
19
  import { PluginLinkError, type PluginLinksService } from './plugin-links.service.js';
20
20
  import { PluginRenameError, type PluginRenameService } from './plugin-rename.service.js';
21
21
  import type { JoinRequestsService } from './join-requests.service.js';
22
+ import { folderTarget } from '../access/access-requests.contract.js';
22
23
  import type { PluginJoinRequestJobs } from './join-request-jobs.service.js';
23
24
  import type { JoinRequestRecord } from './join-request-records.store.js';
24
25
  import type {
@@ -619,7 +620,7 @@ export function createPluginsRoutes(
619
620
  if (!ctx) return;
620
621
  const crs = await workflow.listChangeRequests();
621
622
  res.json({
622
- requests: await joinRequests.list(joinKeyOf(ctx.plugin), ctx.folder, crs, ctx.user),
623
+ requests: await joinRequests.list(joinKeyOf(ctx.plugin), folderTarget(ctx.folder), crs, ctx.user),
623
624
  });
624
625
  } catch (err) {
625
626
  log.error('failed to list join requests:', { err });
@@ -649,7 +650,7 @@ export function createPluginsRoutes(
649
650
  res.status(404).json({ error: 'Not found' });
650
651
  return;
651
652
  }
652
- res.json({ closed: await joinRequests.reconcile(joinKeyOf(ctx.plugin), ctx.folder, cr, ctx.user) });
653
+ res.json({ closed: await joinRequests.reconcile(joinKeyOf(ctx.plugin), folderTarget(ctx.folder), cr, ctx.user) });
653
654
  } catch (err) {
654
655
  log.error('failed to reconcile a join request:', { err });
655
656
  res.status(500).json({ error: 'Failed to update the request' });
@@ -0,0 +1,191 @@
1
+ import fs from 'node:fs/promises';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
5
+ import { NodeGitRunner } from '../../workflow/git/node-git-runner.js';
6
+ import { ManagedRepository, MANAGED_REPOSITORY_DIR } from '../managed-repository.js';
7
+ import { RepositorySource, type GitHubAppRepository } from '../repository-source.js';
8
+
9
+ let root: string;
10
+
11
+ beforeEach(async () => {
12
+ root = await fs.mkdtemp(path.join(os.tmpdir(), 'hexis-managed-'));
13
+ });
14
+
15
+ afterEach(async () => {
16
+ await fs.rm(root, { recursive: true, force: true });
17
+ });
18
+
19
+ const reading = (values: Record<string, string>) => (key: string) => values[key] ?? '';
20
+
21
+ function source(values: Record<string, string>, extra: { fallbackToken?: string; githubApp?: GitHubAppRepository } = {}) {
22
+ const managed = new ManagedRepository(path.join(root, 'managed-repository'));
23
+ return {
24
+ managed,
25
+ source: new RepositorySource({
26
+ read: reading(values),
27
+ fallback: { username: 'x-access-token', token: extra.fallbackToken ?? '' },
28
+ managed,
29
+ ...(extra.githubApp ? { githubApp: extra.githubApp } : {}),
30
+ }),
31
+ };
32
+ }
33
+
34
+ const HOSTED = { kbRepoUrl: 'https://git.example.com/acme/kb.git', gitToken: 'the-token', gitUsername: 'oauth2' };
35
+
36
+ describe('RepositorySource: which way a deployment has its repository', () => {
37
+ it('has none while nothing is configured', () => {
38
+ const { source: s } = source({});
39
+ expect(s.mode()).toBeNull();
40
+ expect(s.url()).toBe('');
41
+ expect(s.answered()).toBe(false);
42
+ expect(s.credentials.token()).toBeNull();
43
+ });
44
+
45
+ it('reads a deployment configured before there was a choice as what it has: an address and a token', () => {
46
+ const { source: s } = source(HOSTED);
47
+ expect(s.mode()).toBe('token');
48
+ expect(s.url()).toBe(HOSTED.kbRepoUrl);
49
+ expect(s.credentials.token()).toBe('the-token');
50
+ expect(s.credentials.username()).toBe('oauth2');
51
+ expect(s.answered()).toBe(true);
52
+ });
53
+
54
+ it('reads a token the environment spells the old way', () => {
55
+ const { source: s } = source({ kbRepoUrl: HOSTED.kbRepoUrl }, { fallbackToken: 'from-GITHUB_TOKEN' });
56
+ expect(s.mode()).toBe('token');
57
+ expect(s.credentials.token()).toBe('from-GITHUB_TOKEN');
58
+ expect(s.answered()).toBe(true);
59
+ });
60
+
61
+ it('is not answered by half of an address and a token', () => {
62
+ expect(source({ kbRepoUrl: HOSTED.kbRepoUrl }).source.answered()).toBe(false);
63
+ expect(source({ gitToken: 'the-token' }).source.answered()).toBe(false);
64
+ });
65
+
66
+ it('ignores a mode it does not know, and reads what is configured', () => {
67
+ expect(source({ ...HOSTED, gitMode: 'carrier-pigeon' }).source.mode()).toBe('token');
68
+ });
69
+
70
+ it('answers for the values a save would put in effect, without the save', () => {
71
+ const { source: s, managed } = source(HOSTED);
72
+ const after = reading({ ...HOSTED, gitMode: 'managed' });
73
+ expect(s.mode(after)).toBe('managed');
74
+ expect(s.url(after)).toBe(managed.path);
75
+ // What is in effect has not moved.
76
+ expect(s.mode()).toBe('token');
77
+ });
78
+ });
79
+
80
+ describe('RepositorySource: a repository the deployment keeps', () => {
81
+ it('is reached by its path, and presented nothing', () => {
82
+ const { source: s, managed } = source({ gitMode: 'managed' });
83
+ expect(s.url()).toBe(managed.path);
84
+ expect(s.url()).toBe(path.join(root, 'managed-repository', MANAGED_REPOSITORY_DIR));
85
+ expect(s.answered()).toBe(true);
86
+ expect(s.credentials.token()).toBeNull();
87
+ });
88
+
89
+ /**
90
+ * One mode's credential is never presented to another mode's repository.
91
+ * A deployment that moved still has its old token stored, and it must not
92
+ * ride along in the environment of every git call made against a folder.
93
+ */
94
+ it('is never presented the token of the repository the deployment had before', () => {
95
+ const { source: s } = source({ ...HOSTED, gitMode: 'managed' }, { fallbackToken: 'from-the-environment' });
96
+ expect(s.credentials.token()).toBeNull();
97
+ expect(s.credentials.username()).toBe('x-access-token');
98
+ });
99
+ });
100
+
101
+ describe('RepositorySource: a repository reached through a GitHub App', () => {
102
+ const app = (overrides: Partial<GitHubAppRepository> = {}): GitHubAppRepository => ({
103
+ url: () => 'https://github.com/acme/kb.git',
104
+ token: () => 'an-installation-token',
105
+ prepare: async () => undefined,
106
+ answered: () => true,
107
+ ...overrides,
108
+ });
109
+
110
+ it('asks the app for the address and the token', () => {
111
+ const { source: s } = source({ gitMode: 'github-app', gitToken: 'a-leftover' }, { githubApp: app() });
112
+ expect(s.url()).toBe('https://github.com/acme/kb.git');
113
+ expect(s.credentials.token()).toBe('an-installation-token');
114
+ expect(s.credentials.username()).toBe('x-access-token');
115
+ expect(s.answered()).toBe(true);
116
+ });
117
+
118
+ it('renews the token before git is run, and only in this mode', async () => {
119
+ let renewed = 0;
120
+ const githubApp = app({ prepare: async () => void (renewed += 1) });
121
+ await source({ gitMode: 'github-app' }, { githubApp }).source.credentials.prepare?.();
122
+ await source(HOSTED, { githubApp }).source.credentials.prepare?.();
123
+ await source({ gitMode: 'managed' }, { githubApp }).source.credentials.prepare?.();
124
+ expect(renewed).toBe(1);
125
+ });
126
+
127
+ it('is unanswered on a deployment that has no such app', () => {
128
+ const { source: s } = source({ gitMode: 'github-app' });
129
+ expect(s.answered()).toBe(false);
130
+ expect(s.url()).toBe('');
131
+ expect(s.credentials.token()).toBeNull();
132
+ });
133
+ });
134
+
135
+ describe('ManagedRepository', () => {
136
+ const runner = new NodeGitRunner(30_000);
137
+ const git = async (cwd: string, ...args: string[]) => (await runner.run(cwd, args)).stdout.trim();
138
+
139
+ it('is created empty, bare, on the branch it is given', async () => {
140
+ const managed = new ManagedRepository(path.join(root, 'managed-repository'));
141
+ expect(await managed.exists()).toBe(false);
142
+ await managed.ensure(runner, 'trunk');
143
+ expect(await managed.exists()).toBe(true);
144
+ expect(await git(managed.path, 'rev-parse', '--is-bare-repository')).toBe('true');
145
+ expect(await git(managed.path, 'symbolic-ref', 'HEAD')).toBe('refs/heads/trunk');
146
+ expect(await git(managed.path, 'for-each-ref')).toBe('');
147
+ });
148
+
149
+ it('is cloned from, pushed to and fetched from like any remote', async () => {
150
+ const managed = new ManagedRepository(path.join(root, 'managed-repository'));
151
+ await managed.ensure(runner);
152
+ const one = path.join(root, 'one');
153
+ await fs.mkdir(one);
154
+ await git(one, 'init', '--initial-branch=main');
155
+ await fs.writeFile(path.join(one, 'README.md'), 'hello\n');
156
+ await git(one, 'add', '.');
157
+ await git(one, '-c', 'user.name=t', '-c', 'user.email=t@example.test', 'commit', '-m', 'first');
158
+ await git(one, 'push', managed.path, 'main');
159
+
160
+ const two = path.join(root, 'two');
161
+ await git(root, 'clone', '-b', 'main', managed.path, two);
162
+ // Whatever this machine's git makes of line endings on checkout.
163
+ expect((await fs.readFile(path.join(two, 'README.md'), 'utf8')).replace(/\r\n/g, '\n')).toBe('hello\n');
164
+ expect(await git(two, 'config', '--get', 'remote.origin.url')).toBe(managed.path);
165
+ });
166
+
167
+ it('is left exactly as it is when it already exists', async () => {
168
+ const managed = new ManagedRepository(path.join(root, 'managed-repository'));
169
+ await managed.ensure(runner);
170
+ const work = path.join(root, 'work');
171
+ await fs.mkdir(work);
172
+ await git(work, 'init', '--initial-branch=main');
173
+ await fs.writeFile(path.join(work, 'a.md'), 'a\n');
174
+ await git(work, 'add', '.');
175
+ await git(work, '-c', 'user.name=t', '-c', 'user.email=t@example.test', 'commit', '-m', 'first');
176
+ await git(work, 'push', managed.path, 'main');
177
+ const before = await git(managed.path, 'for-each-ref');
178
+
179
+ await managed.ensure(runner, 'another-branch');
180
+ expect(await git(managed.path, 'for-each-ref')).toBe(before);
181
+ expect(await git(managed.path, 'symbolic-ref', 'HEAD')).toBe('refs/heads/main');
182
+ });
183
+
184
+ it('refuses a folder that holds something that is not a repository', async () => {
185
+ const managed = new ManagedRepository(path.join(root, 'managed-repository'));
186
+ await fs.mkdir(managed.path, { recursive: true });
187
+ await fs.writeFile(path.join(managed.path, 'somebody.txt'), 'theirs');
188
+ await expect(managed.ensure(runner)).rejects.toThrow(/is not a git repository/);
189
+ expect(await fs.readFile(path.join(managed.path, 'somebody.txt'), 'utf8')).toBe('theirs');
190
+ });
191
+ });