diff --git a/.github/scripts/threat-model-review.py b/.github/scripts/threat-model-review.py index 4f9c5256f4..9809f770c4 100644 --- a/.github/scripts/threat-model-review.py +++ b/.github/scripts/threat-model-review.py @@ -10,8 +10,13 @@ pushes to the same PR pay only for the diff tokens. """ +from __future__ import annotations + import argparse +import ast import fnmatch +import io +import re import sys import anthropic @@ -39,7 +44,8 @@ - console-ui/ Next.js 16 frontend Trust model: coordinator is trusted; providers and consumers are adversarial. -Inference traffic is E2E encrypted via X25519/NaCl box on the coordinator→provider leg. +Request encryption is hop by hop: the coordinator decrypts and re-seals the +request to the provider's attested key (docs/architecture/security/encryption.md). Apple Secure Enclave (non-exportable P-256 key) provides hardware-bound attestation. SIP must be enabled; disabling requires a reboot that kills the process. @@ -74,23 +80,59 @@ def load_threat_model(path: str) -> dict: return yaml.safe_load(f) +def git_path(path: str) -> str: + """Decode Git's optional C quoting, including octal UTF-8 bytes.""" + if not path.startswith('"'): + return path + value = ast.literal_eval(path) + try: + return value.encode("latin-1").decode("utf-8") + except UnicodeError: + return value # core.quotePath=false can leave literal Unicode. + + +def diff_destination(header: str) -> str | None: + paths = re.findall(r'"(?:\\.|[^"\\])*"|\S+', header) + if len(paths) == 2: + destination = git_path(paths[1]) + return destination[2:] if destination.startswith("b/") else None + # Git leaves spaces unquoted. Mode/binary-only changes use the same path + # on both sides; renames/copies also provide explicit destination metadata. + length = (len(header) - 5) // 2 + candidate = header[2:2 + length] + return candidate if header == f"a/{candidate} b/{candidate}" else None + + def parse_diff_by_file(diff_text: str) -> dict[str, str]: """Return ordered {filepath: diff_section_text}.""" files: dict[str, str] = {} current_file: str | None = None buf: list[str] = [] + in_headers = False - for line in diff_text.splitlines(keepends=True): + # Git separates patch lines with LF. Unicode separators inside a hunk are + # file content and must not introduce new apparent diff headers. + for line in io.StringIO(diff_text): if line.startswith("diff --git "): if current_file is not None: files[current_file] = "".join(buf) - current_file = None + current_file = diff_destination(line[len("diff --git "):].rstrip("\n")) buf = [line] - elif line.startswith("+++ b/"): - current_file = line[6:].strip() - buf.append(line) - else: - buf.append(line) + in_headers = True + continue + if line.startswith("@@ "): + in_headers = False + if in_headers: + if line.startswith(("--- ", "+++ ")): + # Unquoted names with spaces end in a tab separator. Literal + # tabs in filenames are C-quoted by Git; filename spaces stay. + path = git_path(line[4:].rstrip("\n").split("\t", 1)[0]) + # Keep the old path for deletions (+++ /dev/null). + if path.startswith(("a/", "b/")): + current_file = path[2:] + elif line.startswith(("rename to ", "copy to ")): + current_file = git_path(line.split(" to ", 1)[1].rstrip("\n")) + buf.append(line) if current_file is not None: files[current_file] = "".join(buf) @@ -124,16 +166,26 @@ def build_focused_diff( for filepath, section in file_diffs.items(): tids = threats_for_file(filepath, threats) + # A move/copy retains the source's threat context. Match both sides, + # but show and budget the patch only once under its destination path. + for line in io.StringIO(section): + if line.startswith("@@ "): + break + if line.startswith(("rename from ", "copy from ")): + source = git_path(line.split(" from ", 1)[1].rstrip("\n")) + tids = list(dict.fromkeys(tids + threats_for_file(source, threats))) if not tids: uncovered.append(filepath) continue if char_budget <= 0: # Budget exhausted — still record that the file is covered - covered[filepath] = (tids, "[diff omitted — total diff budget exhausted]\n") + covered[filepath] = (tids, "") continue - snippet = section[:MAX_FILE_DIFF_CHARS] - if len(section) > MAX_FILE_DIFF_CHARS: - snippet += f"\n[...{filepath} truncated at {MAX_FILE_DIFF_CHARS} chars...]\n" + limit = min(MAX_FILE_DIFF_CHARS, char_budget) + snippet = section[:limit] + if len(section) > limit: + marker = "\n[diff truncated]\n" + snippet = snippet[:limit - len(marker)] + marker if limit >= len(marker) else "" covered[filepath] = (tids, snippet) char_budget -= len(snippet) @@ -173,6 +225,8 @@ def build_user_message( parts.append("\n## Focused diff (security-relevant files only)\n") for filepath, (tids, snippet) in covered.items(): parts.append(f"### `{filepath}` _(threats: {', '.join(tids)})_\n") + if not snippet: + snippet = "[diff omitted — total diff budget exhausted]\n" parts.append(f"```diff\n{snippet}\n```\n") parts.append( @@ -262,4 +316,4 @@ def run(threat_model_path: str, diff_path: str, output_path: str) -> None: parser.add_argument("--diff", required=True, help="Path to PR diff file") parser.add_argument("--output", required=True, help="Output path for the Markdown comment") args = parser.parse_args() - run(args.threat_model, args.diff, args.output) \ No newline at end of file + run(args.threat_model, args.diff, args.output) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b42c81af7d..7ba5e0a349 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -15,6 +15,7 @@ jobs: run: | ./scripts/check-release-version.sh python3 scripts/test-provider-release-resolution.py + python3 scripts/test_review_automation.py ./scripts/sync-install-embed.sh check ./scripts/test-prod-env-refresh.sh - name: Test startup observer against local stubs diff --git a/.github/workflows/codex.yml b/.github/workflows/codex.yml index 03b7c319cb..b6f8c120b0 100644 --- a/.github/workflows/codex.yml +++ b/.github/workflows/codex.yml @@ -51,18 +51,11 @@ jobs: REPO: ${{ github.repository }} PR_NUMBER: ${{ steps.pr.outputs.number }} run: | - json=$(gh api "repos/$REPO/pulls/$PR_NUMBER") - echo "head_sha=$(echo "$json" | jq -r '.head.sha')" >> "$GITHUB_OUTPUT" - echo "base_sha=$(echo "$json" | jq -r '.base.sha')" >> "$GITHUB_OUTPUT" - echo "base_ref=$(echo "$json" | jq -r '.base.ref')" >> "$GITHUB_OUTPUT" - { - echo "title<> "$GITHUB_OUTPUT" + metadata=$(gh api "repos/$REPO/pulls/$PR_NUMBER" | jq -c '{ + head_sha: .head.sha, base_sha: .base.sha, base_ref: .base.ref, + title: (.title // ""), body: (.body // "") + }') + printf 'metadata=%s\n' "$metadata" >> "$GITHUB_OUTPUT" - name: Checkout PR merge commit uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 @@ -72,7 +65,7 @@ jobs: - name: Pre-fetch base and head refs env: - PR_BASE_REF: ${{ steps.meta.outputs.base_ref }} + PR_BASE_REF: ${{ fromJSON(steps.meta.outputs.metadata).base_ref }} PR_NUMBER: ${{ steps.pr.outputs.number }} run: | git fetch --no-tags origin \ @@ -89,8 +82,8 @@ jobs: You are reviewing PR #${{ steps.pr.outputs.number }} for ${{ github.repository }} — the Darkbloom / d-inference decentralized inference project. Review ONLY the changes introduced by this PR. Inspect the diff with: - git log --oneline ${{ steps.meta.outputs.base_sha }}...${{ steps.meta.outputs.head_sha }} - git diff ${{ steps.meta.outputs.base_sha }}...${{ steps.meta.outputs.head_sha }} + git log --oneline ${{ fromJSON(steps.meta.outputs.metadata).base_sha }}...${{ fromJSON(steps.meta.outputs.metadata).head_sha }} + git diff ${{ fromJSON(steps.meta.outputs.metadata).base_sha }}...${{ fromJSON(steps.meta.outputs.metadata).head_sha }} Focus on, in order of importance: 1. Correctness and regressions — broken imports, missing protocol symmetry between `provider-swift/Sources/ProviderCore/Protocol/Messages.swift` (Swift) and `coordinator/protocol/messages.go` (Go), release-bundle consistency across `.github/workflows/release-swift.yml` / `scripts/install.sh` / `LatestProviderVersion`, untested edge cases. @@ -101,10 +94,10 @@ jobs: Be concise and specific. Reference exact file paths and line numbers. Keep feedback under ~400 words. If the PR is clean, say so briefly. PR title: - ${{ steps.meta.outputs.title }} + ${{ fromJSON(steps.meta.outputs.metadata).title }} PR body: - ${{ steps.meta.outputs.body }} + ${{ fromJSON(steps.meta.outputs.metadata).body }} post_feedback: runs-on: blacksmith-4vcpu-ubuntu-2404 diff --git a/docs/developer/build.md b/docs/developer/build.md index 2f6e4d4065..d2856d71d0 100644 --- a/docs/developer/build.md +++ b/docs/developer/build.md @@ -1,6 +1,6 @@ # Build -> Last updated: 2026-09-10 · commit `4f29957d2` +> Last updated: 2026-09-12 · commit `030b1a947` How to build every component of Darkbloom from a fresh clone: the Go coordinator, the Rust prompt-contract sidecar, the Swift provider CLI (with its @@ -11,6 +11,11 @@ Model publishing can pass `HUGGING_FACE_ARTIFACT_JSON` through `scripts/publish-model.sh` to registration. See the [model publishing procedure](../operations/model-migration.md). +PR review automation has local +[input fixtures](test.md#6-scripts-and-release-integrity). They use Python's +standard library, Git, Bash and `jq` to validate review input preparation without +a model API key or a build. + Profiler wire changes require both coordinator and provider builds; the shared Go/Swift fixture and focused checks are described in [test.md](test.md) and [prediction telemetry](../reference/prediction-decision-telemetry.md). diff --git a/docs/developer/test.md b/docs/developer/test.md index 34e02254db..9017257ba4 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1,6 +1,6 @@ # Test -> Last updated: 2026-09-11 · commit `d22ad0cf3` +> Last updated: 2026-09-12 · commit `030b1a947` How to run the unit tests for each component, the end-to-end suite that boots a real coordinator + Swift provider against ephemeral Postgres, and the docs @@ -923,6 +923,14 @@ node --test landing/earn-calculator-core.test.js ### 6. Scripts and release integrity +`python3 scripts/test_review_automation.py` checks review input preparation. +Synthetic patches cover deleted files, both sides of renames, header-like hunk +content and complete omission notices under tiny excerpt limits. A real local +Git diff checks whitespace in filenames. A stubbed `gh` command runs the Codex workflow's +metadata step through Bash and `jq`, checking that multiline PR bodies containing +`EOF` survive the GitHub output format. The fixtures make no API or model calls +and run in Release Integrity CI. + ```bash make benchmark-wrapper-test # python3 -m unittest discover -s gemma_contbatch/tests -t . (in scripts/) ./scripts/check-release-version.sh # ProviderCore.version == coordinator LatestProviderVersion (see operations/provider-release.md) diff --git a/scripts/test_review_automation.py b/scripts/test_review_automation.py new file mode 100644 index 0000000000..9595c3933e --- /dev/null +++ b/scripts/test_review_automation.py @@ -0,0 +1,169 @@ +"""Check review-diff selection with synthetic patches and no model/API calls.""" + +import importlib.util +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import textwrap +import types +import unittest +from unittest.mock import patch + + +ROOT = Path(__file__).resolve().parent.parent +SPEC = importlib.util.spec_from_file_location( + "threat_review", ROOT / ".github/scripts/threat-model-review.py") +REVIEW = importlib.util.module_from_spec(SPEC) +with patch.dict(sys.modules, {name: types.ModuleType(name) for name in ("anthropic", "yaml")}): + SPEC.loader.exec_module(REVIEW) + + +class ReviewAutomationTests(unittest.TestCase): + def test_git_path_separators_preserve_filename_whitespace(self): + name = "coordinator/auth/access policy.go " + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + subprocess.run(["git", "init", "-q", str(root)], check=True) + path = root / name + path.parent.mkdir(parents=True) + path.write_text("old\n") + subprocess.run(["git", "-C", str(root), "add", "--", name], check=True) + path.write_text("new\n") + diff = subprocess.check_output(["git", "-C", str(root), "diff"], text=True) + parsed = REVIEW.parse_diff_by_file(diff) + self.assertEqual(parsed, {name: diff}) + covered, uncovered = REVIEW.build_focused_diff(parsed, [ + {"id": "T-exact", "affected_files": [name]}]) + self.assertEqual(uncovered, []) + self.assertEqual(covered[name][0], ["T-exact"]) + + def test_renames_match_source_and_destination_without_repeating_diff(self): + diff = ('diff --git a/coordinator/auth/check.go b/coordinator/misc/check.go\n' + 'similarity index 100%\nrename from coordinator/auth/check.go\n' + 'rename to coordinator/misc/check.go\n') + covered, uncovered = REVIEW.build_focused_diff(REVIEW.parse_diff_by_file(diff), [ + {"id": "T-auth", "affected_files": ["coordinator/auth/**"]}, + {"id": "T-all", "affected_files": ["coordinator/**"]}, + ]) + self.assertEqual(uncovered, []) + self.assertEqual(len(covered), 1) + threats, snippet = covered["coordinator/misc/check.go"] + self.assertEqual(set(threats), {"T-auth", "T-all"}) + self.assertEqual(len(threats), 2) + self.assertEqual(snippet, diff) + + def test_tiny_budget_keeps_a_complete_omission_notice(self): + for limit in (1, 2, 16): + with self.subTest(limit=limit), patch.object(REVIEW, "MAX_TOTAL_DIFF_CHARS", limit): + covered, uncovered = REVIEW.build_focused_diff({"auth.go": "x" * 100}, [ + {"id": "T-auth", "affected_files": ["auth.go"]}]) + self.assertLessEqual(len(covered["auth.go"][1]), limit) + self.assertIn("diff omitted", REVIEW.build_user_message(covered, uncovered)) + + def test_pr_metadata_round_trips_multiline_text(self): + workflow = (ROOT / ".github/workflows/codex.yml").read_text() + step = workflow.split(" - name: Get PR metadata\n", 1)[1] + script = textwrap.dedent(step.split(" run: |\n", 1)[1] + .split("\n - name:", 1)[0]) + # A normal fenced shell example can contain the old fixed delimiter. + body = 'Before\n```bash\ncat <