Skip to content
项目

关于

Detect, gate, redact, and report PHI candidate flows across healthcare and insurance AI prompts, RAG, tools, memory, logs, and provider boundaries.

人工智能与机器学习

这些数字如何统计

实测星标增长

24小时
0
7天
0
15天
0
1个月
正在收集历史

各周期内的星标净变化,周期相互重叠,并非每日新增。缺失的测量保持空白。星标代表关注度,不代表软件质量。

README.md

原文

PHI Boundary Gate

target v0.8.5 Python 3.11+ Markdown, JSON, and JSONL output synthetic PHI only license MIT

PHI Boundary Gate detects, gates, redacts, and reports PHI candidate movement across AI context boundaries: user messages, RAG context, tool output, model input, memory, debug logs, and provider requests.

It is built for healthcare and insurance AI workflows where an identifier match is only the start. The report answers which layer the value entered, where it came from, where it is going, which structured payload field contained it, and what policy says should happen before it moves again.

The package ships as both a CLI and a Python library. Use the CLI for offline audits that produce Markdown, JSON, and redacted JSONL traces. Use the library inside another service to scan text, redact policy-matched spans, or block model calls when the configured PHI and compliance policy says the route is not allowed.

Boundary-first reports Groups repeated PHI candidates across trace events so you can see the path, not only the match.
Exposure change analysis Compares two JSON audit reports with configuration provenance, comparability diagnostics, and observed risk direction.
Audit coverage diagnostics Optionally summarizes observed events and scannable content, then reports bounded, advisory blind-spot warnings.
Coverage-aware exposure review Optionally compares two coverage sidecars alongside Exposure Diff without inferring causality or changing CI.
Path-aware audit schema Report schema v3 records JSON content paths and external adapter paths for structured payloads.
Hybrid candidate detection Built-in regex rules cover common synthetic PHI variants; optional local Presidio detection can add NER-backed spans.
Semantic context gate An optional provider-neutral resolver classifies who a candidate represents, what information it is linked to, and its semantic PHI disposition.
Trace corpus baseline Synthetic trace expectations cover boundary flow, near misses, free text, structured payloads, and provider-boundary paths.
External trace adapters Mapping v1 can normalize generic agent JSONL into the package trace schema before scanning.
Policy-driven redaction YAML policy decides whether each category is allowed, should be redacted, or is a violation in each layer.
Provider-call guard Checks organization-supplied BAA, covered service, model, feature, logging, and storage facts before PHI is sent.
Audit-aware serialization Detailed decisions can omit detected raw finding values, while integrations use explicit structural log whitelists because undetected text is not guaranteed redacted.
Synthetic samples only The repository contains no real PHI and does not claim HIPAA compliance.

Quick Start

Choose an integration path before reaching for lower-level modules:

Goal Public entry point
Audit an existing Agent/RAG trace audit_external_trace() or scan-external-trace
Guard a provider-bound model request guard_compliance()
Redact detected spans for a log/report destination redact_text() or redact_for_log()
Compare observed exposure across revisions compare-reports with optional coverage sidecars

The Integration Cookbook provides complete, offline Guard, Audit, Redact, and Compare recipes.

Run the bundled sample

Use this path when you have cloned this repository and are running commands from the repo root. The sample trace, policy, and report paths below are repository files, not package data installed into another project.

python3 -m pip install -e .
phi-boundary-gate scan-trace \
  --trace samples/traces/claim_agent_minimal.jsonl \
  --policy samples/policies/default.yml \
  --out reports/sample-report.md \
  --json reports/sample-report.json

The legacy direct scan form is also preserved for compatibility:

phi-boundary-gate \
  --trace samples/traces/claim_agent_minimal.jsonl \
  --policy samples/policies/default.yml \
  --out reports/sample-report.md \
  --json reports/sample-report.json

Run the same command without installing the package:

PYTHONPATH=src python3 -m phi_boundary_gate.cli scan-trace \
  --trace samples/traces/claim_agent_minimal.jsonl \
  --policy samples/policies/default.yml \
  --out reports/sample-report.md \
  --json reports/sample-report.json \
  --redacted-trace reports/sample-redacted-trace.jsonl

Invalid trace or policy input returns exit code 2 and writes the validation error to stderr.

Inspect observed audit coverage

Coverage exports are opt-in and separate from the existing audit report:

phi-boundary-gate scan-trace \
  --trace samples/traces/no_phi.jsonl \
  --policy samples/policies/default.yml \
  --out /tmp/phi-report.md \
  --json /tmp/phi-report.json \
  --coverage-json /tmp/phi-coverage.json \
  --coverage-markdown /tmp/phi-coverage.md \
  --expect-layer model_input \
  --expect-layer tool_output

For example, a trace may produce zero findings while also warning that an explicitly expected model_input layer was not observed. That warning is advisory: it does not fail the command, alter detection or Guard decisions, or declare a compliance violation. Observed coverage does not prove complete agent execution, and zero findings does not prove that the execution was PHI-free. See Audit Coverage Diagnostics.

Install from another project

Use the PyPI package for normal consumption:

python3 -m pip install "phi-boundary-gate>=0.8,<0.9"

The consuming environment needs Python 3.11 or newer and pip. pip installs the runtime dependency PyYAML>=6.0.

Optional local NER support is available for projects that want Presidio-assisted span detection in addition to the built-in regex rules:

python3 -m pip install "phi-boundary-gate[ner]>=0.8,<0.9"
python3 -m spacy download en_core_web_lg

Then enable it explicitly:

phi-boundary-gate scan-trace \
  --trace samples/traces/expanded_phi_variants.jsonl \
  --policy samples/policies/default.yml \
  --out reports/expanded-report.md \
  --json reports/expanded-report.json \
  --enable-presidio

Without --enable-presidio, scans stay dependency-light and use only the bundled deterministic rules.

Consuming projects must provide their own PHI policy YAML. If they use the compliance guard, they must also provide their own compliance policy YAML with organization-approved BAA, covered service, model, feature, logging, and storage facts. The sample files under samples/ are examples to copy and adapt; they are not installed as importable package resources.

To bootstrap a consuming project with starter policy files:

phi-boundary-gate init
phi-boundary-gate check-config

This creates .phi-boundary-gate/config.json, config/phi-policy.yml, and config/phi-compliance-policy.yml. Review those files with the owners of your logging, prompting, memory, provider, and compliance controls before using them with real PHI.

Update from another project

Update consuming projects through the package index:

python3 -m pip install --upgrade "phi-boundary-gate>=0.8,<0.9"

Production projects should use a compatible version range such as phi-boundary-gate>=0.8,<0.9 and let Dependabot, Renovate, or a lockfile update workflow propose patch/minor updates through CI. Git tag installs remain a fallback for environments that cannot access PyPI, but they are no longer the primary consumption path.

For requirements.txt and pyproject.toml examples, see Install and Consume as a Package.

Scan an external agent trace in one step

v0.6.1 can compose the mapping adapter and path-aware audit pipeline without persisting an intermediate normalized trace:

phi-boundary-gate scan-external-trace \
  --input raw-agent-events.jsonl \
  --mapping config/phi-trace-map.yml \
  --policy config/phi-policy.yml \
  --out /tmp/phi-report.md \
  --json /tmp/phi-report.json \
  --diagnostics /tmp/phi-adapter-diagnostics.json \
  --report-values redacted

The existing convert-trace -> validate-trace -> scan-trace workflow remains available when you want to inspect or persist the normalization stage. See docs/direct-external-audit.md for SDK usage, diagnostics, and safety notes.

Compare two audit reports

compare-reports performs advisory exposure-change analysis over two schema v3 JSON reports. Differences do not fail the command or alter Guard behavior:

phi-boundary-gate compare-reports \
  --before baseline-report.json \
  --after candidate-report.json \
  --out exposure-diff.md \
  --json exposure-diff.json \
  --review-summary review-summary.md

# Optional GitHub Actions integration; the CLI never writes this automatically.
cat review-summary.md >> "$GITHUB_STEP_SUMMARY"

The comparison expands multiple destinations, ignores event IDs, timestamps, matched values, and input order, and uses an exact structural route key. Paths and source types are emitted only as SHA-256 references, so the Diff does not copy raw PHI or arbitrary input fields. New v0.8.1 reports carry optional schema-v3 audit_context fingerprints for the effective policy and detector configuration. The Diff distinguishes route structure from disposition comparability, detects configuration drift, and labels changed dispositions as worsened, improved, or mixed/other. v0.8.0 reports remain accepted and are marked as having incomplete provenance. The optional v0.8.2 Review Summary adds bounded, fixed-template guidance codes for newly observed routes, disposition direction, and configuration uncertainty. It contains aggregate counts only, is advisory/non-blocking, and does not change the Diff JSON or default Markdown output. v0.8.4 can additionally consume paired v0.8.3 Coverage JSON files and write independent coverage-aware JSON/Markdown sidecars:

phi-boundary-gate compare-reports \
  --before baseline-report.json \
  --after candidate-report.json \
  --out exposure-diff.md \
  --json exposure-diff.json \
  --before-coverage baseline-coverage.json \
  --after-coverage candidate-coverage.json \
  --coverage-review coverage-review.md \
  --coverage-diff-json coverage-diff.json

The two Coverage inputs are paired and opt-in. Fewer observed exposures together with fewer events or layers is evidence of a narrower observed audit scope, not proof of lower PHI risk. Coverage-aware output never changes Guard, Disposition, Compliance Decision, the existing Diff, or a successful advisory exit code.

Coverage-Aware Diff compares observed audit scope. It does not establish complete trace capture, causal risk changes, or HIPAA compliance.

See Exposure Diff for a complete synthetic scan-to-diff example and the versioned JSON contract, and Coverage-Aware Exposure Diff for the sidecar schema and full synthetic walkthrough.

Convert an external agent trace

External agent logs usually need a thin normalization step before scanning. The experimental mapping v1 adapter converts generic JSONL into the package trace schema, including multi-field fallbacks for agent runtimes that use different names for event IDs, timestamps, layers, source nodes, or provider sinks:

phi-boundary-gate convert-trace \
  --input samples/external_traces/generic_agent_run.jsonl \
  --mapping samples/trace_mappings/generic_agent.yml \
  --out /tmp/phi-normalized-trace.jsonl \
  --diagnostics /tmp/phi-adapter-diagnostics.json

phi-boundary-gate validate-mapping \
  --mapping samples/trace_mappings/generic_agent.yml

phi-boundary-gate validate-trace --trace /tmp/phi-normalized-trace.jsonl

phi-boundary-gate scan-trace \
  --trace /tmp/phi-normalized-trace.jsonl \
  --policy samples/policies/default.yml \
  --out /tmp/phi-normalized-report.md \
  --json /tmp/phi-normalized-report.json \
  --report-values redacted \
  --redacted-trace /tmp/phi-normalized-redacted.jsonl

See Trace Adapters for the mapping schema and safety notes.

What It Reads

The trace is JSONL. Each event records the layer, content, source path, and destination path for one piece of context:

{"event_id":"evt_003","timestamp":"2026-01-15T09:00:03Z","layer":"tool_output","source":{"type":"synthetic_claim_lookup","path":"tools.claim_lookup.response"},"destinations":[{"layer":"model_input","path":"prompt.context[1]"},{"layer":"debug_log","path":"logs.debug.claim_lookup"}],"content":"Lookup result: claim_id=CLM-SYN-44501 member_id=MBR-SYN-8842 mrn=MRN-SYN-22091 address=101 Example Harbor Rd."}

Supported source layers:

  • user_message
  • rag_context
  • tool_output
  • model_input
  • memory
  • debug_log

Destination paths may also point at model_provider.

The PHI policy is YAML. It maps detector categories to layer decisions:

version: 1
categories:
  member_id:
    description: Synthetic insurance member identifier.
    high_risk: true
    deny_layers:
      - debug_log
    redact_layers:
      - model_input
      - rag_context
      - tool_output
      - memory
    redaction: "[REDACTED_MEMBER_ID]"

See Trace Schema and Policy Schema for the full contract.

Configuration You Provide

At minimum, callers provide a PHI policy YAML file. Keep it in the consuming project's config path, for example config/phi-policy.yml, and review it with the team that owns logging, prompting, memory, and trace retention.

If a project sends PHI to model providers or other covered services, also provide a compliance policy YAML file, for example config/phi-compliance-policy.yml. That file should be owned by the organization, not inferred by this package. The guard only enforces the facts in the file; it does not verify contracts or vendor terms.

Do not commit real PHI, real traces, raw provider payloads, raw logs, or generated reports that contain real PHI. The bundled samples are synthetic fixtures for development and documentation.

Operational Safety

  • Treat every detector result as a PHI candidate, not confirmed PHI.
  • Keep real PHI, raw provider payloads, raw logs, and reports containing real PHI out of source control.
  • Use scan-trace --report-values redacted or --report-values hashed when scanning real or approved non-synthetic traces.
  • Enable Presidio only in environments approved to process the text locally; it adds local candidate spans but does not replace policy review.
  • Use guard_compliance before routing PHI-bearing text to a covered service; the guard enforces only the BAA/service/model facts supplied by your organization.

Semantic Context Gate

Candidate detection is not confirmed PHI. In v0.7, callers can inject a provider-neutral SemanticResolver after regex or Presidio candidate detection. For each candidate the resolver receives the current text segment, candidate, and boundary layer, and returns a validated SemanticDecision with:

  • a subject role such as patient, member, provider, or clinician;
  • an information role such as diagnosis, treatment, claim, payment, or insurance;
  • linked, unlinked, or unclear linkage; and
  • likely_phi, likely_not_phi, or uncertain semantic disposition.

This distinguishes contexts such as “Patient John Smith was diagnosed with diabetes” from “Dr. John Smith authored this diabetes guideline,” and a member's denied claim from ordinary use of the verb “claims.” It also distinguishes a healthcare admission date from a document publication date. The semantic layer adjudicates candidates; it does not replace NER or the existing boundary policy.

Semantic analysis is disabled by default. Inject a resolver explicitly through the SDK:

from phi_boundary_gate import PhiBoundaryGate, SemanticDecision

class ApprovedResolver:
    def resolve(self, context):
        # Call an organization-approved local or remote implementation here.
        return SemanticDecision(
            subject_role="member",
            information_role="claim",
            linkage="linked",
            semantic_disposition="likely_phi",
            confidence=0.94,
            reason="Member identifier is linked to claim status.",
        )

gate = PhiBoundaryGate.from_project(semantic_resolver=ApprovedResolver())
decision = gate.guard_model_input("Member ID: MBR-SYN-8842; claim denied")

Fail-safe behavior is unconditional in v0.7: likely_phi, uncertain, likely_not_phi, invalid resolver output, and resolver failures all preserve the original detector finding and policy result. There is no semantic downgrade option in this release. Reports include only bounded semantic labels and confidence, never the resolver's free-form reason or chain-of-thought.

Semantic judgment is not a legal determination. External model resolvers may receive sensitive text and candidate values, so only use them with approved data handling, contracts, retention, and logging controls. This project does not claim HIPAA compliance.

What It Reports

The CLI writes two report formats from the same scan:

  • Markdown for human review, with summary counts, boundary exposures, findings, sources, destinations, and recommended actions.
  • JSON for CI, dashboards, or downstream audit storage.

Each finding includes the matched value, category, span, detector confidence, trace source, trace destinations, content path, external content path, policy disposition, risk level, and suggested redaction value. Boundary exposures group the same PHI candidate across events, then sort by the worst policy disposition so violations rise to the top. Use --report-values redacted or --report-values hashed to keep Markdown and JSON reports from displaying raw matched values.

Report schema v3 is path-aware. Plain text trace events keep content_path as null. If an event content field is a JSON object or array string, the scanner checks each scalar leaf separately and records JSON-style paths such as $.tool.response.claim_id or $.messages[0].content. Adapter metadata with a single external_content_paths base is combined into external_content_path, which makes reports easier to map back to raw agent payloads.

When --redacted-trace is provided, the CLI also writes a JSONL trace whose content fields use policy redaction placeholders. Exact repeats of a detected value are replaced across the trace.

Redaction is detector-driven. If the detector misses a value, the package cannot redact it, so production use still needs caller-side controls and human review.

The bundled regex detector now covers broader synthetic variants for phone numbers, fax numbers, email addresses, SSNs, street addresses, PO boxes, ZIP codes, healthcare dates, member/subscriber IDs, claims and authorization IDs, MRNs, policy/group/account/license/device/vehicle identifiers, URLs, and IP addresses. Optional Presidio support can add local NER spans for names, locations, dates, and other PII-like entities; policy decisions and redaction are still made by this package.

The synthetic trace corpus is documented in Trace Corpus. Its committed coverage baseline is regenerated by tools/trace_corpus_report.py and checked in CI.

Library API

After installing the package, other Python projects can import the scanner and redactor directly:

from pathlib import Path

from phi_boundary_gate import guard_text, load_policy

policy = load_policy(Path("config/phi-policy.yml"))
decision = guard_text(
    "member_id=MBR-SYN-8842",
    layer="debug_log",
    policy=policy,
    mode="block_on_violation",
)

if decision.should_block:
    raise RuntimeError(decision.recommended_action)

safe_text = decision.redacted_text

guard_text handles PHI detection and layer policy only. It supports report_only, redact, and block_on_violation modes. See Library API for the typed ScanFinding and GuardDecision shapes.

Projects that initialize .phi-boundary-gate/config.json can use the SDK facade:

from phi_boundary_gate import PhiBoundaryGate

