Skip to content

Add license-policy detector (flag-only, no auto-merge) #416

Closed

Description

@hyperpolymath

Gap

Hypatia's CI/CD scanning pipeline does not detect basic license-policy inconsistencies (e.g. workspace `Cargo.toml` license field vs `deny.toml` allow-list). This let verisimdb sit with `AGPL-3.0-or-later` in Cargo.toml but only `MPL-2.0` in deny.toml for weeks — every `cargo deny check` CI run on `main` was failing as a result. See verisimdb#82 (the bite) / verisimdb#101 (the manual fix).

Layer-by-layer diagnosis

Sensing — broken

  • `hypatia/cli/src/commands/scan.rs:521–557` `scan_license_compliance()` only checks LICENSE file existence; does not parse Cargo.toml `license` field or deny.toml allow-list
  • `hypatia/lib/rules/*.ex` has no `LicensePolicy` category in `pattern_registry.ex`
  • Panic-attack emits no cargo-deny findings (separate issue filed)

Reasoning — broken

  • No rule classifies "workspace license not in deny.toml allow-list" as a finding
  • The estate license policy (five-way: MPL-2.0 sole / AGPL son / ARR 007 / PMPL three-repo carve-out / don't-touch forks) lives only in agent memory, not in any config or rule file Hypatia can consume

Actuation — working

  • `hypatia/lib/fleet_dispatcher.ex:27–90` `FleetDispatcher.dispatch_routed_action()` routes via the safety triangle (eliminate / suggest / advisory) cleanly — works for any finding that reaches the registry

Constraint (load-bearing — non-negotiable)

Per estate policy (`feedback_no_automated_licence_edits`), license remediation is manual, file-by-file, owner-only. Detector must:

  • File an issue or open a draft PR with `do-not-auto-merge` label for owner review
  • Never dispatch to `robot-repo-automaton` / `:eliminate` tier auto-execute
  • Never bulk-edit SPDX headers — only flag

Proposed shape

  1. New `lib/rules/license_compliance.ex`:
    • Parse workspace + per-crate Cargo.toml `license` fields, plus `mix.exs` `licenses:` if Elixir
    • Parse `deny.toml` `[licenses] allow = [...]`
    • Cross-validate against the LICENSE file's `SPDX-License-Identifier` header
    • Encode the five-way estate rule as a config data file (not memory; e.g. `priv/license_policy.toml`)
  2. Emit `category="LicensePolicy"`, `severity="High"`, `rule_id="LIC001"` weak_points
  3. Dispatch to advisory or draft-PR-for-review path only — flag the finding, name the offending file/line, never auto-fix
  4. Integration point: `lib/pattern_analyzer.ex:54` (`run_scorecard_checks/0`)

Precedent

The R5a/R5b doc-drift detector (echidna#171 + standards#329) is the same shape but for prover counts and pinned-version strings — that's the model to copy. License detection slots in alongside.

Related

  • verisimdb#82, verisimdb#101 (the manual fix)
  • Estate memory: `feedback_estate_license_policy_umbrella`, `feedback_no_automated_licence_edits`
  • Companion issue (sensing dependency): panic-attack — wire `cargo deny check` JSON output into `weak_points`

🤖 Generated with Claude Code

Activity

  1. hyperpolymath commented on Jun 2, 2026

    @hyperpolymath
    OwnerAuthor

    Closing — landed today as a 3-layer pipeline (2026-06-02)

    Today's PRs implement the requested flag-only license-policy detector and shut off auto-PR for license findings at three layers:

    Detection (hypatia)

    • hypatia#414 — extended lib/rules/cicd_rules.ex with @pmpl_exception_repos (paint-type) + @license_exception_paths (echidna docs/CLAUDE.md/etc.) carve-outs + new 3-arity validate_license/3
    • hypatia#415 — flipped lib/scorecard_ingestor.ex SC-010 auto_fixable: false; added license_finding_strategy/0, license_finding_severity_cap/1, license_related_finding?/1, owner_license_classification/0 helpers; added Manual-Only policy header at the top of cicd_rules.ex

    Refusal gate (gitbot-fleet)

    • gitbot-fleet#247 — scripts/dispatch-runner.sh execute_entry() now refuses any entry whose recipe_id or category matches license|spdx|pmpl|mpl-2|agpl|palimpsest with record_outcome ... refused_license_policy for audit; exit-1 banners prepended to fix-license-hygiene.sh / fix-license-file.sh / fix-missing-spdx.sh

    Policy doc (standards)

    • standards#339 — .claude/CLAUDE.md top-of-file "License Policy — Manual Only (highest-priority guardrail)" section + 5-way classification table + cross-pointers

    Trigger: neurophone#99 method-violation (auto-PR reverting PMPL→MPL across ~140 files, closed unmerged 2026-06-02 09:54Z).

    Verified by synthetic test: bash scripts/fix-license-hygiene.sh exits 1 with refusal banner; gh api repos/hyperpolymath/hypatia/contents/lib/scorecard_ingestor.ex confirms SC-010 carries auto_fixable: false with cited directive.

    Future findings (like hypatia#417 below) will continue to be filed by the scanner as flag-only, but will not auto-PR.

    Co-Authored-By: Claude Opus 4.7 (1M context) [email protected]

  2. hyperpolymath commented on Jun 2, 2026

    @hyperpolymath
    OwnerAuthor

    Implementation-ready spec (follow-up to design above)

    Concrete file layout, code skeleton, test cases, and integration point. Implementation flag-only — never dispatch to auto-execute tier.

    File layout

    lib/rules/license_compliance.ex            # new — the detector
    priv/license_policy.toml                   # new — five-way rule as data, not memory
    test/rules/license_compliance_test.exs     # new — unit tests
    

    Plus one-line integration:

    lib/pattern_analyzer.ex                    # +1 call in run_scorecard_checks/0
    lib/pattern_registry.ex                    # +1 category constant: :license_policy
    

    priv/license_policy.toml

    # Estate license-policy umbrella, encoded as data
    # Source: ~/.claude/.../memory/feedback_estate_license_policy_umbrella.md
    # DO NOT modify without owner approval — see feedback_no_automated_licence_edits
    
    [default]
    license = "MPL-2.0"
    applies_to = "sole-owner repos"
    
    [carve_out.son_shared]
    license = "AGPL-3.0-or-later"
    repos = ["idaptik", "burble", "standards", "rattlescript", "vcl-ut", "airborne-submarine-squadron",
             "gossamer", "thejeffparadox", "the-nash-equilibrium", "affinescript"]
    # Note: list is partial; classification per `git log committers` heuristic confirmed by owner
    
    [carve_out.private]
    license = "All-Rights-Reserved"
    repos = ["007"]
    policy = "do-not-scan"  # never even surface findings
    
    [carve_out.palimpsest]
    license = "PMPL-1.0-or-later"
    repos = ["palimpsest-license", "palimpsest-plasma"]
    prospective_repos = ["consent-aware-http"]  # new files only
    
    [third_party]
    policy = "do-not-touch"
    # detection: origin remote does not match hyperpolymath/*; or repo is a known fork
    
    [enforcement]
    dispatch_tier = "advisory"  # NEVER eliminate / auto-execute
    exclude_keywords_from_auto = ["license", "SPDX", "PMPL", "MPL", "AGPL", "GPL", "Apache", "copyright", "attribution", "relicens"]
    # Companion: feedback_pr_sweep_title_keyword_exclusion

    lib/rules/license_compliance.ex skeleton

    # SPDX-License-Identifier: MPL-2.0
    defmodule Hypatia.Rules.LicenseCompliance do
      @moduledoc """
      Cross-validates a repo's license declarations against:
        1. internal consistency: LICENSE file vs Cargo.toml/mix.exs/package.json license fields
        2. deny.toml allow-list (if Cargo workspace) includes the declared license
        3. estate policy: matches the five-way rule for the repo's category
    
      FLAG-ONLY. Emits weak_points with rule_id "LIC001"/"LIC002"/"LIC003".
      Never dispatches to :eliminate tier; routes to :advisory (sustainabot / rhodibot-suggest).
      """
    
      @policy_path Application.app_dir(:hypatia, "priv/license_policy.toml")
    
      def check(repo_path) when is_binary(repo_path) do
        policy = load_policy()
    
        findings =
          []
          |> append_if(internal_mismatch?(repo_path), &{:lic001, internal_mismatch_detail(repo_path)})
          |> append_if(deny_allowlist_gap?(repo_path), &{:lic002, deny_gap_detail(repo_path)})
          |> append_if(estate_policy_mismatch?(repo_path, policy), &{:lic003, estate_mismatch_detail(repo_path, policy)})
    
        Enum.map(findings, &to_weak_point/1)
      end
    
      defp load_policy, do: @policy_path |> File.read!() |> Toml.decode!()
    
      defp internal_mismatch?(repo_path) do
        # LICENSE file's SPDX header / first-line vs manifests
        license_id = read_license_id(repo_path)
        manifest_ids = read_manifest_license_ids(repo_path)
        license_id && manifest_ids != [] && license_id not in manifest_ids
      end
    
      defp deny_allowlist_gap?(repo_path) do
        deny_path = Path.join(repo_path, "deny.toml")
        cargo_path = Path.join(repo_path, "Cargo.toml")
        case {File.read(deny_path), File.read(cargo_path)} do
          {{:ok, deny}, {:ok, cargo}} ->
            license = extract_cargo_workspace_license(cargo)
            license && !license_in_deny_allow?(deny, license)
          _ -> false
        end
      end
    
      defp estate_policy_mismatch?(repo_path, policy) do
        repo_name = Path.basename(repo_path)
        classification = classify_repo(repo_name, policy)
        expected = expected_license_for(classification, policy)
        observed = read_license_id(repo_path)
        expected && observed && expected != observed
      end
    
      defp classify_repo(repo_name, policy) do
        cond do
          repo_name in policy["carve_out"]["private"]["repos"] -> :private
          repo_name in policy["carve_out"]["son_shared"]["repos"] -> :son_shared
          repo_name in policy["carve_out"]["palimpsest"]["repos"] -> :palimpsest
          repo_name in policy["carve_out"]["palimpsest"]["prospective_repos"] -> :palimpsest_prospective
          is_third_party_fork?(repo_name) -> :third_party
          true -> :sole_owner
        end
      end
    
      defp to_weak_point({rule_id, detail}) do
        %{
          rule_id: rule_id |> Atom.to_string() |> String.upcase(),
          category: "LicensePolicy",
          severity: "High",
          detail: detail,
          do_not_automate: true,  # honour feedback_no_automated_licence_edits
          dispatch_hint: :advisory  # never :eliminate
        }
      end
    
      defp append_if(list, true, fun), do: [fun.() | list]
      defp append_if(list, false, _), do: list
    
      # ... extractors (read_license_id / read_manifest_license_ids / extract_cargo_workspace_license / etc.)
    end

    Test cases (essential)

    test/rules/license_compliance_test.exs:

    1. LIC001 detects internal mismatch — fixture: Cargo.toml license = "AGPL-3.0-or-later" + LICENSE = MPL-2.0 text → emit LIC001
    2. LIC002 detects deny.toml gap — fixture: workspace license MPL-2.0 + deny.toml allow-list without MPL-2.0 → emit LIC002
    3. LIC003 detects estate-policy mismatch (sole-owner) — fixture: repo not in any carve-out + LICENSE = AGPL → emit LIC003
    4. LIC003 silent on son-shared repo correctly AGPL'd — fixture: idaptik LICENSE = AGPL → no finding
    5. LIC003 silent on palimpsest carve-out — fixture: palimpsest-license LICENSE = PMPL → no finding
    6. No finding on third-party fork — fixture: repo with non-hyperpolymath origin remote → no finding (do-not-touch)
    7. Never emits :eliminate dispatch_hint — all 3 rules produce dispatch_hint: :advisory always
    8. do_not_automate flag set on every emission — invariant test
    9. Policy data is loadable — priv/license_policy.toml parses cleanly via Toml.decode

    Integration point

    lib/pattern_analyzer.ex — add a single call from run_scorecard_checks/0 (currently around line 54 per design above):

    def run_scorecard_checks(scans) do
      # ... existing checks
      scans ++ Hypatia.Rules.LicenseCompliance.check(File.cwd!())
    end

    lib/pattern_registry.ex — register the category:

    @categories %{
      # ... existing
      license_policy: %{
        name: "LicensePolicy",
        rule_ids: ["LIC001", "LIC002", "LIC003"],
        default_severity: "High",
        dispatch_tier: :advisory,
        do_not_automate: true
      }
    }

    Dispatch wiring (companion in gitbot-fleet)

    FleetDispatcher.dispatch_routed_action/1 must check category == "LicensePolicy" and route to :advisory regardless of confidence score. Never :eliminate. Filed as separate gitbot-fleet issue (see related).

    Estimated effort

    ~4-6 hours including tests. Owner-driven implementation recommended (it's the estate-policy interpreter; deserves owner judgement on edge cases like "is repo X actually son-shared or not").

    🤖 Generated with Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions