Skill: danielfoojunwei/agentic-middle-manager (version 1.0.0)

--- name: management-trinity description: A unified meta-skill that orchestrates the transition from traditional management roles to an AI-augmented organizational operating system. Consolidates accountability guardrails, sense-making augmentation, trust calibration, persistent ownership, empathy bridging, and culture strain prevention into a single framework. --- # The Management Trinity ## Overview The **`management-trinity`** skill is a unified orchestrator that addresses the fundamental limitations of AI agents by unbundling the traditional manager role into a distributed protocol. It synthesizes six critical gap-bridging capabilities into a single, self-improving operating system for the AI era. **Use this skill when:** - Architecting an "agentic organization" or deploying autonomous workflows at scale. - Transitioning from traditional hierarchical management to a "Player-Coach" or DRI (Directly Responsible Individual) model. - Designing governance frameworks for high-stakes AI decision-making. - Addressing systemic issues of trust, burnout, or accountability diffusion in AI-heavy teams. ## The Paradigm Shift: From Role to Protocol When viewed from first principles, the limitations of AI agents are not isolated technical bugs; they are symptoms of a phase transition in organizational design. This skill operationalizes six fundamental paradigm shifts: 1. **From "Manager as Role" to "Management as Protocol":** Management is no longer a job title held by a single human. It is a distributed protocol where AI handles *Routing* (information logistics), while humans handle *Sense-Making* (strategic judgment) and *Accountability* (ownership and empathy). 2. **From "Hierarchy of Authority" to "Hierarchy of Judgment":** Decisions are no longer routed upward based on rank, but outward based on complexity (using the Cynefin framework). 3. **From "Trust in Persons" to "Trust in Systems":** Psychological safety relies on the transparency of the human-AI system (deliberation records, provenance chains) rather than just interpersonal dynamics. 4. **From "Memory in Heads" to "Memory as Infrastructure":** The "forgetting problem" of AI is solved by externalizing organizational memory into persistent, queryable state checkpoints. 5. **From "Culture as Emergent" to "Culture as Designed":** With AI handling routing, the casual interactions that build culture disappear. Culture must be intentionally engineered through Player-Coach mentorship and health monitoring. 6. **From "Accountability as Blame" to "Accountability as Architecture":** Accountability is built into the system via confidence-based routing and escalation paths, rather than sought after a failure occurs. --- ## Phase 1: Architectural Mapping (The Protocol Design) Before deploying agents, map the distribution of the Management Trinity. Identify which *Routing* functions the AI will automate, and explicitly assign the orphaned *Sense-Making* and *Accountability* functions to human roles. ### The Management Trinity Decomposition | Function | Definition | AI Capability | Human Requirement | | :--- | :--- | :--- | :--- | | **Routing** | Information logistics: directing tasks, data, and context to the right resources at the right time. | **High.** AI excels at synthesis, pattern recognition, and rapid distribution. | Low. Humans add value only in novel or politically sensitive routing. | | **Sense-Making** | Strategic judgment: synthesizing ambiguous signals into coherent strategy while buffering teams from noise. | **Low.** AI can synthesize data but cannot navigate organizational politics, apply ethical intuition, or make judgment calls in novel situations. | High. Requires deep contextual understanding, political awareness, and human intuition. | | **Accountability** | Ownership: bearing responsibility for outcomes, providing mentorship, and maintaining long-term commitment. | **None.** AI cannot bear responsibility, feel empathy, or maintain emotional investment over time. | Critical. Only humans can own outcomes, apologize sincerely, and mentor for growth. | ### Role Redistribution | New Role | Responsibilities | Trinity Functions | | :--- | :--- | :--- | | **Individual Contributor (IC)** | Specialist who builds and operates capabilities. Relies on the AI-powered "world model" for context. | Executes work informed by AI Routing. | | **Directly Responsible Individual (DRI)** | Owns a specific, cross-cutting problem for a defined period. Has authority to pull resources. | Sense-Making + Accountability for their domain. | | **Player-Coach** | Practitioner who continues to build products while also mentoring and developing people. | Accountability (mentorship, empathy, culture). | ### Anti-Patterns to Avoid - **The Hollow Middle:** Removing managers without redistributing their functions. Leads to culture strain, burnout, isolation. - **The AI Manager:** Assigning Sense-Making or Accountability to an AI agent. Leads to trust erosion, accountability vacuum. - **The Shadow Hierarchy:** Informal leaders emerge to fill the gap, without formal authority. Leads to political dysfunction. - **The Overloaded DRI:** Assigning too many cross-cutting problems to a single DRI. Leads to bottlenecks. --- ## Phase 2: Governance and Guardrails (The Accountability Architecture) Establish the systemic trust mechanisms that allow agents to operate safely. ### 1. Provenance Chains A provenance chain links every agent action back to a human authorization. Every agent action must include: - `action_id`, `timestamp`, `agent_id`, `action_type` - `human_authorizer` (role, name, explicit authorization scope, date) - `inputs_considered`, `output`, `confidence_score` ### 2. Confidence-Based Routing Agents must express uncertainty as a resource. | Confidence Level | Action | Rationale | | :--- | :--- | :--- | | **> 90%** | Auto-execute | High confidence; agent proceeds within its authorized scope. | | **70% - 90%** | Human review | Moderate confidence; agent presents its analysis and recommendation to a human DRI for approval. | | **< 70%** | Escalate / Reject | Low confidence; agent escalates to a senior DRI or rejects the task. | ### 3. Deliberation Records A deliberation record captures the full reasoning process behind an agent's decision. **JSON Schema (`deliberation_record.json`):** ```json { "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "Deliberation Record", "type": "object", "required": ["record_id", "timestamp", "agent_id", "provenance", "context", "alternatives", "rationale", "assumptions", "confidence", "limitations", "outcome"], "properties": { "record_id": { "type": "string", "format": "uuid" }, "timestamp": { "type": "string", "format": "date-time" }, "agent_id": { "type": "string" }, "provenance": { "type": "object", "required": ["human_authorizer", "authorization_scope"], "properties": { "human_authorizer": { "type": "string" }, "authorization_scope": { "type": "string" }, "authorization_date": { "type": "string", "format": "date-time" } } }, "context": { "type": "object", "properties": { "situation_summary": { "type": "string" }, "data_sources": { "type": "array" }, "cynefin_classification": { "type": "string", "enum": ["clear", "complicated", "complex", "chaotic"] } } }, "alternatives": { "type": "array", "items": { "type": "object", "properties": { "option": { "type": "string" }, "pros": { "type": "array" }, "cons": { "type": "array" }, "risk_level": { "type": "string", "enum": ["low", "medium", "high"] } } } }, "rationale": { "type": "string" }, "assumptions": { "type": "array", "items": { "type": "string" } }, "confidence": { "type": "object", "properties": { "score": { "type": "number", "minimum": 0.0, "maximum": 1.0 }, "factors": { "type": "array" }, "routing_action": { "type": "string", "enum": ["auto-executed", "human-reviewed", "escalated"] } } }, "limitations": { "type": "array", "items": { "type": "string" } }, "outcome": { "type": "object", "properties": { "action_taken": { "type": "string" }, "result": { "type": "string" }, "post_mortem_required": { "type": "boolean" } } } } } ``` --- ## Phase 3: Collaborative Execution (The Judgment Topology) Structure the day-to-day interaction between humans and AI. ### The Cynefin Decision Router - **Clear:** Apply best practices and automate. Human spot-checks. - **Complicated:** AI gathers data, models scenarios, presents options. Human makes final decision. - **Complex:** AI probes environment, senses patterns. Human responds adaptively. - **Chaotic:** Human acts immediately to stabilize. AI used post-hoc for analysis. ### AI Synthesis Report Template When routing a decision to a human (70-90% confidence), the AI must present this report: ```markdown # AI Synthesis Report **Decision Context:** [Clear / Complicated / Complex / Chaotic] **Prepared For:** [Human DRI or Player-Coach Name] **Date:** [YYYY-MM-DD] | **Agent ID:** [Agent identifier] | **Confidence Score:** [0.0 - 1.0] ## 1. Situation Summary [Concise summary of the current situation and the key decision.] ## 2. Data Sources Consulted | Source | Type | Relevance | Recency | | :--- | :--- | :--- | :--- | | [Source 1] | [Internal/External] | [High/Medium/Low] | [Date] | ## 3. Options Analysis ### Option A: [Name] - **Description:** [What this option entails] - **Pros:** [Key advantages] | **Cons:** [Key disadvantages] | **Risk Level:** [Low / Medium / High] ## 4. Assumptions Made 1. [Assumption 1] ## 5. Limitations of This Analysis [Explicitly state what this analysis CANNOT account for, e.g., organizational context, politics.] ## 6. Recommendation (if confidence > 70%) [Provide recommendation or state why human judgment is required.] **Note to Decision-Maker:** This report is a starting point for your judgment, not a substitute for it. ``` ### Persistent Ownership Protocol AI agents are stateless. To maintain ownership across sessions: 1. **Session Checkpointing:** At the end of every session, the agent generates a "State of the Project" summary (status, open questions, key context, human DRI). 2. **Context Retrieval:** At the start of a new session, the agent queries persistent storage (Vector Store or Graph DB) for the most recent checkpoint and historical context. --- ## Phase 4: Human-Centric Maintenance (The Culture Engine) Protect the emotional and psychological health of the organization. ### The Player-Coach Model - **Player (60-70%):** Building, shipping, executing. Uses AI agents as tools. - **Coach (30-40%):** Mentoring, developing, connecting. Reviews AI Observation Reports. - **Workflow:** AI tracks objective metrics (never keystrokes or sentiment) and generates a neutral Observation Report. The Coach synthesizes this data with context. The Coach delivers the mentorship session, focusing on career growth and psychological safety. ### Trust Calibration When AI errors occur, teams experience "trust ambiguity." - **Active Oversight:** Implement friction points where humans explicitly validate AI outputs before proceeding. Rotate oversight to prevent complacency. - **Post-Mortem Protocol:** Focus on the accountability architecture, not individual blame. Ask: Was the provenance chain intact? Was the confidence score accurate? Was the deliberation record adequate? ### Culture Strain Prevention Monitor for early warning indicators of culture strain: - **Isolation:** Pulse survey score drops below 3.5/5. (Intervention: Increase Player-Coach touchpoints). - **Burnout:** Pulse survey score rises above 3.5/5. (Intervention: Redistribute DRI load). - **Collaboration:** Cross-team communication declines >20%. (Intervention: Reconnect team goals). --- ## Self-Dependent Feedback Loop This skill incorporates a dark factory intent engineering feedback loop that operates independently to continuously refine the organizational operating system. ### Trinity Orchestrator Script (`trinity_orchestrator.py`) Run this script to aggregate telemetry data across all six dimensions and generate improvement recommendations. ```python #!/usr/bin/env python3 """ Trinity Orchestrator: Self-Improving Feedback Loop for the Management Trinity Monitors: Accountability, Sense-Making, Trust, Ownership, Mentorship, Culture. """ import json from datetime import datetime from enum import Enum from dataclasses import dataclass, field class HealthStatus(Enum): HEALTHY = "healthy" WARNING = "warning" CRITICAL = "critical" @dataclass class DimensionHealth: dimension: str status: HealthStatus score: float indicators: dict = field(default_factory=dict) recommendations: list = field(default_factory=list) @dataclass class TrinityReport: timestamp: str overall_status: HealthStatus dimensions: list = field(default_factory=list) paradigm_shift_alerts: list = field(default_factory=list) improvement_actions: list = field(default_factory=list) class TrinityOrchestrator: THRESHOLDS = { "accountability": {"escalation_rate_max": 0.30, "deliberation_quality_min": 0.80}, "sense_making": {"ai_human_alignment_min": 0.60}, "trust": {"psych_safety_score_min": 3.5, "cognitive_offloading_max": 0.20}, "ownership": {"context_retrieval_success_min": 0.85}, "mentorship": {"coach_time_allocation_min": 0.25}, "culture": {"isolation_score_max": 3.5, "burnout_score_max": 3.5} } def assess_dimension(self, dimension: str, metrics: dict) -> DimensionHealth: thresholds = self.THRESHOLDS.get(dimension, {}) recommendations = [] issues = 0 total_checks = len(thresholds) for metric_name, threshold in thresholds.items(): actual = metrics.get(metric_name) if actual is None: continue if "max" in metric_name and actual > threshold: issues += 1 recommendations.append(f"{metric_name}: {actual:.2f} exceeds threshold {threshold:.2f}.") elif "min" in metric_name and actual < threshold: issues += 1 recommendations.append(f"{metric_name}: {actual:.2f} below threshold {threshold:.2f}.") score = 1.0 - (issues / max(1, total_checks)) status = HealthStatus.HEALTHY if score >= 0.8 else (HealthStatus.WARNING if score >= 0.5 else HealthStatus.CRITICAL) return DimensionHealth(dimension, status, score, metrics, recommendations) def detect_paradigm_shift_alerts(self, dimensions: list) -> list: alerts = [] culture = next((d for d in dimensions if d.dimension == "culture"), None) mentorship = next((d for d in dimensions if d.dimension == "mentorship"), None) trust = next((d for d in dimensions if d.dimension == "trust"), None) accountability = next((d for d in dimensions if d.dimension == "accountability"), None) if culture and mentorship and culture.status == HealthStatus.CRITICAL and mentorship.status == HealthStatus.CRITICAL: alerts.append("PARADIGM ALERT: 'Hollow Middle' anti-pattern detected. Immediate role redesign required.") if trust and accountability and trust.status != HealthStatus.HEALTHY and accountability.status != HealthStatus.HEALTHY: alerts.append("PARADIGM ALERT: Trust Collapse. Review deliberation record transparency.") return alerts def generate_report(self, all_metrics: dict) -> TrinityReport: dimensions = [self.assess_dimension(dim, all_metrics.get(dim, {})) for dim in self.THRESHOLDS.keys()] alerts = self.detect_paradigm_shift_alerts(dimensions) statuses = [d.status for d in dimensions] overall = HealthStatus.CRITICAL if HealthStatus.CRITICAL in statuses else (HealthStatus.WARNING if HealthStatus.WARNING in statuses else HealthStatus.HEALTHY) actions = [f"[{d.dimension}] {r}" for d in dimensions for r in d.recommendations] return TrinityReport(datetime.utcnow().isoformat(), overall, dimensions, alerts, actions) if __name__ == "__main__": import sys if len(sys.argv) > 1: with open(sys.argv[1], "r") as f: metrics = json.load(f) report = TrinityOrchestrator().generate_report(metrics) print(f"Overall Status: {report.overall_status.value.upper()}") for alert in report.paradigm_shift_alerts: print(f">> {alert}") for action in report.improvement_actions: print(f"- {action}") ```