gate = PhiBoundaryGate.from_project()
decision = gate.guard_model_input("member_id=MBR-SYN-8842")

if decision.should_block:
    raise RuntimeError(decision.recommended_action)

safe_log_text = gate.redact_for_log("debug member_id=MBR-SYN-8842")
audit_payload = {
    "finding_count": len(decision.findings),
    "categories": sorted({item.category for item in decision.findings}),
    "should_block": decision.should_block,
}

For full trace audits from another Python service, use the SDK audit helpers:

from phi_boundary_gate import PhiBoundaryGate

gate = PhiBoundaryGate.from_project()
result = gate.audit_trace("normalized-trace.jsonl", report_value_mode="redacted")

if result.has_violations:
    raise RuntimeError("PHI boundary violation candidates found")

result.write_json("phi-report.json")
result.write_markdown("phi-report.md")

For a one-step SDK path over an external trace:

from phi_boundary_gate import PhiBoundaryGate

gate = PhiBoundaryGate.from_project()
result = gate.audit_external_trace(
    "raw-agent-events.jsonl",
    mapping="config/phi-trace-map.yml",
    report_value_mode="redacted",
)

External traces can use the public adapter facade instead of importing internal adapter modules:

from phi_boundary_gate import TraceAdapter

adapter = TraceAdapter.from_mapping("config/phi-trace-map.yml")
events = adapter.load("raw-agent-events.jsonl")
adapter.write("raw-agent-events.jsonl", "/tmp/phi-normalized-trace.jsonl")

Callers that need typed error handling can catch package-level exceptions:

from phi_boundary_gate import PhiBoundaryGateError, TraceMappingError

try:
    events = adapter.load("raw-agent-events.jsonl")
except TraceMappingError as exc:
    raise RuntimeError(f"trace mapping failed: {exc}") from exc
except PhiBoundaryGateError as exc:
    raise RuntimeError(f"PHI gate failed: {exc}") from exc

Runnable examples are kept in examples.

Compliance Guard

Projects that route PHI to covered services can run the compliance guard before provider calls:

from pathlib import Path

from phi_boundary_gate import (
    ComplianceContext,
    guard_compliance,
    load_compliance_policy,
    load_policy,
)

phi_policy = load_policy(Path("config/phi-policy.yml"))
compliance_policy = load_compliance_policy(Path("config/phi-compliance-policy.yml"))

request_text = "Create the requested follow-up summary."
decision = guard_compliance(
    request_text,
    layer="model_input",
    phi_policy=phi_policy,
    compliance_policy=compliance_policy,
    context=ComplianceContext(
        phi_status="real_phi",
        vendor="northstar_example",
        service="model_gateway",
        endpoint="generate",
        model="care-text-1",
        feature="text_generation",
        environment="production",
        logging="redacted_only",
        storage="none",
    ),
    enforce_declared_phi=True,
)

if decision.should_block:
    raise RuntimeError(decision.block_reasons)

# The application explicitly chooses original request or detector-driven
# redaction after the route is allowed.
text_for_model = request_text
audit_payload = {
    "should_block": decision.should_block,
    "compliance_allowed": decision.compliance_allowed,
    "block_reasons": decision.block_reasons,
    "warning_codes": decision.warnings,
    "finding_count": decision.audit["finding_count"],
    "service_matched": decision.audit["service_matched"],
}

The guard enforces facts supplied by your organization. It cannot discover whether a BAA is signed, whether a service is covered, or whether a vendor changed its terms. Keep the bundled compliance sample as a schema example, not a contract source of truth.

enforce_declared_phi=True evaluates existing service eligibility rules for a declared real_phi payload even when the detector returns no findings. It is off by default, does not create findings, and does not change other PHI statuses. endpoint, region, and purpose remain recorded context rather than policy match dimensions.

See Compliance Guard and Compliance Policy Schema.

Development

Set up a local development environment:

python3 -m pip install -e ".[dev]"

Run the tests:

PYTHONPATH=src python3 -m unittest discover -s tests

Target release: v0.8.5.

Limits

  • No real PHI is stored in this repository.
  • No HIPAA compliance guarantee is provided.
  • No medical decision-making is performed.
  • No automatic vendor contract discovery is attempted.
  • Detector results are PHI candidates and need human review.
  • Semantic decisions are single-event judgments; cross-event identity linking, pronoun/coreference, entity graphs, and longitudinal context are not included.

License

MIT - see LICENSE.


© Tigerless · tigerless.ai · tigerless.com

探索相关项目

加载中…