Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
Tool attribution: scrub 280 published PR bodies, strip it at commit time, and gate it in CI (#802)
Beenu Arora6b9d1227a949
diff --git a/.githooks/attribution-allowlist.txt b/.githooks/attribution-allowlist.txtnew file mode 100755index 000000000..9c2846f01--- /dev/null+++ b/.githooks/attribution-allowlist.txt@@ -0,0 +1,24 @@+# Lines that LOOK like tool attribution but are not, and must never be stripped+# or flagged.+#+# Same syntax as attribution-patterns.txt: one POSIX-ERE pattern per line,+# matched case-insensitively against a single line. An allowlist match wins over+# a pattern match.+#+# Keep this file short and justify every entry. It is the escape hatch for two+# real cases:+#+# 1. A human contributor whose name or employer collides with a vendor string.+# A real person's trailer is legitimate no matter what they are called.+# 2. Prose that names a vendor neutrally rather than as an attribution — for+# example a model identifier appearing in test data, a provider column in a+# cost table, or a changelog line describing a gateway alias.+#+# Adding an entry here is a deliberate, reviewable act: it widens what the gate+# permits, so it belongs in the diff where a reviewer can see it.++# Project automation that commits on the repository's own behalf. These are the+# project's bots, not a third-party development tool claiming authorship.+^[ \t]*co-authored-by:[ \t]*dependabot\[bot\]+^[ \t]*co-authored-by:[ \t]*aisoc-[a-z-]*bot+^[ \t]*co-authored-by:[ \t]*github-actions\[bot\]diff --git a/.githooks/attribution-patterns.txt b/.githooks/attribution-patterns.txtnew file mode 100755index 000000000..6d3c8ca94--- /dev/null+++ b/.githooks/attribution-patterns.txt@@ -0,0 +1,35 @@+# Tool-attribution patterns — the single source of truth.+#+# Both the client-side hook (.githooks/commit-msg, POSIX sh + grep -E) and the+# CI gate (scripts/check_attribution.py, Python re) read THIS file. Keeping one+# list means the hook and the gate cannot drift apart and start disagreeing+# about what counts as a violation.+#+# Syntax: one POSIX-ERE pattern per line, matched case-insensitively against a+# SINGLE line of text. Blank lines and lines starting with '#' are ignored.+#+# Patterns must stay inside the subset of regex that POSIX ERE and Python `re`+# interpret identically: | ( ) [ ] . * + ? ^ $ and backslash-escaped literals.+# No backreferences, no lookaround, no POSIX [[:class:]] names (Python lacks+# them), no \d / \s shorthands (POSIX ERE lacks them). Use [ \t] for spacing.+#+# `[^a-z]*` at the start absorbs leading whitespace and any emoji (an emoji is+# not an ASCII letter), so a "robot" footer is matched without embedding the+# emoji bytes in a pattern file.++# --- Co-author trailers naming a non-human tool -----------------------------+# A human contributor's trailer has no tool name in it and is left alone. See+# .githooks/attribution-allowlist.txt for exempting a human whose real name+# collides with a vendor string.+^[ \t]*co-authored-by:.*(cursor|claude|anthropic|openai|chatgpt|copilot|codex|gemini|devin|windsurf|aider|codeium|tabnine|sourcegraph|bolt\.new|v0\.dev|lovable|replit)++# --- "Made with / Generated with / Built by <tool>" footers -----------------+# `([a-z]+[ \t]+)?` absorbs one optional vendor qualifier, so "Built with GitHub+# Copilot" and "Generated with Claude Code" are caught as well as the bare form.+^[^a-z]*(made|generated|created|written|authored|built|crafted|produced|developed)[ \t]+(with|by|using)[ \t]*\[?[ \t]*([a-z]+[ \t]+)?(cursor|claude|anthropic|openai|chatgpt|gpt-[0-9o]|copilot|codex|gemini|devin|windsurf|aider|codeium|tabnine)++# --- "Powered by / Assisted by <tool>" --------------------------------------+^[^a-z]*(powered|assisted|aided)[ \t]+by[ \t]*\[?[ \t]*([a-z]+[ \t]+)?(cursor|claude|anthropic|openai|chatgpt|copilot|codex|gemini|devin|windsurf|aider|codeium)++# --- A bare vendor URL on its own line (the link half of a stripped footer) --+^[ \t]*<?https?://(www\.)?(cursor\.(com|sh|so)|claude\.(ai|com)|anthropic\.com|codeium\.com|windsurf\.(com|ai)|githubcopilot\.com)diff --git a/.githooks/commit-msg b/.githooks/commit-msgnew file mode 100755index 000000000..5fd449a2a--- /dev/null+++ b/.githooks/commit-msg@@ -0,0 +1,112 @@+#!/bin/sh+# commit-msg — remove tool-attribution lines before they reach a commit.+#+# Why this exists+# ---------------+# AiSOC never attributes work to a development tool or AI assistant, anywhere:+# code, comments, docs, commit messages, commit trailers, PR bodies, release+# notes or marketing copy. Some editors append a `Co-authored-by:` trailer or a+# "Made with <tool>" footer at commit time, without asking and without anything+# in the repository's git config causing it. This hook removes those lines from+# the message after the editor is done with it.+#+# Why commit-msg and not prepare-commit-msg+# -----------------------------------------+# prepare-commit-msg runs BEFORE the editor, so anything the editor appends+# afterwards survives it. commit-msg runs on the final message and therefore+# also covers `git commit -m`, `git commit --amend` and message templates.+#+# Why this is load-bearing for `main`+# -----------------------------------+# The repository squash-merges with squash_merge_commit_message=COMMIT_MESSAGES,+# which means GitHub composes the squash commit body from the branch commits.+# A trailer on any branch commit is therefore copied onto `main` at merge time.+# Stripping it at commit time is what stops it there; scripts/check_attribution.py+# is the backstop that fails CI if one reaches a PR anyway.+#+# This hook NEVER rejects a commit. It rewrites the message and exits 0. A hook+# that can block is a hook that can halt someone's work on a bad pattern; the+# blocking job belongs in CI, where it is visible and can be fixed in one place.++set -u++MSG_FILE="${1:-}"+[ -n "$MSG_FILE" ] && [ -f "$MSG_FILE" ] || exit 0++HOOK_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)+PATTERNS="$HOOK_DIR/attribution-patterns.txt"+ALLOWLIST="$HOOK_DIR/attribution-allowlist.txt"++# Missing pattern file (partial checkout, submodule, older branch) — do nothing+# rather than guess. CI still enforces the rule.+[ -f "$PATTERNS" ] || exit 0+[ -f "$ALLOWLIST" ] || ALLOWLIST=/dev/null++TMP="$MSG_FILE.attribution.$$"++awk -v patfile="$PATTERNS" -v allowfile="$ALLOWLIST" '+function load(file, arr, n, line) {+ n = 0+ while ((getline line < file) > 0) {+ sub(/\r$/, "", line)+ if (line ~ /^[ \t]*#/) continue+ if (line ~ /^[ \t]*$/) continue+ arr[++n] = line+ }+ close(file)+ return n+}+BEGIN {+ npat = load(patfile, pat)+ nallow = load(allowfile, allow)+}+{+ # Lowercase the line so the (all-lowercase) patterns match case-insensitively+ # without relying on a non-POSIX awk flag.+ probe = tolower($0)++ keep = 1+ for (i = 1; i <= npat; i++) {+ if (probe ~ pat[i]) { keep = 0; break }+ }+ if (!keep) {+ for (i = 1; i <= nallow; i++) {+ if (probe ~ allow[i]) { keep = 1; break }+ }+ }++ if (keep) {+ out[++nout] = $0+ } else {+ removed+++ # Note where the removal happened so an orphaned blank line can be+ # collapsed below.+ cut[nout] = 1+ }+ next+}+END {+ if (!removed) exit 1 # nothing to do; caller keeps the original file++ # Trim trailing blank lines left where the footer used to be. Comment lines+ # git appends below the message are preserved.+ while (nout > 0 && out[nout] ~ /^[ \t]*$/) nout--++ if (nout == 0) exit 1 # never hand git an empty message++ # A footer that sat on its own between two blank lines leaves both behind.+ # Drop one at each removal site so surrounding prose keeps its spacing.+ for (i = 1; i <= nout; i++) {+ print out[i]+ if (cut[i] && out[i] ~ /^[ \t]*$/ && (i + 1) <= nout && out[i + 1] ~ /^[ \t]*$/) i+++ }+}+' "$MSG_FILE" > "$TMP" 2>/dev/null++if [ $? -eq 0 ] && [ -s "$TMP" ]; then+ cat "$TMP" > "$MSG_FILE"+ printf 'commit-msg: removed tool-attribution line(s) from the commit message.\n' >&2+fi+rm -f "$TMP"++exit 0diff --git a/.github/workflows/attribution.yml b/.github/workflows/attribution.ymlnew file mode 100644index 000000000..f13211900--- /dev/null+++ b/.github/workflows/attribution.yml@@ -0,0 +1,85 @@+name: Attribution++# AiSOC never attributes work to a development tool or AI assistant. This gate+# fails when such an attribution reaches a commit message, a changed file, or a+# pull request body.+#+# It runs on BOTH pull_request and push-to-main on purpose. A PR-only gate is+# one-directional: it checks what contributors propose but never what actually+# lands, so anything introduced by the merge itself — a squash message composed+# from branch commits, a commit_message passed to the merge API, an edit made in+# the GitHub UI at merge time — would slip past it while the gate stayed green.+# Checking main after the fact closes that direction.+#+# No paths filter. Attribution can appear in any file, and a filtered gate that+# skips is indistinguishable from a gate that passes.++on:+ pull_request:+ push:+ branches: [main]+ workflow_dispatch:++permissions:+ contents: read++concurrency:+ group: attribution-${{ github.ref }}+ cancel-in-progress: true++jobs:+ attribution:+ name: No tool attribution+ runs-on: ubuntu-latest+ timeout-minutes: 10+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7+ with:+ # Full history: the gate reads commit messages, not just the tree.+ fetch-depth: 0++ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0+ with:+ python-version: "3.12"++ # Runs first and on every invocation. If the patterns stop matching, this+ # fails here rather than letting the scan below report a clean tree it+ # never actually inspected properly.+ - name: Self-test (gate is not vacuous, and agrees with the hook)+ run: python3 scripts/check_attribution.py --self-test++ - name: Scan the tree+ run: python3 scripts/check_attribution.py --all++ - name: Scan commit messages and the PR body+ if: github.event_name == 'pull_request'+ env:+ # Via env, never string-interpolated into the shell: a PR body is+ # attacker-controlled text.+ PR_BODY: ${{ github.event.pull_request.body }}+ BASE_REF: ${{ github.base_ref }}+ run: |+ printf '%s' "$PR_BODY" > /tmp/pr-body.md+ git fetch --no-tags origin "$BASE_REF"+ python3 scripts/check_attribution.py \+ --commits "origin/$BASE_REF..HEAD" \+ --diff-base "origin/$BASE_REF" \+ --text-file /tmp/pr-body.md++ - name: Scan commits that landed on main+ if: github.event_name == 'push'+ env:+ BEFORE: ${{ github.event.before }}+ AFTER: ${{ github.sha }}+ run: |+ # A new branch, a force-push, or a first push gives an all-zero or+ # unreachable `before`. Fall back to the tip commit so the step checks+ # something real instead of silently scanning an empty range.+ if [ -z "$BEFORE" ] || [ "$BEFORE" = "0000000000000000000000000000000000000000" ] \+ || ! git cat-file -e "$BEFORE^{commit}" 2>/dev/null; then+ RANGE="$AFTER~1..$AFTER"+ else+ RANGE="$BEFORE..$AFTER"+ fi+ echo "scanning commit range: $RANGE"+ python3 scripts/check_attribution.py --commits "$RANGE"diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 257e9befb..4aa44fa14 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -49,6 +49,64 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0Nothing in `apps/web` consumes these three routes; it calls`/mssp/children`, which is unchanged.+### Added++- **Tool attribution is now prevented at commit time and blocked in CI.** AiSOC+ does not attribute work to a development tool or AI assistant. An audit found+ the rule was being broken automatically: a `Co-authored-by:` trailer naming an+ editor appeared in 214 commits on `main`, and 280 of 732 pull request bodies+ carried a "Made with" or "Generated with" footer. Nothing in the repository+ caused it — no `commit.template`, no `core.hooksPath`, nothing in+ `.git/hooks/` — the editor appended it at commit time, and it survived+ `git commit --amend`.++ - `.githooks/commit-msg` strips the line before it reaches a commit. It is+ wired through `core.hooksPath`, so it is version-controlled and shared with+ every clone rather than living in an untracked `.git/hooks/`;+ `scripts/setup_hooks.sh` installs it and runs automatically as the `prepare`+ script on `pnpm install`. The hook rewrites and never rejects — a hook that+ can block is a hook that can halt someone's work on a bad pattern, so the+ blocking job belongs in CI where it is visible.+ - This is load-bearing rather than cosmetic because the repository+ squash-merges with `squash_merge_commit_message=COMMIT_MESSAGES`: GitHub+ composes the squash commit body from the branch commits, so a trailer on any+ branch commit is copied onto `main` at merge time.+ - `scripts/check_attribution.py` fails CI when attribution appears in a+ commit message, a changed file or the PR body. A human `Co-authored-by:`+ line is never flagged — a pattern only fires when the trailer names a known+ tool — and `dependabot[bot]` is allowlisted.+ - The gate runs on `push` to `main` as well as on `pull_request`. A PR-only+ check is one-directional: it inspects what contributors propose but never+ what actually lands, so anything introduced by the merge itself would pass+ it while the gate stayed green.+ - `--self-test` runs on every CI invocation and checks four directions against+ a shared fixture corpus: the gate detects every known-bad sample (so it+ cannot pass vacuously), flags no known-good sample (so it cannot pass+ direction one by flagging everything), and the hook strips exactly what the+ gate flags in both directions (so the two implementations cannot drift).+ Both read their patterns from the same `.githooks/attribution-patterns.txt`.+ The self-test earned its place immediately by catching a real hole in the+ patterns — `Built with GitHub Copilot` slipped through, because a vendor+ word sat between the verb and the tool name.++### Changed++- **A hosted deployment's hostname no longer appears in self-hosted docs as the+ reader's own URL.** Seven files under `apps/docs/` pointed at the managed+ instance: two `curl` examples told a self-hoster to push their SIEM data to+ somebody else's ingest endpoint, a sample address appeared in a console+ illustration, three white-paper links and a benchmark-scoreboard link sent+ open-source readers to the hosted console, and a JSON Schema `$id` claimed the+ hosted docs domain. These now use `example.com`, in-repo GitHub links, or the+ project's own documentation URL. Pages genuinely *about* the managed offering+ keep naming it, as does the docs build configuration.+- **The Slack bot no longer deep-links an unconfigured deployment to somebody+ else's console.** `AISOC_WEB_BASE_URL` defaulted to a hosted hostname, so a+ self-hoster who deployed the bot without setting it got case cards pointing at+ another instance. It now defaults to `http://localhost:3000`, matching the+ compose default it had silently disagreed with, and both documented defaults+ were corrected with it.+### Security- **`/api/v1/identity-timeline` read every tenant's alerts.** Both routes bounddiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 72e58ae7e..e0aa966ac 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -129,6 +129,47 @@ docs(readme): update deployment instructionstest(agents): add unit tests for investigation agent```+### No tool attribution++AiSOC does not attribute work to a development tool or AI assistant. That+applies to code, comments, docs, commit messages, commit trailers, PR bodies,+release notes and marketing copy alike — no "built with" or "generated with"+footers, and no `Co-authored-by:` trailer naming a tool.++Credit for human contributors is the opposite of this rule, not an exception to+it: a `Co-authored-by:` line naming a real person is welcome and is never+touched, and neither is `dependabot[bot]`.++Some editors append such a trailer at commit time on their own. Install the+repository's hooks once and the trailer is stripped before it reaches a commit:++```bash+sh scripts/setup_hooks.sh # or: pnpm install, which runs it for you+```++This sets `core.hooksPath` to the tracked [`.githooks/`](.githooks) directory,+so the hook arrives with the checkout instead of living in an untracked+`.git/hooks/`. It rewrites the message and never blocks a commit.++This matters beyond your own branch: the repository squash-merges, and GitHub+composes a squash commit's body from the branch commits — so a trailer on any+commit in your PR is copied onto `main` at merge time.++CI enforces the same rule over commits, changed files and the PR body. To check+before pushing:++```bash+python3 scripts/check_attribution.py --self-test+python3 scripts/check_attribution.py --all+python3 scripts/check_attribution.py --commits origin/main..HEAD+```++If it flags something legitimate — a contributor whose name collides with a+vendor string, or prose naming a vendor neutrally rather than as an attribution+— add a justified entry to+[`.githooks/attribution-allowlist.txt`](.githooks/attribution-allowlist.txt) so+a reviewer sees the exemption in the diff.+### Testing- Write tests for all new featuresdiff --git a/apps/docs/docs/benchmark.md b/apps/docs/docs/benchmark.mdindex a7a29ae27..766f0c453 100644--- a/apps/docs/docs/benchmark.md+++ b/apps/docs/docs/benchmark.md@@ -759,8 +759,8 @@ python3 scripts/run_evals.py --json --out report.jsonSubmissions go through a structured GitHub issue template([`.github/ISSUE_TEMPLATE/benchmark_submission.yml`](https://github.com/beenuar/AiSOC/blob/main/.github/ISSUE_TEMPLATE/benchmark_submission.yml)).-Accepted entries are rendered on the [benchmark scoreboard](https://tryaisoc.com/benchmark) in the-web console. Submission rules:+Accepted entries are rendered on the [public benchmark scoreboard](./benchmark-scoreboard.mdx).+Submission rules:1. **Same fixed dataset** — run against the deterministic 200-incident dataset on the commit you submit. No private fixtures.2. **Same harness** — run `scripts/run_evals.py --json --out report.json` with no flags that disable gates. Attach the full `report.json` so per-template macros are auditable.diff --git a/apps/docs/docs/concepts/automation-maturity.md b/apps/docs/docs/concepts/automation-maturity.mdindex 07670a119..844465804 100644--- a/apps/docs/docs/concepts/automation-maturity.md+++ b/apps/docs/docs/concepts/automation-maturity.md@@ -16,7 +16,7 @@ audit-log decision in `remediation_gate_log`.This page is the canonical reference for the model. For a longer,narrative-style treatment with worked examples, migration playbooks, andreferences to industry frameworks, read the-[**L0–L4 Automation Maturity white paper**](https://tryaisoc.com/papers/l0-l4-automation-maturity.pdf).+[**L0–L4 Automation Maturity white paper**](https://github.com/beenuar/AiSOC/blob/main/apps/web/public/papers/l0-l4-automation-maturity.pdf).## Why a tier model@@ -342,7 +342,7 @@ story is mature. A small number of pilot tenants are running L4-whitelistedclosed loops for `isolate_host` on quarantine-tagged hosts.The white paper companion to this page —-[`l0-l4-automation-maturity.pdf`](https://tryaisoc.com/papers/l0-l4-automation-maturity.pdf) —+[`l0-l4-automation-maturity.pdf`](https://github.com/beenuar/AiSOC/blob/main/apps/web/public/papers/l0-l4-automation-maturity.pdf) —goes deeper on:- The case for an explicit maturity model (vs. opaque "automation level"diff --git a/apps/docs/docs/concepts/capabilities.md b/apps/docs/docs/concepts/capabilities.mdindex f5aad0f45..d457f518d 100644--- a/apps/docs/docs/concepts/capabilities.md+++ b/apps/docs/docs/concepts/capabilities.md@@ -87,7 +87,7 @@ hypothesis-driven hunts.|---|---|---|| **Risk-Based Alerting (RBA)** | `services/fusion/app/services/entity_risk.py` | Alerts contribute time-decayed risk points to entities (user, host, src_ip, domain). Points decay exponentially with a configurable half-life. When an entity's score crosses `rba_promotion_threshold`, AiSOC promotes it to an incident with contributing alerts attached. The entity-centric queue surfaces the top-N highest-risk entities. CI-gated at ≥ 50:1 alert-to-incident ratio. || **ChatOps user verification** | `services/actions/app/executors/chatops.py` | Sends Slack/Teams interactive prompts with three HMAC-signed callback choices (acknowledge / deny / escalate). Tokens carry action, case, tenant, user reference, and expiry. Timeout auto-escalates. |-| **L0–L4 remediation maturity tiers** | `/api/v1/remediation` | Each tier unlocks progressively more autonomous remediation. `evaluate_gate()` checks tier, blast-radius, and per-action whitelist before allowing auto-execution. Full gate audit log. See the [Automation Maturity concept page](./automation-maturity.md) and the [L0–L4 white paper](https://tryaisoc.com/papers/l0-l4-automation-maturity.pdf) for the full model. |+| **L0–L4 remediation maturity tiers** | `/api/v1/remediation` | Each tier unlocks progressively more autonomous remediation. `evaluate_gate()` checks tier, blast-radius, and per-action whitelist before allowing auto-execution. Full gate audit log. See the [Automation Maturity concept page](./automation-maturity.md) and the [L0–L4 white paper](https://github.com/beenuar/AiSOC/blob/main/apps/web/public/papers/l0-l4-automation-maturity.pdf) for the full model. |---diff --git a/apps/docs/docs/connectors/universal-capture.md b/apps/docs/docs/connectors/universal-capture.mdindex d72f6e66a..d3a7d593f 100644--- a/apps/docs/docs/connectors/universal-capture.md+++ b/apps/docs/docs/connectors/universal-capture.md@@ -50,7 +50,7 @@ The token never grants any privilege beyond "write events scoped to this templatThe default route. Accepts a single JSON object **or** an NDJSON batch.```bash-curl -X POST https://ingest.tryaisoc.com/v1/inbox/aisoc_inbox_xxxxx \+curl -X POST https://ingest.example.com/v1/inbox/aisoc_inbox_xxxxx \-H "Content-Type: application/json" \-d '{"event": {@@ -109,7 +109,7 @@ CEF:0|Vendor|Product|1.0|100|User login failed|3|src=10.0.0.1 suser=alice cs1=mfDrop-in replacement for `services/collector/event` — useful for on-prem fleets already configured to write to Splunk HEC. Authorization is the standard `Authorization: Splunk <token>` header where `<token>` is the inbox token minted in the console.```bash-curl -X POST https://ingest.tryaisoc.com/v1/inbox/hec \+curl -X POST https://ingest.example.com/v1/inbox/hec \-H "Authorization: Splunk aisoc_inbox_xxxxx" \-H "Content-Type: application/json" \-d '{"event": {"action": "login_failed", "user": "alice"}, "sourcetype": "auth"}'diff --git a/apps/docs/docs/console/queue.md b/apps/docs/docs/console/queue.mdindex 2a59bb4f9..9c1c25a2a 100644--- a/apps/docs/docs/console/queue.md+++ b/apps/docs/docs/console/queue.md@@ -16,7 +16,7 @@ This page documents the bucket model, the SLA timer, the action set, and the API┌──────────────────────────────────────────────────────────────────────────┐│ Investigation Queue [Mine 3] [Unassigned 12] [All 15] ││ ────────────────────────────────────────────────────────────────────── │-│ ● CRIT Impossible travel · [email protected] SLA -2m 04s [Open] │+│ ● CRIT Impossible travel · [email protected] SLA -2m 04s [Open] ││ ● HIGH Defender — credential dump · web-01 SLA 3m 41s [Open] ││ ● HIGH GitHub PAT exfil · svc-deploy SLA 9m 12s [Open] ││ ● MED New OAuth grant · helpdesk@… SLA 1h 22m [Open] │diff --git a/apps/docs/docs/operations/notifications.md b/apps/docs/docs/operations/notifications.mdindex 73398ea4c..cd84b6624 100644--- a/apps/docs/docs/operations/notifications.md+++ b/apps/docs/docs/operations/notifications.md@@ -112,7 +112,7 @@ If push delivery returns `404` or `410` (subscription expired or removed by the| `AISOC_API_SERVICE_TOKEN` | API key with `cases:read,cases:write,alerts:read`. || `AISOC_ACTIONS_SERVICE_TOKEN` | API key with `actions:write` (or shared key). || `AISOC_DEFAULT_TENANT_ID` | UUID of the tenant Slack actions belong to. |-| `AISOC_WEB_BASE_URL` | Optional. Public web URL used for deep-linked cards. Default `https://app.tryaisoc.com`. |+| `AISOC_WEB_BASE_URL` | Optional. Public web URL used for deep-linked cards. Default `http://localhost:3000`. |Slack tokens **must** come from your secret store (Doppler / Vault / k8s Secret). `pnpm preflight` fails the build if it spots a Slack token in tracked files.diff --git a/apps/docs/static/data/scoreboard.schema.json b/apps/docs/static/data/scoreboard.schema.jsonindex df3209dfb..46c061e6c 100644--- a/apps/docs/static/data/scoreboard.schema.json+++ b/apps/docs/static/data/scoreboard.schema.json@@ -1,6 +1,6 @@{"$schema": "http://json-schema.org/draft-07/schema#",- "$id": "https://docs.tryaisoc.com/data/scoreboard.schema.json",+ "$id": "https://beenuar.github.io/AiSOC/data/scoreboard.schema.json","title": "AiSOC public benchmark scoreboard","description": "Append-only weekly eval results. Substrate rows are deterministic CI gates (no LLM); wet-eval rows are live LangGraph agent runs from the T5.5 weekly job. Both shapes share the same fields so the scoreboard table renders uniformly; substrate:true is the explicit marker that prevents substrate numbers from being quoted as live agent performance.","type": "object",diff --git a/package.json b/package.jsonindex 7e5bc5f24..2f153f3e6 100644--- a/package.json+++ b/package.json@@ -10,6 +10,8 @@"packages/*"],"scripts": {+ "prepare": "sh scripts/setup_hooks.sh || exit 0",+ "hooks:setup": "sh scripts/setup_hooks.sh","build": "turbo run build","dev": "turbo run dev","test": "turbo run test",diff --git a/scripts/attribution_fixtures.json b/scripts/attribution_fixtures.jsonnew file mode 100644index 000000000..f1b0388b8--- /dev/null+++ b/scripts/attribution_fixtures.json@@ -0,0 +1,59 @@+{+ "_comment": [+ "Fixture corpus for the tool-attribution gate. One file, used four ways, so",+ "the client-side hook and the CI gate are held to the same definition:",+ "",+ " 1. scripts/check_attribution.py must FLAG every sample in `bad`.",+ " 2. scripts/check_attribution.py must NOT flag any sample in `good`.",+ " 3. .githooks/commit-msg must REMOVE every `bad` line it is handed.",+ " 4. .githooks/commit-msg must PRESERVE every `good` line it is handed.",+ "",+ "A gate that only ever runs against clean input cannot tell you it still",+ "works. 1 and 3 prove it is not vacuous; 2 and 4 prove it has not grown so",+ "broad that it would strip a real contributor's trailer or flag neutral",+ "prose. Checking only one direction is how a gate passes while drift",+ "accumulates in the direction things actually change."+ ],++ "bad": [+ "Co-authored-by: Cursor <[email protected]>",+ "Co-authored-by: cursor-agent <[email protected]>",+ "Co-authored-by: cursoragent <[email protected]>",+ "Co-Authored-By: Claude Opus 4.8 <[email protected]>",+ "Co-authored-by: Claude <[email protected]>",+ "Co-authored-by: GitHub Copilot <[email protected]>",+ "Co-authored-by: Devin <[email protected]>",+ "Made with [Cursor](https://cursor.com)",+ "made with cursor",+ "\ud83e\udd16 Generated with [Claude Code](https://claude.com/claude-code)",+ "Generated with Claude Code",+ "Created by ChatGPT",+ "Built with GitHub Copilot",+ "Written by Codex",+ "Powered by Claude",+ "Assisted by Cursor",+ "https://cursor.com",+ "https://claude.com/claude-code"+ ],++ "good": [+ "Co-authored-by: Beenu Arora <[email protected]>",+ "Co-authored-by: Beenu Arora <[email protected]>",+ "Co-authored-by: Prince Sinha <[email protected]>",+ "Co-authored-by: beenuar <[email protected]>",+ "Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>",+ "Co-authored-by: aisoc-papers-bot <[email protected]>",+ "Signed-off-by: Beenu Arora <[email protected]>",+ "Lockfile regenerated with [email protected] (lockfileVersion 6.0).",+ "pnpm-lock.yaml regenerated with [email protected], lockfileVersion: '6.0'.",+ "The mock cost table named gpt-4o, gpt-4o-mini and claude-3.5-sonnet.",+ "Add gpt-4o-mini and gpt-4o aliases to the LiteLLM gateway config.",+ "The agent is model-agnostic and has been graded against several providers.",+ "OpenAI-compatible endpoints are supported by the LLM gateway.",+ "Anthropic, OpenAI and DeepSeek are all reachable through the same alias.",+ "This detection fires on anomalous Copilot usage in the customer's estate.",+ "A reference AI-SOC platform reports a comparable figure.",+ "The report was generated with scripts/render_eval_charts.py.",+ "Fixtures are created by build_positive() from the rule under test."+ ]+}diff --git a/scripts/check_attribution.py b/scripts/check_attribution.pynew file mode 100644index 000000000..d54dae8d1--- /dev/null+++ b/scripts/check_attribution.py@@ -0,0 +1,293 @@+#!/usr/bin/env python3+"""Tool-attribution gate.++AiSOC never attributes work to a development tool or AI assistant — not in code,+comments, docs, plan files, commit messages, commit trailers, PR bodies, release+notes or marketing copy. This gate fails CI when such an attribution appears in:++ * a commit message on the pull request's commits,+ * a file changed by the pull request (or the whole tree with --all),+ * the pull request body.++It reads its patterns from .githooks/attribution-patterns.txt — the same file+.githooks/commit-msg reads — so the client-side hook that strips attribution and+the server-side gate that blocks it cannot drift apart and start disagreeing.++Legitimate human `Co-authored-by:` trailers are untouched: a pattern only fires+when the trailer names a known tool, so a real contributor is never flagged. The+allowlist (.githooks/attribution-allowlist.txt) is the escape hatch for a human+whose name collides with a vendor string, and for prose that names a vendor+neutrally rather than as an attribution.++Usage:+ python3 scripts/check_attribution.py --self-test+ python3 scripts/check_attribution.py --all+ python3 scripts/check_attribution.py --diff-base origin/main+ python3 scripts/check_attribution.py --commits origin/main..HEAD+ python3 scripts/check_attribution.py --text-file pr-body.md+"""++from __future__ import annotations++import argparse+import json+import re+import subprocess+import sys+from pathlib import Path++ROOT = Path(__file__).resolve().parent.parent+PATTERN_FILE = ROOT / ".githooks" / "attribution-patterns.txt"+ALLOWLIST_FILE = ROOT / ".githooks" / "attribution-allowlist.txt"+FIXTURES = ROOT / "scripts" / "attribution_fixtures.json"+HOOK = ROOT / ".githooks" / "commit-msg"++# Paths that legitimately contain the vendor strings because they are the+# machinery for detecting them, or a record of the cleanup. Scanning these would+# make the gate flag itself.+SELF_REFERENTIAL = {+ ".githooks/attribution-patterns.txt",+ ".githooks/attribution-allowlist.txt",+ ".githooks/commit-msg",+ "scripts/check_attribution.py",+ "scripts/attribution_fixtures.json",+ ".github/workflows/attribution.yml",+}++# Binary / generated paths that are never prose and would only produce noise.+SKIP_SUFFIXES = (+ ".png",+ ".jpg",+ ".jpeg",+ ".gif",+ ".webp",+ ".svg",+ ".ico",+ ".pdf",+ ".woff",+ ".woff2",+ ".ttf",+ ".eot",+ ".zip",+ ".gz",+ ".tar",+ ".jar",+ ".lock",+ ".bin",+ ".onnx",+ ".parquet",+)+SKIP_DIRS = ("node_modules/", ".git/", "dist/", "build/", ".next/", "vendor/")+++def _load_patterns(path: Path) -> list[re.Pattern]:+ if not path.exists():+ sys.exit(f"check_attribution: missing pattern file {path}")+ out = []+ for raw in path.read_text(encoding="utf-8").splitlines():+ line = raw.strip()+ if not line or line.startswith("#"):+ continue+ try:+ out.append(re.compile(line, re.IGNORECASE))+ except re.error as exc:+ sys.exit(f"check_attribution: bad pattern {line!r} in {path.name}: {exc}")+ if not out:+ sys.exit(f"check_attribution: {path.name} defines no patterns — refusing to run vacuously")+ return out+++PATTERNS = _load_patterns(PATTERN_FILE)+ALLOWLIST = _load_patterns(ALLOWLIST_FILE) if ALLOWLIST_FILE.exists() else []+++def is_attribution(line: str) -> bool:+ """True when a single line is tool attribution and not allowlisted."""+ if not any(p.search(line) for p in PATTERNS):+ return False+ return not any(a.search(line) for a in ALLOWLIST)+++def scan_text(text: str, origin: str) -> list[tuple[str, int, str]]:+ hits = []+ for n, line in enumerate(text.splitlines(), 1):+ if is_attribution(line):+ hits.append((origin, n, line.strip()[:200]))+ return hits+++def _git(*args: str) -> str:+ r = subprocess.run(["git", *args], cwd=ROOT, capture_output=True, text=True)+ if r.returncode != 0:+ sys.exit(f"check_attribution: git {' '.join(args)} failed: {r.stderr.strip()[:300]}")+ return r.stdout+++def _skip(rel: str) -> bool:+ return rel in SELF_REFERENTIAL or rel.endswith(SKIP_SUFFIXES) or any(d in rel for d in SKIP_DIRS)+++def scan_files(paths: list[str]) -> list[tuple[str, int, str]]:+ hits = []+ for rel in paths:+ if _skip(rel):+ continue+ p = ROOT / rel+ if not p.is_file():+ continue+ try:+ text = p.read_text(encoding="utf-8")+ except (UnicodeDecodeError, OSError):+ continue+ hits.extend(scan_text(text, rel))+ return hits+++def scan_commits(rev_range: str) -> list[tuple[str, int, str]]:+ """Scan commit messages in a range. Merge commits are included: a squash+ merge composes its message from the branch commits, so a trailer on any of+ them is what lands on main."""+ out = _git("log", "--format=%H%x00%B%x00%x00", rev_range)+ hits = []+ for entry in out.split("\x00\x00"):+ if not entry.strip():+ continue+ sha, _, body = entry.partition("\x00")+ sha = sha.strip()+ if not sha:+ continue+ hits.extend(scan_text(body, f"commit {sha[:12]}"))+ return hits+++def self_test() -> int:+ """Prove the gate is neither vacuous nor over-broad, in both directions, and+ that the hook and the gate agree on the same corpus."""+ data = json.loads(FIXTURES.read_text(encoding="utf-8"))+ bad, good = data["bad"], data["good"]+ failures: list[str] = []++ print(f"self-test: {len(PATTERNS)} patterns, {len(ALLOWLIST)} allowlist entries")+ print(f"self-test: {len(bad)} known-bad and {len(good)} known-good samples\n")++ # Direction 1 — the gate must DETECT every known-bad sample. Without this a+ # broken regex makes the gate pass everything, silently.+ for s in bad:+ if not is_attribution(s):+ failures.append(f"gate MISSED known-bad sample: {s!r}")++ # Direction 2 — the gate must NOT flag any known-good sample. Without this+ # the gate could pass direction 1 by flagging literally everything.+ for s in good:+ if is_attribution(s):+ failures.append(f"gate FLAGGED known-good sample: {s!r}")++ # Direction 3 + 4 — the hook must strip exactly what the gate flags. This is+ # the cross-check that keeps the two implementations honest about the same+ # pattern file; without it they can drift in opposite directions and both+ # look fine in isolation.+ if HOOK.exists():+ for s in bad:+ if _hook_keeps(s):+ failures.append(f"hook did NOT strip known-bad line: {s!r}")+ for s in good:+ if not _hook_keeps(s):+ failures.append(f"hook STRIPPED known-good line: {s!r}")+ else:+ failures.append(f"hook not found at {HOOK} — cannot cross-check")++ if failures:+ print("SELF-TEST FAILED")+ for f in failures:+ print(f" - {f}")+ return 1+ print("SELF-TEST PASSED")+ print(" gate detects every known-bad sample (not vacuous)")+ print(" gate flags no known-good sample (not over-broad)")+ print(" hook strips exactly what the gate flags (no hook/gate drift)")+ return 0+++def _hook_keeps(line: str) -> bool:+ """Run the real hook over a message containing `line`; True if it survived."""+ import tempfile++ with tempfile.NamedTemporaryFile("w", suffix=".msg", delete=False, encoding="utf-8") as fh:+ fh.write(f"chore: fixture subject\n\nbody line that must survive\n\n{line}\n")+ path = fh.name+ try:+ subprocess.run(["sh", str(HOOK), path], capture_output=True, text=True, cwd=ROOT)+ result = Path(path).read_text(encoding="utf-8")+ finally:+ Path(path).unlink(missing_ok=True)+ if "body line that must survive" not in result:+ raise SystemExit(f"hook destroyed real content while processing {line!r}")+ return line in result+++def main() -> int:+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ ap.add_argument("--self-test", action="store_true", help="prove the gate works, both directions")+ ap.add_argument("--all", action="store_true", help="scan every tracked file")+ ap.add_argument("--diff-base", help="scan files changed against this ref")+ ap.add_argument("--commits", help="scan commit messages in this rev range")+ ap.add_argument("--text-file", action="append", default=[], help="scan a text file (e.g. the PR body)")+ args = ap.parse_args()++ if args.self_test:+ return self_test()++ hits: list[tuple[str, int, str]] = []+ scanned: list[str] = []++ if args.all:+ files = [f for f in _git("ls-files").splitlines() if f]+ hits += scan_files(files)+ scanned.append(f"{len(files)} tracked files")++ if args.diff_base:+ files = [f for f in _git("diff", "--name-only", f"{args.diff_base}...HEAD").splitlines() if f]+ hits += scan_files(files)+ scanned.append(f"{len(files)} changed files vs {args.diff_base}")++ if args.commits:+ hits += scan_commits(args.commits)+ n = len([x for x in _git("rev-list", args.commits).splitlines() if x])+ scanned.append(f"{n} commit messages in {args.commits}")++ for tf in args.text_file:+ p = Path(tf)+ if p.is_file() and p.stat().st_size > 0:+ hits += scan_text(p.read_text(encoding="utf-8"), f"text:{p.name}")+ scanned.append(f"text file {p.name}")++ if not scanned:+ ap.error("nothing to scan — pass --all, --diff-base, --commits, --text-file or --self-test")++ # Name the repository that was actually inspected. Every git read below runs+ # against the checkout this script lives in, not the caller's cwd, so a run+ # launched from a different worktree would otherwise print a confident "OK"+ # about a tree it never looked at.+ print(f"check_attribution: repo {ROOT}")+ print("check_attribution: scanned " + ", ".join(scanned))++ if hits:+ print(f"\nFAIL — {len(hits)} tool-attribution violation(s):\n")+ for origin, n, line in hits:+ print(f" {origin}:{n}: {line}")+ print(+ "\nAiSOC does not attribute work to a development tool or AI assistant.\n"+ "Remove the line. If it is a commit trailer, `sh scripts/setup_hooks.sh`\n"+ "installs the hook that strips it automatically, then amend the commit.\n"+ "If this is a false positive (a contributor whose name collides with a\n"+ "vendor string, or neutral prose), add a justified entry to\n"+ ".githooks/attribution-allowlist.txt so a reviewer sees it in the diff."+ )+ return 1++ print("OK — no tool attribution found.")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/setup_hooks.sh b/scripts/setup_hooks.shnew file mode 100755index 000000000..74d58444b--- /dev/null+++ b/scripts/setup_hooks.sh@@ -0,0 +1,62 @@+#!/bin/sh+# Point this clone's git hooks at the tracked .githooks/ directory.+#+# Git hooks live in .git/hooks/, which is not version-controlled and therefore+# not shared with anyone who clones the repository. `core.hooksPath` redirects+# git to a tracked directory instead, so the hooks arrive with the checkout and+# every contributor gets the same ones.+#+# This runs automatically as the `prepare` script on `pnpm install`. Run it by+# hand if you do not use pnpm:+#+# sh scripts/setup_hooks.sh+#+# It is idempotent and safe to run repeatedly.+#+# POSIX sh on purpose, invoked as `sh` and not `bash`. The web image builds on+# Alpine, which ships busybox ash and no bash at all; a `prepare` script that+# assumes bash fails `pnpm install` and takes the whole image build down with+# it. For the same reason package.json runs this as `… || exit 0`: installing+# a git hook is a convenience, and it must never be the reason a build fails.+# CI is what actually enforces the rule.++set -eu++# No git binary at all (slim build image) — nothing to configure.+if ! command -v git >/dev/null 2>&1; then+ echo "setup_hooks: no git binary, nothing to do."+ exit 0+fi++# Not a git checkout (release tarball, Docker build context, vendored copy) —+# there is nothing to configure and that is not an error.+if ! git rev-parse --git-dir >/dev/null 2>&1; then+ echo "setup_hooks: not a git checkout, nothing to do."+ exit 0+fi++ROOT=$(git rev-parse --show-toplevel)+cd "$ROOT"++if [ ! -d .githooks ]; then+ echo "setup_hooks: .githooks/ not found in $ROOT — nothing to configure." >&2+ exit 0+fi++current=$(git config --get core.hooksPath || true)++if [ -n "$current" ] && [ "$current" != ".githooks" ]; then+ # Someone (or another tool, e.g. husky) already owns hooks here. Say so+ # rather than silently stealing the setting.+ echo "setup_hooks: core.hooksPath is already set to '$current', leaving it alone." >&2+ echo "setup_hooks: to use the repository's hooks run: git config core.hooksPath .githooks" >&2+ exit 0+fi++git config core.hooksPath .githooks++# The executable bit is tracked in git, but a checkout with a restrictive umask+# or a filesystem that drops the mode bit (some Windows/WSL setups) needs help.+chmod +x .githooks/* 2>/dev/null || true++echo "setup_hooks: core.hooksPath -> .githooks"diff --git a/services/slack-bot/README.md b/services/slack-bot/README.mdindex 02df96387..e374cf494 100644--- a/services/slack-bot/README.md+++ b/services/slack-bot/README.md@@ -39,7 +39,7 @@ Configured entirely via environment variables (Pydantic settings):| `AISOC_ACTIONS_BASE_URL` | yes | e.g. `http://aisoc-actions:8085` (in-cluster). || `AISOC_API_SERVICE_TOKEN` | yes | `aisoc_…` API key with `cases:read,cases:write,alerts:read`. || `AISOC_ACTIONS_SERVICE_TOKEN` | yes | `aisoc_…` API key with `actions:write` (or shared key). |-| `AISOC_WEB_BASE_URL` | no | Public web URL used to deep-link case cards. Default `https://app.tryaisoc.com`. |+| `AISOC_WEB_BASE_URL` | no | Public web URL used to deep-link case cards. Default `http://localhost:3000`. || `AISOC_DEFAULT_TENANT_ID` | yes | UUID of the tenant Slack actions belong to (single-tenant Slack workspace assumption). || `AISOC_SLACK_BOT_PORT` | no | Bolt FastAPI port. Default `8089`. |diff --git a/services/slack-bot/app/core/config.py b/services/slack-bot/app/core/config.pyindex 9d9130e32..1893a97f8 100644--- a/services/slack-bot/app/core/config.py+++ b/services/slack-bot/app/core/config.py@@ -75,8 +75,12 @@ class SlackBotSettings(BaseSettings):),)AISOC_WEB_BASE_URL: str = Field(- default="https://app.tryaisoc.com",- description="Public web app URL used to deep-link case cards.",+ default="http://localhost:3000",+ description=(+ "Public web app URL used to deep-link case cards. Defaults to the "+ "local console so an unconfigured deployment links to its own "+ "instance rather than somebody else's. Matches the compose default."+ ),)# --- Proactive notification -------------------------------------------diff --git a/tests/test_attribution_gate.py b/tests/test_attribution_gate.pynew file mode 100644index 000000000..43c6b11fe--- /dev/null+++ b/tests/test_attribution_gate.py@@ -0,0 +1,155 @@+"""Tests for the tool-attribution gate, `scripts/check_attribution.py`.++The gate and the client-side hook (`.githooks/commit-msg`) are two+implementations of one rule, so the properties worth asserting are not just+"does it catch a bad line" but "do the two agree, in both directions".++A gate checked only against clean input cannot tell you it still works: a regex+that stops matching turns it into a no-op that reports OK forever. A gate+checked only against bad input can pass by flagging everything, which would+strip a real contributor's `Co-authored-by:` trailer — the exact credit the+project does want to keep. Both directions are asserted here, against the same+fixture corpus the CI self-test uses.+"""++from __future__ import annotations++import importlib.util+import json+import subprocess+import sys+from pathlib import Path++import pytest++_REPO = Path(__file__).resolve().parents[1]+_SCRIPT = _REPO / "scripts" / "check_attribution.py"+_FIXTURES = _REPO / "scripts" / "attribution_fixtures.json"+_HOOK = _REPO / ".githooks" / "commit-msg"+++def _load_gate():+ spec = importlib.util.spec_from_file_location("check_attribution", _SCRIPT)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++gate = _load_gate()+_CORPUS = json.loads(_FIXTURES.read_text(encoding="utf-8"))++[email protected]("sample", _CORPUS["bad"])+def test_gate_detects_known_bad(sample: str) -> None:+ """Not vacuous: every known attribution form is caught."""+ assert gate.is_attribution(sample), f"gate missed attribution: {sample!r}"++[email protected]("sample", _CORPUS["good"])+def test_gate_ignores_known_good(sample: str) -> None:+ """Not over-broad: human trailers and neutral prose are left alone.++ This is the half that protects contributors. `Co-authored-by: Prince Sinha`+ and `dependabot[bot]` are credit the project wants; a model name quoted in+ prose, or a lockfile "regenerated with pnpm", is description, not+ attribution.+ """+ assert not gate.is_attribution(sample), f"gate flagged legitimate text: {sample!r}"+++def _hook_output(line: str) -> str:+ """Run the real hook over a message containing `line`."""+ import tempfile++ with tempfile.NamedTemporaryFile(+ "w", suffix=".msg", delete=False, encoding="utf-8"+ ) as fh:+ fh.write(f"chore: fixture subject\n\nbody line that must survive\n\n{line}\n")+ path = Path(fh.name)+ try:+ subprocess.run(+ ["sh", str(_HOOK), str(path)], capture_output=True, text=True, cwd=_REPO+ )+ return path.read_text(encoding="utf-8")+ finally:+ path.unlink(missing_ok=True)++[email protected]("sample", _CORPUS["bad"])+def test_hook_strips_known_bad(sample: str) -> None:+ out = _hook_output(sample)+ assert sample not in out, f"hook did not strip: {sample!r}"+ assert "body line that must survive" in out, "hook destroyed real content"++[email protected]("sample", _CORPUS["good"])+def test_hook_preserves_known_good(sample: str) -> None:+ out = _hook_output(sample)+ assert sample in out, f"hook stripped legitimate text: {sample!r}"+++def test_hook_and_gate_agree() -> None:+ """The two implementations must not drift apart.++ They read the same pattern file; this asserts they also *behave* the same,+ which is the property that actually matters and the one a shared data file+ alone does not guarantee.+ """+ disagreements = []+ for sample in _CORPUS["bad"] + _CORPUS["good"]:+ flagged = gate.is_attribution(sample)+ stripped = sample not in _hook_output(sample)+ if flagged != stripped:+ disagreements.append(+ f"{sample!r}: gate flagged={flagged}, hook stripped={stripped}"+ )+ assert not disagreements, "hook and gate disagree:\n " + "\n ".join(disagreements)+++def test_patterns_file_is_not_empty() -> None:+ """A pattern file that fails to load would make the gate silently permissive."""+ assert gate.PATTERNS, "no patterns loaded — the gate would pass everything"+++def test_self_test_subcommand_passes() -> None:+ """The same invocation CI runs."""+ r = subprocess.run(+ [sys.executable, str(_SCRIPT), "--self-test"],+ capture_output=True,+ text=True,+ cwd=_REPO,+ )+ assert r.returncode == 0, f"self-test failed:\n{r.stdout}\n{r.stderr}"+++def test_gate_fails_on_a_bad_text_file(tmp_path: Path) -> None:+ """End-to-end through the CLI, not just the predicate: a body with a footer+ must exit non-zero. This is the path CI uses for the PR body."""+ bad = tmp_path / "body.md"+ bad.write_text(+ "Real technical content.\n\nMade with [Cursor](https://cursor.com)\n",+ encoding="utf-8",+ )+ r = subprocess.run(+ [sys.executable, str(_SCRIPT), "--text-file", str(bad)],+ capture_output=True,+ text=True,+ cwd=_REPO,+ )+ assert r.returncode == 1, f"gate passed a body with a footer:\n{r.stdout}"+ assert "Made with" in r.stdout+++def test_gate_passes_a_clean_text_file(tmp_path: Path) -> None:+ clean = tmp_path / "body.md"+ clean.write_text(+ "Real technical content.\n\nCo-authored-by: Prince Sinha <[email protected]>\n",+ encoding="utf-8",+ )+ r = subprocess.run(+ [sys.executable, str(_SCRIPT), "--text-file", str(clean)],+ capture_output=True,+ text=True,+ cwd=_REPO,+ )+ assert r.returncode == 0, f"gate flagged a clean body:\n{r.stdout}"