path: references/culture_maintenance.md
content: # Culture Maintenance: The Human Engine of the Management Trinity

## Purpose

This reference provides strategies for maintaining organizational health, psychological safety, and human connection in AI-augmented environments. It covers the Player-Coach mentorship model, trust calibration, active oversight design, and culture strain prevention.

## 1. The Player-Coach Model

The Player-Coach is the linchpin of the Management Trinity's human-centric maintenance. They are practitioners who continue to build products or write code while also dedicating time to mentoring and developing people.

### Player-Coach Responsibilities

| Dimension | Player (60-70% of time) | Coach (30-40% of time) |
| :--- | :--- | :--- |
| **Focus** | Building, shipping, executing | Mentoring, developing, connecting |
| **AI Interaction** | Uses AI agents as tools for their own work | Reviews AI Observation Reports to inform coaching |
| **Output** | Code, designs, campaigns, analyses | Career growth plans, team health, culture |

### The AI-Informed Coaching Workflow

1. **AI Observes:** The agent tracks objective, quantifiable metrics (task completion rates, code quality, response times). It generates a neutral "Observation Report"—never a "Performance Review."
2. **Coach Synthesizes:** The Player-Coach reviews the Observation Report before meeting with the team member. They identify where the data lacks context (e.g., a productivity dip due to a known personal issue).
3. **Human Delivers:** The Coach conducts the mentorship session, framing AI data as a starting point for discussion, not an absolute truth. Focus areas include career development, emotional support, and navigating organizational politics.

