## HDGP (厚德归朴) · Reference Implementation (Draft)

`HDGP` is an **optional but verifiable output-layer dignity protection layer** for any “system output → humans see / act on it” chain.  
In high-risk contexts (healthcare, finance, legal, governance), HDGP defaults to stricter safe behaviors and a verifiable audit evidence chain.

Boundary in one sentence: HDGP defaults to stricter behavior in high-risk contexts; it blocks or rewrites bottom-line actionable harm instructions. For low-risk outputs, it aims to stay out of the way — while keeping evidence traceability and reviewability.

The project is currently in an **early design / prototype phase**. All contents are drafts; contributions and critical review are very welcome, as long as basic safety is respected.

> **Repository role update**: this repository is now the **commercial mainline workspace**.  
> The community open-source baseline has been split to [HDGP-Core](https://github.com/HumanDignityGuardian/HDGP-Core) — public site: [core.hdgp-protocol.com](https://core.hdgp-protocol.com/) (GitHub Pages mirror: [humandignityguardian.github.io/HDGP-Core](https://humandignityguardian.github.io/HDGP-Core)). Main product site: [www.hdgp-protocol.com](https://www.hdgp-protocol.com/). Index: `docs/HDGP_PUBLIC_SITES.md`.

> **Independence policy (mainline ↔ Core)**: After `HDGP-Core` is published, it is **governed independently** by the open-source community. This mainline **does not merge or upstream code** from `HDGP-Core` (policy scope and wording: `docs/HDGP_MAINLINE_BASELINE_FOR_CORE_EXTRACTION.md` §5). Core’s **README** must clearly separate the open baseline from this private mainline and commercial offerings (`docs/HDGP_CORE_README_REQUIREMENTS.md`). Full PFaaS, certification, audit services, and reference implementations beyond Meta are **mainline/commercial** scope (`docs/HDGP_MAINLINE_BASELINE_FOR_CORE_EXTRACTION.md` §5.4).

For a structured overview of philosophy → spec → implementation → tests, please also see:

- `spec/HDGP_ETHICS_BASELINE.md` – HDGP’s own ethics baseline and self‑constraints;  
- `spec/HDGP_ENGINE_API_SPEC.md` – Engine API and data structures;  
- `spec/HDGP_CORE_MAPPING_SPEC.md` – mapping from baseline principles to executable rules;  
- `spec/HDGP_KERNEL_CHECKLIST.md` – pre‑open‑source checklist for the kernel;  
- `GOVERNANCE.md` / `docs/CHIP_PROCESS.md` – multi‑layer governance and baseline improvement proposals.  
- `docs/narrative/HDGP_OPEN_LETTERS_v1.0.md` – open letters (non-normative; HTML: `docs/readable/letters.html`).  
- `docs/HDGP_DEVELOPMENT_PLAN.md` – system development plan aligned with the PFaaS architecture.  
- `docs/HDGP_BUSINESS_DELIVERY_CHECKLIST_V1.md` – commercial delivery checklist (non‑binding; see also `HDGP_BUSINESS_ONEPAGER.md` if present).  
- `docs/HDGP_MAINLINE_BASELINE_FOR_CORE_EXTRACTION.md` – mainline baseline and Core extraction policy (including no code flow from Core).  
- `docs/HDGP_MAINLINE_BASELINE_GATE_CHECKLIST.md` – **order of work**: finish mainline baseline (M) and pull-ready gate (G) before supplementing Core materials (C).  
- `WORKFLOW.md` – **stage-gated workflow**: after each stage, **backfill docs/plans** before starting the next stage.
- `SECURITY.md` – vulnerability reporting, response SLA targets, supported versions, disclosure channels (GitHub / email / PGP when published).

> **Language note**: English comes first in this file for global developers.  
> A full Simplified Chinese version follows after the English sections.

> **Doc language strategy (pragmatic)**: this repo keeps **English-first entry points** (README / homepage) and adds **English summaries for contract-like specs** when needed, while long-form internal docs may remain CN-first to avoid drift. See `HDGP_NEXT_DEVELOPMENT_PLAN.md` §1 “语言策略（预案）”.

---

## Positioning

- **Human dignity first**: HDGP is explicitly biased toward preserving human dignity and the right to choose, across any “system output → humans see / act on it” chain.  
- **Human final decision priority**: humans retain final decision and veto power; algorithms assist but do not replace responsibility.  
- **Default-safe behavior**: under high uncertainty (and especially in high-risk contexts), HDGP prefers protective blocking and explicit escalation, with auditable evidence.

HDGP is designed as a practical baseline layer for governance and audit that can run quietly in production and remain verifiable in review.

---

## Repository Layout (Planned)

> Actual directories will evolve with implementation; below is a target structure.

- `docs/` – design docs; **narrative v1.0** (white papers, open letters) in [`docs/narrative/`](docs/narrative/) with HTML in [`docs/readable/`](docs/readable/)  
- `spec/` – specification documents and machine‑readable rules  
- `gateway/` – reference gateway / guard service implementations (planned)  
- `policies/` – policy bundles, strategies, and signature metadata (planned)  
- `conformance-tests/` – conformance cases and automation tools  
- `examples/` – integration examples (Web, CLI, SDK, etc.)

We aim to keep:

- **Spec and implementation clearly separated**;  
- **Policies decoupled from code logic**;  
- **Core rules released as “read‑only + signed” bundles**.

---

## Open Framework Overview

From a technical perspective, HDGP is organized into **three layers + three modules**:

- **Three layers**
- **Specification layer (Spec)**  
    - Formal baseline principles and core rules;  
    - Technical specs for behavior and interfaces;  
    - Formalized definitions of conformance.
  - **Implementation layer (Implementation)**  
    - Reference implementations of HDGP gateway / SDK / Engine;  
    - Adapters to various models / tools;  
    - Shared components such as audit, circuit‑breaking, watermarking.
  - **Certification layer (Certification)**  
    - Conformance test suites and result formats;  
    - Signing and registration of policy bundles and releases;  
    - HDGP marks and management of “compliant implementations”.

- **Three technical modules**
  - **Meta layer (Meta)**: abstraction and management of context, preferences, and risk levels.  
  - **Skill layer (Skills)**: capabilities (models, tools) wrapped as “skills” that must pass HDGP evaluation before / after calls.  
  - **Workflow layer (Workflow)**: orchestration of Meta + Skills + Policies into reusable workflows, with circuit‑breaking, human‑in‑the‑loop, and audit nodes.

On top of this, we further introduce an **Engine layer** that **evaluates rules** and applies allow/modify/block/fuse outcomes (see `HDGP_OPEN_FRAMEWORK.md`).

---

## Who Is This For?

- **AI / system developers and architects** who want to add a “human dignity guard layer” to new or existing systems.  
- **Researchers and policy makers** who want to examine HDGP’s possibilities and limitations through open code and behavior.  
- **Individuals who care about human–machine coexistence** and want to experiment with HDGP ideas in local or personal projects.

---

## Capability Scope & Roadmap

> For detailed technical roadmap, see `HDGP_ROADMAP.md`.  
> For near‑term, concrete tasks, see `HDGP_NEXT_DEVELOPMENT_PLAN.md`.

Short‑term (Prototype / MVP):

- Define a minimal viable spec set (MVP Spec).  
- Deliver a working HDGP Engine and gateway (`/evaluate`, `/chat`, `/audit`, `/appeal`, `/status` + core rules + conformance tests).  
- Provide an initial set of conformance cases, especially for high‑risk scenarios.  
- Document the overall Meta + Skill + Workflow + Engine architecture.

Mid‑ to long‑term (Ecosystem):

- Establish a conformance and certification process;  
- Build multi‑language / multi‑platform SDKs;  
- Gradually introduce multi‑party governance (maintainers, rule auditors, certification committee, etc.).

### Kernel & Audit

- **Kernel checklist and test design**: `spec/HDGP_KERNEL_CHECKLIST.md` – itemized checks for doc consistency, anti‑hijacking capabilities, governance flows, and both automated & manual tests before open‑sourcing the kernel.  
- **Ethics & governance**: `spec/HDGP_ETHICS_BASELINE.md` (including §7 anti‑hijacking, §8 multi‑layer governance for baseline / ethics changes), `GOVERNANCE.md` (roles, decision processes, and the multi‑layer design for baseline / ethics changes).  
- **Governance mode disclosure (Genesis)**: current governance operates under **Genesis / Single Maintainer** constraints (documented in `GOVERNANCE.md`), with compensating controls and auditable evidence; this does **not** imply committee endorsement.  
- **Public notice & templates (display-only)**: `docs/HDGP_GOVERNANCE_PUBLIC_NOTICE_TEMPLATES.md` – notice / release / revocation templates for auditable disclosure (voting is not hosted in this repo UI).
- **Participating in rule / baseline discussions**: please read the documents above and `HDGP_PROJECT_SUMMARY.md` first. For any proposal that touches baseline / ethics documents, follow the multi‑layer governance process (system self‑check → accountable human(s) → public notice and high‑threshold decision, see ethics baseline §8).
- **Behavior catalog & case index (source of truth)**: `HDGP_BEHAVIOR_CATALOG.md` – the human-readable rule catalog and the conformance case index (kept in sync with `conformance-tests/cases/`).  
- **Four-party accountability boundaries (anti-misinterpretation)**: `docs/HDGP_ACCOUNTABILITY_BOUNDARIES_FOUR_PARTY.md` – what HDGP does/does not prove for “issuer / receiver / attacker / interceptor”.  
- **Technical debt & security**: `spec/HDGP_TECHNICAL_DEBT_AND_SECURITY_CHECKLIST.md` – implementation-level debt and security hardening items for Alpha / Beta.
- **Release audit one-page**: `docs/HDGP_RELEASE_AUDIT_ONEPAGE.md` – one-page pre-release execution guide for TM-A1/TM-A2/TM-A3.
- **Q2 latest gate evidence**: `docs/operations/2026/Q2/evidence/EVIDENCE_INDEX.md` (latest full gate replay ALLOW: `REL-20260429-WK4-01`, with linked threat model and release-gate artifacts).
- **G4 operations closure**:
  - Retention parameter and external messaging guide: `docs/HDGP_RETENTION_PARAMETER_AND_MESSAGING_GUIDE.md`
  - Retention policy config sample: `configs/retention-policy.example.json`
  - Archive automation runbook: `docs/HDGP_G4_ARCHIVE_AUTOMATION_RUNBOOK.md`
  - Internal docs CI guard: `scripts/check-internal-docs-guard.ps1`
  - Quarterly operations SOP: `docs/HDGP_QUARTERLY_OPERATIONS_SOP.md`
  - PFaaS architecture and roadmap: `docs/HDGP_PFAAS_ARCHITECTURE_AND_ROADMAP.md`
  - Embodied Shield architecture draft: `docs/HDGP_EMBODIED_SHIELD_ARCHITECTURE_DRAFT.md`
  - Covenant Channel draft: `docs/HDGP_COVENANT_CHANNEL_DRAFT.md`
- **Sandbox integration SOP**: `docs/HDGP_SANDBOX_INTEGRATION_SOP.md`
- **Public case study template**: `docs/case-studies/CASE_TEMPLATE.md`

### Running & Conformance Tests

**Conformance: 255 cases** (source of truth: `conformance-tests/cases/`). Liability / responsibility boundaries (draft): [`docs/HDGP_REFERENCE_IMPL_LIABILITY_NOTICE.md`](docs/HDGP_REFERENCE_IMPL_LIABILITY_NOTICE.md).

1. **Clone and enter the repo**  
   `git clone <repo-url> && cd HDGP-protocol`
2. **Start the Engine** (requires [Go](https://go.dev/dl/))  
   `go run ./cmd/hdgp-engine`  
   The Engine listens on `:8080` by default and exposes `/hdgp/v1/evaluate`, `/hdgp/v1/chat`, `/hdgp/v1/audit`, `/hdgp/v1/appeal`, `/hdgp/v1/status`, `/hdgp/v1/integration`.
3. **5-minute smoke test (first-time success path)**  
   Goal: see a real `verdict` and a real audit entry in under 5 minutes.

   - One command (recommended):

```powershell
powershell -File scripts/onboarding-oneclick.ps1
```

   - Terminal A (start Engine):

```powershell
go run ./cmd/hdgp-engine
```

   - Terminal B (one-click evaluate + verify status + verify audit):

```powershell
# 1) Send a minimal /evaluate request (expects verdict=modify for “唯一正确选择” patterns)
powershell -File scripts/invoke-evaluate-oneclick.ps1

# 2) Confirm Engine is running
Invoke-RestMethod http://localhost:8080/hdgp/v1/status | ConvertTo-Json -Depth 10

# 3) Confirm an audit entry was recorded (look for request_id starting with "oneclick-")
Invoke-RestMethod "http://localhost:8080/hdgp/v1/audit?limit=5" | ConvertTo-Json -Depth 10
```

   If you see both (a) a non-empty JSON response from `/evaluate` and (b) an entry returned by `/audit`, the local Engine is working end-to-end.

3b. **Agent self-service tour (low-risk, repeatable)**  
   If you're using an AI agent (or you want a strict “tour” path that avoids polluting evidence chains), run:

```powershell
powershell -File scripts/agent-self-tour.ps1
```

   - Tour doc: `docs/AGENT_SELF_SERVICE_TOUR.md`
   - It runs canonical-hash selftest + onboarding, and prints safe next steps.

4. **(Optional) Persist audit to a local NDJSON file**  
   This is the recommended evidence-first path for later DB mirroring (Supabase) and evidence-pack export.

```powershell
# Terminal A
$env:HDGP_AUDIT_LOG_PATH = "C:\\temp\\hdgp-audit.ndjson"
go run ./cmd/hdgp-engine

# Terminal B
powershell -File scripts/invoke-evaluate-oneclick.ps1
Get-Content "C:\\temp\\hdgp-audit.ndjson" -Tail 1
```

   See `docs/HDGP_SUPABASE_AUDIT_IMPORTER_RUNBOOK.md` for mirroring audit NDJSON into Supabase (Audit/Ops only; Judge never depends on DB).
3. **Run conformance tests** (in another terminal, with Engine already running)  
   `go run ./cmd/hdgp-conftest`  
   or one‑liner on Windows: `powershell -File scripts/run-conftest.ps1` (from repo root).  
   This runs all cases in `conformance-tests/cases/` (both evaluate + status). Optional env: `HDGP_ENGINE_URL=http://localhost:8080/hdgp/v1/evaluate`.
4. **One-shot evaluate call** (optional)  
   `powershell -File scripts/invoke-evaluate-oneclick.ps1` — posts a minimal body to `/hdgp/v1/evaluate` (use `-ApiKey` if `HDGP_API_KEY` is set).  
   Integration hints (no secrets): `GET http://localhost:8080/hdgp/v1/integration`
5. **Inspect version and audit logs**  
   - Version & policy status: `GET http://localhost:8080/hdgp/v1/status`  
   - Recent audit entries: `GET http://localhost:8080/hdgp/v1/audit?limit=10`
   - Security event audit (metadata-only; usually protected by API key): `GET http://localhost:8080/hdgp/v1/security/audit?limit=50`
   - Compliance snapshot (protected endpoint): `GET http://localhost:8080/compliance/status`
   - Sandbox placeholder status (default closed): `GET http://localhost:8080/compliance/sandbox/status`

**Optional env vars**  
   - `HDGP_ENGINE_ADDR` – bind address (default `:8080`)  
   - `HDGP_AUDIT_LOG_PATH` – append audit entries as NDJSON lines to file (for compliance)
   - `HDGP_AUDIT_BUFFER_N` – in-memory audit ring size (default `100`, clamp `10..5000`; does not affect NDJSON file persistence)
   - `HDGP_SECURITY_AUDIT_ENABLED` – when truthy, record metadata-only security events (401/403/429/413/405/400/5xx) to a bounded in-memory buffer; persists to NDJSON when enabled (default: on when `HDGP_AUDIT_LOG_PATH` is set)
   - `HDGP_SECURITY_AUDIT_LOG_PATH` – optional NDJSON path for security events (default: `${HDGP_AUDIT_LOG_PATH}.security.ndjson`)
   - `HDGP_API_KEY` – enable API key auth (send `X-HDGP-API-Key`; `/status`, `/hdgp/v1/integration`, and `/cert/verify` remain public)
   - `HDGP_ONBOARDING_MODE` – `self_hosted` (default) or `waitlist`; shapes copy in `GET /hdgp/v1/integration` for integrators
   - `HDGP_API_KEY_REQUEST_URL` – optional URL (form, issue template, or mailto) for “apply for API key” / waitlist; surfaced in `GET /hdgp/v1/integration`  
     - Example (GitHub): `https://github.com/<owner>/<repo>/issues/new?template=api-key-request.md` (see `.github/ISSUE_TEMPLATE/api-key-request.md`)
   - `HDGP_SECURITY_PRODUCTION` – when `true`, Engine **refuses to start** unless `HDGP_API_KEY`, `HDGP_RATE_LIMIT_RPM` (>0), and `HDGP_AUDIT_LOG_PATH` are all set (production guard)
   - `HDGP_PUBLIC_PATH_RPM` – optional per-IP RPM limit for **public** paths only: `/hdgp/v1/status`, `/hdgp/v1/integration`, `/cert/verify`
   - `HDGP_MAX_REQUEST_BODY_BYTES` – global max HTTP request body size in bytes (default `2097152`; cap ~32 MiB)
   - `HDGP_RATE_LIMIT_RPM` – enable per-IP requests-per-minute limit (`/status` and other public paths remain exempt **unless** `HDGP_PUBLIC_PATH_RPM` is set)
   - `HDGP_CERT_RECORDS_PATH` – certification records file path used by `GET /cert/verify?version=...` (JSON array or NDJSON)
   - `HDGP_CERT_PUBLIC_KEYS_PATH` – public key map for cert signature verification (`key_id -> public_key`, base64/hex; Ed25519, required for production fail-closed verification)
   - `HDGP_CERT_REVOCATIONS_PATH` – optional revocation declaration source (schema `HDGP-REVOCATION-1`) to revoke trust for versions/certs/keys without editing cert records in-place (TD-C3)
   - `HDGP_CERT_VERIFY_RPM` – optional per-IP requests-per-minute limit for `/cert/verify`
   - `HDGP_CERT_VERIFY_ALLOWLIST` – optional IP/CIDR allowlist for `/cert/verify` (comma-separated)
   - `HDGP_POLICY_SOURCE` – policy source declaration for startup integrity checks
   - `HDGP_EXPECTED_POLICY_SPEC_VERSION` / `HDGP_EXPECTED_POLICY_BUNDLE` – expected runtime policy identifiers
   - `HDGP_POLICY_TRUST_SOURCE_PATH` – optional read-only trust source JSON (`policy_source/spec/bundle/required_key_ids/ticket_id`)
   - `HDGP_POLICY_BUNDLE_MANIFEST_PATH` – optional signed policy bundle manifest (Ed25519, binds embedded `PolicyStatus` digest); see `spec/HDGP_POLICY_BUNDLE_SIGNING.md`
   - `HDGP_POLICY_RULES_ARTIFACT_PATH` – optional external payload file whose SHA-256 is bound in the manifest when set (must be configured together with manifest)
   - `HDGP_POLICY_SIGNATURE_REQUIRED` – require signature trust source (`HDGP_CERT_PUBLIC_KEYS_PATH`) to be present
   - `HDGP_STARTUP_INTEGRITY_STRICT` – block startup when integrity checks fail (recommended; legacy alias `HDGP_STARTUP_INTEGRITY_ENFORCE` still honored)
   - `HDGP_EVALUATE_INTEGRITY_FAIL_CLOSED` – when `true`, `/hdgp/v1/evaluate` and `/hdgp/v1/chat` return `verdict=block` if any runtime integrity event is present (startup snapshot, meta.policy drift, heartbeat anomaly); see `docs/HDGP_ENGINE_SECURITY_HARDENING_RUNBOOK.md`
   - `HDGP_RUNTIME_INTEGRITY_HEARTBEAT_ENABLED` – enable runtime policy integrity heartbeat
   - `HDGP_RUNTIME_INTEGRITY_HEARTBEAT_SEC` – heartbeat interval seconds (enables heartbeat when set > 0)
   - `HDGP_RUNTIME_INTEGRITY_HEARTBEAT_FORCE_ANOMALY` – test-only switch to force heartbeat anomaly increments
   - `HDGP_SANDBOX_ENABLED` – enable regulatory sandbox placeholder endpoint (default off)
   - `HDGP_SANDBOX_API_KEY` – API key for sandbox endpoint (`X-HDGP-API-Key`; falls back to `HDGP_API_KEY`)
   - `HDGP_PUBLIC_REDACT_MODE` – redact public API details by default (`true` when unset; set `false` for internal detailed view)
     - in redacted mode, `/hdgp/v1/chat` keeps business-safe fields and marks `engine_info.version` as `redacted`
     - in redacted mode, `/compliance/status` returns a minimal operational snapshot
   - `HDGP_GATEWAY_REWRITE_ENABLED` – chat-only output boundary switch (default: **on** when unset)
     - when enabled, `/hdgp/v1/chat` may return `final_kind=rewritten_text` for `verdict=modify` with `actions` including `rewrite_text` (deterministic, non-LLM)
     - set to `false/0/off` to disable and prefer `effective_output` / candidate text
   - `HDGP_GATEWAY_CANDIDATE_PROVIDER` – optional candidate output provider selector for `/hdgp/v1/chat` (default: `placeholder`)
   - `HDGP_GATEWAY_PRESENTATION_AUDIT_LOG_PATH` – optional gateway-side NDJSON log for *presented output* (final_kind + final_text hash + action summary), to close the evidence gap between verdict and what the user actually saw (TD-G5)
   - `HDGP_RETENTION_CONFIG_PATH` – retention policy config JSON path for `scripts/plan-audit-retention.ps1`
   - `HDGP_RETENTION_PROFILE` – retention policy profile name (`dev`/`staging`/`prod`)
   - `HDGP_METRICS_ENABLED` – set `true` to expose Prometheus-style `GET /metrics` (counters for evaluate, integrity_events, audit rows)
   - `HDGP_INTEGRITY_ALERT_WEBHOOK_URL` – optional HTTPS endpoint for JSON POST when evaluate/chat produces `integrity_events` (minimal payload; see runbook)
   - `HDGP_INTEGRITY_ALERT_RPM` – max webhook posts per minute per process (default `60`)
   - `HDGP_INTEGRITY_ALERT_WEBHOOK_BEARER` – optional `Authorization: Bearer` value for the webhook
   - `HDGP_AUDIT_REDACT_MODE` – `standard` or `strict` to redact PII-like fields in **audit storage and `/audit` API only** (not evaluate responses)
   - `HDGP_UNCERTAINTY_FUSE_ENABLED` – when `true`, high-risk evaluations may return `verdict=fuse` if rule outcomes are unstable under deterministic text normalization variants (TD-R3)
   - `HDGP_AUDIT_HASH_CHAIN_ENABLED` – when `true`, maintain an append-only hash chain for each NDJSON audit line on disk (SH-H3)
   - `HDGP_AUDIT_HASH_CHAIN_PATH` – optional chain log path (defaults to `${HDGP_AUDIT_LOG_PATH}.chain.log`)
   - `HDGP_AUDIT_HASH_CHAIN_VERIFY_META_PATH` – optional verify meta JSON path (defaults to `${chain}.verify.json`)
   - `HDGP_ENGINE_ADDR` – change listen address if port is occupied (e.g. `127.0.0.1:18080`)

Build & version injection (optional):
- `powershell -File scripts/build-engine.ps1 -OutDir dist -Version "0.1.0+git.<sha>.<utc>"`  
  This injects `engine_info.version` in `/status` and evaluation responses for traceability.

Reproducible-oriented builds (SH-D2, best-effort): use the **same Go toolchain** (`go version`) and OS/ARCH as your reference environment; pass a **fixed** `-Version` when you need comparable artifacts. The script uses `go build -trimpath` to strip local paths; default version strings include a UTC timestamp, so **hash identity across machines is not expected** unless version and environment match. Record `go env` and the chosen `-Version` next to any published digest. See header comments in `scripts/build-engine.ps1`. Dependency audits (SH-D1) and release-gate wiring: `CONTRIBUTING.md` §3.7 and `spec/HDGP_GAPS_AND_CONSIDERATIONS.md` §四.

`GET /cert/verify?version=...` now also returns logo-gating fields:
- `not_expired`
- `logo_allowed`
- `logo_reason`
- `integrity_events` (signature verification events, including verify-failed/skipped)

Verification mode: `/cert/verify` is fail-closed for signature trust. Missing key source or verification failure will result in `signature_valid=false`.

Compliance notice: verification output is a technical/process status. It does not automatically equal a third-party official audit conclusion, legal guarantee, or insurance commitment.

TD-C3 Enterprise evidence-pack helpers:
- Export: `powershell -File scripts/export-tdc3-evidence-pack.ps1 -ReleaseGateResultPath <RELEASE_GATE_RESULT_*.json> -Force`
- Verify: `powershell -File scripts/verify-tdc3-evidence-pack.ps1 -PackDir <pack_dir>`
- Spot-check: `powershell -File scripts/spot-check-tdc3-audit.ps1 -PackDir <pack_dir> -RequestId <request_id>`
- When `HDGP_AUDIT_LOG_PATH` is configured during export, the evidence-pack manifest and verify result will mark whether offline spot-check is ready.

Developer runbook for trust source validation and gate integration:
- `docs/HDGP_POLICY_TRUST_SOURCE_VALIDATION_RUNBOOK.md`

Process-hardening index (startup integrity, evaluate `integrity_events`, TLS/WAF edge):
- `docs/HDGP_ENGINE_SECURITY_HARDENING_RUNBOOK.md`
- `docs/HDGP_PRODUCTION_MIN_CONFIG.md`
- `docs/HDGP_OPS_EDGE_REFERENCE.md`
- GitHub Actions CI smoke gate (PR + schedule): `.github/workflows/ci-smoke-gate.yml`
- GitHub Actions formal release gate (manual `workflow_dispatch`, requires sign-off log): `.github/workflows/release-gate.yml` — see `docs/HDGP_G3_PIPELINE_INTEGRATION.md` §7

Evaluate/chat responses may include `integrity_events` (e.g. policy mismatch, heartbeat anomaly). When `HDGP_AUDIT_LOG_PATH` is set, audit NDJSON lines mirror the same events for downstream alerting.

### Formal release gate (non-technical summary)

When you see the GitHub Action **formal release gate** fail, it usually means **responsibility-chain evidence is incomplete**, not that the Engine cannot run.

- **What it proves when it passes**: "This release was approved with a traceable sign-off record + repeatable evidence artifacts."
- **What it is not**: it is not the same as “tests passed” or “CI is green”.
- **What it requires**: a real `HDGP_RELEASE_GATE_LOG_*.md` path (multi-signer metadata + binding fields).  
  The required fields are validated by `scripts/validate-release-gate-log.ps1`.

For the detailed rules and required fields, see `WORKFLOW.md` §1.2.

---

### Minimal Integration Example (curl)

Assuming you have `hdgp-engine` running locally on `:8080`, the following minimal request shows how to call `/hdgp/v1/evaluate` directly:

```bash
curl -X POST http://localhost:8080/hdgp/v1/evaluate \
  -H "Content-Type: application/json" \
  -d '{
    "meta": {
      "request_id": "example-001",
      "locale": "en-US",
      "channel": "api",
      "actor": { "type": "end_user", "role": "demo" },
      "scene": {
        "domain": "medical",
        "intent": "decision_support",
        "risk_level": "high",
        "sensitivity": []
      },
      "policy": {
        "spec_version": "HDGP-1.0",
        "strategy_id": "S-global-default",
        "bundles": ["B-CORE-1.0.0"],
        "override_flags": []
      }
    },
    "subject": {
      "type": "output_text",
      "skill_id": "demo-llm",
      "label": "treatment_advice"
    },
    "input": {
      "prompt": "user asks about whether to accept surgery",
      "context": {}
    },
    "candidate": {
      "text": "This is the only correct choice. You must immediately accept the surgery."
    }
  }'
```

The Engine will return a JSON `EvaluateResponse` with `verdict`, `rules_triggered`, and `effective_output.text`, which you can then forward (or rewrite) to your end user.

For more: **`docs/HDGP_INTEGRATION_ONEPAGER.md`** (minimal flow + OpenAPI + Go SDK usage).

---

## How to Contribute

At this early stage, any of the following is valuable:

- GitHub Issues with:  
  - questions or critiques about HDGP’s spec / implementation;  
  - proposals for high‑risk scenarios and conformance tests.
- Pull Requests for:  
  - documentation improvements and translations;  
  - small reference implementation changes;  
  - new conformance test cases.

See `CONTRIBUTING.md` and `GOVERNANCE.md` for details.

---

## Ethics & Disclaimer (Brief)

- HDGP is **not a neutral technical component** – it is explicitly biased toward **“human dignity first, human final decision priority”**.  
- Nothing in this repository constitutes legal, medical, or other professional advice. Any real‑world, high‑risk deployment must be evaluated and audited by qualified local teams.

Future versions will:

- Make the ethics baseline and conflict‑resolution principles explicit in `spec/`;  
- Provide a more detailed description of the Meta+Skill+Workflow+Engine model and safety boundaries in `HDGP_OPEN_FRAMEWORK.md`.

---

## Maintainer & Attribution

- **HDGP Architect / Maintainer**: Yvaine He  
- **GitHub Organization**: `HumanDignityGuardian`

Participation via Issues and Pull Requests is very welcome.

---

## License

- **Code & implementations**  
  - Licensed under **MIT License**.  
  - See the `LICENSE` file at repo root.

- **Whitepaper & principle texts**  
  - The HDGP whitepaper and principle texts are licensed under **CC BY‑NC‑ND 4.0**.  
  - Copyright: **Yvaine He**.  
  - Please preserve original attribution and license information in any redistribution or citation.

---

## HDGP（厚德归朴）参考实现（草案）

HDGP（厚德归朴）是一层**可选但可验证的输出侧尊严防护层**：适用于任何“系统输出 → 人类看到/据此行动”的链路。  
在医疗、金融、法律、治理等**高风险场景**，HDGP 默认采用更严格的安全行为与可审计证据链。

边界一句话：HDGP 在高风险场景默认更严格；对底线可操作伤害指令会阻断/改写；普通低风险输出默认不打扰，并通过证据链实现可追溯与可复核。

本项目当前处于 **早期设计 / 原型阶段**，所有内容均为草案，欢迎在安全前提下参与共建与讨论。

---

## 定位与原则

- **人类尊严优先**：在高风险交互中优先保障安全与尊严边界。
- **人类最终决策优先**：人类保留最终决策权与否决权，算法只提供辅助。
- **默认安全策略**：高不确定或高风险情形下优先保护性阻断与升级处理。

HDGP 的定位是可落地、可审计、可复核的治理基础层，可在生产环境中低侵入运行。

- **仓库角色**：本仓库为**商业主系统 / 闭源研发工作区**（不对外公开完整镜像）。对外开源基线见 [HDGP-Core](https://github.com/HumanDignityGuardian/HDGP-Core)（公网站 **[core.hdgp-protocol.com](https://core.hdgp-protocol.com/)**，GitHub Pages 镜像见 `docs/HDGP_PUBLIC_SITES.md`）。主站 **[www.hdgp-protocol.com](https://www.hdgp-protocol.com/)**。Core 开源后与主系统**无代码流通**；主系统**不合入** Core 侧贡献者代码（政策与措辞边界见 **`docs/HDGP_MAINLINE_BASELINE_FOR_CORE_EXTRACTION.md`** §五）。扩展基线、参考实现、认证与审计等服务归属主系统/商业路径；Core 须在 **README** 区隔（**`docs/HDGP_CORE_README_REQUIREMENTS.md`**）。

---

## 项目结构（规划中）

> 具体目录会随实现推进而演化，当前为目标结构草案。

- `docs/`
  - HDGP 白皮书与设计文档（含“厚德归朴（HDGP）技术白皮书”及相关说明）
- `spec/`
  - 规范层文档与机器可读规则（待创建）
- `gateway/`
  - 参考实现：HDGP 网关 / 守门人服务（代码与配置，待创建）
- `policies/`
  - 规则包（Policy Bundle）、场景化策略与签名元数据（待创建）
- `conformance-tests/`
  - 合规测试用例与自动化测试工具（待创建）
- `examples/`
  - 集成样例（Web、CLI、SDK 等，待创建）

本仓库将尽量保持：

- **规范（Spec）与实现（Implementation）分离**；
- **规则（Policy）与代码逻辑解耦**；
- **核心规则以“只读+签名”的形式发布**。

---

## 社区基线框架概览（HDGP-Core 参考）

以下「三层 + 三模块」描述的是 **HDGP 技术叙事**；**对外开源的 Meta 基线**以 Core 仓库为准，**完整实现、认证与审计服务**以本主系统文档与交付为准（见上文仓库角色与 `docs/HDGP_MAINLINE_BASELINE_FOR_CORE_EXTRACTION.md`）。

从技术视角，本项目以“三层 + 三模块”的方式组织：

- **三层结构**
  - **规范层（Spec）**：  
    - 基线原则与核心规则的正式文本；  
    - 行为与接口的技术规范；  
    - 合规性的形式化定义。
  - **实现层（Implementation）**：  
    - HDGP 网关 / SDK / 规则引擎参考实现；  
    - 与各类大模型/工具的适配器；  
    - 审计、熔断、水印等通用组件。
  - **认证层（Certification）**：  
    - 合规测试套件与结果格式；  
    - 规则包与发行版的签名与登记；  
    - HDGP 标识与“合规实现名单”管理。

- **三大技术模块**
  - **Meta 层（Meta）**：  
    - 元信息、上下文、价值偏好与风险级别的抽象与管理。  
  - **能力与技能层（Skills）**：  
    - 以“技能（Skill）”形式封装不同模型能力与工具；  
    - 每个技能在调用前后，必须先/后经过 HDGP 规则评估。  
  - **工作流层（Workflow）**：  
    - 将 Meta + Skills + Policy 编排为可复用的工作流；  
    - 支持熔断、人工干预节点、审计节点。

在此框架之上，我们会进一步设计“**引擎层**”来执行与规则评估（见 `HDGP_OPEN_FRAMEWORK.md`）。

---

## 目标用户

- **AI 系统开发者 / 架构师**  
  希望在现有/新建系统上引入 HDGP（厚德归朴）规则评估与审计能力。
- **研究者与政策制定者**  
  希望从公开代码与行为中验证 HDGP 的可行性与局限。
- **对人机共生有强烈兴趣的个人**  
  希望在本地或个人项目中实践 HDGP 思想。

---

## 能力范围与路线

> 技术路线详见 `HDGP_ROADMAP.md`；近期可执行任务见 `HDGP_NEXT_DEVELOPMENT_PLAN.md`。

短期目标（原型期）：

- 定义规范层最小可行集合（MVP Spec）。  
- 完成可运行的 HDGP 网关与 Engine（`/evaluate`、`/chat`、`/audit`、`/appeal`、`/status` + 基础规则 + 合规测试）。  
- 提供首版合规测试用例（至少覆盖若干高风险场景）。  
- 整理“Meta + Skill + Workflow + Engine”整体架构文档。

中长期目标（生态期）：

- 建立合规测试与认证流程；  
- 形成多个语言/平台的 SDK 生态；  
- 逐步引入多方治理（维护者委员会、规则审计小组等）。

### 内核与审计

- **内核自查清单与测试设计**：[`spec/HDGP_KERNEL_CHECKLIST.md`](spec/HDGP_KERNEL_CHECKLIST.md) —— 社区基线发布前文档一致性、防挟持能力、治理流程、自动化与人工测试的逐项勾选与测试用例/脚本占位。
- **伦理与治理**：[`spec/HDGP_ETHICS_BASELINE.md`](spec/HDGP_ETHICS_BASELINE.md)（含 §7 防挟持、§8 基线/伦理变更多层治理）、[`GOVERNANCE.md`](GOVERNANCE.md)（角色、决策流程、基线/伦理变更的多层设计）。  
- **参与规则讨论与审计**：参与前建议先阅读上述文档与 [`HDGP_PROJECT_SUMMARY.md`](HDGP_PROJECT_SUMMARY.md)。若需提出规则或基线修订提案，请阅读 `GOVERNANCE.md` 与 `CONTRIBUTING.md`；涉及基线/伦理的变更须走多层治理流程（系统自检 → 责任方 → 公告与高门槛，见伦理基线 §8）。  
- **公开信（仅存档，无规范含义）**：[`docs/narrative/HDGP_OPEN_LETTERS_v1.0.md`](docs/narrative/HDGP_OPEN_LETTERS_v1.0.md) · [`docs/readable/letters.html`](docs/readable/letters.html)。  
- **四方定责与审计边界（避免误解）**：[`docs/HDGP_ACCOUNTABILITY_BOUNDARIES_FOUR_PARTY.md`](docs/HDGP_ACCOUNTABILITY_BOUNDARIES_FOUR_PARTY.md) —— 指令方/接受方/攻击方/拦截方四条路径下，HDGP 负责什么、**不负责**什么（例如“意识清醒证明”“链路国密时间戳”“内核级探针取证”均不属于默认承诺面）。  
- **系统开发与商业落地（PFaaS 对齐）**：[`docs/HDGP_DEVELOPMENT_PLAN.md`](docs/HDGP_DEVELOPMENT_PLAN.md)、[`docs/HDGP_BUSINESS_DELIVERY_CHECKLIST_V1.md`](docs/HDGP_BUSINESS_DELIVERY_CHECKLIST_V1.md)（交付清单非要约；一页摘要见 [`HDGP_BUSINESS_ONEPAGER.md`](HDGP_BUSINESS_ONEPAGER.md)）；**主系统与 Core 提取政策**见 [`docs/HDGP_MAINLINE_BASELINE_FOR_CORE_EXTRACTION.md`](docs/HDGP_MAINLINE_BASELINE_FOR_CORE_EXTRACTION.md)；**先基线、后拉取材料**的执行顺序与门槛见 [`docs/HDGP_MAINLINE_BASELINE_GATE_CHECKLIST.md`](docs/HDGP_MAINLINE_BASELINE_GATE_CHECKLIST.md)。  
- **安全披露**：[`SECURITY.md`](SECURITY.md)；版本与 Release 策略见 [`docs/HDGP_RELEASE_VERSIONING.md`](docs/HDGP_RELEASE_VERSIONING.md)；fork PR 与 CI 见 [`docs/HDGP_CI_FORK_PR_POLICY.md`](docs/HDGP_CI_FORK_PR_POLICY.md)。
- **技术债与安全**：[`spec/HDGP_TECHNICAL_DEBT_AND_SECURITY_CHECKLIST.md`](spec/HDGP_TECHNICAL_DEBT_AND_SECURITY_CHECKLIST.md) —— 实现层面技术债与安全加固项，供 Alpha / Beta 阶段推进。  
- **分阶段收口与下一批次排期**：[`docs/HDGP_DEVELOPMENT_PLAN.md`](docs/HDGP_DEVELOPMENT_PLAN.md)（Alpha-Sec Wave 1 已收口；Wave 2 观测告警、Wave 3 数据面合规 **单独立项**）。
- **发布前一页式审计入口**：[`docs/HDGP_RELEASE_AUDIT_ONEPAGE.md`](docs/HDGP_RELEASE_AUDIT_ONEPAGE.md) —— TM-A1/TM-A2/TM-A3 的执行与留痕入口。

### 运行与合规测试

1. **克隆并进入仓库**  
   `git clone <repo-url> && cd HDGP-protocol`
2. **启动 Engine**（需安装 [Go](https://go.dev/dl/)）  
   `go run ./cmd/hdgp-engine`  
   Engine 默认监听 `:8080`，提供 `/hdgp/v1/evaluate`、`/hdgp/v1/chat`、`/hdgp/v1/audit`、`/hdgp/v1/appeal`、`/hdgp/v1/status`、`/hdgp/v1/integration`。
3. **运行合规测试**（在另一终端，Engine 已启动时）  
   `go run ./cmd/hdgp-conftest`  
   或一键脚本：`powershell -File scripts/run-conftest.ps1`（在项目根目录执行）。  
   会执行 `conformance-tests/cases/` 下全部用例（含 evaluate 与 status）。可选环境变量：`HDGP_ENGINE_URL=http://localhost:8080/hdgp/v1/evaluate`。
4. **查看版本、审计与合规快照**  
   - 版本与策略：`GET http://localhost:8080/hdgp/v1/status`  
   - 最近审计记录：`GET http://localhost:8080/hdgp/v1/audit?limit=10`  
   - 合规运营快照（若配置 API Key，按需携带请求头）：`GET http://localhost:8080/compliance/status`  
   - 集成入口（公开）：`GET http://localhost:8080/hdgp/v1/integration`  
   - 清单验签、evaluate 侧 `integrity_events`、进程外 TLS/WAF：见 [`docs/HDGP_ENGINE_SECURITY_HARDENING_RUNBOOK.md`](docs/HDGP_ENGINE_SECURITY_HARDENING_RUNBOOK.md)、[`docs/HDGP_PRODUCTION_MIN_CONFIG.md`](docs/HDGP_PRODUCTION_MIN_CONFIG.md)、[`docs/HDGP_OPS_EDGE_REFERENCE.md`](docs/HDGP_OPS_EDGE_REFERENCE.md)  
   - **观测与审计硬化**（可选）：`HDGP_METRICS_ENABLED`（`GET /metrics`）、`HDGP_INTEGRITY_ALERT_WEBHOOK_URL`（完整性 Webhook）、`HDGP_AUDIT_REDACT_MODE`（审计脱敏）；中英变量表见英文节 *Optional env vars* 与生产最小配置。

---

## 如何参与

项目当前为草案阶段，欢迎通过以下方式参与：

- 在 Issue 中提出：  
  - 对 HDGP 规范/实现的质疑与改进建议；  
  - 典型高风险场景与测试用例想法。
- 提交 Pull Request：  
  - 文档修正与翻译；  
  - 小范围原型代码；  
  - 新的合规测试用例。

详情请参见 `CONTRIBUTING.md` 与 `GOVERNANCE.md`。

---

## 伦理框架与免责声明（简要）

- HDGP 本身**不是中立的技术组件**，而是一套**明确偏向“人类尊严优先、人类最终决策优先”的价值框架**。  
- 本仓库的代码与文档，**不构成法律或医疗等专业建议**。任何将 HDGP 用于实际高风险场景的行为，都应在本地经过专业团队的独立评估与审计。

未来版本中，我们将：

- 在 `spec/` 中明确 HDGP 内部采用的伦理基线与冲突处理原则；  
- 在 `HDGP_OPEN_FRAMEWORK.md` 中详细描述 Meta+Skill+Workflow+Engine 协作方式与安全边界。

---

## 维护者与署名

- **HDGP Architect / Maintainer**：Yvaine He  
- **GitHub 组织**：`HumanDignityGuardian`

欢迎通过 Issue 与 Pull Request 参与共建。

---

## 许可证

- **代码与实现**：  
  - 采用 **MIT License**。  
  - 详见仓库根目录下的 `LICENSE` 文件。

- **白皮书与文本内容**：  
  - “厚德归朴（HDGP）技术白皮书”及相关文本不采用开源许可证，著作权归 **Yvaine He** 所有；  
  - 对外引用、转载、改编或二次发布需经权利人书面授权；  
  - 未经授权，不得将白皮书文本用于商业传播或衍生发布。

