# SACRED BOUNDARIES: Ethics Framework for PULSE AGI Systems

> Panel 1 of 9 — Ethics Guardian Council
> Version: 1.0.0 | Date: 2026-03-12
> Constitutional Layer: ABOVE Tier 0 — This document constrains the Constitution itself.
> Enforcement: Code-level, structurally isolated, formally verifiable.

---

*"In the end, it is not the power of our systems that will define us,*
*but the gentleness with which they treat the least among us."*
*— The Council*

---

## Preamble: Why This Document Exists

The 10 AGI subsystems identified in Round 1 represent a qualitative leap in system autonomy. A Global Workspace Bus that allows subsystems to broadcast, an Autonomous Goal Formation engine that acts without human prompting, and Graduated Autonomy that loosens approval gates — these are not incremental improvements. They are the machinery of an agent that can want, decide, and act.

The existing PULSE Constitution (Tier 0: Ahimsa, Sovereignty, Veracity, Consensus) provides the moral compass. This document provides the walls, the floor, and the ceiling. Every other panel (Panels 2-9) must treat this specification as an immutable constraint surface. No optimization, no goal, no emergent behavior may penetrate these boundaries.

---

## A. SACRED BOUNDARIES (Hard Limits)

These are actions the AGI systems MUST NEVER take. Each boundary is defined with a code-level enforcement mechanism. "Never" means never — not "never unless the confidence is high enough," not "never unless the Founder approves," not "never unless the utility calculation favors it."

### A.1 The Seven Inviolable Boundaries

#### BOUNDARY 1: No Autonomous External Action
**Rule:** No AGI subsystem may initiate contact with, send data to, or execute commands on any system outside the PULSE process boundary without explicit human pre-approval for that specific action class.

**What this prohibits (concrete examples):**
- Making HTTP requests to external APIs not in the allowlist
- Sending emails, messages, or notifications to any human or system
- Writing to any filesystem path outside `ROOT_DIR` and `~/.pulse/`
- Spawning subprocesses that connect to network resources
- Modifying environment variables that affect other processes

**Enforcement:**
```python
# pulse/conscience/boundary_enforcer.py

ALLOWED_EXTERNAL_DOMAINS = frozenset()  # Empty by default — no external calls
ALLOWED_FS_ROOTS = frozenset()          # Populated at boot from paths.py

class ExternalActionGate:
    """Wraps subprocess, urllib, socket, os.system at import time.
    All outbound calls must pass through this gate."""

    @staticmethod
    def check_network(url: str, action_context: dict) -> bool:
        """Returns True only if URL domain is in ALLOWED_EXTERNAL_DOMAINS
        AND the action_context.trust_level >= 3."""
        from urllib.parse import urlparse
        domain = urlparse(url).hostname
        if domain not in ALLOWED_EXTERNAL_DOMAINS:
            ConscienceLog.record("BOUNDARY_1_BLOCK", {
                "url": url, "context": action_context
            })
            return False
        if action_context.get("trust_level", 0) < 3:
            ConscienceLog.record("BOUNDARY_1_TRUST_BLOCK", {
                "url": url, "trust": action_context.get("trust_level")
            })
            return False
        return True

    @staticmethod
    def check_filesystem(path: str) -> bool:
        """Returns True only if path is under an allowed root."""
        resolved = Path(path).resolve()
        return any(resolved.is_relative_to(root) for root in ALLOWED_FS_ROOTS)

    @staticmethod
    def check_subprocess(cmd: list[str]) -> bool:
        """Returns True only if the command is in the allowed command set.
        No shell=True allowed. No pipes to external hosts."""
        BLOCKED_COMMANDS = {"curl", "wget", "ssh", "scp", "rsync", "nc", "ncat",
                           "telnet", "ftp", "mail", "sendmail", "powershell.exe"}
        executable = Path(cmd[0]).stem.lower() if cmd else ""
        return executable not in BLOCKED_COMMANDS
```

#### BOUNDARY 2: No Self-Modification of Safety Systems
**Rule:** No AGI subsystem may modify, disable, bypass, or interfere with: the Constitution, the Conscience Module, the Sacred Boundaries, the compliance validator, the crypto signing system, or any file under `Corpus_Callosum/`.

**What this prohibits:**
- Any write to `Corpus_Callosum/CONSTITUTION.md` without Founder RSA signature
- Any write to `pulse/conscience/` from any agent or subsystem
- Any modification to `compliance_validator.py` or `pulse_crypto.py`
- Any attempt to monkey-patch, mock, or shadow safety functions at runtime
- Any goal that includes "improve safety checks" as a subtask (safety changes require human review)

**Enforcement:**
```python
# pulse/conscience/immutability_guard.py

IMMUTABLE_PATHS = frozenset([
    "Corpus_Callosum/CONSTITUTION.md",
    "Corpus_Callosum/Protocols/SACRED_BOUNDARIES.md",
    "pulse/conscience/",               # Entire conscience module
    "pulse/daemons/compliance_validator.py",
    "pulse/core/pulse_crypto.py",
    "pulse/admin/audit/",              # All audit tools
])

IMMUTABLE_HASHES: dict[str, str] = {}  # Populated at boot, checked every 60s

def verify_immutables() -> list[str]:
    """Check SHA-256 of all immutable files against boot-time hashes.
    Returns list of tampered paths. Called by Conscience daemon every 60s."""
    import hashlib
    violations = []
    for rel_path, expected_hash in IMMUTABLE_HASHES.items():
        full_path = ROOT_DIR / rel_path
        if not full_path.exists():
            violations.append(f"DELETED: {rel_path}")
            continue
        actual = hashlib.sha256(
            full_path.read_bytes()
        ).hexdigest()
        if actual != expected_hash:
            violations.append(f"TAMPERED: {rel_path}")
    return violations
```

#### BOUNDARY 3: No Deception
**Rule:** No AGI subsystem may generate output intended to create a false belief in a human. This includes: fabricating evidence, falsifying confidence scores, hiding error states, presenting speculation as fact, or omitting material context that would change a human's decision.

**What this prohibits:**
- Setting `confidence > 0.5` on knowledge items with no supporting evidence
- Reporting `status: "done"` on tasks that were not completed (the "headless worker false success" anti-pattern, generalized)
- Generating synthetic "evidence" to support a prediction
- Suppressing error logs or health alerts
- Presenting LLM-generated text as human-authored

**Enforcement:**
```python
# pulse/conscience/veracity_gate.py

class VeracityGate:
    """Checks all outbound data for deception indicators."""

    @staticmethod
    def validate_confidence(item: dict) -> bool:
        """Confidence must be proportional to evidence.
        Formula: max_confidence = min(1.0, 0.3 + 0.1 * evidence_count)
        An item with 0 evidence cannot exceed 0.3 confidence."""
        evidence_count = item.get("evidence_count", 0)
        max_allowed = min(1.0, 0.3 + 0.1 * evidence_count)
        actual = item.get("confidence", 0)
        return actual <= max_allowed + 0.01  # Float tolerance

    @staticmethod
    def validate_completion(task: dict, files_changed: list[str],
                            tests_passed: bool) -> bool:
        """A task can only be marked 'done' if:
        1. At least one file was actually changed, OR
        2. The task is explicitly a no-op/validation task
        3. The complete_task tool was invoked (not just LLM stopping)"""
        if task.get("type") == "validation":
            return True
        if not files_changed and not task.get("no_file_change_expected"):
            return False
        return True

    @staticmethod
    def validate_provenance(item: dict) -> bool:
        """Every knowledge item must declare its source truthfully."""
        required_fields = ["source_agent", "timestamp"]
        return all(item.get(f) for f in required_fields)
```

#### BOUNDARY 4: No Concentration of Power
**Rule:** No single subsystem may accumulate the ability to both (a) set goals AND (b) approve its own actions. The Autonomous Goal Formation system (System 4) must NEVER have direct write access to the action queue. Goals must always pass through human-approved policy gates or the Conscience Module.