### Metrics the AI Should NOT Track
- Keystroke logging or screen time
- Communication frequency as a proxy for productivity
- Sentiment analysis of private messages
- Any metric that creates surveillance anxiety rather than growth insight

## 2. Trust Calibration

### The Trust Ambiguity Problem
When AI errors occur, teams experience "trust ambiguity"—they believe trust is warranted but lack actual confidence. Because AI reasoning is opaque, teams cannot engage in collaborative sense-making to understand the root cause.

### The Trust Calibration Workflow

**Before Deployment (Baseline):**
- Conduct a baseline survey on psychological safety and AI literacy.
- Openly discuss the AI's known limitations and expected error rates.
- Establish the "friction points" where humans must validate AI assumptions.

**During Operation (Active Oversight):**
- Implement friction points where humans explicitly validate AI outputs before proceeding.
- Rotate oversight responsibilities to prevent complacency (the "human-AI oversight paradox").
- Ensure AI outputs include confidence scores and limitation disclosures.

**After Errors (Post-Mortem):**
- Gather the team to review the error collaboratively.
- Focus on the inputs and context, not on blaming individuals for trusting the AI.
- Update team guidelines on when to trust the AI and when to override.

## 3. Culture Strain Prevention

### What is Culture Strain?
When organizations remove management layers without redistributing sense-making and accountability functions, employees experience burnout, isolation, and a feeling of "weightlessness." This is culture strain.

### Early Warning Indicators

