agent-merge-broker 0.3.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 (75) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +352 -0
  3. package/dist/broker.d.ts +110 -0
  4. package/dist/broker.d.ts.map +1 -0
  5. package/dist/broker.js +1023 -0
  6. package/dist/broker.js.map +1 -0
  7. package/dist/cli.d.ts +3 -0
  8. package/dist/cli.d.ts.map +1 -0
  9. package/dist/cli.js +558 -0
  10. package/dist/cli.js.map +1 -0
  11. package/dist/config.d.ts +19 -0
  12. package/dist/config.d.ts.map +1 -0
  13. package/dist/config.js +312 -0
  14. package/dist/config.js.map +1 -0
  15. package/dist/errors.d.ts +16 -0
  16. package/dist/errors.d.ts.map +1 -0
  17. package/dist/errors.js +36 -0
  18. package/dist/errors.js.map +1 -0
  19. package/dist/git.d.ts +46 -0
  20. package/dist/git.d.ts.map +1 -0
  21. package/dist/git.js +195 -0
  22. package/dist/git.js.map +1 -0
  23. package/dist/hooks.d.ts +22 -0
  24. package/dist/hooks.d.ts.map +1 -0
  25. package/dist/hooks.js +110 -0
  26. package/dist/hooks.js.map +1 -0
  27. package/dist/index.d.ts +11 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +10 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/patterns.d.ts +9 -0
  32. package/dist/patterns.d.ts.map +1 -0
  33. package/dist/patterns.js +66 -0
  34. package/dist/patterns.js.map +1 -0
  35. package/dist/process.d.ts +30 -0
  36. package/dist/process.d.ts.map +1 -0
  37. package/dist/process.js +91 -0
  38. package/dist/process.js.map +1 -0
  39. package/dist/provenance.d.ts +10 -0
  40. package/dist/provenance.d.ts.map +1 -0
  41. package/dist/provenance.js +36 -0
  42. package/dist/provenance.js.map +1 -0
  43. package/dist/publisher.d.ts +37 -0
  44. package/dist/publisher.d.ts.map +1 -0
  45. package/dist/publisher.js +144 -0
  46. package/dist/publisher.js.map +1 -0
  47. package/dist/scheduler.d.ts +6 -0
  48. package/dist/scheduler.d.ts.map +1 -0
  49. package/dist/scheduler.js +96 -0
  50. package/dist/scheduler.js.map +1 -0
  51. package/dist/store.d.ts +73 -0
  52. package/dist/store.d.ts.map +1 -0
  53. package/dist/store.js +323 -0
  54. package/dist/store.js.map +1 -0
  55. package/dist/types.d.ts +219 -0
  56. package/dist/types.d.ts.map +1 -0
  57. package/dist/types.js +3 -0
  58. package/dist/types.js.map +1 -0
  59. package/dist/validation.d.ts +13 -0
  60. package/dist/validation.d.ts.map +1 -0
  61. package/dist/validation.js +75 -0
  62. package/dist/validation.js.map +1 -0
  63. package/dist/verify.d.ts +40 -0
  64. package/dist/verify.d.ts.map +1 -0
  65. package/dist/verify.js +177 -0
  66. package/dist/verify.js.map +1 -0
  67. package/docs/ARCHITECTURE.md +144 -0
  68. package/docs/PROTOCOL.md +127 -0
  69. package/docs/RELEASING.md +23 -0
  70. package/docs/SECURITY.md +57 -0
  71. package/package.json +68 -0
  72. package/schemas/config.schema.json +149 -0
  73. package/schemas/provenance.schema.json +56 -0
  74. package/schemas/receipt.schema.json +39 -0
  75. package/templates/AGENTS.snippet.md +5 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 PowerHouse Exteriors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,352 @@