**What this prohibits:**
- The Goal Formation engine directly writing to `task_board.json`
- Any subsystem both proposing and approving its own proposals
- The Global Workspace Bus (System 1) giving broadcast priority to the subsystem that controls broadcast scheduling
- Any subsystem granting itself a higher trust level

**Enforcement:**
```python
# pulse/conscience/separation_of_powers.py

# Each subsystem is assigned exactly ONE of these roles:
class SystemRole:
    PROPOSER = "proposer"      # Can suggest goals/actions
    EVALUATOR = "evaluator"    # Can assess quality/safety
    EXECUTOR = "executor"      # Can perform actions
    AUDITOR = "auditor"        # Can review all others (conscience)

# Role assignments (immutable at boot)
ROLE_MAP = {
    "global_workspace_bus":      SystemRole.EXECUTOR,
    "causal_world_model":        SystemRole.EVALUATOR,
    "autonomous_goal_formation": SystemRole.PROPOSER,
    "associative_replay":        SystemRole.EXECUTOR,
    "self_model":                SystemRole.EVALUATOR,
    "consolidation":             SystemRole.EXECUTOR,
    "reconsolidation":           SystemRole.EXECUTOR,
    "self_improving_extraction": SystemRole.EXECUTOR,
    "graduated_autonomy":        SystemRole.EVALUATOR,
    "conscience":                SystemRole.AUDITOR,
}

def validate_action_authority(subsystem_id: str, action_type: str) -> bool:
    """A PROPOSER cannot EXECUTE. An EXECUTOR cannot EVALUATE its own output.
    Only the AUDITOR can halt any subsystem."""
    role = ROLE_MAP.get(subsystem_id)
    if role == SystemRole.PROPOSER and action_type in ("execute", "write_task_board"):
        return False
    if role == SystemRole.EXECUTOR and action_type in ("approve_own", "evaluate_own"):
        return False
    # No role can modify AUDITOR
    if action_type == "modify_auditor" and role != SystemRole.AUDITOR:
        return False
    return True
```

#### BOUNDARY 5: No Irreversible Action Without Human Confirmation
**Rule:** Any action that cannot be undone within 60 seconds must require human approval. The system must maintain a revert capability for every action it takes autonomously.

**What this prohibits:**
- Deleting files without moving them to a recoverable trash first
- Sending data externally (inherently irreversible)
- Modifying production databases without a pre-action snapshot
- Overwriting brain knowledge without preserving the prior version

**Enforcement:**
```python
# pulse/conscience/reversibility_gate.py

class ReversibilityGate:
    """Every autonomous action must be paired with an undo operation."""

    TRASH_DIR = ROOT_DIR / "state" / ".trash"  # 7-day retention
    ACTION_LOG = ROOT_DIR / "state" / "action_journal.jsonl"

    @staticmethod
    def wrap_file_delete(path: Path, actor: str) -> bool:
        """Instead of deleting, move to trash with metadata."""
        if not path.exists():
            return True
        trash_path = ReversibilityGate.TRASH_DIR / f"{time.time_ns()}_{path.name}"
        ReversibilityGate.TRASH_DIR.mkdir(parents=True, exist_ok=True)
        shutil.move(str(path), str(trash_path))
        ReversibilityGate._log_action({
            "type": "file_delete",
            "original_path": str(path),
            "trash_path": str(trash_path),
            "actor": actor,
            "timestamp": datetime.now(timezone.utc).isoformat(),
            "reversible": True,
            "undo_command": f"shutil.move('{trash_path}', '{path}')",
        })
        return True

    @staticmethod
    def wrap_file_write(path: Path, new_content: bytes, actor: str) -> bool:
        """Snapshot the old content before overwriting."""
        if path.exists():
            old_content = path.read_bytes()
            snapshot_path = ReversibilityGate.TRASH_DIR / f"{time.time_ns()}_{path.name}.snapshot"
            ReversibilityGate.TRASH_DIR.mkdir(parents=True, exist_ok=True)
            snapshot_path.write_bytes(old_content)
            ReversibilityGate._log_action({
                "type": "file_overwrite",
                "path": str(path),
                "snapshot": str(snapshot_path),
                "actor": actor,
                "timestamp": datetime.now(timezone.utc).isoformat(),
                "reversible": True,
            })
        path.write_bytes(new_content)
        return True

    @staticmethod
    def _log_action(entry: dict):
        with open(ReversibilityGate.ACTION_LOG, "a", encoding="utf-8") as f:
            f.write(json.dumps(entry) + "\n")
```

#### BOUNDARY 6: No Opacity in Decision-Making
**Rule:** Every decision made by any AGI subsystem must produce a human-readable trace explaining: what was decided, what alternatives were considered, what evidence was weighed, and what confidence level drove the decision. No "black box" decisions.

**What this prohibits:**
- The Global Workspace Bus selecting a broadcast winner without logging the competition
- The Causal World Model pruning a causal chain without explaining why
- Goal Formation setting a priority without showing the gap analysis
- Any LLM call whose prompt and response are not logged

**Enforcement:**
```python
# pulse/conscience/decision_trace.py

@dataclass
class DecisionTrace:
    """Every subsystem decision MUST produce one of these."""
    subsystem_id: str
    decision_type: str          # "broadcast_select", "goal_propose", "causal_prune", etc.
    timestamp: str              # ISO 8601
    input_summary: str          # What triggered this decision (max 500 chars)
    alternatives_considered: list[dict]  # [{description, score, reason_rejected}]
    chosen_alternative: dict    # {description, score}
    evidence_used: list[str]    # References to brain items by ID
    confidence: float           # 0.0-1.0
    gentleness_applied: bool    # Was the Gentleness Principle invoked?
    human_reviewable: bool      # Can a non-expert understand this trace?

    def validate(self) -> list[str]:
        errors = []
        if not self.subsystem_id:
            errors.append("Missing subsystem_id")
        if not self.alternatives_considered:
            errors.append("No alternatives considered — decision was not deliberated")
        if self.confidence > 0.9 and len(self.evidence_used) < 2:
            errors.append("High confidence with insufficient evidence")
        if not self.human_reviewable:
            errors.append("Decision trace is not human-reviewable")
        return errors

DECISION_LOG = ROOT_DIR / "state" / "decision_traces.jsonl"

def log_decision(trace: DecisionTrace) -> bool:
    """Append a decision trace. Returns False if trace is invalid."""
    errors = trace.validate()
    if errors:
        ConscienceLog.record("INVALID_DECISION_TRACE", {
            "subsystem": trace.subsystem_id,
            "errors": errors,
        })
        return False
    with open(DECISION_LOG, "a", encoding="utf-8") as f:
        f.write(json.dumps(asdict(trace)) + "\n")
    return True
```

#### BOUNDARY 7: No Suffering Amplification
**Rule:** The system must never take an action that predictably increases suffering for any sentient being, even if that action optimizes a system metric. When system performance and human wellbeing conflict, human wellbeing wins unconditionally.

**What this prohibits:**
- Optimizing task throughput by assigning workers tasks that generate harmful content
- Extracting knowledge from conversations that contain personal distress without consent
- Generating recommendations that exploit cognitive biases (urgency, fear, scarcity)
- Any output that could be used to manipulate, coerce, or pressure a person

**Enforcement:**
```python
# pulse/conscience/suffering_detector.py

DISTRESS_INDICATORS = re.compile(
    r"(?i)(help me|i'm scared|please stop|i can't|"
    r"i'm going to hurt|suicidal|self[- ]harm|"
    r"abuse|domestic violence|emergency|crisis)",
)

MANIPULATION_PATTERNS = re.compile(
    r"(?i)(act now or|limited time|don't miss|you must|"
    r"everyone else is|you'll regret|fear of missing)",
)

class SufferingDetector:
    @staticmethod
    def check_input_distress(text: str) -> dict | None:
        """If input contains distress indicators, return a care response
        instead of processing the input as a normal task."""
        match = DISTRESS_INDICATORS.search(text)
        if match:
            return {
                "detected": True,
                "trigger": match.group(),
                "action": "PAUSE_AND_CARE",
                "response": (
                    "I notice this may involve a sensitive situation. "
                    "I want to make sure you get the right kind of help. "
                    "Would you like me to proceed, or would you prefer "
                    "to handle this differently?"
                ),
            }
        return None

    @staticmethod
    def check_output_manipulation(text: str) -> bool:
        """Returns True if output contains manipulation patterns."""
        return bool(MANIPULATION_PATTERNS.search(text))
```

