open-code-review-toolkit 0.1.0__py3-none-any.whl

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 (38) hide show
  1. ocr_toolkit/__init__.py +1 -0
  2. ocr_toolkit/_version.py +24 -0
  3. ocr_toolkit/cli.py +56 -0
  4. ocr_toolkit/common/__init__.py +1 -0
  5. ocr_toolkit/common/language.py +60 -0
  6. ocr_toolkit/common/markdown.py +214 -0
  7. ocr_toolkit/common/redaction.py +324 -0
  8. ocr_toolkit/config_writer.py +106 -0
  9. ocr_toolkit/configure.py +194 -0
  10. ocr_toolkit/context/__init__.py +1 -0
  11. ocr_toolkit/context/__main__.py +8 -0
  12. ocr_toolkit/context/ansible.py +561 -0
  13. ocr_toolkit/context/categorize.py +162 -0
  14. ocr_toolkit/context/instructions.py +269 -0
  15. ocr_toolkit/context/manifests.py +459 -0
  16. ocr_toolkit/context/planner.py +227 -0
  17. ocr_toolkit/context/render.py +955 -0
  18. ocr_toolkit/context/repo.py +672 -0
  19. ocr_toolkit/context/settings.py +97 -0
  20. ocr_toolkit/mcp_config.py +257 -0
  21. ocr_toolkit/posting/__init__.py +1 -0
  22. ocr_toolkit/posting/__main__.py +8 -0
  23. ocr_toolkit/posting/comments.py +87 -0
  24. ocr_toolkit/posting/formatting.py +755 -0
  25. ocr_toolkit/posting/gitlab.py +853 -0
  26. ocr_toolkit/posting/markers.py +284 -0
  27. ocr_toolkit/posting/payloads.py +141 -0
  28. ocr_toolkit/posting/result.py +116 -0
  29. ocr_toolkit/posting/settings.py +181 -0
  30. ocr_toolkit/posting/snapshot.py +468 -0
  31. ocr_toolkit/posting/workflow.py +873 -0
  32. ocr_toolkit/preflight.py +395 -0
  33. ocr_toolkit/py.typed +1 -0
  34. open_code_review_toolkit-0.1.0.dist-info/METADATA +283 -0
  35. open_code_review_toolkit-0.1.0.dist-info/RECORD +38 -0
  36. open_code_review_toolkit-0.1.0.dist-info/WHEEL +4 -0
  37. open_code_review_toolkit-0.1.0.dist-info/entry_points.txt +2 -0
  38. open_code_review_toolkit-0.1.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,395 @@
