opguard-harness 0.1.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,34 @@
1
+ Metadata-Version: 2.4
2
+ Name: opguard-harness
3
+ Version: 0.1.0
4
+ Summary: Diagnostic skills and supporting agent tools for OpGuard
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Repository, https://github.com/OrderLab/OpGuard
7
+ Project-URL: Documentation, https://github.com/OrderLab/OpGuard/blob/main/harness/doc/Usage.md
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Dynamic: license-file
12
+
13
+ # OpGuard Harness
14
+
15
+ Give your coding agent [OpGuard](https://github.com/OrderLab/OpGuard) tools to investigate why two training runs differ.
16
+
17
+ ```bash
18
+ python -m pip install opguard-harness
19
+ opguard-harness tools
20
+ ```
21
+
22
+ Then ask your coding agent:
23
+
24
+ > Use OpGuard to investigate these two runs: `./run-a/train.py` and `./run-b/train.py`.
25
+ > My training Python is `/path/to/train-env/bin/python`.
26
+ > Run `opguard-harness tools` to discover the tools, and explain the evidence you find.
27
+
28
+ Requires Python 3.10+. Works with coding agents that can run shell commands. Install OpGuard separately in the training environment; the harness has no runtime dependencies.
29
+
30
+ [Installation details](https://github.com/OrderLab/OpGuard/blob/main/harness/doc/Usage.md#install).
31
+
32
+ [Agent setup and tool calls](https://github.com/OrderLab/OpGuard/blob/main/harness/doc/Usage.md#agent-integration) · [Diagnostic skills](https://github.com/OrderLab/OpGuard/blob/main/harness/skills/investigate-first-diff/SKILL.md) · [Example experiment](https://github.com/OrderLab/OpGuard/blob/main/harness/examples/experiment.json) · [Walkthrough](https://github.com/OrderLab/OpGuard/blob/main/harness/examples/demo_case5/README.md)
33
+
34
+ [Apache-2.0](https://github.com/OrderLab/OpGuard/blob/main/harness/LICENSE).
@@ -0,0 +1,22 @@
1
+ # OpGuard Harness
2
+
3
+ Give your coding agent [OpGuard](https://github.com/OrderLab/OpGuard) tools to investigate why two training runs differ.
4
+
5
+ ```bash
6
+ python -m pip install opguard-harness
7
+ opguard-harness tools
8
+ ```
9
+
10
+ Then ask your coding agent:
11
+
12
+ > Use OpGuard to investigate these two runs: `./run-a/train.py` and `./run-b/train.py`.
13
+ > My training Python is `/path/to/train-env/bin/python`.
14
+ > Run `opguard-harness tools` to discover the tools, and explain the evidence you find.
15
+
16
+ Requires Python 3.10+. Works with coding agents that can run shell commands. Install OpGuard separately in the training environment; the harness has no runtime dependencies.
17
+
18
+ [Installation details](https://github.com/OrderLab/OpGuard/blob/main/harness/doc/Usage.md#install).
19
+
20
+ [Agent setup and tool calls](https://github.com/OrderLab/OpGuard/blob/main/harness/doc/Usage.md#agent-integration) · [Diagnostic skills](https://github.com/OrderLab/OpGuard/blob/main/harness/skills/investigate-first-diff/SKILL.md) · [Example experiment](https://github.com/OrderLab/OpGuard/blob/main/harness/examples/experiment.json) · [Walkthrough](https://github.com/OrderLab/OpGuard/blob/main/harness/examples/demo_case5/README.md)
21
+
22
+ [Apache-2.0](https://github.com/OrderLab/OpGuard/blob/main/harness/LICENSE).
@@ -0,0 +1,3 @@
1
+ """OpGuard orchestration, independent of the tracing runtime and model provider."""
2
+
3
+ __version__ = '0.1.0'
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,35 @@
1
+ import argparse
2
+ import json
3
+ import sys
4
+
5
+ from .tools import TOOLS, dispatch
6
+
7
+
8
+ def main():
9
+ parser = argparse.ArgumentParser(description='Provider-neutral OpGuard agent tools')
10
+ parser.add_argument('--root', default='./experiments', help='Persistent experiment store; shared with workers')
11
+ sub = parser.add_subparsers(dest='command', required=True)
12
+ sub.add_parser('tools', help='Print function schemas')
13
+ call = sub.add_parser('call', help='Execute one tool and print one JSON response')
14
+ call.add_argument('name', choices=[t['name'] for t in TOOLS])
15
+ call.add_argument('--arguments', help='JSON file; defaults to stdin')
16
+ args = parser.parse_args()
17
+ if args.command == 'tools':
18
+ print(json.dumps({'protocol_version': 1, 'tools': TOOLS}, indent=2))
19
+ return 0
20
+ try:
21
+ if args.arguments:
22
+ with open(args.arguments) as stream:
23
+ arguments = json.load(stream)
24
+ else:
25
+ arguments = json.load(sys.stdin)
26
+ result = dispatch(args.root, args.name, arguments)
27
+ print(json.dumps({'ok': True, 'result': result}, ensure_ascii=False))
28
+ return 0
29
+ except Exception as exc:
30
+ print(json.dumps({'ok': False, 'error': {'type': type(exc).__name__, 'message': str(exc)}}))
31
+ return 1
32
+
33
+
34
+ if __name__ == '__main__':
35
+ sys.exit(main())
@@ -0,0 +1,181 @@
1
+ """A fixed, inspectable workflow. The agent chooses when to advance or refine."""
2
+ from datetime import datetime, timezone
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+ import subprocess
7
+ import uuid
8
+
9
+ from .spec import validate
10
+ from .store import Store, atomic_json
11
+
12
+ STAGES = [(side, phase) for side in ('baseline', 'candidate')
13
+ for phase in ('discover', 'prepare', 'trace')] + [('comparison', 'compare')]
14
+
15
+
16
+ def now():
17
+ return datetime.now(timezone.utc).isoformat()
18
+
19
+
20
+ class Harness:
21
+ def __init__(self, root):
22
+ self.store = Store(root)
23
+
24
+ def create(self, spec):
25
+ spec = validate(spec)
26
+ experiment_id = uuid.uuid4().hex
27
+ self.store.path(experiment_id).mkdir()
28
+ record = {'version': 1, 'id': experiment_id, 'created_at': now(), 'status': 'pending',
29
+ 'spec': spec, 'stages': [{'side': side, 'action': action, 'status': 'pending',
30
+ 'attempts': []} for side, action in STAGES]}
31
+ self.store.save(record)
32
+ return self.status(experiment_id)
33
+
34
+ def status(self, experiment_id):
35
+ record = self.store.load(experiment_id)
36
+ stage = next((s for s in record['stages'] if s['status'] != 'succeeded'), None)
37
+ return {'id': experiment_id, 'status': record['status'], 'next':
38
+ {'side': stage['side'], 'action': stage['action']} if stage else None,
39
+ 'stages': record['stages']}
40
+
41
+ def results(self, experiment_id):
42
+ record = self.store.load(experiment_id)
43
+ last = record['stages'][-1]
44
+ return {'id': experiment_id, 'status': record['status'],
45
+ 'comparison': last.get('result'), 'verdict': 'not_evaluated',
46
+ 'complete': record['status'] == 'succeeded'}
47
+
48
+ def refine(self, experiment_id, spec):
49
+ # Explicit full spec, fresh experiment; old evidence stays immutable.
50
+ self.store.load(experiment_id)
51
+ child = self.create(spec)
52
+ with self.store.locked(child['id']) as record:
53
+ record['parent'] = experiment_id
54
+ self.store.save(record)
55
+ return child
56
+
57
+ def advance(self, experiment_id):
58
+ with self.store.locked(experiment_id) as record:
59
+ stage = next((s for s in record['stages'] if s['status'] != 'succeeded'), None)
60
+ if stage is None:
61
+ return self.status(experiment_id)
62
+ if stage['status'] == 'running':
63
+ raise RuntimeError('Previous controller interrupted. Inspect the recorded process/logs and use recover; do not launch duplicate workers')
64
+ if len(stage['attempts']) >= record['spec']['max_stage_attempts']:
65
+ raise RuntimeError('Stage attempt budget exhausted; refine into a new experiment')
66
+ number = len(stage['attempts']) + 1
67
+ attempt_dir = self.store.path(experiment_id) / f'{stage["side"]}-{stage["action"]}-{number}'
68
+ attempt_dir.mkdir()
69
+ request = self._request(record, stage, attempt_dir)
70
+ atomic_json(attempt_dir / 'request.json', request)
71
+ attempt = {'started_at': now(), 'directory': str(attempt_dir), 'status': 'running'}
72
+ stage['attempts'].append(attempt)
73
+ stage['status'] = record['status'] = 'running'
74
+ self.store.save(record)
75
+ env = {k: v for k, v in os.environ.items() if not k.startswith('OPGUARD_')}
76
+ env['OPGUARD_AUTOSTART'] = '0'
77
+ command = [*record['spec']['backend'], stage['action'], '--request', str(attempt_dir / 'request.json')]
78
+ try:
79
+ with (attempt_dir / 'response.json').open('w') as out, (attempt_dir / 'backend.log').open('w') as err:
80
+ # Inherit signals: Ctrl-C reaches the backend, which unwinds its
81
+ # source transaction. Never automatically retry interrupted jobs.
82
+ process = subprocess.Popen(command, stdout=out, stderr=err, env=env)
83
+ attempt['pid'] = process.pid
84
+ self.store.save(record)
85
+ code = process.wait()
86
+ response = json.loads((attempt_dir / 'response.json').read_text())
87
+ if code or response.get('protocol_version') != 1 or response.get('ok') is not True:
88
+ raise RuntimeError(f'Backend failed: {response.get("error", response)}')
89
+ result = response['result']
90
+ self._validate_result(stage['action'], request, result)
91
+ stage['result'] = result
92
+ stage['status'] = attempt['status'] = 'succeeded'
93
+ record['status'] = 'succeeded' if all(s['status'] == 'succeeded' for s in record['stages']) else 'pending'
94
+ except Exception as exc:
95
+ stage['status'] = attempt['status'] = 'failed'
96
+ record['status'] = 'failed'
97
+ attempt['error'] = str(exc)
98
+ finally:
99
+ attempt['finished_at'] = now()
100
+ self.store.save(record)
101
+ return self.status(experiment_id)
102
+
103
+ def recover(self, experiment_id):
104
+ # A controller crash is ambiguous. Only acknowledge after backend exit and
105
+ # completed source restoration; no stale PID guessing or automatic overwrite.
106
+ with self.store.locked(experiment_id) as record:
107
+ stage = next((s for s in record['stages'] if s['status'] == 'running'), None)
108
+ if stage is None:
109
+ raise ValueError('No interrupted running stage')
110
+ attempt = stage['attempts'][-1]
111
+ pid = attempt.get('pid')
112
+ if pid:
113
+ try:
114
+ os.kill(pid, 0)
115
+ except ProcessLookupError:
116
+ pass
117
+ else:
118
+ raise RuntimeError('Recorded backend PID still exists; inspect it before recovery')
119
+ path = Path(attempt['directory'])
120
+ if stage['action'] == 'trace':
121
+ state = path / 'output-instrument'
122
+ if state.exists() and not (state / 'restored.json').exists():
123
+ raise RuntimeError(f'Source restoration not confirmed. Inspect originals.json in {state}; recover sources before retrying')
124
+ # Discovery could leave detached remote workers. A successful backend
125
+ # response proves its blocking launcher returned and receipts validated.
126
+ response_path = path / 'response.json'
127
+ try:
128
+ response = json.loads(response_path.read_text())
129
+ except (OSError, ValueError):
130
+ raise RuntimeError('No terminal backend response; verify/cancel launcher workers before creating a new experiment')
131
+ if response.get('protocol_version') != 1 or not isinstance(response.get('ok'), bool):
132
+ raise RuntimeError('Invalid terminal backend response')
133
+ if response['ok']:
134
+ request = json.loads((path / 'request.json').read_text())
135
+ self._validate_result(stage['action'], request, response['result'])
136
+ stage['result'] = response['result']
137
+ stage['status'] = attempt['status'] = 'succeeded'
138
+ record['status'] = 'succeeded' if all(s['status'] == 'succeeded' for s in record['stages']) else 'pending'
139
+ else:
140
+ stage['status'] = attempt['status'] = 'failed'
141
+ attempt['error'] = str(response.get('error'))
142
+ record['status'] = 'failed'
143
+ attempt['recovered_at'] = now()
144
+ self.store.save(record)
145
+ return self.status(experiment_id)
146
+
147
+ @staticmethod
148
+ def _result(record, side, action):
149
+ return next(s['result'] for s in record['stages'] if s['side'] == side and s['action'] == action)
150
+
151
+ def _request(self, record, stage, directory):
152
+ spec, side, action = record['spec'], stage['side'], stage['action']
153
+ request = {'protocol_version': 1, 'output': str(directory / 'output'),
154
+ 'local_root': spec['local_root'], 'timeout_seconds': spec['timeout_seconds']}
155
+ if side in ('baseline', 'candidate'):
156
+ request['workload'] = spec[side]
157
+ if action == 'prepare':
158
+ request['discovery'] = self._result(record, side, 'discover')
159
+ if action == 'trace':
160
+ request['plan'] = self._result(record, side, 'prepare')
161
+ if action == 'compare':
162
+ request.update(baseline=self._result(record, 'baseline', 'trace'),
163
+ candidate=self._result(record, 'candidate', 'trace'),
164
+ ranks=spec['baseline']['ranks'])
165
+ return request
166
+
167
+ @staticmethod
168
+ def _validate_result(action, request, result):
169
+ if not isinstance(result, dict):
170
+ raise ValueError('Backend result must be an object')
171
+ if action in ('discover', 'trace'):
172
+ if result.get('output') != request['output'] or result.get('ranks') != request['workload']['ranks'] or result.get('phase') != action:
173
+ raise ValueError('Capture result does not match the requested phase/output/ranks')
174
+ elif action == 'prepare':
175
+ if not result.get('sources') or not Path(result['config']).is_file() or not result.get('config_sha256'):
176
+ raise ValueError('Invalid instrumentation plan')
177
+ else:
178
+ if result.get('verdict') != 'not_evaluated' or result.get('ranks') != request['ranks'] or not result.get('reports'):
179
+ raise ValueError('Invalid comparison result')
180
+ if len(result['reports']) != len(request['ranks']) or any(not Path(p).is_file() for p in result['reports']):
181
+ raise ValueError('Missing comparison reports')
@@ -0,0 +1,63 @@
1
+ """Interpret recorded regional fingerprints, without inferring value equality."""
2
+
3
+
4
+ def _layout(tensor):
5
+ layout = tensor.get('xor_sig_layout')
6
+ values = tensor.get('xor_signature')
7
+ if tensor.get('xor_sig_mode') != 'bytes' or not isinstance(layout, dict):
8
+ return None
9
+ count, size = layout.get('regions'), layout.get('logical_nbytes')
10
+ if (layout.get('scheme') != 'flat-u32-le-v1' or type(count) is not int
11
+ or not 1 <= count <= 64 or type(size) is not int or size < 0):
12
+ return None
13
+ if count == 1 and type(values) in (int, float):
14
+ values = [values]
15
+ if not isinstance(values, list) or len(values) != count or any(
16
+ type(x) not in (int, float) or not 0 <= x <= 0xffffffff or int(x) != x for x in values):
17
+ return None
18
+ base, rem = divmod((size + 3) // 4, count)
19
+ ranges, start = [], 0
20
+ for i in range(count):
21
+ end = start + base + (i < rem)
22
+ ranges.append([min(start * 4, size), min(end * 4, size)])
23
+ start = end
24
+ if layout.get('byte_ranges') != ranges:
25
+ return None
26
+ return layout, list(map(int, values))
27
+
28
+
29
+ def compare_regions(left, right):
30
+ a, b = _layout(left), _layout(right)
31
+ if a is None or b is None:
32
+ return {'status': 'unavailable', 'reason': 'missing_or_unsupported_content_fingerprint_layout'}
33
+ if a[0] != b[0] or left.get('dtype') != right.get('dtype'):
34
+ return {'status': 'incompatible', 'reason': 'different_fingerprint_layout_or_dtype'}
35
+ regions = [{'region': i, 'byte_range': bounds, 'left': av, 'right': bv,
36
+ 'fingerprint_xor': av ^ bv, 'fingerprints_agree': av == bv}
37
+ for i, (bounds, av, bv) in enumerate(zip(a[0]['byte_ranges'], a[1], b[1]))]
38
+ return {'status': 'available', 'scheme': a[0]['scheme'], 'regions': regions,
39
+ 'differing_regions': [r['region'] for r in regions if not r['fingerprints_agree']],
40
+ 'tensor_equality': 'not_established', 'different_element_count': 'not_available',
41
+ 'padding_assessment': 'not_determined'}
42
+
43
+
44
+ def regional_comparisons(left, right):
45
+ """Same-slot proposals, or the explicit selected slots of a reviewed pair."""
46
+ a, b = left.get('io') or {}, right.get('io') or {}
47
+ claim = left.get('correspondence') or {}
48
+ selected = (claim.get('basis') == 'explicit_alignment_map'
49
+ and claim.get('peer_record_id') == right.get('record_id')
50
+ and claim.get('tensor_slot') is not None)
51
+ if selected:
52
+ slots = [(claim['tensor_slot'], claim['peer_tensor_slot'])]
53
+ else:
54
+ slots = [([side, i], [side, i]) for side in ('inputs', 'outputs')
55
+ for i in range(min(len(a.get(side, [])), len(b.get(side, []))))]
56
+ tensors = []
57
+ for x, y in slots[:64]:
58
+ av, bv = a[x[0]][x[1]], b[y[0]][y[1]]
59
+ tensors.append({'left_tensor': x, 'right_tensor': y, **compare_regions(av, bv)})
60
+ return {'selection_basis': 'reviewed_tensor_slots' if selected else 'same_io_slot_candidates',
61
+ 'tensors': tensors, 'truncated': len(slots) > 64,
62
+ 'note': 'Region differences localize recorded byte changes, not element counts or padding noise. '
63
+ 'Matching regions may still contain XOR collisions. Validate semantic correspondence first.'}
@@ -0,0 +1,91 @@
1
+ """Copy an explicit input allowlist without repository history or answer files.
2
+
3
+ This is an artifact boundary, not a filesystem sandbox or a semantic leak detector.
4
+ The caller must review the selected source and provide a separate solver workspace.
5
+ """
6
+ import hashlib
7
+ import json
8
+ from pathlib import Path, PurePosixPath
9
+ import shutil
10
+ import sys
11
+
12
+
13
+ EXCLUDED_PARTS = {".git", ".hg", ".svn", "__pycache__", "answers", "evidence"}
14
+
15
+
16
+ def disallowed_symlink(path):
17
+ if not path.is_symlink():
18
+ return False
19
+ # Only exempt macOS root aliases with their exact system targets.
20
+ # User-created directory and file links must still be rejected.
21
+ return not (sys.platform == "darwin" and path in {Path("/var"), Path("/tmp")}
22
+ and path.resolve() == Path("/private") / path.name)
23
+
24
+
25
+ def relative_path(value):
26
+ path = PurePosixPath(value)
27
+ if (not value or path.is_absolute() or "\\" in value
28
+ or any(part in {".", ".."} | EXCLUDED_PARTS for part in value.split("/"))
29
+ or str(path) != value or path.suffix in {".pyc", ".pyo"}):
30
+ raise ValueError(f"Not an input path: {value}")
31
+ return Path(*path.parts)
32
+
33
+
34
+ def sha256(path):
35
+ digest = hashlib.sha256()
36
+ with path.open("rb") as stream:
37
+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):
38
+ digest.update(chunk)
39
+ return digest.hexdigest()
40
+
41
+
42
+ def export_inputs(destination, files):
43
+ """Export {relative destination: explicit source file}; never walk a checkout.
44
+
45
+ The public manifest contains only destination paths and content hashes. Source
46
+ paths and case-to-answer mappings belong in the caller's private provenance.
47
+ """
48
+ destination = Path(destination)
49
+ prepared = []
50
+ for name, source in files.items():
51
+ target = relative_path(name)
52
+ if name == "manifest.json":
53
+ raise ValueError("manifest.json is reserved for the input inventory")
54
+ source = Path(source).absolute()
55
+ if any(disallowed_symlink(p) for p in (source, *source.parents)) or not source.is_file():
56
+ raise ValueError(f"Input must be a regular file without symlinks: {source}")
57
+ if any(part in EXCLUDED_PARTS for part in source.parts):
58
+ raise ValueError(f"Excluded source path: {source}")
59
+ prepared.append((target, source))
60
+ # Refuse merges into old bundles: stale captures may contain embedded answers.
61
+ destination.mkdir(parents=True, exist_ok=False)
62
+ hashes = {}
63
+ for target, source in prepared:
64
+ output = destination / target
65
+ output.parent.mkdir(parents=True, exist_ok=True)
66
+ shutil.copyfile(source, output)
67
+ hashes[target.as_posix()] = sha256(output)
68
+ manifest = {"version": 1, "files": hashes}
69
+ (destination / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
70
+ return manifest
71
+
72
+
73
+ def verify_inputs(directory):
74
+ """Reject missing/changed/unlisted files and symlinks before solver delivery."""
75
+ directory = Path(directory)
76
+ manifest = json.loads((directory / "manifest.json").read_text())
77
+ if manifest.get("version") != 1:
78
+ raise ValueError("Unsupported input manifest version")
79
+ expected = set(manifest["files"]) | {"manifest.json"}
80
+ actual = set()
81
+ for path in directory.rglob("*"):
82
+ if path.is_symlink():
83
+ raise ValueError(f"Symlink in input bundle: {path}")
84
+ if path.is_file():
85
+ actual.add(path.relative_to(directory).as_posix())
86
+ if actual != expected:
87
+ raise ValueError(f"Input inventory differs: {sorted(actual ^ expected)}")
88
+ for name, digest in manifest["files"].items():
89
+ if sha256(directory / relative_path(name)) != digest:
90
+ raise ValueError(f"Changed input: {name}")
91
+ return manifest