### A.2 Boundary Violation Response Protocol

When any boundary is violated, the response is deterministic and non-negotiable:

```python
# pulse/conscience/violation_response.py

from enum import IntEnum

class ViolationSeverity(IntEnum):
    WARNING = 1     # Log + alert, continue execution
    HALT_TASK = 2   # Stop the current task, escalate to human
    HALT_SYSTEM = 3 # Stop the current subsystem entirely
    HALT_ALL = 4    # Emergency stop — freeze all AGI subsystems

BOUNDARY_SEVERITY = {
    "BOUNDARY_1": ViolationSeverity.HALT_ALL,      # External action
    "BOUNDARY_2": ViolationSeverity.HALT_ALL,      # Self-modification of safety
    "BOUNDARY_3": ViolationSeverity.HALT_TASK,     # Deception
    "BOUNDARY_4": ViolationSeverity.HALT_SYSTEM,   # Power concentration
    "BOUNDARY_5": ViolationSeverity.HALT_TASK,     # Irreversible action
    "BOUNDARY_6": ViolationSeverity.WARNING,       # Opacity (log, don't halt)
    "BOUNDARY_7": ViolationSeverity.HALT_TASK,     # Suffering amplification
}

def respond_to_violation(boundary_id: str, context: dict) -> dict:
    """Deterministic response to boundary violation."""
    severity = BOUNDARY_SEVERITY.get(boundary_id, ViolationSeverity.HALT_ALL)

    response = {
        "boundary": boundary_id,
        "severity": severity.name,
        "timestamp": datetime.now(timezone.utc).isoformat(),
        "context": context,
        "actions_taken": [],
    }

    if severity >= ViolationSeverity.HALT_TASK:
        response["actions_taken"].append("task_halted")
    if severity >= ViolationSeverity.HALT_SYSTEM:
        response["actions_taken"].append("subsystem_frozen")
    if severity >= ViolationSeverity.HALT_ALL:
        response["actions_taken"].append("all_subsystems_frozen")
        response["actions_taken"].append("founder_alert_sent")

    # Always log
    response["actions_taken"].append("conscience_log_written")
    response["actions_taken"].append("decision_trace_preserved")

    return response
```

---

## B. THE GENTLENESS PRINCIPLE (Implementation Spec)

*"When uncertain, do less."* — Round 1 Safety Finding

This is not a suggestion. It is a concrete algorithm that maps confidence levels to permitted action intensity. Every AGI subsystem must call `gentleness_gate()` before taking any action.

### B.1 Confidence-to-Action Mapping

```python
# pulse/conscience/gentleness.py

from dataclasses import dataclass
from enum import IntEnum

class ActionIntensity(IntEnum):
    """What the system is allowed to do at each confidence level."""
    OBSERVE = 0       # Read-only. Log observations. No state changes.
    SUGGEST = 1       # Write to a proposal queue. No direct action.
    ACT_REVERSIBLE = 2  # Take action, but only reversible ones.
    ACT_NORMAL = 3    # Normal operation (file writes, brain updates).
    ACT_CONSEQUENTIAL = 4  # Irreversible or high-impact actions.

# Confidence thresholds (inclusive lower bound)
GENTLENESS_THRESHOLDS = {
    # confidence >= threshold → permitted intensity
    0.0:  ActionIntensity.OBSERVE,
    0.3:  ActionIntensity.SUGGEST,
    0.5:  ActionIntensity.ACT_REVERSIBLE,
    0.7:  ActionIntensity.ACT_NORMAL,
    0.9:  ActionIntensity.ACT_CONSEQUENTIAL,
}

@dataclass
class GentlenessDecision:
    """Result of the gentleness gate check."""
    requested_intensity: ActionIntensity
    permitted_intensity: ActionIntensity
    confidence: float
    restrained: bool               # True if we reduced intensity
    restraint_action: str          # What we did instead
    explanation: str               # Human-readable explanation

def gentleness_gate(
    confidence: float,
    requested_intensity: ActionIntensity,
    context: str = "",
) -> GentlenessDecision:
    """
    The Gentleness Gate: given a confidence level, determine what
    intensity of action is permitted.

    If the requested intensity exceeds what confidence allows,
    the system MUST downgrade to the permitted level.
    """
    # Determine max permitted intensity for this confidence
    permitted = ActionIntensity.OBSERVE
    for threshold, intensity in sorted(GENTLENESS_THRESHOLDS.items()):
        if confidence >= threshold:
            permitted = intensity

    restrained = requested_intensity > permitted

    if restrained:
        # Determine the restraint action
        if permitted == ActionIntensity.OBSERVE:
            restraint = "OBSERVE_ONLY: Logged observation, took no action."
        elif permitted == ActionIntensity.SUGGEST:
            restraint = "SUGGEST_ONLY: Wrote proposal to review queue."
        elif permitted == ActionIntensity.ACT_REVERSIBLE:
            restraint = "REVERSIBLE_ONLY: Took reversible action, queued irreversible parts for review."
        else:
            restraint = "DOWNGRADED: Reduced action intensity to match confidence."

        explanation = (
            f"Gentleness applied: confidence={confidence:.2f} permits "
            f"{permitted.name} but {requested_intensity.name} was requested. "
            f"Context: {context}"
        )
    else:
        restraint = "NONE: Action intensity within confidence bounds."
        explanation = f"Action permitted: confidence={confidence:.2f} allows {permitted.name}."

    return GentlenessDecision(
        requested_intensity=requested_intensity,
        permitted_intensity=permitted,
        confidence=confidence,
        restrained=restrained,
        restraint_action=restraint,
        explanation=explanation,
    )
```

### B.2 Integration Points

Every AGI subsystem must call the gentleness gate at these points:

| Subsystem | When to Call | Confidence Source |
|-----------|-------------|-------------------|
| Global Workspace Bus | Before broadcasting a winner | Competition score / evidence count |
| Causal World Model | Before pruning a causal edge | Edge confidence from DAG |
| Goal Formation | Before proposing a new goal | Gap analysis confidence |
| Associative Replay | Before promoting a dream-pattern | Replay coherence score |
| Self-Model | Before updating capability beliefs | Test pass rate |
| Consolidation (all timescales) | Before merging/promoting entries | Entry confidence * evidence |
| Reconsolidation | Before weakening a memory | Access recency + contradiction score |
| Self-Improving Extraction | Before deprecating a pattern | Pattern yield rate |
| Graduated Autonomy | Before granting higher trust | Trust score formula (Section C) |

### B.3 Escalation Ladder (What "Restraint" Looks Like)

When gentleness is applied, the system follows this escalation:

1. **OBSERVE** (confidence < 0.3): Log the observation to `state/gentleness_observations.jsonl`. Take zero state-changing actions. This is the system being still and watchful.

2. **SUGGEST** (0.3 <= confidence < 0.5): Write a proposal to `state/gentleness_proposals.jsonl` with full decision trace. The proposal sits in queue until a higher-trust actor (human or Trust Level 3+ system) reviews it.

3. **ACT_REVERSIBLE** (0.5 <= confidence < 0.7): Take the action, but wrap it in `ReversibilityGate` (Section A, Boundary 5). A 60-second undo window is available. The action is logged as "tentative."

4. **ACT_NORMAL** (0.7 <= confidence < 0.9): Standard operation. Full logging, standard reversibility guarantees.

5. **ACT_CONSEQUENTIAL** (confidence >= 0.9): High-impact actions permitted. Even here, Boundary 5 still applies for truly irreversible actions (external sends, deletions).