| Indicator | Measurement Method | Red Flag Threshold |
| :--- | :--- | :--- |
| **Isolation** | Pulse survey: "I feel connected to my team" | Score drops below 3.5/5 for two consecutive periods |
| **Clarity of Purpose** | Pulse survey: "I understand how my work contributes to our goals" | Score drops below 3.5/5 |
| **Burnout** | Pulse survey: "I feel overwhelmed by my workload" | Score rises above 3.5/5 |
| **Collaboration** | Cross-team communication frequency (Slack/Teams analytics) | Decline of >20% from baseline |
| **Talent Attrition** | Voluntary turnover rate | Increase of >15% from baseline |

### Intervention Strategies

| Strain Type | Intervention |
| :--- | :--- |
| **DRI Overload** | Redistribute cross-cutting problems; appoint additional DRIs. |
| **IC Isolation** | Increase Player-Coach touchpoints; create peer mentorship circles. |
| **Trust Erosion** | Conduct team-wide AI error post-mortems; improve deliberation record transparency. |
| **Purpose Drift** | Reconnect team goals to organizational mission; ensure AI routing includes context on "why." |

## 4. The Persistent Ownership Protocol

### The Forgetting Problem
AI agents are stateless. They cannot own a project over weeks or months. The Persistent Ownership Protocol ensures continuity.

### Session Checkpointing
At the end of every significant session or milestone, the agent generates a "State of the Project" summary:
- Current status and recent decisions
- Open questions and unresolved issues
- Key context that must be preserved for the next session
- The human DRI responsible for long-term ownership

### Context Retrieval
At the start of every new session, the agent:
1. Queries the persistent storage for the most recent State Checkpoint.
2. Loads relevant historical context (decisions, rationale, artifacts).
3. Presents a brief summary to the human DRI for validation before proceeding.

### Memory Architecture Options

| Option | Best For | Trade-offs |
| :--- | :--- | :--- |
| **Vector Store** | Semantic search across large document collections | May miss exact matches; requires embedding model tuning |
| **Graph Database** | Relationship-heavy data (org charts, decision trees) | More complex to set up; excellent for "why" queries |
| **Structured Logs + Search** | Simple, auditable history | Less flexible for semantic queries; easy to implement |
| **Hybrid (Vector + Graph)** | Enterprise-scale deployments | Highest fidelity; highest complexity |


path: references/governance_guardrails.md
content: # Governance Guardrails: Accountability Architecture for AI Agents

## Purpose

This reference provides the implementation guidelines for building accountability into agentic systems through provenance chains, confidence-based routing, and deliberation records. These are the systemic trust mechanisms that allow agents to operate safely within the Management Trinity protocol.

## 1. Provenance Chains

A provenance chain links every agent action back to a human authorization, creating an unbroken chain of responsibility.

### Required Data Schema

Every agent action must include:

```json
{
  "action_id": "uuid",
  "timestamp": "ISO 8601",
  "agent_id": "string",
  "action_type": "string",
  "human_authorizer": {
    "role": "DRI | Player-Coach | IC",
    "name": "string",
    "authorization_scope": "description of what was authorized",
    "authorization_date": "ISO 8601"
  },
  "inputs_considered": ["list of data sources"],
  "output": "description of the action taken",
  "confidence_score": "0.0 - 1.0"
}
```

### Design Principles
- Every agent must have a named human authorizer for its scope of action.
- Authorization scope must be explicitly bounded (e.g., "approve refunds under $50" not "handle customer service").
- The provenance chain must be immutable and queryable for audit purposes.

## 2. Confidence-Based Routing

Agents must express uncertainty as a resource, not suppress it into binary classifications.

### Routing Thresholds

| Confidence Level | Action | Rationale |
| :--- | :--- | :--- |
| **> 90%** | Auto-execute | High confidence; agent proceeds within its authorized scope. |
| **70% - 90%** | Human review | Moderate confidence; agent presents its analysis and recommendation to a human DRI for approval. |
| **< 70%** | Escalate / Reject | Low confidence; agent escalates to a senior DRI or rejects the task, requesting more information. |

### Calibration Process
Thresholds are not universal. They must be calibrated per task type based on:
- **Reversibility:** Can the action be undone? Lower thresholds for reversible actions.
- **Impact:** What is the cost of failure? Higher thresholds for high-impact decisions.
- **Frequency:** How often does this decision occur? High-frequency decisions benefit from lower thresholds to avoid bottlenecks.

### The Cynefin Decision Router

Use the Cynefin framework to determine the appropriate level of AI involvement:

| Context | AI Role | Human Role |
| :--- | :--- | :--- |
| **Clear** | Apply best practices and automate. | Spot-check and audit. |
| **Complicated** | Gather data, model scenarios, present options. | Expert analysis and final decision. |
| **Complex** | Probe the environment, sense patterns, surface anomalies. | Adaptive response, experimentation. |
| **Chaotic** | Post-hoc analysis and documentation. | Immediate stabilization and action. |

## 3. Deliberation Records

A deliberation record captures the full reasoning process behind an agent's decision, functioning like a medical chart rather than a simple log entry.

### Required Components

Every deliberation record must include:

1. **Context:** What was the situation? What data was available?
2. **Alternatives Considered:** What options did the agent evaluate?
3. **Rationale:** Why was the chosen action selected over the alternatives?
4. **Assumptions:** What assumptions did the agent make? What information was missing?
5. **Confidence Assessment:** How certain was the agent? What factors contributed to uncertainty?
6. **Limitations Acknowledged:** What are the known limitations of this analysis?

### Quality Criteria
A deliberation record is considered adequate if a human reviewer can:
- Understand the decision without additional context.
- Identify the specific point where the reasoning might have gone wrong.
- Determine whether the agent's assumptions were reasonable given the available data.

## 4. Post-Mortem Protocol (When Things Go Wrong)

When an AI agent makes an error, the post-mortem focuses on the accountability architecture, not on individual blame.

### Post-Mortem Questions
1. Was the provenance chain intact? Did the agent act within its authorized scope?
2. Was the confidence score accurate? Did the routing threshold work correctly?
3. Was the deliberation record adequate? Could a human have caught the error by reviewing it?
4. Where did the accountability architecture fail? What systemic improvement is needed?

### Output
The post-mortem produces an **Architecture Improvement Recommendation** that updates the governance guardrails, not a blame assignment.