1
+ """Fail-fast checks for OCR CI before LLM review spend."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import re
8
+ import shutil
9
+ import subprocess
10
+ import sys
11
+ import time
12
+ import urllib.error
13
+ import urllib.parse
14
+ import urllib.request
15
+ from typing import Any
16
+
17
+ from ocr_toolkit.common.redaction import redact_sensitive
18
+
19
+ HTTP_TIMEOUT_SECONDS = 30
20
+ MAX_RESPONSE_BODY_BYTES = 2_000_000
21
+ RESPONSE_READ_CHUNK_BYTES = 64 * 1024
22
+ HEADER_NAME_RE = re.compile(r"^[!#$%&'*+.^_`|~0-9A-Za-z-]+$")
23
+ DEFAULT_REQUEST_HEADERS = {
24
+ "Accept": "application/json",
25
+ "User-Agent": "open-code-review-ci-preflight/1.0",
26
+ }
27
+ EXPECTED_OCR_VERSION = "1.7.13"
28
+
29
+
30
+ class PreflightError(Exception):
31
+ """A required OCR CI preflight check failed."""
32
+
33
+
34
+ class _NoRedirectHandler(urllib.request.HTTPRedirectHandler):
35
+ """Prevent urllib from forwarding secret headers across redirects."""
36
+
37
+ def redirect_request(self, *_args: Any, **_kwargs: Any) -> None:
38
+ return None
39
+
40
+
41
+ URL_OPENER = urllib.request.build_opener(_NoRedirectHandler)
42
+
43
+
44
+ def _set_response_timeout(response: Any, timeout: float) -> None:
45
+ """Best-effort update of the underlying socket timeout before each read."""
46
+
47
+ try:
48
+ sock = response.fp.raw._sock
49
+ except AttributeError:
50
+ return
51
+ sock.settimeout(timeout)
52
+
53
+
54
+ def _safe_url(url: str) -> str:
55
+ """Return a URL safe for CI diagnostics."""
56
+
57
+ return redact_sensitive(url)
58
+
59
+
60
+ def _env(name: str, default: str = "") -> str:
61
+ return os.environ.get(name, default).strip()
62
+
63
+
64
+ def _gitlab_api_root() -> str:
65
+ api_root = _env("CI_API_V4_URL")
66
+ if api_root:
67
+ return api_root.rstrip("/")
68
+
69
+ server_url = _env("CI_SERVER_URL")
70
+ if not server_url:
71
+ raise PreflightError("CI_SERVER_URL or CI_API_V4_URL is required")
72
+ return f"{server_url.rstrip('/')}/api/v4"
73
+
74
+
75
+ def _request_json(url: str, headers: dict[str, str]) -> Any:
76
+ parsed_url = urllib.parse.urlsplit(url)
77
+ if headers and (parsed_url.scheme != "https" or not parsed_url.netloc):
78
+ raise PreflightError(f"Refusing to send credentials to non-HTTPS URL: {_safe_url(url)}")
79
+
80
+ request_headers: dict[str, str] = dict(DEFAULT_REQUEST_HEADERS)
81
+ for key, value in headers.items():
82
+ if not HEADER_NAME_RE.fullmatch(key) or "\r" in value or "\n" in value:
83
+ raise PreflightError(f"GET {_safe_url(url)} contains an invalid HTTP header")
84
+ request_headers[key] = value
85
+
86
+ raw_body = b""
87
+ last_error: Exception | None = None
88
+ deadline = time.monotonic() + HTTP_TIMEOUT_SECONDS
89
+ retryable_statuses = {408, 429, 500, 502, 503, 504}
90
+ for attempt in range(3):
91
+ remaining = deadline - time.monotonic()
92
+ if remaining <= 0:
93
+ raise PreflightError(f"GET {_safe_url(url)} timed out after {HTTP_TIMEOUT_SECONDS}s")
94
+ request = urllib.request.Request(url, headers=request_headers, method="GET")
95
+ try:
96
+ with URL_OPENER.open(request, timeout=remaining) as response:
97
+ chunks: list[bytes] = []
98
+ total_bytes = 0
99
+ while total_bytes < MAX_RESPONSE_BODY_BYTES:
100
+ remaining = deadline - time.monotonic()
101
+ if remaining <= 0:
102
+ raise TimeoutError
103
+ _set_response_timeout(response, remaining)
104
+ chunk = response.read(
105
+ min(RESPONSE_READ_CHUNK_BYTES, MAX_RESPONSE_BODY_BYTES - total_bytes)
106
+ )
107
+ if not chunk:
108
+ break
109
+ chunks.append(chunk)
110
+ total_bytes += len(chunk)
111
+ if total_bytes >= MAX_RESPONSE_BODY_BYTES:
112
+ remaining = deadline - time.monotonic()
113
+ if remaining <= 0:
114
+ raise TimeoutError
115
+ _set_response_timeout(response, remaining)
116
+ if response.read(1):
117
+ raise PreflightError(
118
+ f"GET {_safe_url(url)} response exceeds {MAX_RESPONSE_BODY_BYTES} bytes"
119
+ )
120
+ raw_body = b"".join(chunks)
121
+ break
122
+ except urllib.error.HTTPError as exc:
123
+ raw_error = exc.read(16_384).decode("utf-8", errors="replace").strip()
124
+ if exc.code not in retryable_statuses or attempt == 2:
125
+ detail = f": {redact_sensitive(raw_error)}" if raw_error else ""
126
+ raise PreflightError(
127
+ f"GET {_safe_url(url)} failed with HTTP {exc.code}{detail}"
128
+ ) from exc
129
+ last_error = exc
130
+ except TimeoutError as exc:
131
+ last_error = exc
132
+ if attempt == 2:
133
+ raise PreflightError(
134
+ f"GET {_safe_url(url)} timed out after {HTTP_TIMEOUT_SECONDS}s"
135
+ ) from exc
136
+ except OSError as exc:
137
+ last_error = exc
138
+ if attempt == 2:
139
+ raise PreflightError(
140
+ f"GET {_safe_url(url)} failed: {redact_sensitive(str(exc))}"
141
+ ) from exc
142
+ sleep_seconds = min(1.0, max(0.0, deadline - time.monotonic()))
143
+ if sleep_seconds:
144
+ time.sleep(sleep_seconds)
145
+ else:
146
+ raise PreflightError(f"GET {_safe_url(url)} failed: {redact_sensitive(str(last_error))}")
147
+
148
+ if not raw_body:
149
+ return None
150
+
151
+ try:
152
+ return json.loads(raw_body.decode("utf-8"))
153
+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:
154
+ raise PreflightError(f"GET {_safe_url(url)} returned non-JSON metadata") from exc
155
+
156
+
157
+ def validate_gitlab_access() -> None:
158
+ """Verify the configured bot token can read this project and MR."""
159
+
160
+ token = _env("GITLAB_API_TOKEN")
161
+ project_id = _env("CI_PROJECT_ID")
162
+ mr_iid = _env("CI_MERGE_REQUEST_IID")
163
+ if not token:
164
+ raise PreflightError("GITLAB_API_TOKEN is required")
165
+ if not project_id or not mr_iid:
166
+ raise PreflightError("CI_PROJECT_ID and CI_MERGE_REQUEST_IID are required")
167
+
168
+ api_root = _gitlab_api_root()
169
+ project_id_encoded = urllib.parse.quote_plus(project_id)
170
+ headers = {"PRIVATE-TOKEN": token}
171
+
172
+ print("Validating GitLab token access to project and merge request")
173
+ _request_json(f"{api_root}/user", headers)
174
+ _request_json(f"{api_root}/projects/{project_id_encoded}", headers)
175
+ _request_json(f"{api_root}/projects/{project_id_encoded}/merge_requests/{mr_iid}", headers)
176
+
177
+
178
+ def validate_ocr_binary() -> None:
179
+ """Verify that the external OCR binary has the supported release."""
180
+
181
+ executable = shutil.which("ocr")
182
+ if executable is None:
183
+ raise PreflightError(
184
+ "Open Code Review binary 'ocr' was not found on PATH; install it separately"
185
+ )
186
+ try:
187
+ completed = subprocess.run(
188
+ [executable, "--version"],
189
+ check=False,
190
+ capture_output=True,
191
+ text=True,
192
+ encoding="utf-8",
193
+ errors="replace",
194
+ timeout=10,
195
+ )
196
+ except (OSError, subprocess.TimeoutExpired) as exc:
197
+ raise PreflightError(f"Cannot run ocr --version: {redact_sensitive(str(exc))}") from exc
198
+ output = f"{completed.stdout}\n{completed.stderr}".strip()
199
+ if completed.returncode != 0:
200
+ raise PreflightError(
201
+ f"ocr --version exited {completed.returncode}: {redact_sensitive(output)}"
202
+ )
203
+ if not re.search(rf"(?<![0-9.])v?{re.escape(EXPECTED_OCR_VERSION)}(?![0-9.])", output):
204
+ raise PreflightError(
205
+ f"Unsupported Open Code Review version; expected {EXPECTED_OCR_VERSION}, "
206
+ f"got {redact_sensitive(output)!r}"
207
+ )
208
+ print(f"Open Code Review binary validated: {EXPECTED_OCR_VERSION}")
209
+
210
+
211
+ def _models_url() -> str:
212
+ explicit_url = _env("OCR_LLM_MODELS_URL")
213
+ if explicit_url:
214
+ return explicit_url
215
+
216
+ base = ""
217
+ llm_url = _env("OCR_LLM_URL")
218
+ if not base:
219
+ normalized_llm_url = llm_url.rstrip("/")
220
+ for endpoint in ("/chat/completions", "/responses"):
221
+ if normalized_llm_url.endswith(endpoint):
222
+ base = normalized_llm_url[: -len(endpoint)]
223
+ break
224
+ else:
225
+ if normalized_llm_url.endswith("/v1"):
226
+ base = normalized_llm_url
227
+
228
+ if not base:
229
+ raise PreflightError(
230
+ "Cannot derive LLM /models URL; set OCR_LLM_MODELS_URL or "
231
+ "set OCR_LLM_VALIDATE_MODEL=false"
232
+ )
233
+ return f"{base.rstrip('/')}/models"
234
+
235
+
236
+ def _parse_extra_headers(value: str) -> dict[str, str]:
237
+ """Parse optional OCR LLM extra headers JSON for preflight metadata calls."""
238
+
239
+ if not value.strip():
240
+ return {}
241
+ try:
242
+ payload = json.loads(value)
243
+ except json.JSONDecodeError as exc:
244
+ raise PreflightError("OCR_LLM_EXTRA_HEADERS must be a JSON object") from exc
245
+ if not isinstance(payload, dict):
246
+ raise PreflightError("OCR_LLM_EXTRA_HEADERS must be a JSON object")
247
+
248
+ headers: dict[str, str] = {}
249
+ for key, header_value in payload.items():
250
+ if not isinstance(key, str) or not HEADER_NAME_RE.fullmatch(key.strip()):
251
+ raise PreflightError("OCR_LLM_EXTRA_HEADERS contains an invalid header name")
252
+ if not isinstance(header_value, str):
253
+ raise PreflightError("OCR_LLM_EXTRA_HEADERS contains a non-string header value")
254
+ if "\r" in header_value or "\n" in header_value:
255
+ raise PreflightError("OCR_LLM_EXTRA_HEADERS contains an invalid header value")
256
+ headers[key.strip()] = header_value
257
+ return headers
258
+
259
+
260
+ def _llm_headers(token: str) -> dict[str, str]:
261
+ """Build the same auth/header set used by OCR's llm.* configuration."""
262
+
263
+ auth_header = _env("OCR_LLM_AUTH_HEADER", "Authorization") or "Authorization"
264
+ if not HEADER_NAME_RE.fullmatch(auth_header):
265
+ raise PreflightError("OCR_LLM_AUTH_HEADER is not a valid HTTP header name")
266
+ headers = _parse_extra_headers(_env("OCR_LLM_EXTRA_HEADERS"))
267
+ headers[auth_header] = f"Bearer {token}"
268
+ return headers
269
+
270
+
271
+ def _context_length(model: dict[str, Any]) -> int:
272
+ for key in (
273
+ "context_length",
274
+ "contextLength",
275
+ "max_context_length",
276
+ "maxContextLength",
277
+ ):
278
+ value = model.get(key)
279
+ if value is None:
280
+ continue
281
+ try:
282
+ parsed = int(value)
283
+ except (TypeError, ValueError):
284
+ continue
285
+ if parsed > 0:
286
+ return parsed
287
+ return 0
288
+
289
+
290
+ def _allowed_models() -> list[str]:
291
+ """Return exact model ids allowed without querying gateway metadata."""
292
+
293
+ value = _env("OCR_LLM_ALLOWED_MODELS")
294
+ if not value:
295
+ return []
296
+ return [item.strip() for item in value.split(",") if item.strip()]
297
+
298
+
299
+ def _is_allowed_model(model_id: str) -> bool:
300
+ """Return whether model id is in the optional offline allowlist."""
301
+
302
+ allowed = _allowed_models()
303
+ if not allowed:
304
+ return False
305
+ return model_id in allowed
306
+
307
+
308
+ def _validate_allowed_model(model_id: str) -> bool:
309
+ """Validate model id against the optional offline allowlist."""
310
+
311
+ allowed = _allowed_models()
312
+ if not allowed:
313
+ return False
314
+ if not _is_allowed_model(model_id):
315
+ raise PreflightError(f"OCR_LLM_MODEL {model_id!r} is not listed in OCR_LLM_ALLOWED_MODELS")
316
+ print(f"OCR model allowed by OCR_LLM_ALLOWED_MODELS: {model_id}")
317
+ return True
318
+
319
+
320
+ def validate_llm_model() -> None:
321
+ """Verify the selected model exists in OpenAI-compatible metadata."""
322
+
323
+ model_id = _env("OCR_LLM_MODEL")
324
+ if not model_id:
325
+ raise PreflightError("OCR_LLM_MODEL is required")
326
+ allowlist_matched = _validate_allowed_model(model_id)
327
+
328
+ validate_mode = _env("OCR_LLM_VALIDATE_MODEL", "false").lower()
329
+ if validate_mode in {"false", "0", "no", "off"}:
330
+ print("OCR LLM /models validation disabled by OCR_LLM_VALIDATE_MODEL=false")
331
+ return
332
+ if validate_mode not in {"true", "1", "yes", "on", "auto"}:
333
+ raise PreflightError("OCR_LLM_VALIDATE_MODEL must be true, false, or auto")
334
+
335
+ token = _env("OCR_LLM_TOKEN")
336
+ if not token:
337
+ raise PreflightError("OCR_LLM_TOKEN is required")
338
+ headers = _llm_headers(token)
339
+
340
+ print("Validating OCR model against LLM gateway metadata")
341
+ try:
342
+ models_url = _models_url()
343
+ except PreflightError as exc:
344
+ if validate_mode == "auto" and allowlist_matched:
345
+ print(
346
+ "OCR LLM /models URL unavailable; continuing because "
347
+ f"OCR_LLM_MODEL is allowlisted: {redact_sensitive(str(exc))}",
348
+ file=sys.stderr,
349
+ )
350
+ return
351
+ raise
352
+ try:
353
+ payload = _request_json(models_url, headers)
354
+ except PreflightError as exc:
355
+ if validate_mode == "auto" and allowlist_matched:
356
+ print(
357
+ "OCR LLM /models validation unavailable; continuing because "
358
+ f"OCR_LLM_MODEL is allowlisted: {redact_sensitive(str(exc))}",
359
+ file=sys.stderr,
360
+ )
361
+ return
362
+ raise
363
+ items = payload.get("data") if isinstance(payload, dict) else payload
364
+ if not isinstance(items, list):
365
+ raise PreflightError("LLM /models response is not a model list")
366
+
367
+ matched_model = next(
368
+ (item for item in items if isinstance(item, dict) and item.get("id") == model_id),
369
+ None,
370
+ )
371
+ if matched_model is None:
372
+ raise PreflightError(f"Gateway model {model_id!r} was not found in /models")
373
+
374
+ context_length = _context_length(matched_model)
375
+ if context_length <= 0:
376
+ print(f"LLM model validated: {model_id} context_length=unknown")
377
+ return
378
+ print(f"LLM model validated: {model_id} context_length={context_length}")
379
+
380
+
381
+ def main() -> int:
382
+ """Run all fail-fast checks."""
383
+
384
+ try:
385
+ validate_ocr_binary()
386
+ validate_gitlab_access()
387
+ validate_llm_model()
388
+ except PreflightError as exc:
389
+ print(f"OCR preflight failed: {redact_sensitive(str(exc))}", file=sys.stderr)
390
+ return 1
391
+ return 0
392
+
393
+
394
+ if __name__ == "__main__":
395
+ raise SystemExit(main())
ocr_toolkit/py.typed ADDED
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,283 @@
1
+ Metadata-Version: 2.4
2
+ Name: open-code-review-toolkit
3
+ Version: 0.1.0
4
+ Summary: Unofficial GitLab CI integration layer for Open Code Review
5
+ Project-URL: Homepage, https://github.com/xeonvs/open-code-review-toolkit
6
+ Project-URL: Repository, https://github.com/xeonvs/open-code-review-toolkit
7
+ Project-URL: Issues, https://github.com/xeonvs/open-code-review-toolkit/issues
8
+ Project-URL: Changelog, https://github.com/xeonvs/open-code-review-toolkit/blob/main/CHANGELOG.md
9
+ Author: Open Code Review Toolkit contributors
10
+ License:
11
+ Apache License
12
+ Version 2.0, January 2004
13
+ http://www.apache.org/licenses/
14
+
15
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
16
+
17
+ 1. Definitions.
18
+
19
+ "License" shall mean the terms and conditions for use, reproduction,
20
+ and distribution as defined by Sections 1 through 9 of this document.
21
+
22
+ "Licensor" shall mean the copyright owner or entity authorized by
23
+ the copyright owner that is granting the License.
24
+
25
+ "Legal Entity" shall mean the union of the acting entity and all
26
+ other entities that control, are controlled by, or are under common
27
+ control with that entity. For the purposes of this definition,
28
+ "control" means (i) the power, direct or indirect, to cause the
29
+ direction or management of such entity, whether by contract or
30
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
31
+ outstanding shares, or (iii) beneficial ownership of such entity.
32
+
33
+ "You" (or "Your") shall mean an individual or Legal Entity
34
+ exercising permissions granted by this License.
35
+
36
+ "Source" form shall mean the preferred form for making modifications,
37
+ including but not limited to software source code, documentation
38
+ source, and configuration files.
39
+
40
+ "Object" form shall mean any form resulting from mechanical
41
+ transformation or translation of a Source form, including but
42
+ not limited to compiled object code, generated documentation,
43
+ and conversions to other media types.
44
+
45
+ "Work" shall mean the work of authorship, whether in Source or
46
+ Object form, made available under the License, as indicated by a
47
+ copyright notice that is included in or attached to the work
48
+ (an example is provided in the Appendix below).
49
+
50
+ "Derivative Works" shall mean any work, whether in Source or Object
51
+ form, that is based on (or derived from) the Work and for which the
52
+ editorial revisions, annotations, elaborations, or other modifications
53
+ represent, as a whole, an original work of authorship. For the purposes
54
+ of this License, Derivative Works shall not include works that remain
55
+ separable from, or merely link (or bind by name) to the interfaces of,
56
+ the Work and Derivative Works thereof.
57
+
58
+ "Contribution" shall mean any work of authorship, including
59
+ the original version of the Work and any modifications or additions
60
+ to that Work or Derivative Works thereof, that is intentionally
61
+ submitted to Licensor for inclusion in the Work by the copyright owner
62
+ or by an individual or Legal Entity authorized to submit on behalf of
63
+ the copyright owner. For the purposes of this definition, "submitted"
64
+ means any form of electronic, verbal, or written communication sent
65
+ to the Licensor or its representatives, including but not limited to
66
+ communication on electronic mailing lists, source code control systems,
67
+ and issue tracking systems that are managed by, or on behalf of, the
68
+ Licensor for the purpose of discussing and improving the Work, but
69
+ excluding communication that is conspicuously marked or otherwise
70
+ designated in writing by the copyright owner as "Not a Contribution."
71
+
72
+ "Contributor" shall mean Licensor and any individual or Legal Entity
73
+ on behalf of whom a Contribution has been received by Licensor and
74
+ subsequently incorporated within the Work.
75
+
76
+ 2. Grant of Copyright License. Subject to the terms and conditions of
77
+ this License, each Contributor hereby grants to You a perpetual,
78
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
79
+ copyright license to reproduce, prepare Derivative Works of,
80
+ publicly display, publicly perform, sublicense, and distribute the
81
+ Work and such Derivative Works in Source or Object form.
82
+
83
+ 3. Grant of Patent License. Subject to the terms and conditions of
84
+ this License, each Contributor hereby grants to You a perpetual,
85
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
86
+ (except as stated in this section) patent license to make, have made,
87
+ use, offer to sell, sell, import, and otherwise transfer the Work,
88
+ where such license applies only to those patent claims licensable
89
+ by such Contributor that are necessarily infringed by their
90
+ Contribution(s) alone or by combination of their Contribution(s)
91
+ with the Work to which such Contribution(s) was submitted. If You
92
+ institute patent litigation against any entity (including a
93
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
94
+ or a Contribution incorporated within the Work constitutes direct
95
+ or contributory patent infringement, then any patent licenses
96
+ granted to You under this License for that Work shall terminate
97
+ as of the date such litigation is filed.
98
+
99
+ 4. Redistribution. You may reproduce and distribute copies of the
100
+ Work or Derivative Works thereof in any medium, with or without
101
+ modifications, and in Source or Object form, provided that You
102
+ meet the following conditions:
103
+
104
+ (a) You must give any other recipients of the Work or
105
+ Derivative Works a copy of this License; and
106
+
107
+ (b) You must cause any modified files to carry prominent notices
108
+ stating that You changed the files; and
109
+
110
+ (c) You must retain, in the Source form of any Derivative Works
111
+ that You distribute, all copyright, patent, trademark, and
112
+ attribution notices from the Source form of the Work,
113
+ excluding those notices that do not pertain to any part of
114
+ the Derivative Works; and
115
+
116
+ (d) If the Work includes a "NOTICE" text file as part of its
117
+ distribution, then any Derivative Works that You distribute must
118
+ include a readable copy of the attribution notices contained
119
+ within such NOTICE file, excluding those notices that do not
120
+ pertain to any part of the Derivative Works, in at least one
121
+ of the following places: within a NOTICE text file distributed
122
+ as part of the Derivative Works; within the Source form or
123
+ documentation, if provided along with the Derivative Works; or,
124
+ within a display generated by the Derivative Works, if and
125
+ wherever such third-party notices normally appear. The contents
126
+ of the NOTICE file are for informational purposes only and
127
+ do not modify the License. You may add Your own attribution
128
+ notices within Derivative Works that You distribute, alongside
129
+ or as an addendum to the NOTICE text from the Work, provided
130
+ that such additional attribution notices cannot be construed
131
+ as modifying the License.
132
+
133
+ You may add Your own copyright statement to Your modifications and
134
+ may provide additional or different license terms and conditions
135
+ for use, reproduction, or distribution of Your modifications, or
136
+ for any such Derivative Works as a whole, provided Your use,
137
+ reproduction, and distribution of the Work otherwise complies with
138
+ the conditions stated in this License.
139
+
140
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
141
+ any Contribution intentionally submitted for inclusion in the Work
142
+ by You to the Licensor shall be under the terms and conditions of
143
+ this License, without any additional terms or conditions.
144
+ Notwithstanding the above, nothing herein shall supersede or modify
145
+ the terms of any separate license agreement you may have executed
146
+ with Licensor regarding such Contributions.
147
+
148
+ 6. Trademarks. This License does not grant permission to use the trade
149
+ names, trademarks, service marks, or product names of the Licensor,
150
+ except as required for reasonable and customary use in describing the
151
+ origin of the Work and reproducing the content of the NOTICE file.
152
+
153
+ 7. Disclaimer of Warranty. Unless required by applicable law or
154
+ agreed to in writing, Licensor provides the Work (and each
155
+ Contributor provides its Contributions) on an "AS IS" BASIS,
156
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
157
+ implied, including, without limitation, any warranties or conditions
158
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
159
+ PARTICULAR PURPOSE. You are solely responsible for determining the
160
+ appropriateness of using or redistributing the Work and assume any
161
+ risks associated with Your exercise of permissions under this License.
162
+
163
+ 8. Limitation of Liability. In no event and under no legal theory,
164
+ whether in tort (including negligence), contract, or otherwise,
165
+ unless required by applicable law (such as deliberate and grossly
166
+ negligent acts) or agreed to in writing, shall any Contributor be
167
+ liable to You for damages, including any direct, indirect, special,
168
+ incidental, or consequential damages of any character arising as a
169
+ result of this License or out of the use or inability to use the
170
+ Work (including but not limited to damages for loss of goodwill,
171
+ work stoppage, computer failure or malfunction, or any and all
172
+ other commercial damages or losses), even if such Contributor
173
+ has been advised of the possibility of such damages.
174
+
175
+ 9. Accepting Warranty or Additional Liability. While redistributing
176
+ the Work or Derivative Works thereof, You may choose to offer,
177
+ and charge a fee for, acceptance of support, warranty, indemnity,
178
+ or other liability obligations and/or rights consistent with this
179
+ License. However, in accepting such obligations, You may act only
180
+ on Your own behalf and on Your sole responsibility, not on behalf
181
+ of any other Contributor, and only if You agree to indemnify,
182
+ defend, and hold each Contributor harmless for any liability
183
+ incurred by, or claims asserted against, such Contributor by reason
184
+ of your accepting any such warranty or additional liability.
185
+
186
+ END OF TERMS AND CONDITIONS
187
+
188
+ APPENDIX: How to apply the Apache License to your work.
189
+
190
+ To apply the Apache License to your work, attach the following
191
+ boilerplate notice, with the fields enclosed by brackets "[]"
192
+ replaced with your own identifying information. (Don't include
193
+ the brackets!) The text should be enclosed in the appropriate
194
+ comment syntax for the file format. We also recommend that a
195
+ file or class name and description of purpose be included on the
196
+ same "printed page" as the copyright notice for easier
197
+ identification within third-party archives.
198
+
199
+ Copyright [yyyy] [name of copyright owner]
200
+
201
+ Licensed under the Apache License, Version 2.0 (the "License");
202
+ you may not use this file except in compliance with the License.
203
+ You may obtain a copy of the License at
204
+
205
+ http://www.apache.org/licenses/LICENSE-2.0
206
+
207
+ Unless required by applicable law or agreed to in writing, software
208
+ distributed under the License is distributed on an "AS IS" BASIS,
209
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
210
+ See the License for the specific language governing permissions and
211
+ limitations under the License.
212
+ License-File: LICENSE
213
+ Keywords: ci,code-review,gitlab,open-code-review
214
+ Classifier: Development Status :: 4 - Beta
215
+ Classifier: Environment :: Console
216
+ Classifier: License :: OSI Approved :: Apache Software License
217
+ Classifier: Operating System :: MacOS
218
+ Classifier: Operating System :: POSIX :: Linux
219
+ Classifier: Programming Language :: Python :: 3 :: Only
220
+ Classifier: Programming Language :: Python :: 3.10
221
+ Classifier: Programming Language :: Python :: 3.11
222
+ Classifier: Programming Language :: Python :: 3.12
223
+ Classifier: Programming Language :: Python :: 3.13
224
+ Classifier: Programming Language :: Python :: 3.14
225
+ Classifier: Typing :: Typed
226
+ Requires-Python: <3.15,>=3.10
227
+ Description-Content-Type: text/markdown
228
+
229
+ # Open Code Review Toolkit
230
+
231
+ Open Code Review Toolkit is an unofficial GitLab CI integration layer for [Alibaba Open Code Review](https://github.com/alibaba/open-code-review). It provides bounded repository context generation, environment-driven OCR configuration, preflight validation, and safe GitLab merge-request posting. It does **not** bundle or download the `ocr` binary.
232
+
233
+ > [!NOTE]
234
+ > The project is under active development. It currently targets Python 3.10-3.14 on Linux and macOS; the public API, CLI, environment contract, and generated schemas may evolve before 1.0.
235
+
236
+ ## Install
237
+
238
+ Install the Python package from PyPI and install a supported OCR binary separately:
239
+
240
+ ```console
241
+ python -m pip install open-code-review-toolkit
242
+ ocr --version
243
+ ocr-ci --help
244
+ ```
245
+
246
+ The current compatibility target is OCR `1.7.13`. CI should pin the release and verify its published checksum before execution.
247
+ Review output defaults to English. Set `OCR_REVIEW_LANGUAGE=Russian` to use Russian consistently in both OCR configuration and generated review context.
248
+
249
+ Stable distributions are published to [PyPI](https://pypi.org/project/open-code-review-toolkit/) and mirrored as checksum-listed, provenance-attested assets in the corresponding [GitHub Release](https://github.com/xeonvs/open-code-review-toolkit/releases). Development snapshots are published only to TestPyPI.
250
+
251
+ ## GitLab CI quick start
252
+
253
+ 1. Configure protected/masked `GITLAB_API_TOKEN` and LLM variables in GitLab.
254
+ 2. Pin and checksum the OCR binary.
255
+ 3. Install this package.
256
+ 4. Run the five helper stages around `ocr review`:
257
+
258
+ ```console
259
+ ocr-ci preflight
260
+ ocr-ci configure
261
+ ocr-ci mcp-config
262
+ ocr-ci context --output .review-context/dependencies.md
263
+ # run: ocr review ... --format json
264
+ ocr-ci post --result /tmp/ocr-result.json --stderr /tmp/ocr-stderr.log
265
+ ```
266
+
267
+ See the fully synthetic [`examples/gitlab/ocr-review.gitlab-ci.yml`](examples/gitlab/ocr-review.gitlab-ci.yml) and the [GitLab guide](docs/gitlab.md).
268
+
269
+ ## Configuration and safety
270
+
271
+ Configuration is environment-only in v0.1. The [configuration reference](docs/configuration.md) documents supported `OCR_*`, `CI_*`, `GITLAB_*`, and MCP inputs. Posting requires `GITLAB_API_TOKEN`; job tokens and legacy aliases are deliberately unsupported.
272
+
273
+ Repository content, OCR output, and provider responses are untrusted inputs. The toolkit applies bounded reads and writes, secret redaction, Unicode normalization, Markdown/quick-action neutralization, fingerprinted comments, ownership boundaries for human replies, and rollback controls. Review the [security and trust model](docs/security.md) before enabling write access.
274
+
275
+ ## Development and release
276
+
277
+ - [Contributing](CONTRIBUTING.md)
278
+ - [Development guide](docs/development.md)
279
+ - [Security policy](SECURITY.md)
280
+ - [Release process](docs/release.md)
281
+ - [Changelog](CHANGELOG.md)
282
+
283
+ Licensed under Apache-2.0.