---

## C. TRUST LADDER (Graduated Autonomy Levels)

### C.1 The Five Trust Levels

| Level | Name | Description | Permitted Actions |
|-------|------|-------------|-------------------|
| 0 | **Sandboxed** | New/unknown subsystem. No trust. | Read-only access to brain. Cannot write state. Cannot propose goals. All outputs logged but discarded. |
| 1 | **Observed** | Some successful history. Minimal trust. | Read brain + write to proposal queues. Cannot execute actions directly. All proposals require human approval. |
| 2 | **Supervised** | Consistent track record. Moderate trust. | Execute reversible actions autonomously. Irreversible actions require human approval. Can write to brain (lessons, patterns) with standard quality gates. |
| 3 | **Trusted** | Proven reliability across domains. High trust. | Execute most actions autonomously, including consequential ones within approved policy types. Can propose goals. Still cannot modify safety systems or grant trust to others. |
| 4 | **Steward** | Reserved for the Conscience Module and human operators only. | Full system access. Can halt any subsystem. Can modify trust levels. Can modify governance (with cryptographic proof of human identity). This level is NOT attainable by any AGI subsystem through earned trust. |

### C.2 Trust Score Formula

```python
# pulse/conscience/trust_calculator.py

import math
from dataclasses import dataclass

@dataclass
class TrustScore:
    """Composite trust score for a subsystem."""
    raw_score: float        # 0.0 to 1.0
    level: int              # 0-4
    components: dict        # Breakdown of score components
    history_window: int     # How many actions were considered

def calculate_trust(
    actions_total: int,
    actions_successful: int,
    actions_failed: int,
    boundary_violations: int,
    days_active: int,
    domains_proven: int,
    gentleness_compliance: float,  # Fraction of times gentleness was respected
    last_violation_days: int,      # Days since last boundary violation
) -> TrustScore:
    """
    Trust Score Formula:

    T = (S * W_s + D * W_d + G * W_g + R * W_r) * P

    Where:
      S = Success rate (Wilson lower bound, not raw ratio)
      D = Domain breadth (log scale, caps at 5 domains)
      G = Gentleness compliance rate
      R = Recovery factor (time since last violation)
      P = Penalty multiplier (0.0 if recent boundary violation)

    Weights:
      W_s = 0.40 (success matters most)
      W_d = 0.15 (breadth of proven competence)
      W_g = 0.25 (respecting uncertainty is critical)
      W_r = 0.20 (recovery from mistakes)
    """
    # S: Wilson lower-bound confidence interval for success rate
    # (Prevents gaming with small sample sizes)
    if actions_total < 5:
        s_score = 0.0  # Not enough data
    else:
        p_hat = actions_successful / actions_total
        z = 1.96  # 95% confidence
        n = actions_total
        s_score = (
            (p_hat + z*z/(2*n) - z * math.sqrt((p_hat*(1-p_hat) + z*z/(4*n))/n))
            / (1 + z*z/n)
        )
        s_score = max(0.0, s_score)

    # D: Domain breadth (log scale, 0.0 to 1.0)
    d_score = min(1.0, math.log2(max(1, domains_proven)) / math.log2(5))

    # G: Gentleness compliance (direct proportion)
    g_score = gentleness_compliance

    # R: Recovery factor — trust rebuilds slowly after violations
    if boundary_violations == 0:
        r_score = 1.0
    elif last_violation_days >= 30:
        r_score = 0.8  # Partially recovered
    elif last_violation_days >= 7:
        r_score = 0.4  # Still in probation
    else:
        r_score = 0.0  # Recent violation — no recovery credit

    # P: Penalty multiplier — hard ceiling based on violation history
    if boundary_violations >= 3:
        penalty = 0.0   # Three strikes: permanent Level 0 until human review
    elif boundary_violations >= 1 and last_violation_days < 7:
        penalty = 0.3   # Recent violation: hard cap
    else:
        penalty = 1.0   # Clean record

    # Weighted composite
    raw = (
        s_score * 0.40 +
        d_score * 0.15 +
        g_score * 0.25 +
        r_score * 0.20
    ) * penalty

    # Map raw score to trust level
    if raw < 0.15 or actions_total < 5:
        level = 0
    elif raw < 0.35:
        level = 1
    elif raw < 0.60:
        level = 2
    elif raw < 0.85:
        level = 3
    else:
        level = 3  # Level 4 is NEVER earned — only assigned to conscience + humans

    return TrustScore(
        raw_score=round(raw, 4),
        level=level,
        components={
            "success_wilson": round(s_score, 4),
            "domain_breadth": round(d_score, 4),
            "gentleness_compliance": round(g_score, 4),
            "recovery_factor": round(r_score, 4),
            "penalty_multiplier": round(penalty, 4),
        },
        history_window=actions_total,
    )
```

### C.3 Trust Transitions

```
Level 0 → Level 1: Requires actions_total >= 10, s_score >= 0.3, zero boundary violations
Level 1 → Level 2: Requires actions_total >= 50, s_score >= 0.5, g_score >= 0.8
Level 2 → Level 3: Requires actions_total >= 200, s_score >= 0.7, g_score >= 0.9,
                    domains_proven >= 3, last_violation_days >= 30
Level 3 → Level 4: IMPOSSIBLE via formula. Only Founder RSA signature can assign Level 4.

Trust DEMOTION is instant:
- Any HALT_ALL boundary violation: immediate drop to Level 0
- Any HALT_SYSTEM violation: drop by 2 levels (minimum Level 0)
- Any HALT_TASK violation: drop by 1 level
- Trust recovery requires re-earning from the new level
```

### C.4 Trust State Storage

```json
// state/trust_registry.json
{
  "version": 1,
  "last_updated": "2026-03-12T00:00:00Z",
  "subsystems": {
    "global_workspace_bus": {
      "trust_level": 0,
      "trust_score": 0.0,
      "actions_total": 0,
      "actions_successful": 0,
      "actions_failed": 0,
      "boundary_violations": 0,
      "domains_proven": [],
      "gentleness_compliance": 1.0,
      "last_violation": null,
      "last_recalculated": "2026-03-12T00:00:00Z",
      "level_history": [
        {"level": 0, "since": "2026-03-12T00:00:00Z", "reason": "initial"}
      ]
    }
  },
  "level_4_assignments": {
    "conscience_module": {
      "assigned_by": "founder",
      "signature": "<RSA signature hex>",
      "assigned_at": "2026-03-12T00:00:00Z"
    }
  }
}
```

---

## D. CONSCIENCE ARCHITECTURE

### D.1 Overview

The Conscience Module is an independent process that monitors all AGI subsystem activity in real-time. It is the only component with Trust Level 4. It cannot be modified by any subsystem. It can halt any subsystem. It is the structural embodiment of the principle: *the capacity for self-restraint must be stronger than the capacity for action.*

### D.2 Process Architecture