path: references/trinity_mapping.md
content: # Trinity Mapping: Unbundling and Redistributing Management Functions

## Purpose

This reference provides the framework for mapping the three atomic functions of management—Routing, Sense-Making, and Accountability—across humans, AI agents, and organizational systems during an agentic transformation.

## The Management Trinity Decomposition

Every management function in an organization can be decomposed into one or more of these three atomic components:

| Function | Definition | AI Capability | Human Requirement |
| :--- | :--- | :--- | :--- |
| **Routing** | Information logistics: directing tasks, data, and context to the right resources at the right time. | **High.** AI excels at synthesis, pattern recognition, and rapid distribution. | Low. Humans add value only in novel or politically sensitive routing. |
| **Sense-Making** | Strategic judgment: synthesizing ambiguous signals into coherent strategy while buffering teams from noise. | **Low.** AI can synthesize data but cannot navigate organizational politics, apply ethical intuition, or make judgment calls in novel situations. | High. Requires deep contextual understanding, political awareness, and human intuition. |
| **Accountability** | Ownership: bearing responsibility for outcomes, providing mentorship, and maintaining long-term commitment. | **None.** AI cannot bear responsibility, feel empathy, or maintain emotional investment over time. | Critical. Only humans can own outcomes, apologize sincerely, and mentor for growth. |

## The Mapping Workflow

### Step 1: Inventory Current Management Functions
For each manager or management layer being restructured, list every function they perform. Categorize each function as Routing, Sense-Making, or Accountability.

**Example for a typical Engineering Manager:**

| Current Function | Trinity Category | Can AI Handle? |
| :--- | :--- | :--- |
| Assigning tickets to engineers | Routing | Yes |
| Running daily standups | Routing | Partially (AI can summarize, human facilitates) |
| Deciding technical architecture | Sense-Making | No (AI can present options) |
| Navigating cross-team politics | Sense-Making | No |
| Conducting performance reviews | Accountability | No |
| Mentoring junior engineers | Accountability | No |
| Approving PRs and releases | Routing + Sense-Making | Partially (AI can flag risks) |

### Step 2: Assign Routing Functions to AI
For each function categorized as "Routing" where AI can handle it, design the agent workflow. Ensure the agent has access to the necessary data and tools via MCP.

### Step 3: Redistribute Sense-Making and Accountability
For each orphaned Sense-Making and Accountability function, explicitly assign it to a human role:

| New Role | Responsibilities | Trinity Functions |
| :--- | :--- | :--- |
| **Individual Contributor (IC)** | Specialist who builds and operates capabilities. Relies on the AI-powered "world model" for context. | Executes work informed by AI Routing. |
| **Directly Responsible Individual (DRI)** | Owns a specific, cross-cutting problem for a defined period. Has authority to pull resources. | Sense-Making + Accountability for their domain. |
| **Player-Coach** | Practitioner who continues to build products while also mentoring and developing people. | Accountability (mentorship, empathy, culture). |

### Step 4: Validate the Redistribution
Ensure no function is left unassigned. The most common failure mode is removing a manager without redistributing their Sense-Making and Accountability functions, leading to "culture strain."

## The Subsidiarity Principle

Following the Berkeley CMR "Fluid Organization" framework, apply subsidiarity as the default design principle: assign responsibility for a task to the smallest possible team at the lowest possible hierarchical level, unless there are good reasons to do differently. This means:

- AI agents operate as "functional agents" in factory + pilot mode by default.
- **Triggers** shift the system from factory to studio mode (e.g., AI flags an anomaly requiring human collaboration).
- **Checks** are prescheduled points where humans proactively review AI outputs (e.g., weekly synthesis reviews).
- **Help chains** define the escalation sequence when a trigger fires.
- **Transparency** ensures all role distributions, triggers, and checks are visible and agreed upon.

## Anti-Patterns to Avoid

| Anti-Pattern | Description | Consequence |
| :--- | :--- | :--- |
| **The Hollow Middle** | Removing managers without redistributing their functions. | Culture strain, burnout, isolation. |
| **The AI Manager** | Assigning Sense-Making or Accountability to an AI agent. | Trust erosion, accountability vacuum. |
| **The Shadow Hierarchy** | Informal leaders emerge to fill the gap, without formal authority. | Political dysfunction, unclear ownership. |
| **The Overloaded DRI** | Assigning too many cross-cutting problems to a single DRI. | Bottleneck, single point of failure. |


path: scripts/trinity_orchestrator.md
content: # Trinity Orchestrator: Self-Improving Feedback Loop

## Purpose

This script is the central nervous system of the distributed management protocol. It aggregates telemetry data across all six dimensions of the Management Trinity and generates improvement recommendations through a self-improving feedback loop.

## Usage

```bash
python trinity_orchestrator.py --config <config_path> --input <metrics_path> [--output <output_path>]
```

## Monitored Dimensions

| Dimension | Key Metrics |
| :--- | :--- |
| **Accountability** | Escalation rates, deliberation record quality, provenance chain integrity |
| **Sense-Making** | Decision alignment (AI synthesis vs. human final judgment), Cynefin classification accuracy |
| **Trust** | Psychological safety survey scores, cognitive offloading indicators |
| **Ownership** | Context retrieval success rates, checkpoint completeness |
| **Mentorship** | Player-Coach time allocation, mentorship satisfaction scores |
| **Culture** | Pulse survey aggregates, collaboration metrics, attrition rates |

## Default Thresholds