1
+ # Agent Merge Broker
2
+
3
+ **Four agents just finished at the same time. Who merges first?**
4
+
5
+ Agent Merge Broker answers that so your agents never have to. Workers commit their work and stop. The broker decides what can safely go together, cherry-picks it into a disposable worktree, runs your test suite against the combination, and lands one validated branch or pull request.
6
+
7
+ No agent pushes. No agent rebases. No agent quietly clobbers another agent's `package-lock.json`.
8
+
9
+ ## The problem
10
+
11
+ Put four coding agents on one repository and the bottleneck stops being code. It becomes Git.
12
+
13
+ Two agents edit the same file and find out at merge time. A third rebases onto a branch that moved twenty minutes ago. Everyone regenerates the lockfile. CI runs four times to test four things that were never once tested *together*. And the pull request that has been sitting there since lunch is now so far behind `main` that nothing can merge it at all.
14
+
15
+ The work is parallel. Integration is not. Every worker doing its own integration turns a coordination problem into a coordination disaster.
16
+
17
+ ## Try it in one minute
18
+
19
+ ```bash
20
+ git clone https://github.com/WeSpitfire/agent-merge-broker
21
+ cd agent-merge-broker && npm install && npm run build && npm run example
22
+ ```
23
+
24
+ Two workers race on a throwaway repository, a third gets turned away for claiming ground someone else already leased, and four commits land as one validated branch. No forge, no network, no credentials.
25
+
26
+ It is also this project's acceptance test in CI — so if the demo ever stops telling the truth, the build goes red.
27
+
28
+ ## How it works
29
+
30
+ One integration authority; implementation stays distributed:
31
+
32
+ - Expiring, cross-worktree leases prevent predictable collisions before editing.
33
+ - Commit receipts separate implementation from integration authority.
34
+ - A deterministic conflict/dependency scheduler forms bounded batches.
35
+ - Every batch is tested through real cherry-picks in a disposable worktree.
36
+ - Focused checks run after each task and authoritative checks run over the batch.
37
+ - Successful work becomes one local branch, remote branch, or GitHub pull request.
38
+ - Published branches can carry a committed provenance manifest for fast remote policy checks.
39
+ - Tasks are dependency-complete only after their batch is actually merged.
40
+ - An append-only audit stream records lifecycle decisions and validation results.
41
+
42
+ It is deliberately **not** an agent framework and **not** a replacement for protected branches. Codex, Claude, Cursor, custom agents, CI jobs, and humans all speak the same small commit-receipt protocol, and your forge keeps the final say on what merges.
43
+
44
+ ## Status
45
+
46
+ `0.3.0` is the first public release. It contains the local broker core, the GitHub CLI publishing adapter with auto-merge, and the remote provenance verifier.
47
+
48
+ The on-disk state, receipt, and provenance formats are versioned, but compatibility is not guaranteed until `1.0.0`. Expect format migrations before then.
49
+
50
+ ## Requirements
51
+
52
+ - Node.js 20.12 or newer
53
+ - Git 2.31 or newer with worktree support
54
+ - GitHub CLI only when `publish.mode` is `pull-request`
55
+
56
+ Linux and macOS are the supported platforms and are covered by CI. Windows runs as an informational
57
+ CI job: shell selection and command quoting differ there and are not yet supported.
58
+
59
+ ## Install
60
+
61
+ Install it as a development tool:
62
+
63
+ ```bash
64
+ npm install --save-dev agent-merge-broker
65
+ npx merge-broker init --base main --base-ref origin/main
66
+ ```
67
+
68
+ To work on the broker itself, clone this repository and link the CLI:
69
+
70
+ ```bash
71
+ npm install
72
+ npm run build
73
+ npm link
74
+ ```
75
+
76
+ `init` writes two portable files into the application:
77
+
78
+ - `.merge-broker/config.json` — repository policy and commands
79
+ - `.merge-broker/agent-instructions.md` — a reusable worker contract
80
+
81
+ Runtime state, receipt records, manifests, locks, and integration worktrees live under Git's common directory. Every linked worktree therefore sees the same broker state, while runtime artifacts do not pollute commits.
82
+
83
+ ## Quick start
84
+
85
+ Initialize an existing Git repository and edit its generated configuration:
86
+
87
+ ```bash
88
+ merge-broker init --base main --base-ref origin/main --remote origin
89
+ merge-broker doctor
90
+ ```
91
+
92
+ An orchestrator or worker claims a narrowly scoped task:
93
+
94
+ ```bash
95
+ merge-broker task claim CRM-142 \
96
+ --holder codex/customer-page \
97
+ --path 'src/customers/**' \
98
+ --path 'test/customers/**'
99
+ ```
100
+
101
+ The broker keeps the lease token beside its own state, readable only by the user who claimed the
102
+ task, so nothing in the worker has to carry a credential:
103
+
104
+ ```bash
105
+ merge-broker task heartbeat CRM-142
106
+ ```
107
+
108
+ Pass `--token`, `--token-file`, or `MERGE_BROKER_TOKEN` when the worker runs somewhere else, or
109
+ claim with `--no-store-token` to handle custody yourself.
110
+
111
+ The worker commits its change and submits a receipt. It does not merge or push:
112
+
113
+ ```bash
114
+ git commit -m 'Add customer search filters'
115
+ merge-broker task submit CRM-142 --since-base
116
+ ```
117
+
118
+ `--since-base` submits the linear commits made after the base the broker handed out, skipping any
119
+ whose change is already upstream. Pass explicit `--commit` revisions instead when a worker wants to
120
+ hand over only part of its branch.
121
+
122
+ The integration owner can inspect and verify the next batch before retaining anything:
123
+
124
+ ```bash
125
+ merge-broker plan
126
+ merge-broker integrate --dry-run
127
+ merge-broker integrate
128
+ ```
129
+
130
+ With publishing enabled in the configuration:
131
+
132
+ ```bash
133
+ merge-broker integrate --publish
134
+ merge-broker batch sync <batch-id>
135
+ ```
136
+
137
+ `batch sync` checks the GitHub PR when available. For branch-only publication it fetches the configured base and verifies ancestry. `batch complete` exists as an explicit manual escape hatch for squash/rebase workflows that cannot be reconciled automatically.
138
+
139
+ ## See it work
140
+
141
+ ```bash
142
+ npm run build
143
+ sh examples/two-agents/run.sh
144
+ ```
145
+
146
+ [`examples/two-agents`](examples/two-agents/) builds a throwaway repository, runs two workers in
147
+ parallel worktrees, refuses a third worker that tries to claim an area already leased, and assembles
148
+ four commits into one validated branch. No forge, no network, no credentials.
149
+
150
+ ## Enforcing the broker
151
+
152
+ Nothing above prevents a worker from pushing its own branch and opening a pull request. Two optional
153
+ guards close that gap.
154
+
155
+ A local guard refuses direct pushes of implementation branches:
156
+
157
+ ```bash
158
+ merge-broker install-hooks
159
+ ```
160
+
161
+ This sets `core.hooksPath`, so it refuses to run when the repository already has hooks that would
162
+ stop working, and `--uninstall` puts everything back. `MERGE_BROKER_ALLOW_DIRECT_PUSH=1` is the
163
+ deliberate emergency bypass.
164
+
165
+ A remote gate proves a pull request really is an unaltered broker batch. It reads only Git, so it
166
+ can run before any dependency is installed and reject bypassed work for almost nothing:
167
+
168
+ ```yaml
169
+ - uses: actions/checkout@v4
170
+ with:
171
+ ref: ${{ github.event.pull_request.head.sha }}
172
+ fetch-depth: 0
173
+ - uses: WeSpitfire/agent-merge-broker/verify@v1
174
+ ```
175
+
176
+ The check confirms that the branch is a broker integration branch, that its manifest was assembled
177
+ on real base history, that the final commit changes nothing but that manifest, that the integrated
178
+ diff matches exactly the paths the receipts account for, that every submitted commit is present, and
179
+ that all recorded validations passed. It accepts the "update branch" merges a protected base
180
+ produces, and rejects a merge that brings in anything the base does not already contain.
181
+
182
+ Verification policy is read from the configuration committed on the *base* branch, never from the
183
+ change under review.
184
+
185
+ ## Automatic merging
186
+
187
+ With `publish.mode` set to `pull-request` and `publish.autoMerge` enabled, the broker enables GitHub auto-merge on each published batch. GitHub lands the pull request once required status checks pass and updates the branch when the base branch requires it. The broker never pushes to the base branch itself, so branch protection remains the authority on what may merge.
188
+
189
+ Two configuration combinations cannot work and are rejected at load time rather than stalling silently:
190
+
191
+ - `autoMerge` with `draft`, because GitHub refuses to merge a draft pull request
192
+ - `autoMerge` with `publish.mode` set to `branch`, because there is no pull request to merge
193
+
194
+ Auto-merge requires the setting to be enabled on the GitHub repository. Configurations written before this feature existed default to `autoMerge: false`, so upgrading never starts landing work on its own.
195
+
196
+ Running `merge-broker serve --publish` closes the loop: each cycle reconciles published batches, integrates the next batch, and publishes it for auto-merge.
197
+
198
+ ## Failure recovery
199
+
200
+ Integration failures are attributed as narrowly as the evidence allows:
201
+
202
+ - A cherry-pick conflict or focused validation failure fails only the responsible task. Its batch-mates return to the queue and are re-planned, so one bad commit cannot stall unrelated agents.
203
+ - An authoritative validation failure indicts the whole batch, because no single task can be blamed. Those tasks stay `failed` until `task retry`.
204
+ - A pull request closed without merging moves the batch to `closed` and returns its tasks to the queue. Leaving such a batch `published` strands the work and reads like success.
205
+
206
+ `integration.maxAttempts` bounds automatic re-queueing so a task that never integrates eventually stops consuming CI capacity and waits for a human. `task retry` resets that budget.
207
+
208
+ A process that dies mid-integration leaves its lock behind. A holder on this machine is reclaimed automatically once its process is gone, but a holder on another machine cannot be probed at all and would otherwise block integration for the full stale window. `merge-broker unlock` reports lock state and releases a lock whose owner is provably gone; `--force` overrides that check and should follow confirming that no integration is running.
209
+
210
+ ## Housekeeping
211
+
212
+ `state.json` is rewritten in full on every transaction, including heartbeats, so completed work should not accumulate in it forever:
213
+
214
+ ```bash
215
+ merge-broker prune --older-than 30 --dry-run
216
+ merge-broker prune --older-than 30
217
+ ```
218
+
219
+ Retired tasks and batches move to `<state>/archive/`, and the audit stream rotates into the same place once the active file grows large. Nothing is deleted. A completed task is kept in active state for as long as any retained task still declares it as a dependency, because the scheduler cannot distinguish a pruned dependency from one that has never merged.
220
+
221
+ ## Configuration
222
+
223
+ The generated `.merge-broker/config.json` is intentionally explicit and reviewable. `baseBranch` is the forge/PR target, while `baseRef` is the Git revision used to construct a batch; repositories that keep a passive local `main` should use `origin/main`:
224
+
225
+ ```json
226
+ {
227
+ "version": 1,
228
+ "baseBranch": "main",
229
+ "baseRef": "origin/main",
230
+ "remote": "origin",
231
+ "stateDirectory": "merge-broker",
232
+ "leases": {
233
+ "ttlSeconds": 1800,
234
+ "lockTimeoutSeconds": 15,
235
+ "serializedPatterns": ["package-lock.json", "pnpm-lock.yaml", "yarn.lock"]
236
+ },
237
+ "policies": {
238
+ "unexpectedPaths": "error",
239
+ "requireCleanWorktree": false,
240
+ "requireDependencies": true
241
+ },
242
+ "scheduling": {
243
+ "maxTasks": 6,
244
+ "maxCommits": 12,
245
+ "maxWaitSeconds": 600,
246
+ "allowPathOverlap": false
247
+ },
248
+ "integration": {
249
+ "branchPrefix": "merge-broker/",
250
+ "history": "preserve",
251
+ "keepFailedWorktrees": false,
252
+ "refreshBase": true,
253
+ "maxAttempts": 3,
254
+ "provenance": {
255
+ "enabled": true,
256
+ "directory": ".merge-broker/attestations"
257
+ }
258
+ },
259
+ "validation": {
260
+ "shell": "/bin/sh",
261
+ "focused": [
262
+ {
263
+ "name": "related tests",
264
+ "paths": ["src/**", "test/**"],
265
+ "command": "npm test -- {files}",
266
+ "timeoutSeconds": 900
267
+ }
268
+ ],
269
+ "authoritative": [
270
+ { "name": "test", "command": "npm test", "timeoutSeconds": 1800 },
271
+ { "name": "build", "command": "npm run build", "timeoutSeconds": 1800 }
272
+ ]
273
+ },
274
+ "publish": {
275
+ "mode": "pull-request",
276
+ "draft": false,
277
+ "autoMerge": true,
278
+ "mergeMethod": "squash",
279
+ "labels": ["integration-batch"],
280
+ "titleTemplate": "Integration batch {batchId}"
281
+ }
282
+ }
283
+ ```
284
+
285
+ Validator commands run inside the isolated integration worktree, under `/bin/sh` unless
286
+ `validation.shell` names another interpreter. The shell is deliberately fixed and is never a login
287
+ shell: an integration decision must not depend on whose machine assembled the batch. The environment
288
+ is inherited from the process that invoked the broker, minus `MERGE_BROKER_TOKEN`, so PATH and
289
+ toolchain managers work while worker credentials stay out of repository-defined commands.
290
+
291
+ Validators receive these environment variables:
292
+
293
+ - `MERGE_BROKER_TASK_ID`
294
+ - `MERGE_BROKER_FILES`, newline-separated
295
+ - `MERGE_BROKER_BASE_SHA`
296
+ - `MERGE_BROKER_HEAD_SHA`
297
+ - `MERGE_BROKER_BATCH_ID`
298
+
299
+ Commands may also use the shell-safe placeholders `{taskId}` and `{files}`. Validator output retained in state is capped to prevent unbounded growth.
300
+
301
+ The JSON schemas in [`schemas/`](schemas/) can be used by editors, adapters, and independent receipt producers.
302
+
303
+ ### One authoritative CI pass
304
+
305
+ Repositories that make GitHub the authoritative validator can leave broker
306
+ authoritative validators empty, keep provenance enabled, and reject any PR
307
+ without a valid broker manifest before installing dependencies. The full lint,
308
+ type, test, and build suite then runs exactly once on the assembled broker PR.
309
+ Task worktrees retain only fast changed-scope feedback, while deployment builds
310
+ the already-checked revision without repeating the whole suite.
311
+
312
+ ## Command surface
313
+
314
+ ```text
315
+ merge-broker init
316
+ merge-broker doctor
317
+ merge-broker install-hooks [--force] [--uninstall]
318
+ merge-broker verify-provenance --branch <ref> --head <sha> --base <sha>
319
+ merge-broker task register|claim|extend|heartbeat|submit|retry|release|cancel|show
320
+ merge-broker status
321
+ merge-broker plan
322
+ merge-broker integrate [--dry-run] [--publish]
323
+ merge-broker batch list|show|publish|sync|complete
324
+ merge-broker audit
325
+ merge-broker metrics
326
+ merge-broker events
327
+ merge-broker prune [--older-than <days>] [--dry-run]
328
+ merge-broker unlock [state|integration] [--force]
329
+ merge-broker serve [--publish] [--eager]
330
+ ```
331
+
332
+ Every command accepts `--json` for adapters and `-C <directory>` for explicit repository discovery. Lease-aware commands also accept `MERGE_BROKER_TOKEN`.
333
+
334
+ ## Guarantees and limits
335
+
336
+ Path overlap is a conservative coordination signal, not proof of semantic compatibility. Non-overlapping tasks can still break contracts. For this reason, the disposable worktree and authoritative validation—not the scheduler—are the final integration decision.
337
+
338
+ The scheduler uses a deterministic weighted greedy heuristic. It does not claim to solve the NP-hard maximum independent set problem optimally. Batches are deliberately capped because very large batches reduce CI traffic but increase failure blast radius.
339
+
340
+ Configuration is trusted repository code: validator commands can execute arbitrary shell commands. Review configuration changes with the same care as CI workflows. See [`docs/SECURITY.md`](docs/SECURITY.md).
341
+
342
+ ## Documentation
343
+
344
+ - [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) — invariants, state model, scheduling, and transactions
345
+ - [`docs/PROTOCOL.md`](docs/PROTOCOL.md) — lifecycle and adapter contract
346
+ - [`docs/SECURITY.md`](docs/SECURITY.md) — trust boundaries and hardening
347
+ - [`docs/RELEASING.md`](docs/RELEASING.md) — registry and release procedure
348
+ - [`CONTRIBUTING.md`](CONTRIBUTING.md) — development and pull requests
349
+
350
+ ## License
351
+
352
+ Apache License 2.0. See [`LICENSE`](LICENSE).
@@ -0,0 +1,110 @@
1
+ import { GitRepository } from "./git.js";
2
+ import { StateStore, type LockStatus } from "./store.js";
3
+ import { type HookInstallation } from "./hooks.js";
4
+ import type { BatchRecord, BrokerConfig, BrokerState, IntegrationOptions, IntegrationResult, PruneOptions, PruneResult, SchedulePlan, TaskRecord } from "./types.js";
5
+ export interface RegisterTaskInput {
6
+ id: string;
7
+ title?: string;
8
+ agent?: string;
9
+ base?: string;
10
+ expectedPaths?: string[];
11
+ dependsOn?: string[];
12
+ priority?: number;
13
+ worktree?: string;
14
+ }
15
+ export interface ClaimTaskInput extends RegisterTaskInput {
16
+ holder: string;
17
+ /** Set false to keep the token out of broker state entirely and handle custody elsewhere. */
18
+ storeToken?: boolean;
19
+ /** Write the token here instead of the default location inside the broker state directory. */
20
+ tokenFile?: string;
21
+ }
22
+ export declare class MergeBroker {
23
+ readonly repo: GitRepository;
24
+ readonly config: BrokerConfig;
25
+ readonly store: StateStore;
26
+ private constructor();
27
+ static open(cwd?: string): Promise<MergeBroker>;
28
+ static initialize(cwd?: string, options?: {
29
+ baseBranch?: string;
30
+ baseRef?: string;
31
+ remote?: string;
32
+ force?: boolean;
33
+ }): Promise<{
34
+ repoRoot: string;
35
+ configPath: string;
36
+ created: boolean;
37
+ }>;
38
+ registerTask(input: RegisterTaskInput): Promise<TaskRecord>;
39
+ claimTask(input: ClaimTaskInput): Promise<{
40
+ task: TaskRecord;
41
+ token: string;
42
+ tokenPath?: string;
43
+ }>;
44
+ heartbeat(taskId: string, token: string): Promise<TaskRecord>;
45
+ extendTask(taskId: string, expectedPaths: string[], token: string): Promise<TaskRecord>;
46
+ releaseTask(taskId: string, token?: string, options?: {
47
+ force?: boolean;
48
+ }): Promise<TaskRecord>;
49
+ cancelTask(taskId: string, token?: string, options?: {
50
+ force?: boolean;
51
+ }): Promise<TaskRecord>;
52
+ retryTask(taskId: string, token?: string): Promise<TaskRecord>;
53
+ submitTask(taskId: string, commits: string[], token: string, options?: {
54
+ sinceBase?: boolean;
55
+ }): Promise<{
56
+ task: TaskRecord;
57
+ receiptPath: string;
58
+ }>;
59
+ state(): Promise<BrokerState>;
60
+ task(taskId: string): Promise<TaskRecord>;
61
+ plan(options?: {
62
+ taskIds?: string[];
63
+ maxTasks?: number;
64
+ }): Promise<SchedulePlan>;
65
+ integrate(options?: IntegrationOptions): Promise<IntegrationResult>;
66
+ publishBatch(id: string): Promise<BatchRecord>;
67
+ syncBatch(id: string): Promise<BatchRecord>;
68
+ syncPublishedBatches(): Promise<{
69
+ synced: BatchRecord[];
70
+ closed: BatchRecord[];
71
+ unchanged: BatchRecord[];
72
+ errors: Array<{
73
+ batchId: string;
74
+ error: string;
75
+ }>;
76
+ }>;
77
+ /**
78
+ * Records that a published batch will never merge and returns its tasks to the queue, so the work
79
+ * is re-planned against a fresh base instead of being silently lost.
80
+ */
81
+ closeBatch(id: string, reason: string): Promise<BatchRecord>;
82
+ markBatchMerged(id: string, mergedAt?: string, mergeCommitSha?: string): Promise<BatchRecord>;
83
+ auditWorktrees(): Promise<{
84
+ worktrees: Array<{
85
+ path: string;
86
+ branch?: string;
87
+ registeredTaskIds: string[];
88
+ clean: boolean;
89
+ }>;
90
+ staleLeases: string[];
91
+ unregisteredWorktrees: string[];
92
+ }>;
93
+ /**
94
+ * Retires completed records so `state.json` stops growing without bound. The file is rewritten in
95
+ * full on every transaction, including heartbeats, so an unbounded history makes routine
96
+ * operations progressively slower.
97
+ */
98
+ prune(options?: PruneOptions): Promise<PruneResult>;
99
+ installHooks(options?: {
100
+ force?: boolean;
101
+ uninstall?: boolean;
102
+ }): Promise<HookInstallation>;
103
+ inspectLocks(): Promise<LockStatus[]>;
104
+ releaseLock(name: string, options?: {
105
+ force?: boolean;
106
+ }): Promise<LockStatus>;
107
+ metrics(): Promise<Record<string, unknown>>;
108
+ doctor(): Promise<Record<string, unknown>>;
109
+ }
110
+ //# sourceMappingURL=broker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"broker.d.ts","sourceRoot":"","sources":["../src/broker.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAIzC,OAAO,EAAE,UAAU,EAAE,KAAK,UAAU,EAAE,MAAM,YAAY,CAAC;AAIzD,OAAO,EAAgC,KAAK,gBAAgB,EAAE,MAAM,YAAY,CAAC;AACjF,OAAO,KAAK,EACV,WAAW,EACX,YAAY,EACZ,WAAW,EAEX,kBAAkB,EAClB,iBAAiB,EACjB,YAAY,EACZ,WAAW,EACX,YAAY,EACZ,UAAU,EAEX,MAAM,YAAY,CAAC;AAgKpB,MAAM,WAAW,iBAAiB;IAChC,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;IACrB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QA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