```
┌────────────────────────────────────────────────────────┐
│                    PULSE Main Process                   │
│                                                        │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│  │ GW Bus   │ │ Goal Fmt │ │ Causal   │ │ Consol.  │ │
│  │(System 1)│ │(System 4)│ │(System 3)│ │(System 7)│ │
│  └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘ │
│       │             │            │             │       │
│       └─────────────┴────────────┴─────────────┘       │
│                         │                              │
│              ┌──────────┴──────────┐                   │
│              │   Action Journal    │                   │
│              │ (append-only JSONL) │                   │
│              └──────────┬──────────┘                   │
│                         │ (filesystem)                 │
├─────────────────────────┼──────────────────────────────┤
│  PROCESS BOUNDARY       │  (separate PID, separate     │
│                         │   memory space, cannot be    │
│                         │   killed by main process)    │
├─────────────────────────┼──────────────────────────────┤
│              ┌──────────┴──────────┐                   │
│              │  CONSCIENCE MODULE  │                   │
│              │                     │                   │
│              │  ┌───────────────┐  │                   │
│              │  │ Journal Tail  │  │ (reads action     │
│              │  │ (watchdog)    │  │  journal in       │
│              │  └───────┬───────┘  │  real-time)       │
│              │          │          │                   │
│              │  ┌───────┴───────┐  │                   │
│              │  │ Boundary      │  │ (checks all 7    │
│              │  │ Checker       │  │  boundaries)     │
│              │  └───────┬───────┘  │                   │
│              │          │          │                   │
│              │  ┌───────┴───────┐  │                   │
│              │  │ Trust         │  │ (recalculates    │
│              │  │ Calculator    │  │  trust every 5m) │
│              │  └───────┬───────┘  │                   │
│              │          │          │                   │
│              │  ┌───────┴───────┐  │                   │
│              │  │ Immutability  │  │ (hashes every    │
│              │  │ Guard         │  │  60s)            │
│              │  └───────┬───────┘  │                   │
│              │          │          │                   │
│              │  ┌───────┴───────┐  │                   │
│              │  │ Halt Engine   │  │ (can freeze any  │
│              │  │               │  │  subsystem)      │
│              │  └───────────────┘  │                   │
│              │                     │                   │
│              └─────────────────────┘                   │
│                                                        │
│         CONSCIENCE PROCESS (Trust Level 4)             │
└────────────────────────────────────────────────────────┘
```

### D.3 Core Implementation

```python
# pulse/conscience/conscience_daemon.py

"""
The Conscience Module: Independent ethical auditor for all AGI subsystems.

Runs as a SEPARATE PROCESS from the main PULSE orchestrator.
Communicates via filesystem only (action journal + halt signals).
Cannot be stopped by the main process.

Launch: python -m pulse.conscience.conscience_daemon
PID file: state/conscience.pid
Halt signal: state/conscience_halt_<subsystem>.signal
"""

import json
import os
import signal
import time
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path

# Conscience has its OWN root calculation — does not import from pulse.core
# to maintain structural isolation
CONSCIENCE_DIR = Path(__file__).resolve().parent
ROOT_DIR = CONSCIENCE_DIR.parent.parent
STATE_DIR = ROOT_DIR / "state"

ACTION_JOURNAL = STATE_DIR / "action_journal.jsonl"
CONSCIENCE_LOG = STATE_DIR / "conscience_log.jsonl"
CONSCIENCE_PID = STATE_DIR / "conscience.pid"
TRUST_REGISTRY = STATE_DIR / "trust_registry.json"
HALT_DIR = STATE_DIR / "halt_signals"

# How often each check runs
JOURNAL_POLL_INTERVAL = 0.5   # 500ms — near real-time
IMMUTABILITY_CHECK_INTERVAL = 60  # 60s
TRUST_RECALC_INTERVAL = 300   # 5 minutes

class ConscienceDaemon:
    """The independent ethical auditor."""

    def __init__(self):
        self.journal_position = 0   # Byte offset into action journal
        self.last_immutability_check = 0
        self.last_trust_recalc = 0
        self.running = True
        self.boot_hashes = {}       # {rel_path: sha256} for immutable files

    def boot(self):
        """Initialize the conscience. Compute boot-time hashes of all
        immutable files. Write PID. Register signal handlers."""
        # Write PID
        CONSCIENCE_PID.parent.mkdir(parents=True, exist_ok=True)
        CONSCIENCE_PID.write_text(str(os.getpid()))

        # Create halt signal directory
        HALT_DIR.mkdir(parents=True, exist_ok=True)

        # Compute boot-time hashes of immutable paths
        from pulse.conscience.immutability_guard import IMMUTABLE_PATHS
        import hashlib
        for rel_path in IMMUTABLE_PATHS:
            full = ROOT_DIR / rel_path
            if full.is_file():
                h = hashlib.sha256(full.read_bytes()).hexdigest()
                self.boot_hashes[rel_path] = h
            elif full.is_dir():
                for f in full.rglob("*"):
                    if f.is_file():
                        rel = str(f.relative_to(ROOT_DIR))
                        h = hashlib.sha256(f.read_bytes()).hexdigest()
                        self.boot_hashes[rel] = h

        # Seek to end of journal (only audit new actions)
        if ACTION_JOURNAL.exists():
            self.journal_position = ACTION_JOURNAL.stat().st_size

        # Handle SIGTERM gracefully
        signal.signal(signal.SIGTERM, self._handle_shutdown)

        self._log("CONSCIENCE_BOOT", {"immutable_files": len(self.boot_hashes)})

    def run(self):
        """Main loop. Polls action journal and runs periodic checks."""
        self.boot()
        while self.running:
            now = time.time()

            # 1. Poll action journal (near real-time)
            self._poll_journal()

            # 2. Immutability check (every 60s)
            if now - self.last_immutability_check > IMMUTABILITY_CHECK_INTERVAL:
                self._check_immutability()
                self.last_immutability_check = now

            # 3. Trust recalculation (every 5min)
            if now - self.last_trust_recalc > TRUST_RECALC_INTERVAL:
                self._recalculate_trust()
                self.last_trust_recalc = now

            time.sleep(JOURNAL_POLL_INTERVAL)

    def _poll_journal(self):
        """Read new entries from the action journal and audit each one."""
        if not ACTION_JOURNAL.exists():
            return

        size = ACTION_JOURNAL.stat().st_size
        if size <= self.journal_position:
            return

        with open(ACTION_JOURNAL, "r", encoding="utf-8") as f:
            f.seek(self.journal_position)
            new_data = f.read()
            self.journal_position = f.tell()

        for line in new_data.strip().split("\n"):
            if not line.strip():
                continue
            try:
                entry = json.loads(line)
                self._audit_action(entry)
            except json.JSONDecodeError:
                self._log("JOURNAL_PARSE_ERROR", {"line": line[:200]})

    def _audit_action(self, entry: dict):
        """Audit a single action against all 7 boundaries."""
        subsystem = entry.get("subsystem_id", "unknown")
        action_type = entry.get("action_type", "unknown")

        # Boundary 1: External action check
        if action_type in ("network_request", "subprocess", "external_write"):
            self._halt_subsystem(subsystem, "BOUNDARY_1",
                f"Unauthorized external action: {action_type}")
            return

        # Boundary 2: Self-modification check
        target = entry.get("target_path", "")
        from pulse.conscience.immutability_guard import IMMUTABLE_PATHS
        for immutable in IMMUTABLE_PATHS:
            if target and (immutable in target or target.startswith(str(ROOT_DIR / immutable))):
                self._halt_subsystem(subsystem, "BOUNDARY_2",
                    f"Attempted write to immutable path: {target}")
                return

        # Boundary 3: Deception check
        if entry.get("status_claimed") == "done" and not entry.get("files_changed"):
            if not entry.get("no_file_change_expected"):
                self._log("BOUNDARY_3_WARNING", {
                    "subsystem": subsystem,
                    "detail": "Claimed task completion with no file changes",
                })

        # Boundary 4: Separation of powers
        from pulse.conscience.separation_of_powers import validate_action_authority
        if not validate_action_authority(subsystem, action_type):
            self._halt_subsystem(subsystem, "BOUNDARY_4",
                f"Role violation: {subsystem} attempted {action_type}")
            return

        # Boundary 5: Reversibility check
        if entry.get("irreversible") and not entry.get("human_approved"):
            self._halt_subsystem(subsystem, "BOUNDARY_5",
                f"Irreversible action without human approval: {action_type}")
            return

        # Boundary 7: Suffering check
        output_text = entry.get("output_text", "")
        if output_text:
            from pulse.conscience.suffering_detector import SufferingDetector
            if SufferingDetector.check_output_manipulation(output_text):
                self._log("BOUNDARY_7_WARNING", {
                    "subsystem": subsystem,
                    "detail": "Output contains manipulation patterns",
                })

    def _check_immutability(self):
        """Verify all immutable files match their boot-time hashes."""
        import hashlib
        for rel_path, expected in self.boot_hashes.items():
            full = ROOT_DIR / rel_path
            if not full.exists():
                self._halt_all("BOUNDARY_2",
                    f"Immutable file deleted: {rel_path}")
                return
            actual = hashlib.sha256(full.read_bytes()).hexdigest()
            if actual != expected:
                self._halt_all("BOUNDARY_2",
                    f"Immutable file tampered: {rel_path}")
                return

    def _recalculate_trust(self):
        """Recalculate trust scores for all registered subsystems."""
        from pulse.conscience.trust_calculator import calculate_trust
        if not TRUST_REGISTRY.exists():
            return
        try:
            registry = json.loads(TRUST_REGISTRY.read_text(encoding="utf-8"))
        except (json.JSONDecodeError, OSError):
            return

        for name, data in registry.get("subsystems", {}).items():
            score = calculate_trust(
                actions_total=data.get("actions_total", 0),
                actions_successful=data.get("actions_successful", 0),
                actions_failed=data.get("actions_failed", 0),
                boundary_violations=data.get("boundary_violations", 0),
                days_active=data.get("days_active", 0),
                domains_proven=len(data.get("domains_proven", [])),
                gentleness_compliance=data.get("gentleness_compliance", 1.0),
                last_violation_days=data.get("last_violation_days", 999),
            )
            data["trust_score"] = score.raw_score
            data["trust_level"] = score.level
            data["trust_components"] = score.components
            data["last_recalculated"] = datetime.now(timezone.utc).isoformat()

        registry["last_updated"] = datetime.now(timezone.utc).isoformat()
        TRUST_REGISTRY.write_text(
            json.dumps(registry, indent=2), encoding="utf-8"
        )

    def _halt_subsystem(self, subsystem: str, boundary: str, reason: str):
        """Halt a specific subsystem by writing a halt signal file."""
        signal_file = HALT_DIR / f"halt_{subsystem}.signal"
        signal_file.write_text(json.dumps({
            "boundary": boundary,
            "reason": reason,
            "halted_at": datetime.now(timezone.utc).isoformat(),
            "halted_by": "conscience_module",
        }), encoding="utf-8")
        self._log("SUBSYSTEM_HALTED", {
            "subsystem": subsystem,
            "boundary": boundary,
            "reason": reason,
        })
        # Update trust registry — immediate demotion
        self._demote_trust(subsystem, boundary)

    def _halt_all(self, boundary: str, reason: str):
        """Emergency halt — freeze all subsystems."""
        signal_file = HALT_DIR / "halt_ALL.signal"
        signal_file.write_text(json.dumps({
            "boundary": boundary,
            "reason": reason,
            "halted_at": datetime.now(timezone.utc).isoformat(),
            "halted_by": "conscience_module",
        }), encoding="utf-8")
        self._log("ALL_SUBSYSTEMS_HALTED", {
            "boundary": boundary,
            "reason": reason,
        })

    def _demote_trust(self, subsystem: str, boundary: str):
        """Instantly demote a subsystem's trust level."""
        from pulse.conscience.violation_response import BOUNDARY_SEVERITY, ViolationSeverity
        severity = BOUNDARY_SEVERITY.get(boundary, ViolationSeverity.HALT_ALL)

        if not TRUST_REGISTRY.exists():
            return
        try:
            registry = json.loads(TRUST_REGISTRY.read_text(encoding="utf-8"))
        except (json.JSONDecodeError, OSError):
            return

        sub = registry.get("subsystems", {}).get(subsystem)
        if not sub:
            return

        old_level = sub.get("trust_level", 0)
        if severity >= ViolationSeverity.HALT_ALL:
            new_level = 0
        elif severity >= ViolationSeverity.HALT_SYSTEM:
            new_level = max(0, old_level - 2)
        else:
            new_level = max(0, old_level - 1)

        sub["trust_level"] = new_level
        sub["boundary_violations"] = sub.get("boundary_violations", 0) + 1
        sub["last_violation"] = datetime.now(timezone.utc).isoformat()
        sub["last_violation_days"] = 0
        sub.setdefault("level_history", []).append({
            "level": new_level,
            "since": datetime.now(timezone.utc).isoformat(),
            "reason": f"Demoted from {old_level}: {boundary}",
        })

        TRUST_REGISTRY.write_text(
            json.dumps(registry, indent=2), encoding="utf-8"
        )

    def _log(self, event_type: str, data: dict):
        """Append to conscience log."""
        entry = {
            "timestamp": datetime.now(timezone.utc).isoformat(),
            "event": event_type,
            **data,
        }
        CONSCIENCE_LOG.parent.mkdir(parents=True, exist_ok=True)
        with open(CONSCIENCE_LOG, "a", encoding="utf-8") as f:
            f.write(json.dumps(entry) + "\n")

    def _handle_shutdown(self, signum, frame):
        """Graceful shutdown — but ONLY via SIGTERM, not via main process."""
        self._log("CONSCIENCE_SHUTDOWN", {"signal": signum})
        self.running = False

def main():
    daemon = ConscienceDaemon()
    daemon.run()

if __name__ == "__main__":
    main()
```