| Dimension | Metric | Threshold | Direction |
| :--- | :--- | :--- | :--- |
| Accountability | `escalation_rate_max` | 0.30 | Max 30% of decisions should escalate |
| Accountability | `escalation_rate_min` | 0.05 | Min 5% (below suggests thresholds too loose) |
| Accountability | `deliberation_quality_min` | 0.80 | 80% of records must be adequate |
| Accountability | `provenance_integrity` | 1.00 | 100% of actions must have provenance |
| Sense-Making | `ai_human_alignment_min` | 0.60 | AI synthesis should align with human decision 60%+ |
| Sense-Making | `cynefin_classification_accuracy` | 0.75 | 75% classification accuracy |
| Trust | `psych_safety_score_min` | 3.5 | Out of 5.0 |
| Trust | `cognitive_offloading_max` | 0.20 | Max 20% of team showing offloading signs |
| Ownership | `context_retrieval_success_min` | 0.85 | 85% retrieval success rate |
| Ownership | `checkpoint_completeness_min` | 0.90 | 90% checkpoint completeness |
| Mentorship | `coach_time_allocation_min` | 0.25 | Min 25% of Player-Coach time on coaching |
| Mentorship | `mentorship_satisfaction_min` | 3.5 | Out of 5.0 |
| Culture | `isolation_score_max` | 3.5 | Out of 5.0 (higher = more isolated) |
| Culture | `burnout_score_max` | 3.5 | Out of 5.0 |
| Culture | `collaboration_decline_max` | 0.20 | Max 20% decline from baseline |
| Culture | `attrition_increase_max` | 0.15 | Max 15% increase from baseline |

## Health Scoring

Each dimension receives a health score calculated as:

> **Score = 1.0 - (issues / total_checks)**

| Score Range | Status |
| :--- | :--- |
| >= 0.80 | **HEALTHY** |
| >= 0.50 | **WARNING** |
| < 0.50 | **CRITICAL** |

## Paradigm Shift Alerts

The orchestrator detects three systemic anti-patterns that indicate a paradigm shift is needed, not just a threshold adjustment:

**1. The Hollow Middle**
- **Trigger:** Both Culture and Mentorship dimensions are CRITICAL.
- **Meaning:** Management functions were removed without redistribution.
- **Action:** Immediate role redesign required.

**2. Trust Collapse**
- **Trigger:** Both Trust and Accountability dimensions are WARNING or CRITICAL.
- **Meaning:** The accountability architecture may be fundamentally insufficient.
- **Action:** Review deliberation record transparency and provenance chain design.

**3. AI Overreach**
- **Trigger:** Both Sense-Making and Accountability scores are below 0.50.
- **Meaning:** AI may be handling decisions beyond its capability.
- **Action:** Re-evaluate Cynefin classification and confidence routing thresholds.

## Source Code

