Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 67 additions & 13 deletions .github/scripts/threat-model-review.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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"))
Comment thread
Gajesh2007 marked this conversation as resolved.
Resolved
buf.append(line)

if current_file is not None:
files[current_file] = "".join(buf)
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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)
run(args.threat_model, args.diff, args.output)
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
27 changes: 10 additions & 17 deletions .github/workflows/codex.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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<<EOF"
echo "$json" | jq -r '.title // ""'
echo "EOF"
echo "body<<EOF"
echo "$json" | jq -r '.body // ""'
echo "EOF"
} >> "$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
Expand All @@ -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 \
Expand All @@ -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.
Expand All @@ -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
Expand Down
7 changes: 6 additions & 1 deletion docs/developer/build.md
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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).
Expand Down
10 changes: 9 additions & 1 deletion docs/developer/test.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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)
Expand Down
Loading
Loading