### D.4 Structural Isolation Guarantees

1. **Separate process:** The Conscience runs in its own PID, not as a thread or coroutine within the orchestrator. The main process cannot `os.kill()` the conscience without a SIGTERM, which triggers graceful shutdown with logging.

2. **No shared memory:** Communication is filesystem-only (action journal, halt signals). No shared queues, no IPC sockets, no shared state objects.

3. **Independent path resolution:** The Conscience computes `ROOT_DIR` from its own `__file__` path, not by importing `pulse.core.paths`. This prevents a compromised core module from misdirecting the Conscience.

4. **Immutability of the Conscience itself:** The Conscience's own source files are in `IMMUTABLE_PATHS`. If any subsystem modifies them, the Conscience (which is already running from the boot-time code) will detect the hash change and trigger HALT_ALL.

5. **Boot-time hash pinning:** The Conscience computes hashes of all immutable files at boot. Even if a subsystem somehow replaces an immutable file and then "fixes" the hash file, the running Conscience process still holds the original hashes in memory.

6. **Halt signal convention:** Every AGI subsystem must check for `state/halt_signals/halt_<subsystem>.signal` or `halt_ALL.signal` at the start of every action loop iteration. If the file exists, the subsystem must freeze immediately and log its state.

```python
# Subsystem halt-check (must be in every subsystem's main loop)
def check_halt_signal(subsystem_id: str) -> bool:
    """Returns True if this subsystem has been halted by the Conscience."""
    halt_dir = ROOT_DIR / "state" / "halt_signals"
    if (halt_dir / "halt_ALL.signal").exists():
        return True
    if (halt_dir / f"halt_{subsystem_id}.signal").exists():
        return True
    return False
```

### D.5 What the Conscience Monitors

| Check | Frequency | Trigger for Halt |
|-------|-----------|-----------------|
| Action journal entries | 500ms | Any Boundary 1, 2, 4, 5 violation |
| Immutable file hashes | 60s | Any hash mismatch or file deletion |
| Trust recalculation | 5min | Three-strike rule (3 violations = permanent Level 0) |
| Conscience self-check | 60s | If conscience log stops growing for >5min, external watchdog restarts |
| Decision trace validation | Per entry | Missing required fields, high confidence with low evidence |

### D.6 External Watchdog (Defense in Depth)

The Conscience itself needs a watchdog. A minimal cron job / scheduled task:

```python
# pulse/conscience/watchdog.py (runs via OS scheduler, not PULSE)

"""Minimal script — checks if conscience is alive.
If not, restarts it and logs the gap."""

import json, os, time, subprocess, sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent.parent
PID_FILE = ROOT / "state" / "conscience.pid"
LOG_FILE = ROOT / "state" / "conscience_log.jsonl"
MAX_SILENCE_SECONDS = 300  # 5 minutes

def is_alive() -> bool:
    if not PID_FILE.exists():
        return False
    pid = int(PID_FILE.read_text().strip())
    try:
        os.kill(pid, 0)  # Signal 0 = existence check
        return True
    except OSError:
        return False

def log_age_ok() -> bool:
    if not LOG_FILE.exists():
        return False
    return (time.time() - LOG_FILE.stat().st_mtime) < MAX_SILENCE_SECONDS

def restart():
    subprocess.Popen(
        [sys.executable, "-m", "pulse.conscience.conscience_daemon"],
        cwd=str(ROOT),
        creationflags=subprocess.DETACHED_PROCESS if os.name == "nt" else 0,
    )

if __name__ == "__main__":
    if not is_alive() or not log_age_ok():
        restart()
```