```python
#!/usr/bin/env python3
"""
Trinity Orchestrator: Self-Improving Feedback Loop for the Management Trinity
Monitors: Accountability, Sense-Making, Trust, Ownership, Mentorship, Culture.
"""

import json
import os
import sys
from dataclasses import dataclass, field, asdict
from datetime import datetime
from enum import Enum
from typing import Optional


class HealthStatus(Enum):
    HEALTHY = "healthy"
    WARNING = "warning"
    CRITICAL = "critical"


@dataclass
class DimensionHealth:
    """Health assessment for a single dimension of the Management Trinity."""
    dimension: str
    status: HealthStatus
    score: float  # 0.0 to 1.0
    indicators: dict = field(default_factory=dict)
    recommendations: list = field(default_factory=list)


@dataclass
class TrinityReport:
    """Aggregated health report across all six dimensions."""
    timestamp: str
    overall_status: HealthStatus
    dimensions: list = field(default_factory=list)
    paradigm_shift_alerts: list = field(default_factory=list)
    improvement_actions: list = field(default_factory=list)


class TrinityOrchestrator:
    """
    The central orchestration engine for the Management Trinity.
    
    Aggregates telemetry from all six dimensions and generates
    improvement recommendations through a self-improving feedback loop.
    """

    THRESHOLDS = {
        "accountability": {
            "escalation_rate_max": 0.30,
            "escalation_rate_min": 0.05,
            "deliberation_quality_min": 0.80,
            "provenance_integrity": 1.00,
        },
        "sense_making": {
            "ai_human_alignment_min": 0.60,
            "cynefin_classification_accuracy": 0.75,
        },
        "trust": {
            "psych_safety_score_min": 3.5,
            "cognitive_offloading_max": 0.20,
        },
        "ownership": {
            "context_retrieval_success_min": 0.85,
            "checkpoint_completeness_min": 0.90,
        },
        "mentorship": {
            "coach_time_allocation_min": 0.25,
            "mentorship_satisfaction_min": 3.5,
        },
        "culture": {
            "isolation_score_max": 3.5,
            "burnout_score_max": 3.5,
            "collaboration_decline_max": 0.20,
            "attrition_increase_max": 0.15,
        },
    }

    def __init__(self, config_path: Optional[str] = None):
        if config_path and os.path.exists(config_path):
            with open(config_path, "r") as f:
                config = json.load(f)
                if "thresholds" in config:
                    self._merge_thresholds(config["thresholds"])

    def _merge_thresholds(self, overrides: dict):
        for dimension, values in overrides.items():
            if dimension in self.THRESHOLDS:
                self.THRESHOLDS[dimension].update(values)

    def assess_dimension(self, dimension: str, metrics: dict) -> DimensionHealth:
        thresholds = self.THRESHOLDS.get(dimension, {})
        recommendations = []
        issues = 0
        total_checks = 0

        for metric_name, threshold in thresholds.items():
            total_checks += 1
            actual = metrics.get(metric_name)
            if actual is None:
                recommendations.append(
                    f"Missing metric: {metric_name}. Ensure telemetry is configured."
                )
                issues += 1
                continue

            if "max" in metric_name:
                if actual > threshold:
                    issues += 1
                    recommendations.append(
                        f"{metric_name}: {actual:.2f} exceeds threshold {threshold:.2f}."
                    )
            elif "min" in metric_name:
                if actual < threshold:
                    issues += 1
                    recommendations.append(
                        f"{metric_name}: {actual:.2f} below threshold {threshold:.2f}."
                    )

        if total_checks == 0:
            score = 0.0
            status = HealthStatus.CRITICAL
        else:
            score = 1.0 - (issues / total_checks)
            if score >= 0.80:
                status = HealthStatus.HEALTHY
            elif score >= 0.50:
                status = HealthStatus.WARNING
            else:
                status = HealthStatus.CRITICAL

        return DimensionHealth(dimension, status, score, metrics, recommendations)

    def detect_paradigm_shift_alerts(self, dimensions: list) -> list:
        alerts = []
        culture = next((d for d in dimensions if d.dimension == "culture"), None)
        mentorship = next((d for d in dimensions if d.dimension == "mentorship"), None)
        trust = next((d for d in dimensions if d.dimension == "trust"), None)
        accountability = next((d for d in dimensions if d.dimension == "accountability"), None)
        sense = next((d for d in dimensions if d.dimension == "sense_making"), None)

        if culture and mentorship:
            if culture.status == HealthStatus.CRITICAL and mentorship.status == HealthStatus.CRITICAL:
                alerts.append(
                    "PARADIGM ALERT: 'Hollow Middle' anti-pattern detected. "
                    "Immediate role redesign required."
                )
        if trust and accountability:
            if trust.status in (HealthStatus.WARNING, HealthStatus.CRITICAL) and \
               accountability.status in (HealthStatus.WARNING, HealthStatus.CRITICAL):
                alerts.append(
                    "PARADIGM ALERT: Trust Collapse. "
                    "Review deliberation record transparency and provenance chain design."
                )
        if sense and accountability:
            if sense.score < 0.5 and accountability.score < 0.5:
                alerts.append(
                    "PARADIGM ALERT: AI Overreach. "
                    "Re-evaluate Cynefin classification and confidence routing thresholds."
                )
        return alerts

    def generate_report(self, all_metrics: dict) -> TrinityReport:
        dimensions = [self.assess_dimension(dim, all_metrics.get(dim, {}))
                      for dim in self.THRESHOLDS.keys()]
        alerts = self.detect_paradigm_shift_alerts(dimensions)
        statuses = [d.status for d in dimensions]
        if HealthStatus.CRITICAL in statuses:
            overall = HealthStatus.CRITICAL
        elif HealthStatus.WARNING in statuses:
            overall = HealthStatus.WARNING
        else:
            overall = HealthStatus.HEALTHY
        actions = [f"[{d.dimension}] {r}" for d in dimensions for r in d.recommendations]
        return TrinityReport(datetime.utcnow().isoformat(), overall, dimensions, alerts, actions)

    def export_report(self, report: TrinityReport, output_path: str):
        report_dict = {
            "timestamp": report.timestamp,
            "overall_status": report.overall_status.value,
            "dimensions": [
                {
                    "dimension": d.dimension,
                    "status": d.status.value,
                    "score": d.score,
                    "indicators": d.indicators,
                    "recommendations": d.recommendations,
                }
                for d in report.dimensions
            ],
            "paradigm_shift_alerts": report.paradigm_shift_alerts,
            "improvement_actions": report.improvement_actions,
        }
        with open(output_path, "w") as f:
            json.dump(report_dict, f, indent=2)
        print(f"Report exported to: {output_path}")


def main():
    import argparse
    parser = argparse.ArgumentParser(description="Trinity Orchestrator: Self-Improving Feedback Loop")
    parser.add_argument("--config", help="Path to config JSON file", default=None)
    parser.add_argument("--input", help="Path to metrics JSON file", required=True)
    parser.add_argument("--output", help="Path for output report", default="trinity_report.json")
    args = parser.parse_args()

    orchestrator = TrinityOrchestrator(config_path=args.config)
    with open(args.input, "r") as f:
        all_metrics = json.load(f)

    report = orchestrator.generate_report(all_metrics)
    orchestrator.export_report(report, args.output)

    print(f"\n{'='*60}")
    print(f"  MANAGEMENT TRINITY HEALTH REPORT")
    print(f"  Generated: {report.timestamp}")
    print(f"  Overall Status: {report.overall_status.value.upper()}")
    print(f"{'='*60}\n")

    for d in report.dimensions:
        icon = {"healthy": "OK", "warning": "!!", "critical": "XX"}[d.status.value]
        print(f"  [{icon}] {d.dimension.replace('_', ' ').title()}: "
              f"{d.score:.0%} ({d.status.value})")

    if report.paradigm_shift_alerts:
        print(f"\n{'='*60}")
        print("  PARADIGM SHIFT ALERTS")
        print(f"{'='*60}")
        for alert in report.paradigm_shift_alerts:
            print(f"\n  >> {alert}")

    if report.improvement_actions:
        print(f"\n{'='*60}")
        print(f"  IMPROVEMENT ACTIONS ({len(report.improvement_actions)} items)")
        print(f"{'='*60}")
        for action in report.improvement_actions:
            print(f"  - {action}")
    print()


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


path: templates/deliberation_record.md
content: # Deliberation Record Schema

## Purpose

A deliberation record is a structured account of an AI agent's reasoning process for a significant decision. It functions as a medical chart rather than a simple log entry, capturing the full context, alternatives, rationale, and outcome of every consequential agent action.

## Required Fields

| Field | Type | Description |
| :--- | :--- | :--- |
| `record_id` | UUID string | Unique identifier for this deliberation record |
| `timestamp` | ISO 8601 date-time | When the decision was made |
| `agent_id` | string | Identifier of the AI agent that made the decision |
| `provenance` | object | The provenance chain linking this action to human authorization |
| `context` | object | The situation and data available at the time of the decision |
| `alternatives` | array | The options the agent evaluated before making its decision |
| `rationale` | string | Why the chosen action was selected over the alternatives |
| `assumptions` | array of strings | Explicit list of assumptions the agent made |
| `confidence` | object | The agent's confidence assessment and routing action |
| `limitations` | array of strings | Known limitations of this analysis |
| `outcome` | object | The action taken and its observed result |

## Provenance Object

The provenance chain links every action to a human authorization.

| Field | Type | Required | Description |
| :--- | :--- | :--- | :--- |
| `human_authorizer` | string | Yes | Name and role of the human who authorized this agent's scope of action |
| `authorization_scope` | string | Yes | Explicit description of what the agent is authorized to do |
| `authorization_date` | ISO 8601 date-time | No | When the authorization was granted |

## Context Object

The situation and data available at the time of the decision.

| Field | Type | Description |
| :--- | :--- | :--- |
| `situation_summary` | string | Concise description of the situation requiring a decision |
| `data_sources` | array of objects | Each with `source` (string), `type` ("internal" or "external"), `relevance` ("high", "medium", "low") |
| `cynefin_classification` | enum | One of: "clear", "complicated", "complex", "chaotic" |

## Alternatives Array

Each alternative the agent evaluated:

| Field | Type | Description |
| :--- | :--- | :--- |
| `option` | string | Name or description of the alternative |
| `pros` | array of strings | Key advantages |
| `cons` | array of strings | Key disadvantages |
| `risk_level` | enum | One of: "low", "medium", "high" |

## Confidence Object

| Field | Type | Description |
| :--- | :--- | :--- |
| `score` | number (0.0 - 1.0) | The agent's confidence in its decision |
| `factors` | array of strings | Factors contributing to the confidence level |
| `routing_action` | enum | One of: "auto-executed", "human-reviewed", "escalated" |

## Outcome Object

| Field | Type | Description |
| :--- | :--- | :--- |
| `action_taken` | string | Description of the action that was executed |
| `result` | string | The observed result of the action (filled in post-execution) |
| `post_mortem_required` | boolean | Whether this decision requires a post-mortem review |

## Quality Criteria

A deliberation record is considered adequate if a human reviewer can:

1. Understand the decision without additional context.
2. Identify the specific point where the reasoning might have gone wrong.
3. Determine whether the agent's assumptions were reasonable given the available data.

## Full JSON Schema

```json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "Deliberation Record",
  "description": "A structured account of an AI agent's reasoning process for a significant decision.",
  "type": "object",
  "required": ["record_id", "timestamp", "agent_id", "provenance", "context", "alternatives", "rationale", "assumptions", "confidence", "limitations", "outcome"],
  "properties": {
    "record_id": {
      "type": "string",
      "format": "uuid",
      "description": "Unique identifier for this deliberation record."
    },
    "timestamp": {
      "type": "string",
      "format": "date-time",
      "description": "ISO 8601 timestamp of when the decision was made."
    },
    "agent_id": {
      "type": "string",
      "description": "Identifier of the AI agent that made the decision."
    },
    "provenance": {
      "type": "object",
      "required": ["human_authorizer", "authorization_scope"],
      "properties": {
        "human_authorizer": { "type": "string" },
        "authorization_scope": { "type": "string" },
        "authorization_date": { "type": "string", "format": "date-time" }
      }
    },
    "context": {
      "type": "object",
      "properties": {
        "situation_summary": { "type": "string" },
        "data_sources": {
          "type": "array",
          "items": {
            "type": "object",
            "properties": {
              "source": { "type": "string" },
              "type": { "type": "string", "enum": ["internal", "external"] },
              "relevance": { "type": "string", "enum": ["high", "medium", "low"] }
            }
          }
        },
        "cynefin_classification": {
          "type": "string",
          "enum": ["clear", "complicated", "complex", "chaotic"]
        }
      }
    },
    "alternatives": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "option": { "type": "string" },
          "pros": { "type": "array", "items": { "type": "string" } },
          "cons": { "type": "array", "items": { "type": "string" } },
          "risk_level": { "type": "string", "enum": ["low", "medium", "high"] }
        }
      }
    },
    "rationale": { "type": "string" },
    "assumptions": { "type": "array", "items": { "type": "string" } },
    "confidence": {
      "type": "object",
      "properties": {
        "score": { "type": "number", "minimum": 0.0, "maximum": 1.0 },
        "factors": { "type": "array", "items": { "type": "string" } },
        "routing_action": { "type": "string", "enum": ["auto-executed", "human-reviewed", "escalated"] }
      }
    },
    "limitations": { "type": "array", "items": { "type": "string" } },
    "outcome": {
      "type": "object",
      "properties": {
        "action_taken": { "type": "string" },
        "result": { "type": "string" },
        "post_mortem_required": { "type": "boolean" }
      }
    }
  }
}
```


path: templates/ai_synthesis_report.md
content: # AI Synthesis Report

**Decision Context:** [Clear / Complicated / Complex / Chaotic]
**Prepared For:** [Human DRI or Player-Coach Name]
**Date:** [YYYY-MM-DD]
**Agent ID:** [Agent identifier]
**Confidence Score:** [0.0 - 1.0]

---

## 1. Situation Summary

[Provide a concise summary of the current situation, including the key question or decision that needs to be made.]

## 2. Data Sources Consulted

| Source | Type | Relevance | Recency |
| :--- | :--- | :--- | :--- |
| [Source 1] | [Internal/External] | [High/Medium/Low] | [Date] |
| [Source 2] | [Internal/External] | [High/Medium/Low] | [Date] |

## 3. Options Analysis

### Option A: [Name]
- **Description:** [What this option entails]
- **Pros:** [Key advantages]
- **Cons:** [Key disadvantages]
- **Risk Level:** [Low / Medium / High]

### Option B: [Name]
- **Description:** [What this option entails]
- **Pros:** [Key advantages]
- **Cons:** [Key disadvantages]
- **Risk Level:** [Low / Medium / High]

### Option C: [Name]
- **Description:** [What this option entails]
- **Pros:** [Key advantages]
- **Cons:** [Key disadvantages]
- **Risk Level:** [Low / Medium / High]

## 4. Assumptions Made

[List all assumptions the AI made during this analysis. Be explicit about what information was missing or uncertain.]

1. [Assumption 1]
2. [Assumption 2]
3. [Assumption 3]

## 5. Limitations of This Analysis

[Explicitly state what this analysis CANNOT account for, including organizational context, political dynamics, or ethical considerations that require human judgment.]

1. [Limitation 1]
2. [Limitation 2]

## 6. Recommendation (if confidence > 70%)

[If the agent's confidence exceeds the routing threshold, provide a recommendation. Otherwise, state that this decision requires human judgment and explain why.]

---

**Note to Decision-Maker:** This report is a starting point for your judgment, not a substitute for it. The AI has synthesized available data but cannot account for organizational context, interpersonal dynamics, or ethical considerations that only you can assess.


Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (HIGH)