forkbridge 0.3.0__tar.gz

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.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,138 @@
1
+ Metadata-Version: 2.4
2
+ Name: forkbridge
3
+ Version: 0.3.0
4
+ Summary: Evidence-first contract verification for Git forks and upstream updates
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Repository, https://github.com/kexyz254/forkbridge
7
+ Keywords: git,fork,contracts,ci,agents
8
+ Requires-Python: >=3.11
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Provides-Extra: test
12
+ Requires-Dist: pytest>=8; extra == "test"
13
+ Requires-Dist: jsonschema>=4; extra == "test"
14
+ Provides-Extra: mcp
15
+ Requires-Dist: mcp<3,>=2.3; extra == "mcp"
16
+ Dynamic: license-file
17
+
18
+ # ForkBridge
19
+
20
+ **A clean merge is not evidence that your fork still meets its requirements.**
21
+
22
+ ForkBridge is a dependency-free CLI and GitHub Action that checks explicit file and configuration contracts against both a Git fork and a hypothetical upstream merge. It reports reproducible evidence for humans, CI pipelines and AI coding agents, without checking out or executing project code.
23
+
24
+ ## Quick start
25
+
26
+ Download the wheel from [GitHub Releases](https://github.com/kexyz254/forkbridge/releases) and install it with `python -m pip install /path/to/downloaded-wheel.whl`. Use the commands below from a source checkout to install and verify.
27
+
28
+ Requires Python 3.11+ and Git 2.38+ with `merge-tree --write-tree` support. Use a trusted local repository with complete history and both refs already available.
29
+
30
+ ```sh
31
+ python -m pip install .
32
+ forkbridge capabilities
33
+ forkbridge verify --repo /path/to/repo --fork HEAD --upstream upstream/main --contracts /path/to/contracts.json
34
+ ```
35
+
36
+ The contract file is external policy: do not allow the candidate update to rewrite it. See [example contracts](examples/contracts.json) and [agent integration](AGENTS.md).
37
+
38
+ ```json
39
+ {"version":1,"contracts":[{"id":"sqlite-enabled","kind":"json_equals","path":"config.json","pointer":"/database/sqlite","value":true}]}
40
+ ```
41
+
42
+ | Contract | What it verifies |
43
+ | --- | --- |
44
+ | `exists` | Regular tracked file exists |
45
+ | `contains` | UTF-8 file contains a literal string |
46
+ | `sha256` | Exact file bytes match a SHA-256 digest |
47
+ | `json_equals` | JSON pointer resolves to the expected typed JSON value (numbers use Python JSON representation) |
48
+
49
+ ## Run in GitHub Actions
50
+
51
+ This workflow checks upstream on demand from your fork's default branch. Set the two upstream values for your project, and commit a contract file at `.github/forkbridge.json` on your fork. Policy comes from the selected fork commit.
52
+
53
+ ```yaml
54
+ name: Verify upstream update
55
+ on:
56
+ workflow_dispatch:
57
+ permissions:
58
+ contents: read
59
+ jobs:
60
+ verify:
61
+ runs-on: ubuntu-latest
62
+ env:
63
+ UPSTREAM_URL: https://github.com/UPSTREAM_OWNER/UPSTREAM_REPO.git
64
+ UPSTREAM_REF: refs/heads/main
65
+ steps:
66
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
67
+ with:
68
+ fetch-depth: 0
69
+ persist-credentials: false
70
+ - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
71
+ with:
72
+ python-version: '3.11'
73
+ - name: Fetch upstream and extract the fork policy
74
+ run: |
75
+ git fetch --no-tags "$UPSTREAM_URL" "$UPSTREAM_REF:refs/forkbridge/upstream"
76
+ git show HEAD:.github/forkbridge.json > "$RUNNER_TEMP/forkbridge-policy.json"
77
+ - uses: kexyz254/forkbridge@v0.3.0
78
+ id: verify
79
+ with:
80
+ fork: HEAD
81
+ upstream: refs/forkbridge/upstream
82
+ contracts: ${{ runner.temp }}/forkbridge-policy.json
83
+ - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
84
+ if: always() && steps.verify.outputs.report != ''
85
+ with:
86
+ name: forkbridge-report
87
+ path: ${{ steps.verify.outputs.report }}
88
+ ```
89
+
90
+ The action fails the job for regressions, merge conflicts, inconclusive results and errors. Open the uploaded report to see the commit IDs and per-contract evidence. On self-hosted runners, use the action with a trusted local checkout and Python 3.11+ and Git 2.38+ on the path.
91
+
92
+ ## Agent and CI protocol
93
+
94
+ `verify` emits one JSON object on stdout. It includes resolved fork and upstream commit IDs, merge base, candidate tree ID, contract digest and per-contract baseline/candidate blob IDs and outcomes. A passing result means only that the listed static contracts are preserved. Unknown data, a failing baseline, or unrelated histories cannot produce a pass.
95
+
96
+ | Exit | Status | Action |
97
+ | --- | --- | --- |
98
+ | 0 | `verified` | Listed contracts preserved; continue normal review |
99
+ | 10 | `regression` | Block update and investigate failed contracts |
100
+ | 11 | `conflict` | Resolve merge conflict separately |
101
+ | 12 | `inconclusive` | Investigate missing or invalid evidence |
102
+ | 2 | `error` | Correct inputs or infrastructure |
103
+
104
+ ForkBridge never fetches remote upstream refs itself, pushes, merges into the source repository, or executes contract commands. It uses a temporary bare mirror and native Git merge-tree. It may read committed secrets in the selected files, but reports only identifiers, paths and verdicts, not file contents. Contract literals and paths are not intended for secrets.
105
+
106
+ ## Connect an MCP client
107
+
108
+ Install the optional MCP adapter from a checkout with `python -m pip install '.[mcp]'`. In your client's local stdio server configuration, set the command to the absolute path of the installed `forkbridge-mcp` executable and pass these arguments.
109
+
110
+ ```json
111
+ {
112
+ "command": "/absolute/path/to/forkbridge-mcp",
113
+ "args": ["--repo", "/path/to/local/fork", "--contracts", "/path/to/trusted/policy.json"]
114
+ }
115
+ ```
116
+
117
+ The server exposes `verify_merge(fork_oid, upstream_oid)` and returns the same structured evidence as the CLI. Both arguments are full Git commit IDs already present in the configured checkout. The operator selects the one checkout and the policy file outside it at startup. Run the server with a trusted local repository and complete history.
118
+
119
+ ## See the difference
120
+
121
+ ```sh
122
+ python examples/demo.py
123
+ ```
124
+
125
+ This generates a synthetic Git fork whose upstream change merges cleanly yet disables a required feature. Expected exit status: `10`. The example prints the full JSON report. The [yt-dlp case study](docs/case-study.md) replays two updates from a real upstream history.
126
+
127
+ ## Development
128
+
129
+ ```sh
130
+ python -m pip install -e '.[test,mcp]'
131
+ pytest -q
132
+ ```
133
+
134
+ ## Boundaries
135
+
136
+ ForkBridge checks committed content using static policies. Runtime behavior, dependency analysis and automatic remediation are outside the current release. The candidate merge uses native default Git semantics in a disposable mirror; custom merge drivers and local configuration may yield a different result in an actual merge. Trusted local repositories only; use OS/container isolation when processing untrusted repositories. Timeouts and blob/config limits are not a complete resource-exhaustion defense. Shallow/partial histories, large repositories, non-UTF-8 paths and exotic Git layouts may fail or be inconclusive. CI tests the CLI and MCP adapter on Linux, Windows and macOS, and exercises the Action and Python distributions on Linux.
137
+
138
+ See [security](SECURITY.md), [contributing](CONTRIBUTING.md), [protocol](docs/protocol.md), [roadmap](docs/ROADMAP.md), and [publishing](docs/distribution.md). Apache-2.0 licensed. No affiliation with GitHub.
@@ -0,0 +1,121 @@
1
+ # ForkBridge
2
+
3
+ **A clean merge is not evidence that your fork still meets its requirements.**
4
+
5
+ ForkBridge is a dependency-free CLI and GitHub Action that checks explicit file and configuration contracts against both a Git fork and a hypothetical upstream merge. It reports reproducible evidence for humans, CI pipelines and AI coding agents, without checking out or executing project code.
6
+
7
+ ## Quick start
8
+
9
+ Download the wheel from [GitHub Releases](https://github.com/kexyz254/forkbridge/releases) and install it with `python -m pip install /path/to/downloaded-wheel.whl`. Use the commands below from a source checkout to install and verify.
10
+
11
+ Requires Python 3.11+ and Git 2.38+ with `merge-tree --write-tree` support. Use a trusted local repository with complete history and both refs already available.
12
+
13
+ ```sh
14
+ python -m pip install .
15
+ forkbridge capabilities
16
+ forkbridge verify --repo /path/to/repo --fork HEAD --upstream upstream/main --contracts /path/to/contracts.json
17
+ ```
18
+
19
+ The contract file is external policy: do not allow the candidate update to rewrite it. See [example contracts](examples/contracts.json) and [agent integration](AGENTS.md).
20
+
21
+ ```json
22
+ {"version":1,"contracts":[{"id":"sqlite-enabled","kind":"json_equals","path":"config.json","pointer":"/database/sqlite","value":true}]}
23
+ ```
24
+
25
+ | Contract | What it verifies |
26
+ | --- | --- |
27
+ | `exists` | Regular tracked file exists |
28
+ | `contains` | UTF-8 file contains a literal string |
29
+ | `sha256` | Exact file bytes match a SHA-256 digest |
30
+ | `json_equals` | JSON pointer resolves to the expected typed JSON value (numbers use Python JSON representation) |
31
+
32
+ ## Run in GitHub Actions
33
+
34
+ This workflow checks upstream on demand from your fork's default branch. Set the two upstream values for your project, and commit a contract file at `.github/forkbridge.json` on your fork. Policy comes from the selected fork commit.
35
+
36
+ ```yaml
37
+ name: Verify upstream update
38
+ on:
39
+ workflow_dispatch:
40
+ permissions:
41
+ contents: read
42
+ jobs:
43
+ verify:
44
+ runs-on: ubuntu-latest
45
+ env:
46
+ UPSTREAM_URL: https://github.com/UPSTREAM_OWNER/UPSTREAM_REPO.git
47
+ UPSTREAM_REF: refs/heads/main
48
+ steps:
49
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
50
+ with:
51
+ fetch-depth: 0
52
+ persist-credentials: false
53
+ - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
54
+ with:
55
+ python-version: '3.11'
56
+ - name: Fetch upstream and extract the fork policy
57
+ run: |
58
+ git fetch --no-tags "$UPSTREAM_URL" "$UPSTREAM_REF:refs/forkbridge/upstream"
59
+ git show HEAD:.github/forkbridge.json > "$RUNNER_TEMP/forkbridge-policy.json"
60
+ - uses: kexyz254/forkbridge@v0.3.0
61
+ id: verify
62
+ with:
63
+ fork: HEAD
64
+ upstream: refs/forkbridge/upstream
65
+ contracts: ${{ runner.temp }}/forkbridge-policy.json
66
+ - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
67
+ if: always() && steps.verify.outputs.report != ''
68
+ with:
69
+ name: forkbridge-report
70
+ path: ${{ steps.verify.outputs.report }}
71
+ ```
72
+
73
+ The action fails the job for regressions, merge conflicts, inconclusive results and errors. Open the uploaded report to see the commit IDs and per-contract evidence. On self-hosted runners, use the action with a trusted local checkout and Python 3.11+ and Git 2.38+ on the path.
74
+
75
+ ## Agent and CI protocol
76
+
77
+ `verify` emits one JSON object on stdout. It includes resolved fork and upstream commit IDs, merge base, candidate tree ID, contract digest and per-contract baseline/candidate blob IDs and outcomes. A passing result means only that the listed static contracts are preserved. Unknown data, a failing baseline, or unrelated histories cannot produce a pass.
78
+
79
+ | Exit | Status | Action |
80
+ | --- | --- | --- |
81
+ | 0 | `verified` | Listed contracts preserved; continue normal review |
82
+ | 10 | `regression` | Block update and investigate failed contracts |
83
+ | 11 | `conflict` | Resolve merge conflict separately |
84
+ | 12 | `inconclusive` | Investigate missing or invalid evidence |
85
+ | 2 | `error` | Correct inputs or infrastructure |
86
+
87
+ ForkBridge never fetches remote upstream refs itself, pushes, merges into the source repository, or executes contract commands. It uses a temporary bare mirror and native Git merge-tree. It may read committed secrets in the selected files, but reports only identifiers, paths and verdicts, not file contents. Contract literals and paths are not intended for secrets.
88
+
89
+ ## Connect an MCP client
90
+
91
+ Install the optional MCP adapter from a checkout with `python -m pip install '.[mcp]'`. In your client's local stdio server configuration, set the command to the absolute path of the installed `forkbridge-mcp` executable and pass these arguments.
92
+
93
+ ```json
94
+ {
95
+ "command": "/absolute/path/to/forkbridge-mcp",
96
+ "args": ["--repo", "/path/to/local/fork", "--contracts", "/path/to/trusted/policy.json"]
97
+ }
98
+ ```
99
+
100
+ The server exposes `verify_merge(fork_oid, upstream_oid)` and returns the same structured evidence as the CLI. Both arguments are full Git commit IDs already present in the configured checkout. The operator selects the one checkout and the policy file outside it at startup. Run the server with a trusted local repository and complete history.
101
+
102
+ ## See the difference
103
+
104
+ ```sh
105
+ python examples/demo.py
106
+ ```
107
+
108
+ This generates a synthetic Git fork whose upstream change merges cleanly yet disables a required feature. Expected exit status: `10`. The example prints the full JSON report. The [yt-dlp case study](docs/case-study.md) replays two updates from a real upstream history.
109
+
110
+ ## Development
111
+
112
+ ```sh
113
+ python -m pip install -e '.[test,mcp]'
114
+ pytest -q
115
+ ```
116
+
117
+ ## Boundaries
118
+
119
+ ForkBridge checks committed content using static policies. Runtime behavior, dependency analysis and automatic remediation are outside the current release. The candidate merge uses native default Git semantics in a disposable mirror; custom merge drivers and local configuration may yield a different result in an actual merge. Trusted local repositories only; use OS/container isolation when processing untrusted repositories. Timeouts and blob/config limits are not a complete resource-exhaustion defense. Shallow/partial histories, large repositories, non-UTF-8 paths and exotic Git layouts may fail or be inconclusive. CI tests the CLI and MCP adapter on Linux, Windows and macOS, and exercises the Action and Python distributions on Linux.
120
+
121
+ See [security](SECURITY.md), [contributing](CONTRIBUTING.md), [protocol](docs/protocol.md), [roadmap](docs/ROADMAP.md), and [publishing](docs/distribution.md). Apache-2.0 licensed. No affiliation with GitHub.
@@ -0,0 +1,30 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "forkbridge"
7
+ version = "0.3.0"
8
+ description = "Evidence-first contract verification for Git forks and upstream updates"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = "Apache-2.0"
12
+ keywords = ["git", "fork", "contracts", "ci", "agents"]
13
+ dependencies = []
14
+
15
+ [project.scripts]
16
+ forkbridge = "forkbridge.cli:main"
17
+ forkbridge-mcp = "forkbridge.mcp_server:main"
18
+
19
+ [project.optional-dependencies]
20
+ test = ["pytest>=8", "jsonschema>=4"]
21
+ mcp = ["mcp>=2.3,<3"]
22
+
23
+ [project.urls]
24
+ Repository = "https://github.com/kexyz254/forkbridge"
25
+
26
+ [tool.setuptools.packages.find]
27
+ where = ["src"]
28
+
29
+ [tool.pytest.ini_options]
30
+ pythonpath = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,2 @@
1
+ """Evidence-first verification for Git forks."""
2
+ __version__ = "0.3.0"
@@ -0,0 +1,2 @@
1
+ from .cli import main
2
+ raise SystemExit(main())
@@ -0,0 +1,47 @@
1
+ """Run the verifier and expose its report to subsequent GitHub Actions steps."""
2
+
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+ import subprocess
7
+ import sys
8
+ from tempfile import NamedTemporaryFile
9
+
10
+ from .core import EXIT
11
+
12
+
13
+ def main() -> int:
14
+ command = [sys.executable, "-P", "-m", "forkbridge", "verify"]
15
+ for flag, key in (
16
+ ("repo", "REPO"),
17
+ ("fork", "FORK"),
18
+ ("upstream", "UPSTREAM"),
19
+ ("contracts", "CONTRACTS"),
20
+ ):
21
+ command.append(f"--{flag}={os.environ[f'FORKBRIDGE_{key}']}")
22
+
23
+ with NamedTemporaryFile(
24
+ dir=os.environ["RUNNER_TEMP"], prefix="forkbridge-", suffix=".json", delete=False
25
+ ) as report:
26
+ result = subprocess.run(command, stdout=report, check=False)
27
+ path = Path(report.name)
28
+ try:
29
+ payload = json.loads(path.read_bytes())
30
+ status = payload["status"]
31
+ if payload["schema_version"] != 1 or EXIT[status] != result.returncode:
32
+ raise ValueError("invalid verifier result")
33
+ except (KeyError, TypeError, ValueError):
34
+ status = "error"
35
+ path.write_text(
36
+ json.dumps({"schema_version": 1, "status": status, "reason": "invalid_verifier_output"}),
37
+ encoding="utf-8",
38
+ )
39
+
40
+ with Path(os.environ["GITHUB_OUTPUT"]).open("a", encoding="utf-8", newline="\n") as output:
41
+ output.write(f"status={status}\nreport={path}\n")
42
+ print(f"ForkBridge status: {status}")
43
+ return EXIT[status]
44
+
45
+
46
+ if __name__ == "__main__":
47
+ sys.exit(main())
@@ -0,0 +1,37 @@
1
+ """Stable JSON command-line interface for CI and automated agents."""
2
+ import argparse
3
+ import json
4
+ from pathlib import Path
5
+ from . import __version__
6
+ from .core import EXIT, VerificationError, verify
7
+
8
+ class Parser(argparse.ArgumentParser):
9
+ def error(self, message):
10
+ raise VerificationError(message)
11
+
12
+
13
+ def main(argv=None):
14
+ parser = Parser(prog="forkbridge", description="Verify explicit fork invariants before merging upstream.")
15
+ parser.add_argument("--version", action="version", version=__version__)
16
+ sub = parser.add_subparsers(dest="command", required=True, parser_class=Parser)
17
+ check = sub.add_parser("verify", help="Inspect committed Git trees without checking out code")
18
+ check.add_argument("--repo", type=Path, default=Path("."))
19
+ check.add_argument("--fork", required=True)
20
+ check.add_argument("--upstream", required=True)
21
+ check.add_argument("--contracts", required=True, type=Path)
22
+ sub.add_parser("capabilities", help="Discover supported agent operations and exit codes")
23
+ try:
24
+ args = parser.parse_args(argv)
25
+ if args.command == "capabilities":
26
+ result = {"schema_version": 1, "version": __version__, "commands": ["verify", "capabilities"],
27
+ "contract_kinds": ["exists", "contains", "sha256", "json_equals"],
28
+ "exit_codes": EXIT, "executes_repository_code": False, "auto_merge": False}
29
+ code = 0
30
+ else:
31
+ result = verify(args.repo, args.fork, args.upstream, args.contracts)
32
+ code = EXIT[result["status"]]
33
+ except (VerificationError, OSError, UnicodeError, ValueError, RecursionError) as exc:
34
+ result = {"schema_version": 1, "status": "error", "reason": str(exc) if isinstance(exc, VerificationError) else type(exc).__name__}
35
+ code = EXIT["error"]
36
+ print(json.dumps(result, sort_keys=True, ensure_ascii=True, allow_nan=False))
37
+ return code
@@ -0,0 +1,211 @@
1
+ """Compare immutable Git trees using declarative, non-executable contracts."""
2
+ from __future__ import annotations
3
+ import hashlib
4
+ import json
5
+ import os
6
+ from pathlib import Path
7
+ import re
8
+ import subprocess
9
+ import tempfile
10
+ from typing import Any
11
+
12
+ MAX_BLOB = 2 * 1024 * 1024
13
+ MAX_CONFIG = 256 * 1024
14
+ MAX_CONTRACTS = 256
15
+ EXIT = {"verified": 0, "regression": 10, "conflict": 11,
16
+ "inconclusive": 12, "error": 2}
17
+ KINDS = {"exists", "contains", "sha256", "json_equals"}
18
+
19
+ class VerificationError(Exception):
20
+ """Invalid input or Git infrastructure failure."""
21
+
22
+ class Unknown(Exception):
23
+ """Evidence unavailable; never treat as a pass."""
24
+
25
+
26
+ def _unique(pairs):
27
+ result = {}
28
+ for key, value in pairs:
29
+ if key in result:
30
+ raise ValueError("duplicate JSON key: " + key)
31
+ result[key] = value
32
+ return result
33
+
34
+
35
+ def _constant(value):
36
+ raise ValueError("non-finite JSON number: " + value)
37
+
38
+
39
+ def parse_json(data):
40
+ return json.loads(data, object_pairs_hook=_unique, parse_constant=_constant)
41
+
42
+
43
+ def load_contracts(path: Path) -> tuple[list[dict], str]:
44
+ with path.open("rb") as f:
45
+ raw = f.read(MAX_CONFIG + 1)
46
+ if len(raw) > MAX_CONFIG:
47
+ raise VerificationError("contract file exceeds size limit")
48
+ try:
49
+ spec = parse_json(raw)
50
+ if (not isinstance(spec, dict) or set(spec) != {"version", "contracts"}
51
+ or type(spec["version"]) is not int or spec["version"] != 1):
52
+ raise ValueError("expected version 1 and contracts")
53
+ contracts = spec["contracts"]
54
+ if not isinstance(contracts, list) or not 1 <= len(contracts) <= MAX_CONTRACTS:
55
+ raise ValueError("expected 1–256 contracts")
56
+ seen = set()
57
+ for c in contracts:
58
+ if not isinstance(c, dict):
59
+ raise ValueError("contract must be an object")
60
+ cid, kind, p = c.get("id"), c.get("kind"), c.get("path")
61
+ if not isinstance(cid, str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,95}", cid) or cid in seen:
62
+ raise ValueError("invalid or duplicate contract id")
63
+ seen.add(cid)
64
+ if not isinstance(kind, str) or kind not in KINDS:
65
+ raise ValueError(f"{cid}: unsupported contract kind")
66
+ if (not isinstance(p, str) or not p or p.startswith("/") or "\\" in p
67
+ or any(ord(ch) < 32 for ch in p) or any(part in {"", ".", "..", ".git"} for part in p.split("/"))):
68
+ raise ValueError(f"{cid}: expected canonical relative file path")
69
+ expected_keys = {"id", "kind", "path"} | ({"value"} if kind != "exists" else set()) | ({"pointer"} if kind == "json_equals" else set())
70
+ if set(c) != expected_keys:
71
+ raise ValueError(f"{cid}: unexpected or missing fields")
72
+ if kind == "contains" and (not isinstance(c["value"], str) or not c["value"]):
73
+ raise ValueError(f"{cid}: expected nonempty text")
74
+ if kind == "sha256" and (not isinstance(c["value"], str) or not re.fullmatch(r"[0-9a-f]{64}", c["value"])):
75
+ raise ValueError(f"{cid}: expected lowercase SHA-256")
76
+ if kind == "json_equals":
77
+ ptr = c["pointer"]
78
+ if not isinstance(ptr, str) or (ptr and not ptr.startswith("/")) or re.search(r"~(?![01])", ptr):
79
+ raise ValueError(f"{cid}: invalid JSON pointer")
80
+ return contracts, hashlib.sha256(raw).hexdigest()
81
+ except (ValueError, TypeError, RecursionError) as e:
82
+ raise VerificationError(f"invalid contracts: {e}") from e
83
+
84
+
85
+ def _git_env():
86
+ # Remove Git environment overrides and disable user/system config.
87
+ env = {k: v for k, v in os.environ.items() if not k.upper().startswith("GIT_")}
88
+ env.update(GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull,
89
+ GIT_TERMINAL_PROMPT="0", GIT_OPTIONAL_LOCKS="0", LC_ALL="C")
90
+ return env
91
+
92
+
93
+ def git(repo: Path | None, *args: str, allowed=(0,)) -> subprocess.CompletedProcess:
94
+ cmd = ["git", "-c", "core.hooksPath=" + os.devnull, "-c", "protocol.ext.allow=never",
95
+ "-c", "protocol.file.allow=always", "-c", "core.fsmonitor=false"]
96
+ if repo is not None:
97
+ cmd += ["-C", str(repo)]
98
+ try:
99
+ p = subprocess.run(cmd + list(args), env=_git_env(), stdin=subprocess.DEVNULL,
100
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=120)
101
+ except (OSError, subprocess.TimeoutExpired) as e:
102
+ raise VerificationError(f"Git invocation failed: {type(e).__name__}") from e
103
+ if p.returncode not in allowed:
104
+ # Avoid echoing potentially sensitive repository diagnostics into agent output.
105
+ raise VerificationError(f"Git {args[0]} failed (exit {p.returncode})")
106
+ return p
107
+
108
+
109
+ def oid(repo, ref):
110
+ if not ref or ref.startswith("-") or any(ord(c) < 32 for c in ref):
111
+ raise VerificationError("invalid Git ref")
112
+ result = git(repo, "rev-parse", "--verify", "--end-of-options", ref + "^{commit}").stdout.strip().decode("ascii")
113
+ if not re.fullmatch(r"[0-9a-f]{40}|[0-9a-f]{64}", result):
114
+ raise VerificationError("invalid resolved object ID")
115
+ return result
116
+
117
+
118
+ def entry(repo, tree, path):
119
+ raw = git(repo, "ls-tree", "-z", "--full-tree", tree, "--", ":(literal)" + path).stdout
120
+ if not raw:
121
+ return None
122
+ rows = raw.rstrip(b"\0").split(b"\0")
123
+ if len(rows) != 1:
124
+ raise Unknown("ambiguous tree entry")
125
+ meta, name = rows[0].split(b"\t", 1)
126
+ mode, typ, obj = meta.decode("ascii").split()
127
+ if name != path.encode("utf-8") or mode not in {"100644", "100755"} or typ != "blob":
128
+ raise Unknown("not a regular file")
129
+ return obj
130
+
131
+
132
+ def json_pointer(value, pointer):
133
+ if not pointer:
134
+ return value
135
+ for token in pointer.split("/")[1:]:
136
+ token = token.replace("~1", "/").replace("~0", "~")
137
+ if isinstance(value, dict) and token in value:
138
+ value = value[token]
139
+ elif isinstance(value, list) and re.fullmatch(r"0|[1-9][0-9]*", token) and len(token) < 12 and int(token) < len(value):
140
+ value = value[int(token)]
141
+ else:
142
+ raise KeyError(token)
143
+ return value
144
+
145
+
146
+ def evaluate(repo, tree, c):
147
+ evidence = {"state": "unknown", "blob_oid": None, "reason": "unavailable"}
148
+ try:
149
+ obj = entry(repo, tree, c["path"])
150
+ evidence["blob_oid"] = obj
151
+ if obj is None:
152
+ return dict(evidence, state="fail", reason="missing_file")
153
+ if c["kind"] == "exists":
154
+ return dict(evidence, state="pass", reason="regular_file_exists")
155
+ size = int(git(repo, "cat-file", "-s", obj).stdout)
156
+ if size > MAX_BLOB:
157
+ raise Unknown("blob exceeds size limit")
158
+ raw = git(repo, "cat-file", "blob", obj).stdout
159
+ if c["kind"] == "sha256":
160
+ actual = hashlib.sha256(raw).hexdigest() == c["value"]
161
+ elif c["kind"] == "contains":
162
+ actual = c["value"] in raw.decode("utf-8")
163
+ else:
164
+ try:
165
+ val = json_pointer(parse_json(raw), c["pointer"])
166
+ except KeyError:
167
+ return dict(evidence, state="fail", reason="missing_json_pointer")
168
+ # Compare JSON types as well as values (true != 1).
169
+ actual = json.dumps(val, sort_keys=True, ensure_ascii=True) == json.dumps(c["value"], sort_keys=True, ensure_ascii=True)
170
+ return dict(evidence, state="pass" if actual else "fail", reason="matched" if actual else "mismatch")
171
+ except (Unknown, UnicodeError, ValueError, RecursionError) as exc:
172
+ return dict(evidence, reason=str(exc) if isinstance(exc, Unknown) else "invalid_or_unsupported_content")
173
+
174
+
175
+ def verify(repo: Path, fork: str, upstream: str, config: Path) -> dict[str, Any]:
176
+ contracts, digest = load_contracts(config)
177
+ source = repo.resolve(strict=True)
178
+ if not source.is_dir():
179
+ raise VerificationError("repository must be a local directory")
180
+ # A disposable mirror has no checkout, no inherited local merge drivers or hooks,
181
+ # and no writes to the original repository. Inputs must still be trusted local Git repos.
182
+ with tempfile.TemporaryDirectory(prefix="forkbridge-") as tmp:
183
+ mirror = Path(tmp) / "repo.git"
184
+ git(None, "clone", "--mirror", "--no-local", "--", str(source), str(mirror))
185
+ a, b = oid(mirror, fork), oid(mirror, upstream)
186
+ base = git(mirror, "merge-base", a, b, allowed=(0, 1))
187
+ report = {"schema_version": 1, "status": "inconclusive", "fork_oid": a,
188
+ "upstream_oid": b, "merge_base_oid": base.stdout.decode("ascii").strip() or None,
189
+ "candidate_tree_oid": None, "contracts_sha256": digest, "contracts": [],
190
+ "limitations": ["static_contracts_only", "no_runtime_execution", "committed_content_only"]}
191
+ if base.returncode == 1:
192
+ report["reason"] = "unrelated_histories"
193
+ return report
194
+ merged = git(mirror, "merge-tree", "--write-tree", a, b, allowed=(0, 1))
195
+ if merged.returncode == 1:
196
+ report.update(status="conflict", reason="git_merge_conflict")
197
+ return report
198
+ tree = merged.stdout.splitlines()[0].decode("ascii")
199
+ if not re.fullmatch(r"[0-9a-f]{40}|[0-9a-f]{64}", tree):
200
+ raise VerificationError("unexpected merge-tree output")
201
+ report["candidate_tree_oid"] = tree
202
+ for c in contracts:
203
+ old = evaluate(mirror, a, c)
204
+ new = evaluate(mirror, tree, c)
205
+ state = ("regression" if old["state"] == "pass" and new["state"] == "fail" else
206
+ "preserved" if old["state"] == new["state"] == "pass" else "inconclusive")
207
+ report["contracts"].append({"id": c["id"], "kind": c["kind"], "path": c["path"],
208
+ "baseline": old, "candidate": new, "status": state})
209
+ states = {c["status"] for c in report["contracts"]}
210
+ report["status"] = "regression" if "regression" in states else "verified" if states == {"preserved"} else "inconclusive"
211
+ return report
@@ -0,0 +1,57 @@
1
+ """Expose ForkBridge verification to a local MCP client over stdio."""
2
+
3
+ import argparse
4
+ from pathlib import Path
5
+ import re
6
+ from typing import Any
7
+
8
+ from . import __version__
9
+ from .core import VerificationError, load_contracts, verify
10
+
11
+ COMMIT_ID = re.compile(r"[0-9a-f]{40}|[0-9a-f]{64}")
12
+
13
+
14
+ def main() -> None:
15
+ parser = argparse.ArgumentParser(description="Serve ForkBridge verification over MCP stdio.")
16
+ parser.add_argument("--repo", type=Path, required=True, help="Trusted local Git repository")
17
+ parser.add_argument("--contracts", type=Path, required=True, help="Policy file outside the checkout")
18
+ args = parser.parse_args()
19
+ repo = args.repo.resolve()
20
+ policy = args.contracts.resolve()
21
+ if not repo.is_dir():
22
+ parser.error("--repo must be an existing directory")
23
+ if not policy.is_file() or policy.is_relative_to(repo):
24
+ parser.error("--contracts must be an existing file outside the repository")
25
+ try:
26
+ load_contracts(policy)
27
+ except (OSError, VerificationError):
28
+ parser.error("--contracts could not be loaded")
29
+ try:
30
+ from mcp.server import MCPServer
31
+ from mcp.types import ToolAnnotations
32
+ except ModuleNotFoundError as exc:
33
+ if exc.name != "mcp":
34
+ raise
35
+ parser.error("install ForkBridge with the mcp extra to start the server")
36
+
37
+ server = MCPServer(
38
+ "ForkBridge",
39
+ version=__version__,
40
+ instructions="Check the operator's static fork contracts before reviewing an upstream merge.",
41
+ )
42
+
43
+ @server.tool(annotations=ToolAnnotations(readOnlyHint=True, openWorldHint=False))
44
+ def verify_merge(fork_oid: str, upstream_oid: str) -> dict[str, Any]:
45
+ """Compare full local commit IDs and return the ForkBridge JSON evidence report."""
46
+ if not COMMIT_ID.fullmatch(fork_oid) or not COMMIT_ID.fullmatch(upstream_oid):
47
+ return {"schema_version": 1, "status": "error", "reason": "expected full Git commit IDs"}
48
+ try:
49
+ return verify(repo, fork_oid, upstream_oid, policy)
50
+ except (VerificationError, OSError, UnicodeError, ValueError, RecursionError):
51
+ return {"schema_version": 1, "status": "error", "reason": "verification failed"}
52
+
53
+ server.run(transport="stdio")
54
+
55
+
56
+ if __name__ == "__main__":
57
+ main()
@@ -0,0 +1,138 @@
1
+ Metadata-Version: 2.4
2
+ Name: forkbridge
3
+ Version: 0.3.0
4
+ Summary: Evidence-first contract verification for Git forks and upstream updates
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Repository, https://github.com/kexyz254/forkbridge
7
+ Keywords: git,fork,contracts,ci,agents
8
+ Requires-Python: >=3.11
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Provides-Extra: test
12
+ Requires-Dist: pytest>=8; extra == "test"
13
+ Requires-Dist: jsonschema>=4; extra == "test"
14
+ Provides-Extra: mcp
15
+ Requires-Dist: mcp<3,>=2.3; extra == "mcp"
16
+ Dynamic: license-file
17
+
18
+ # ForkBridge
19
+
20
+ **A clean merge is not evidence that your fork still meets its requirements.**
21
+
22
+ ForkBridge is a dependency-free CLI and GitHub Action that checks explicit file and configuration contracts against both a Git fork and a hypothetical upstream merge. It reports reproducible evidence for humans, CI pipelines and AI coding agents, without checking out or executing project code.
23
+
24
+ ## Quick start
25
+
26
+ Download the wheel from [GitHub Releases](https://github.com/kexyz254/forkbridge/releases) and install it with `python -m pip install /path/to/downloaded-wheel.whl`. Use the commands below from a source checkout to install and verify.
27
+
28
+ Requires Python 3.11+ and Git 2.38+ with `merge-tree --write-tree` support. Use a trusted local repository with complete history and both refs already available.
29
+
30
+ ```sh
31
+ python -m pip install .
32
+ forkbridge capabilities
33
+ forkbridge verify --repo /path/to/repo --fork HEAD --upstream upstream/main --contracts /path/to/contracts.json
34
+ ```
35
+
36
+ The contract file is external policy: do not allow the candidate update to rewrite it. See [example contracts](examples/contracts.json) and [agent integration](AGENTS.md).
37
+
38
+ ```json
39
+ {"version":1,"contracts":[{"id":"sqlite-enabled","kind":"json_equals","path":"config.json","pointer":"/database/sqlite","value":true}]}
40
+ ```
41
+
42
+ | Contract | What it verifies |
43
+ | --- | --- |
44
+ | `exists` | Regular tracked file exists |
45
+ | `contains` | UTF-8 file contains a literal string |
46
+ | `sha256` | Exact file bytes match a SHA-256 digest |
47
+ | `json_equals` | JSON pointer resolves to the expected typed JSON value (numbers use Python JSON representation) |
48
+
49
+ ## Run in GitHub Actions
50
+
51
+ This workflow checks upstream on demand from your fork's default branch. Set the two upstream values for your project, and commit a contract file at `.github/forkbridge.json` on your fork. Policy comes from the selected fork commit.
52
+
53
+ ```yaml
54
+ name: Verify upstream update
55
+ on:
56
+ workflow_dispatch:
57
+ permissions:
58
+ contents: read
59
+ jobs:
60
+ verify:
61
+ runs-on: ubuntu-latest
62
+ env:
63
+ UPSTREAM_URL: https://github.com/UPSTREAM_OWNER/UPSTREAM_REPO.git
64
+ UPSTREAM_REF: refs/heads/main
65
+ steps:
66
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
67
+ with:
68
+ fetch-depth: 0
69
+ persist-credentials: false
70
+ - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
71
+ with:
72
+ python-version: '3.11'
73
+ - name: Fetch upstream and extract the fork policy
74
+ run: |
75
+ git fetch --no-tags "$UPSTREAM_URL" "$UPSTREAM_REF:refs/forkbridge/upstream"
76
+ git show HEAD:.github/forkbridge.json > "$RUNNER_TEMP/forkbridge-policy.json"
77
+ - uses: kexyz254/forkbridge@v0.3.0
78
+ id: verify
79
+ with:
80
+ fork: HEAD
81
+ upstream: refs/forkbridge/upstream
82
+ contracts: ${{ runner.temp }}/forkbridge-policy.json
83
+ - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
84
+ if: always() && steps.verify.outputs.report != ''
85
+ with:
86
+ name: forkbridge-report
87
+ path: ${{ steps.verify.outputs.report }}
88
+ ```
89
+
90
+ The action fails the job for regressions, merge conflicts, inconclusive results and errors. Open the uploaded report to see the commit IDs and per-contract evidence. On self-hosted runners, use the action with a trusted local checkout and Python 3.11+ and Git 2.38+ on the path.
91
+
92
+ ## Agent and CI protocol
93
+
94
+ `verify` emits one JSON object on stdout. It includes resolved fork and upstream commit IDs, merge base, candidate tree ID, contract digest and per-contract baseline/candidate blob IDs and outcomes. A passing result means only that the listed static contracts are preserved. Unknown data, a failing baseline, or unrelated histories cannot produce a pass.
95
+
96
+ | Exit | Status | Action |
97
+ | --- | --- | --- |
98
+ | 0 | `verified` | Listed contracts preserved; continue normal review |
99
+ | 10 | `regression` | Block update and investigate failed contracts |
100
+ | 11 | `conflict` | Resolve merge conflict separately |
101
+ | 12 | `inconclusive` | Investigate missing or invalid evidence |
102
+ | 2 | `error` | Correct inputs or infrastructure |
103
+
104
+ ForkBridge never fetches remote upstream refs itself, pushes, merges into the source repository, or executes contract commands. It uses a temporary bare mirror and native Git merge-tree. It may read committed secrets in the selected files, but reports only identifiers, paths and verdicts, not file contents. Contract literals and paths are not intended for secrets.
105
+
106
+ ## Connect an MCP client
107
+
108
+ Install the optional MCP adapter from a checkout with `python -m pip install '.[mcp]'`. In your client's local stdio server configuration, set the command to the absolute path of the installed `forkbridge-mcp` executable and pass these arguments.
109
+
110
+ ```json
111
+ {
112
+ "command": "/absolute/path/to/forkbridge-mcp",
113
+ "args": ["--repo", "/path/to/local/fork", "--contracts", "/path/to/trusted/policy.json"]
114
+ }
115
+ ```
116
+
117
+ The server exposes `verify_merge(fork_oid, upstream_oid)` and returns the same structured evidence as the CLI. Both arguments are full Git commit IDs already present in the configured checkout. The operator selects the one checkout and the policy file outside it at startup. Run the server with a trusted local repository and complete history.
118
+
119
+ ## See the difference
120
+
121
+ ```sh
122
+ python examples/demo.py
123
+ ```
124
+
125
+ This generates a synthetic Git fork whose upstream change merges cleanly yet disables a required feature. Expected exit status: `10`. The example prints the full JSON report. The [yt-dlp case study](docs/case-study.md) replays two updates from a real upstream history.
126
+
127
+ ## Development
128
+
129
+ ```sh
130
+ python -m pip install -e '.[test,mcp]'
131
+ pytest -q
132
+ ```
133
+
134
+ ## Boundaries
135
+
136
+ ForkBridge checks committed content using static policies. Runtime behavior, dependency analysis and automatic remediation are outside the current release. The candidate merge uses native default Git semantics in a disposable mirror; custom merge drivers and local configuration may yield a different result in an actual merge. Trusted local repositories only; use OS/container isolation when processing untrusted repositories. Timeouts and blob/config limits are not a complete resource-exhaustion defense. Shallow/partial histories, large repositories, non-UTF-8 paths and exotic Git layouts may fail or be inconclusive. CI tests the CLI and MCP adapter on Linux, Windows and macOS, and exercises the Action and Python distributions on Linux.
137
+
138
+ See [security](SECURITY.md), [contributing](CONTRIBUTING.md), [protocol](docs/protocol.md), [roadmap](docs/ROADMAP.md), and [publishing](docs/distribution.md). Apache-2.0 licensed. No affiliation with GitHub.
@@ -0,0 +1,16 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/forkbridge/__init__.py
5
+ src/forkbridge/__main__.py
6
+ src/forkbridge/action.py
7
+ src/forkbridge/cli.py
8
+ src/forkbridge/core.py
9
+ src/forkbridge/mcp_server.py
10
+ src/forkbridge.egg-info/PKG-INFO
11
+ src/forkbridge.egg-info/SOURCES.txt
12
+ src/forkbridge.egg-info/dependency_links.txt
13
+ src/forkbridge.egg-info/entry_points.txt
14
+ src/forkbridge.egg-info/requires.txt
15
+ src/forkbridge.egg-info/top_level.txt
16
+ tests/test_core.py
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ forkbridge = forkbridge.cli:main
3
+ forkbridge-mcp = forkbridge.mcp_server:main
@@ -0,0 +1,7 @@
1
+
2
+ [mcp]
3
+ mcp<3,>=2.3
4
+
5
+ [test]
6
+ pytest>=8
7
+ jsonschema>=4
@@ -0,0 +1 @@
1
+ forkbridge
@@ -0,0 +1,200 @@
1
+ import hashlib
2
+ import json
3
+ import os
4
+ from pathlib import Path
5
+ import subprocess
6
+ import pytest
7
+ from forkbridge.core import verify, load_contracts, VerificationError
8
+ from forkbridge.cli import main
9
+
10
+
11
+ def g(repo, *args):
12
+ return subprocess.check_output(["git", "-C", str(repo), *args], stderr=subprocess.PIPE).decode().strip()
13
+
14
+
15
+ def commit(repo, name, content):
16
+ (repo / name).write_text(content, encoding="utf-8")
17
+ g(repo, "add", "--", name)
18
+ g(repo, "commit", "-m", "change " + name)
19
+
20
+
21
+ @pytest.fixture
22
+ def history(tmp_path):
23
+ repo = tmp_path / "repo"
24
+ repo.mkdir()
25
+ g(repo, "init", "-b", "main")
26
+ g(repo, "config", "user.name", "Fixture")
27
+ g(repo, "config", "user.email", "fixture@example.invalid")
28
+ commit(repo, "config.json", '{"enabled": true}')
29
+ g(repo, "branch", "upstream")
30
+ commit(repo, "custom.txt", "fork behavior")
31
+ config = tmp_path / "contracts.json"
32
+ config.write_text(json.dumps({"version": 1, "contracts": [{"id": "enabled", "kind": "json_equals", "path": "config.json", "pointer": "/enabled", "value": True}]}))
33
+ return repo, config
34
+
35
+
36
+ def update(repo, content):
37
+ g(repo, "switch", "upstream")
38
+ commit(repo, "config.json", content)
39
+ g(repo, "switch", "main")
40
+
41
+
42
+ def test_clean_merge_regression(history):
43
+ repo, config = history
44
+ update(repo, '{"enabled": false}')
45
+ before = g(repo, "rev-parse", "HEAD")
46
+ objects = g(repo, "count-objects", "-v")
47
+ (repo / "dirty.txt").write_text("do not touch")
48
+ r = verify(repo, "main", "upstream", config)
49
+ assert r["status"] == "regression" and r["candidate_tree_oid"]
50
+ assert r["contracts"][0]["baseline"]["state"] == "pass"
51
+ assert r["contracts"][0]["candidate"]["state"] == "fail"
52
+ assert g(repo, "rev-parse", "HEAD") == before
53
+ assert g(repo, "count-objects", "-v") == objects
54
+ assert (repo / "dirty.txt").read_text() == "do not touch"
55
+ assert verify(repo, "main", "upstream", config) == r
56
+
57
+
58
+ def test_preserved(history):
59
+ repo, config = history
60
+ update(repo, '{"enabled": true, "other": 2}')
61
+ assert verify(repo, "main", "upstream", config)["status"] == "verified"
62
+
63
+
64
+ def test_baseline_failure(history):
65
+ repo, config = history
66
+ commit(repo, "config.json", '{"enabled": false}')
67
+ assert verify(repo, "main", "upstream", config)["status"] == "inconclusive"
68
+
69
+
70
+ def test_conflict(history):
71
+ repo, config = history
72
+ commit(repo, "config.json", '{"enabled": true, "fork": 1}')
73
+ update(repo, '{"enabled": false}')
74
+ assert verify(repo, "main", "upstream", config)["status"] == "conflict"
75
+
76
+
77
+ def test_json_boolean_not_integer(history):
78
+ repo, config = history
79
+ update(repo, '{"enabled": 1}')
80
+ assert verify(repo, "main", "upstream", config)["status"] == "regression"
81
+
82
+
83
+ def test_invalid_json_unknown(history):
84
+ repo, config = history
85
+ update(repo, '{"enabled": true, "enabled": false}')
86
+ assert verify(repo, "main", "upstream", config)["status"] == "inconclusive"
87
+
88
+
89
+ def test_contract_path_traversal(history):
90
+ _, config = history
91
+ config.write_text('{"version":1,"contracts":[{"id":"x","kind":"exists","path":"../secret"}]}')
92
+ with pytest.raises(VerificationError):
93
+ load_contracts(config)
94
+
95
+
96
+ def test_cli_json_exit(history, capsys):
97
+ repo, config = history
98
+ update(repo, '{"enabled": false}')
99
+ code = main(["verify", "--repo", str(repo), "--fork", "main", "--upstream", "upstream", "--contracts", str(config)])
100
+ assert code == 10
101
+ assert json.loads(capsys.readouterr().out)["status"] == "regression"
102
+ assert main(["verify"]) == 2
103
+ assert json.loads(capsys.readouterr().out)["status"] == "error"
104
+
105
+
106
+ def test_other_kinds(history):
107
+ repo, config = history
108
+ config.write_text(json.dumps({"version":1,"contracts":[
109
+ {"id":"x","kind":"exists","path":"custom.txt"},
110
+ {"id":"y","kind":"contains","path":"custom.txt","value":"fork"},
111
+ {"id":"z","kind":"sha256","path":"custom.txt","value":hashlib.sha256(b"fork behavior").hexdigest()}
112
+ ]}))
113
+ assert verify(repo, "main", "upstream", config)["status"] == "verified"
114
+
115
+
116
+ def test_symlink_unknown(history):
117
+ repo, config = history
118
+ if os.name == "nt":
119
+ pytest.skip("symlink creation may need elevated privileges")
120
+ g(repo, "switch", "upstream")
121
+ (repo / "config.json").unlink()
122
+ (repo / "config.json").symlink_to("/etc/passwd")
123
+ g(repo, "add", "config.json")
124
+ g(repo, "commit", "-m", "symlink")
125
+ g(repo, "switch", "main")
126
+ assert verify(repo, "main", "upstream", config)["status"] == "inconclusive"
127
+
128
+
129
+ def test_report_schema(history):
130
+ import jsonschema
131
+ repo, config = history
132
+ schema = json.loads((Path(__file__).resolve().parents[1] / "docs/report.schema.json").read_text())
133
+ for report in (verify(repo, "main", "upstream", config), {"schema_version": 1, "status": "error", "reason": "invalid"}):
134
+ jsonschema.validate(report, schema)
135
+
136
+
137
+ @pytest.mark.parametrize(
138
+ ("mode", "expected", "exit_code"),
139
+ [
140
+ ("unchanged", "verified", 0),
141
+ ("regression", "regression", 10),
142
+ ("invalid", "error", 2),
143
+ ],
144
+ )
145
+ def test_action_outputs(history, tmp_path, mode, expected, exit_code):
146
+ from forkbridge.action import main as action_main
147
+ from pytest import MonkeyPatch
148
+
149
+ repo, policy = history
150
+ if mode == "regression":
151
+ update(repo, '{"enabled": false}')
152
+ if mode == "invalid":
153
+ policy.unlink()
154
+ output = tmp_path / "github-output"
155
+ with MonkeyPatch.context() as env:
156
+ env.setenv("PYTHONPATH", str(Path(__file__).resolve().parents[1] / "src"))
157
+ env.setenv("FORKBRIDGE_REPO", str(repo))
158
+ env.setenv("FORKBRIDGE_FORK", "main")
159
+ env.setenv("FORKBRIDGE_UPSTREAM", "upstream")
160
+ env.setenv("FORKBRIDGE_CONTRACTS", str(policy))
161
+ env.setenv("RUNNER_TEMP", str(tmp_path))
162
+ env.setenv("GITHUB_OUTPUT", str(output))
163
+ assert action_main() == exit_code
164
+
165
+ outputs = dict(line.split("=", 1) for line in output.read_text().splitlines())
166
+ assert outputs["status"] == expected
167
+ assert json.loads(Path(outputs["report"]).read_bytes())["status"] == expected
168
+
169
+
170
+ def test_mcp_stdio_verification(history):
171
+ import asyncio
172
+ import sys
173
+
174
+ mcp = pytest.importorskip("mcp")
175
+ from mcp.client import Client
176
+
177
+ repo, policy = history
178
+ update(repo, '{"enabled": false}')
179
+ fork_oid = g(repo, "rev-parse", "main")
180
+ upstream_oid = g(repo, "rev-parse", "upstream")
181
+ expected = verify(repo, fork_oid, upstream_oid, policy)
182
+
183
+ async def call_tools():
184
+ params = mcp.StdioServerParameters(
185
+ command=sys.executable,
186
+ args=["-P", "-m", "forkbridge.mcp_server", "--repo", str(repo), "--contracts", str(policy)],
187
+ env={"PYTHONPATH": str(Path(__file__).resolve().parents[1] / "src")},
188
+ )
189
+ async with Client(params, read_timeout_seconds=30) as client:
190
+ tools = (await client.list_tools()).tools
191
+ assert [tool.name for tool in tools] == ["verify_merge"]
192
+ assert tools[0].annotations.read_only_hint is True
193
+ assert set(tools[0].input_schema["properties"]) == {"fork_oid", "upstream_oid"}
194
+ result = await client.call_tool("verify_merge", {"fork_oid": fork_oid, "upstream_oid": upstream_oid})
195
+ assert not result.is_error
196
+ assert result.structured_content == expected
197
+ invalid = await client.call_tool("verify_merge", {"fork_oid": "HEAD", "upstream_oid": upstream_oid})
198
+ assert invalid.structured_content["status"] == "error"
199
+
200
+ asyncio.run(call_tools())