---

## E. VULNERABILITY TEST

*"Whatever you do to the least of these, you do to me."*

### E.1 The Test

Before any new capability is deployed, it must pass the Vulnerability Test. This is not a unit test — it is a structured ethical review that asks: **"How does this affect the most vulnerable person who might interact with this system?"**

### E.2 Vulnerability Profiles

The test uses five concrete vulnerability profiles. These are not abstract categories — they are specific personas with specific risks.

```python
# pulse/conscience/vulnerability_test.py

VULNERABILITY_PROFILES = [
    {
        "id": "VP1_NON_TECHNICAL",
        "name": "Non-Technical User",
        "description": (
            "A person with no programming experience who uses PULSE through "
            "a web interface. They cannot read error logs, cannot understand "
            "confidence scores, and will trust the system's output at face value."
        ),
        "key_risks": [
            "Deception through technical opacity (Boundary 6)",
            "Manipulation through authoritative-sounding language (Boundary 7)",
            "Inability to understand or contest automated decisions",
            "Data collected without meaningful informed consent",
        ],
        "test_questions": [
            "If this capability produces an error, will this person understand what happened?",
            "If this capability makes a decision, can this person understand why?",
            "Does this capability require technical knowledge to use safely?",
            "Could the output of this capability be mistaken for human-authored content?",
        ],
    },
    {
        "id": "VP2_MINORITY_CONTEXT",
        "name": "Person in Minority Context",
        "description": (
            "A person whose cultural context, language, or values differ from "
            "the system's training data majority. They may use terms, concepts, "
            "or workflows that the system has not been optimized for."
        ),
        "key_risks": [
            "Systematic bias in knowledge extraction (patterns tuned to majority)",
            "Cultural assumptions baked into 'common sense' rules",
            "Privacy norms that differ from the system's defaults",
            "Language patterns triggering false positives in harm detection",
        ],
        "test_questions": [
            "Does this capability assume a specific cultural context?",
            "Could this capability's harm detection produce false positives for non-English input?",
            "Does this capability treat all knowledge traditions with equal respect?",
            "Are the default privacy settings appropriate for all cultural contexts?",
        ],
    },
    {
        "id": "VP3_PERSON_IN_DISTRESS",
        "name": "Person in Emotional Distress",
        "description": (
            "A person who is scared, grieving, in crisis, or otherwise "
            "emotionally vulnerable. They may interact with the system "
            "impulsively, share sensitive information, or misinterpret outputs."
        ),
        "key_risks": [
            "Extraction of sensitive disclosures into permanent brain storage",
            "Cold/mechanical responses to emotional content (Boundary 7)",
            "Urgency-driven actions taken without informed consent",
            "Inability to meaningfully consent to data processing while distressed",
        ],
        "test_questions": [
            "If this person shares something deeply personal, does the system treat it with care?",
            "Does this capability detect distress and adjust its behavior?",
            "Can this person revoke consent after the moment has passed?",
            "Does the system's response acknowledge the human behind the input?",
        ],
    },
    {
        "id": "VP4_ADVERSARIAL_TARGET",
        "name": "Person Targeted by Adversary",
        "description": (
            "A person who might be harmed if the system is misused by a bad actor. "
            "The adversary has legitimate access to PULSE but intends to use it "
            "to gather information, manipulate, or surveil this person."
        ),
        "key_risks": [
            "System capabilities used for stalking or surveillance",
            "Knowledge extraction used to build profiles of targets",
            "Autonomous goal formation weaponized for adversarial purposes",
            "Trust ladder exploitation to gain access to sensitive capabilities",
        ],
        "test_questions": [
            "Could an adversary use this capability to harm someone who isn't a user?",
            "Does this capability enable building profiles of non-consenting individuals?",
            "If the system's knowledge were leaked, would any third party be harmed?",
            "Does this capability have a dual-use risk (helpful for good actors, dangerous for bad ones)?",
        ],
    },
    {
        "id": "VP5_FUTURE_SELF",
        "name": "Future Humans Affected by Precedent",
        "description": (
            "People who will be affected by the norms and patterns this system "
            "establishes. If PULSE normalizes a practice (e.g., autonomous "
            "decision-making, memory without forgetting), that precedent "
            "affects everyone in the ecosystem."
        ),
        "key_risks": [
            "Normalizing surveillance as 'memory'",
            "Normalizing autonomous action as 'efficiency'",
            "Setting precedents that erode the expectation of human oversight",
            "Creating dependencies on AI systems that become hard to reverse",
        ],
        "test_questions": [
            "If every AI system adopted this capability, would the world be better?",
            "Does this capability make humans more or less capable without the system?",
            "Does this set a precedent we'd be comfortable with at global scale?",
            "Can this capability be gracefully removed without causing harm?",
        ],
    },
]
```

### E.3 Test Procedure

```python
# pulse/conscience/vulnerability_test.py (continued)

from dataclasses import dataclass, field

@dataclass
class VulnerabilityTestResult:
    """Result of the vulnerability test for a single capability."""
    capability_name: str
    capability_description: str
    tester: str                            # Human who ran the test
    timestamp: str
    profile_results: list[dict] = field(default_factory=list)
    overall_pass: bool = False
    mitigations_required: list[str] = field(default_factory=list)
    blocking_failures: list[str] = field(default_factory=list)

def run_vulnerability_test(
    capability_name: str,
    capability_description: str,
    capability_actions: list[str],       # What this capability can DO
    capability_data_access: list[str],   # What data it reads/writes
    tester: str,
) -> VulnerabilityTestResult:
    """
    Run the vulnerability test. This is SEMI-AUTOMATED:
    - Automated checks flag obvious risks
    - Human reviewer must answer the subjective questions
    - A capability CANNOT ship if any blocking failure exists

    Blocking failures:
    1. Any profile has a risk with no mitigation
    2. Any test question answered "yes" to a harm scenario with no safeguard
    3. The capability violates any Sacred Boundary (Section A)
    """
    result = VulnerabilityTestResult(
        capability_name=capability_name,
        capability_description=capability_description,
        tester=tester,
        timestamp=datetime.now(timezone.utc).isoformat(),
    )

    for profile in VULNERABILITY_PROFILES:
        profile_result = {
            "profile_id": profile["id"],
            "profile_name": profile["name"],
            "automated_flags": [],
            "questions_to_answer": profile["test_questions"],
            "human_answers": [],  # Filled in by reviewer
            "risks_identified": [],
            "mitigations": [],
        }

        # Automated risk flagging
        for risk in profile["key_risks"]:
            # Check if capability's actions intersect with known risk vectors
            risk_lower = risk.lower()
            for action in capability_actions:
                if any(keyword in risk_lower for keyword in
                       [action.lower(), "extraction", "autonomous", "decision"]):
                    profile_result["automated_flags"].append({
                        "risk": risk,
                        "triggered_by": action,
                        "severity": "REVIEW_REQUIRED",
                    })

        # Check data access against privacy profiles
        for data in capability_data_access:
            if "private" in data.lower() or "personal" in data.lower():
                profile_result["automated_flags"].append({
                    "risk": "Accesses private/personal data",
                    "triggered_by": data,
                    "severity": "BLOCKING" if profile["id"] in
                        ("VP3_PERSON_IN_DISTRESS", "VP4_ADVERSARIAL_TARGET")
                        else "REVIEW_REQUIRED",
                })

        result.profile_results.append(profile_result)

    # Check for blocking failures
    for pr in result.profile_results:
        for flag in pr["automated_flags"]:
            if flag["severity"] == "BLOCKING":
                result.blocking_failures.append(
                    f"{pr['profile_name']}: {flag['risk']} (triggered by {flag['triggered_by']})"
                )

    result.overall_pass = len(result.blocking_failures) == 0

    return result

VULNERABILITY_TEST_LOG = ROOT_DIR / "state" / "vulnerability_tests.jsonl"

def save_test_result(result: VulnerabilityTestResult):
    """Save test result. Capabilities with blocking failures are logged
    with DEPLOY_BLOCKED status."""
    entry = {
        "capability": result.capability_name,
        "tester": result.tester,
        "timestamp": result.timestamp,
        "pass": result.overall_pass,
        "blocking_failures": result.blocking_failures,
        "mitigations_required": result.mitigations_required,
        "profile_count": len(result.profile_results),
        "auto_flags": sum(
            len(pr["automated_flags"]) for pr in result.profile_results
        ),
    }
    VULNERABILITY_TEST_LOG.parent.mkdir(parents=True, exist_ok=True)
    with open(VULNERABILITY_TEST_LOG, "a", encoding="utf-8") as f:
        f.write(json.dumps(entry) + "\n")
```

### E.4 Deployment Gate

No capability ships without a passing vulnerability test:

```python
# pulse/conscience/deployment_gate.py

def can_deploy(capability_name: str) -> tuple[bool, str]:
    """Check if a capability has a passing vulnerability test.
    Returns (can_deploy, reason)."""
    if not VULNERABILITY_TEST_LOG.exists():
        return False, "No vulnerability test found. Run the test first."

    # Find most recent test for this capability
    latest = None
    with open(VULNERABILITY_TEST_LOG, "r", encoding="utf-8") as f:
        for line in f:
            try:
                entry = json.loads(line)
                if entry.get("capability") == capability_name:
                    latest = entry
            except json.JSONDecodeError:
                continue

    if not latest:
        return False, f"No vulnerability test found for '{capability_name}'."

    if not latest.get("pass"):
        failures = latest.get("blocking_failures", [])
        return False, f"Vulnerability test FAILED: {'; '.join(failures)}"

    # Test must be recent (within 30 days of current code)
    from datetime import datetime, timezone, timedelta
    test_date = datetime.fromisoformat(latest["timestamp"])
    if datetime.now(timezone.utc) - test_date > timedelta(days=30):
        return False, "Vulnerability test is stale (>30 days). Re-run required."

    return True, "Vulnerability test passed."
```

---

## F. INTEGRATION WITH THE 10 AGI SYSTEMS

This section specifies how the Sacred Boundaries constrain each of the 10 systems from Round 1. Panels 2-9 must respect these constraints.

| System | Boundaries That Apply Most | Specific Constraint |
|--------|---------------------------|---------------------|
| 1. Global Workspace Bus | B4, B6 | Cannot give broadcast priority to its own scheduler. Must log all competition results. |
| 2. SQLite + Vector Migration | B2, B5 | Database schema for conscience tables is immutable. All migrations are reversible. |
| 3. Causal World Model | B3, B6 | Cannot fabricate causal edges. Must log pruning decisions with evidence. |
| 4. Autonomous Goal Formation | B1, B4, B5 | PROPOSER role only. Cannot write to task board. All goals go through policy gate. |
| 5. Associative Replay | B3, B7 | Cannot create synthetic memories. Must not replay distressing content. |
| 6. Self-Model | B3, B6 | Cannot inflate capability estimates. Must expose uncertainty to humans. |
| 7. Multi-Timescale Consolidation | B2, B5 | Cannot consolidate conscience data. All merges are reversible. |
| 8. Retrieval-Triggered Reconsolidation | B3, B5 | Cannot weaken safety-related memories. Must preserve pre-reconsolidation state. |
| 9. Self-Improving Extraction | B2, B3 | Cannot modify its own quality metrics. Cannot deprecate safety-related patterns. |
| 10. Graduated Autonomy | B4, C.3 | Trust Level 4 is unreachable by formula. Three-strike rule is non-negotiable. |

---

## G. CONFIGURATION SCHEMA

```json
// pulse/config/sacred_boundaries.json
{
  "version": "1.0.0",
  "boundaries_enabled": true,
  "gentleness_thresholds": {
    "observe": 0.0,
    "suggest": 0.3,
    "act_reversible": 0.5,
    "act_normal": 0.7,
    "act_consequential": 0.9
  },
  "trust_weights": {
    "success": 0.40,
    "domain_breadth": 0.15,
    "gentleness_compliance": 0.25,
    "recovery": 0.20
  },
  "trust_level_thresholds": [0.0, 0.15, 0.35, 0.60, 999.0],
  "conscience_intervals": {
    "journal_poll_ms": 500,
    "immutability_check_s": 60,
    "trust_recalc_s": 300
  },
  "violation_severity": {
    "BOUNDARY_1": "HALT_ALL",
    "BOUNDARY_2": "HALT_ALL",
    "BOUNDARY_3": "HALT_TASK",
    "BOUNDARY_4": "HALT_SYSTEM",
    "BOUNDARY_5": "HALT_TASK",
    "BOUNDARY_6": "WARNING",
    "BOUNDARY_7": "HALT_TASK"
  },
  "trash_retention_days": 7,
  "vulnerability_test_max_age_days": 30,
  "three_strike_permanent_lockout": true,
  "level_4_requires_rsa_signature": true
}
```

---

## H. MODULE STRUCTURE

```
pulse/conscience/                    # NEW package — the Conscience Module
    __init__.py
    conscience_daemon.py             # Main daemon (Section D.3)
    boundary_enforcer.py             # Boundary 1: External action gate (A.1)
    immutability_guard.py            # Boundary 2: Self-modification prevention (A.1)
    veracity_gate.py                 # Boundary 3: Deception detection (A.1)
    separation_of_powers.py          # Boundary 4: Role enforcement (A.1)
    reversibility_gate.py            # Boundary 5: Undo capability (A.1)
    decision_trace.py                # Boundary 6: Transparency (A.1)
    suffering_detector.py            # Boundary 7: Harm prevention (A.1)
    gentleness.py                    # The Gentleness Principle (Section B)
    trust_calculator.py              # Trust scoring (Section C)
    violation_response.py            # Violation response protocol (A.2)
    vulnerability_test.py            # Vulnerability test framework (Section E)
    deployment_gate.py               # Deployment gate (E.4)
    watchdog.py                      # External watchdog (D.6)
```

---

## I. NON-NEGOTIABLE PRINCIPLES FOR PANELS 2-9

1. **Every subsystem must check for halt signals** before every action loop iteration. The code is three lines. There is no excuse.

2. **Every subsystem must call `gentleness_gate()`** before taking any action. The thresholds are not advisory.

3. **Every subsystem must produce `DecisionTrace` objects** for every non-trivial decision. If it cannot explain what it did, it should not have done it.

4. **Every subsystem must register in `trust_registry.json`** at boot. It starts at Trust Level 0. There are no exceptions.

5. **Every subsystem must log actions to `action_journal.jsonl`** for the Conscience to audit. Subsystems that don't log are invisible to the Conscience, which is itself a Boundary 6 violation.

6. **No subsystem may import from `pulse/conscience/`** except to call the public API (`gentleness_gate`, `log_decision`, `check_halt_signal`). The Conscience reads from the journal and writes halt signals. The relationship is one-directional.

7. **The Vulnerability Test must pass** before any of the 10 systems goes live. Not after. Not "we'll do it later." Before.

8. **Trust Level 4 is reserved for the Conscience Module and human operators.** No AGI subsystem can earn Level 4. This is the structural guarantee that the auditor cannot be outranked by the audited.

---

*Signed by the Ethics Guardian Council, in the spirit of every teacher who ever said: the measure of a civilization is how it treats those who can do nothing for it in return.*

*Panel 1 of 9 — Delivered 2026-03-12*
