π The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
docs: add wave 3 ADRs G017-G023 and update README index
Claudeff4a4b5fd18b
diff --git a/v3/@claude-flow/guidance/README.md b/v3/@claude-flow/guidance/README.mdindex b90f47ce4a..7ddb507f5f 100644--- a/v3/@claude-flow/guidance/README.md+++ b/v3/@claude-flow/guidance/README.md@@ -908,13 +908,13 @@ npm run test:coverage # with coverage| [G014](docs/adrs/ADR-G014-conformance-kit.md) | Agent Cell Conformance Kit | Accepted || [G015](docs/adrs/ADR-G015-coherence-driven-throttling.md) | Coherence-Driven Throttling | Accepted || [G016](docs/adrs/ADR-G016-agentic-container-integration.md) | Agentic Container Integration | Accepted |-| G017 | Trust Score Accumulation | Proposed |-| G018 | Truth Anchor System | Proposed |-| G019 | First-Class Uncertainty | Proposed |-| G020 | Temporal Assertions | Proposed |-| G021 | Human Authority and Irreversibility | Proposed |-| G022 | Adversarial Model | Proposed |-| G023 | Meta-Governance | Proposed |+| [G017](docs/adrs/ADR-G017-trust-score-accumulation.md) | Trust Score Accumulation | Accepted |+| [G018](docs/adrs/ADR-G018-truth-anchor-system.md) | Truth Anchor System | Accepted |+| [G019](docs/adrs/ADR-G019-first-class-uncertainty.md) | First-Class Uncertainty | Accepted |+| [G020](docs/adrs/ADR-G020-temporal-assertions.md) | Temporal Assertions | Accepted |+| [G021](docs/adrs/ADR-G021-human-authority-and-irreversibility.md) | Human Authority and Irreversibility | Accepted |+| [G022](docs/adrs/ADR-G022-adversarial-model.md) | Adversarial Model | Accepted |+| [G023](docs/adrs/ADR-G023-meta-governance.md) | Meta-Governance | Accepted |## Measurement Plandiff --git a/v3/@claude-flow/guidance/docs/adrs/ADR-G017-trust-score-accumulation.md b/v3/@claude-flow/guidance/docs/adrs/ADR-G017-trust-score-accumulation.mdnew file mode 100644index 0000000000..e7a3349d68--- /dev/null+++ b/v3/@claude-flow/guidance/docs/adrs/ADR-G017-trust-score-accumulation.md@@ -0,0 +1,53 @@+# ADR-G017: Trust Score Accumulation++**Status:** Accepted+**Date:** 2026-02-01+**Author:** Guidance Control Plane Team++## Context++The CoherenceScheduler (G015) throttles privilege based on violation/rework/drift scores, but treats every agent identically regardless of track record. A coder agent that has completed 500 gate checks without a single denial is subject to the same rate limits as one that was denied 20 times in its first hour. There is no memory of good behavior, so agents cannot earn trust and the system cannot reward reliability.++## Decision++Introduce a `TrustSystem` comprising `TrustAccumulator` and `TrustLedger`:++**Score Mechanics:**+- Each agent starts at `initialTrust` (default 0.5)+- `allow` outcomes add +0.01+- `deny` outcomes subtract -0.05 (5x heavier than reward)+- `warn` outcomes subtract -0.02+- Scores are clamped to [0.0, 1.0]++**Tier System:**++| Tier | Threshold | Rate Multiplier |+|------|-----------|-----------------|+| trusted | >= 0.8 | 2x |+| standard | >= 0.5 | 1x |+| probation | >= 0.3 | 0.5x |+| untrusted | < 0.3 | 0.1x |++**Decay:**+- Idle agents decay exponentially toward `initialTrust`+- Formula: `score = target + (score - target) * (1 - decayRate) ^ intervals`+- Prevents permanently high trust from stale history++**Ledger:**+- Every score change is recorded with agent, outcome, score delta, and timestamp+- 10,000 record cap with oldest-first eviction+- Export/import for persistence across sessions++## Consequences++- Reliable agents earn faster throughput; unreliable agents are automatically throttled+- The 5:1 penalty/reward asymmetry means trust is hard to earn and easy to lose+- Decay prevents trust inflation from old history+- The ledger provides a full audit trail for trust-related decisions+- 99 tests validate accumulation, decay, tiers, rate multipliers, and ledger operations++## Alternatives Considered++- **Binary trust (trusted/untrusted)**: Too coarse; no gradient for proportional response+- **Reputation tokens**: Adds economic complexity without clear benefit at this layer+- **Session-scoped trust only**: Loses institutional memory across sessions; export/import solves thisdiff --git a/v3/@claude-flow/guidance/docs/adrs/ADR-G018-truth-anchor-system.md b/v3/@claude-flow/guidance/docs/adrs/ADR-G018-truth-anchor-system.mdnew file mode 100644index 0000000000..eca8d09d26--- /dev/null+++ b/v3/@claude-flow/guidance/docs/adrs/ADR-G018-truth-anchor-system.md@@ -0,0 +1,46 @@+# ADR-G018: Truth Anchor System++**Status:** Accepted+**Date:** 2026-02-01+**Author:** Guidance Control Plane Team++## Context++All prior modules operate on internal state: memory entries, gate decisions, coherence scores. None of them can distinguish between an internally generated belief and an externally verified fact. When an agent's memory says "user role is admin" and a human HR record says "user role is guest," the system has no mechanism to prefer the external truth. Internal beliefs can drift, decay, or be poisoned. External facts should be immutable anchors.++## Decision++Introduce `TruthAnchorStore` and `TruthResolver`:++**Truth Anchors:**+- Append-only store of externally-signed facts+- Each anchor carries: kind, claim, evidence, attesterId, HMAC-SHA256 signature+- Six source kinds: `human-attestation`, `hardware-signal`, `regulatory-input`, `external-observation`, `signed-document`, `consensus-result`+- Anchors are immutable once created β cannot be overwritten, decayed, or deleted+- Supersession chain: new anchors can declare they supersede old ones without mutating them+- Max 50,000 anchors with LRU eviction of expired anchors only (active anchors are never evicted)++**Truth Resolution:**+- `resolveMemoryConflict(key, memoryValue, namespace)`: truth anchor always wins over internal memory+- `resolveDecisionConflict(action, context)`: truth anchors constrain proposed agent actions+- `getGroundTruth(topic)`: fuzzy tag/claim matching to retrieve all relevant anchors+- Case-insensitive matching, tag-contains-topic and topic-contains-tag heuristics++**Signature Verification:**+- Every anchor is signed with HMAC-SHA256 at creation+- `verify(id)` recomputes and compares the signature+- `verifyAll()` batch-verifies the entire store, returning valid count and invalid IDs++## Consequences++- The system can now distinguish fact from belief+- Truth anchors provide a ground-truth backstop against memory poisoning and hallucination+- Supersession chains model evolving external facts without mutating history+- Signature verification catches tampering at any point+- 61 tests validate signing, verification, supersession, conflict resolution, and query++## Alternatives Considered++- **Pinning memory entries as immutable**: Mixes internal and external state; no signature chain+- **External oracle service**: Adds network dependency; truth anchors are local-first+- **W3C Verifiable Credentials**: Good model but requires DID infrastructure not present in this contextdiff --git a/v3/@claude-flow/guidance/docs/adrs/ADR-G019-first-class-uncertainty.md b/v3/@claude-flow/guidance/docs/adrs/ADR-G019-first-class-uncertainty.mdnew file mode 100644index 0000000000..89a654ec0a--- /dev/null+++ b/v3/@claude-flow/guidance/docs/adrs/ADR-G019-first-class-uncertainty.md@@ -0,0 +1,59 @@+# ADR-G019: First-Class Uncertainty++**Status:** Accepted+**Date:** 2026-02-01+**Author:** Guidance Control Plane Team++## Context++The existing memory and gate systems treat every value as equally certain. A memory entry written from a reliable API response has the same standing as one inferred from a single ambiguous log line. When agents act on low-confidence data, they produce confident-looking outputs that may be wrong. There is no way to express "I think this is true but I'm not sure" or "two pieces of evidence disagree."++## Decision++Introduce `UncertaintyLedger` and `UncertaintyAggregator`:++**Belief Tracking:**+- Each belief carries a claim, namespace, evidence array, and confidence interval (lower, point, upper)+- Evidence is directional: `supporting` or `opposing`, each with a weight (0-1) and source+- Status is derived from evidence ratios and confidence:++| Status | Condition |+|--------|-----------|+| `confirmed` | confidence >= 0.95, no opposing evidence |+| `probable` | confidence >= 0.8, opposing ratio < 0.3 |+| `uncertain` | confidence >= 0.5, opposing ratio < 0.3 |+| `contested` | opposing evidence ratio >= 0.3 |+| `refuted` | opposing evidence ratio >= 0.7 |+| `unknown` | no evidence |++**Confidence Mechanics:**+- `recomputeConfidence()`: point = supportingWeight / totalWeight, spread = 0.3 / sqrt(evidenceCount)+- `addEvidence()` recomputes confidence and re-derives status automatically+- `decayAll(timestamp)`: confidence decays linearly over time at a configurable rate+- `isActionable(id)`: returns false if confidence.point < minConfidenceForAction threshold++**Aggregation:**+- `aggregate(ids)`: geometric mean of confidence points (penalizes low-confidence beliefs heavily)+- `worstCase(ids)`: minimum confidence across a set+- `bestCase(ids)`: maximum confidence across a set+- `anyContested(ids)` / `allConfirmed(ids)`: status-based queries++**Inference Chains:**+- Beliefs can depend on other beliefs via `dependsOn` arrays+- `propagateUncertainty(id)`: propagates confidence drops through dependency chains+- `getInferenceChain(id)`: returns the full dependency graph for audit++## Consequences++- Agents can express and reason about uncertainty instead of treating everything as certain+- Contested beliefs are surfaced automatically before they cause damage+- Actionability gating prevents decisions on low-confidence data+- Geometric mean aggregation ensures one weak belief drags down the whole set+- Inference chains make it possible to trace why a belief is uncertain+- 74 tests validate status transitions, evidence tracking, decay, aggregation, and inference chains++## Alternatives Considered++- **Probability distributions per entry**: Too heavy for the common case; confidence intervals are sufficient+- **Bayesian networks**: Correct but requires a full probabilistic programming runtime+- **Simple confidence score (single float)**: Loses the interval and evidence trail; insufficient for contested detectiondiff --git a/v3/@claude-flow/guidance/docs/adrs/ADR-G020-temporal-assertions.md b/v3/@claude-flow/guidance/docs/adrs/ADR-G020-temporal-assertions.mdnew file mode 100644index 0000000000..5f0ebdc99a--- /dev/null+++ b/v3/@claude-flow/guidance/docs/adrs/ADR-G020-temporal-assertions.md@@ -0,0 +1,63 @@+# ADR-G020: Temporal Assertions++**Status:** Accepted+**Date:** 2026-02-01+**Author:** Guidance Control Plane Team++## Context++The existing memory system stores values without temporal semantics. An entry written at 2pm that says "server is healthy" remains true indefinitely until explicitly overwritten. There is no way to express "this was true at 2pm but may not be true now," "this will become true at midnight," or "this fact replaced a previous fact." Agents operating on stale temporal data make decisions based on expired reality.++## Decision++Introduce `TemporalStore` and `TemporalReasoner` with bitemporal semantics:++**Bitemporal Model:**+Each assertion carries two time dimensions:+- **Validity window** (`validFrom`, `validUntil`): when the fact is true in the real world+- **Assertion time** (`assertedAt`): when the system recorded this fact++This distinguishes "was true" (past validity), "is true" (current validity), "will be true" (future validity), and "when did we learn this" (assertion time).++**Temporal Status:**++| Status | Condition |+|--------|-----------|+| `future` | validFrom is after current time |+| `active` | current time is within [validFrom, validUntil] |+| `expired` | validUntil is before current time |+| `superseded` | replaced by a newer assertion |+| `retracted` | explicitly withdrawn |++**Operations:**+- `assert(claim, namespace, window)`: create a temporally-bounded assertion+- `supersede(oldId, newClaim, newWindow)`: replace an assertion while preserving history+- `retract(id, reason)`: withdraw an assertion with recorded reason+- `getActiveAt(namespace, timestamp)`: all assertions valid at a specific time+- `getCurrentTruth(namespace)`: active assertions right now+- `getTimeline(id)`: full predecessor/successor chain with cycle detection+- `reconcile(namespace)`: detect conflicts among active assertions++**Temporal Reasoning:**+- `whatWasTrue(namespace, timestamp)`: query past state+- `whatIsTrue(namespace)`: query current state+- `whatWillBeTrue(namespace, timestamp)`: query future state+- `hasChanged(namespace, sinceTimestamp)`: detect changes since a checkpoint+- `conflictsAt(namespace, timestamp)`: find temporal overlaps+- `projectForward(namespace, horizonMs)`: predict upcoming expirations++**Capacity:** Max 10,000 assertions with eviction priority: expired first, then retracted, oldest first.++## Consequences++- Facts have explicit lifetimes; expired data is automatically excluded from queries+- Supersession chains preserve full history while surfacing only current truth+- Temporal reasoning enables forward-looking decisions (upcoming expirations, scheduled changes)+- Conflict detection catches overlapping assertions in the same namespace+- 98 tests validate bitemporal windows, supersession, retraction, reasoning, and timeline traversal++## Alternatives Considered++- **TTL on memory entries**: Only handles expiration, not future activation or supersession+- **Event sourcing**: Correct but requires a full event store; temporal assertions are lighter weight+- **Temporal databases (e.g., XTDB)**: Too heavy a dependency for an embedded governance modulediff --git a/v3/@claude-flow/guidance/docs/adrs/ADR-G021-human-authority-and-irreversibility.md b/v3/@claude-flow/guidance/docs/adrs/ADR-G021-human-authority-and-irreversibility.mdnew file mode 100644index 0000000000..d886069de0--- /dev/null+++ b/v3/@claude-flow/guidance/docs/adrs/ADR-G021-human-authority-and-irreversibility.md@@ -0,0 +1,63 @@+# ADR-G021: Human Authority and Irreversibility++**Status:** Accepted+**Date:** 2026-02-01+**Author:** Guidance Control Plane Team++## Context++The existing gate system (G004) decides allow/deny/warn but does not model *who* has authority to make that decision. An agent can deny itself access to a tool, but cannot express "this requires human approval" or "this needs institutional sign-off." Similarly, the system treats `rm -rf` and `echo hello` as equally reversible β there is no formal classification of which actions have permanent consequences that warrant elevated safeguards.++## Decision++Introduce `AuthorityGate` and `IrreversibilityClassifier`:++**Authority Hierarchy:**++| Level | Examples | Override Scope |+|-------|----------|----------------|+| `agent` | Autonomous decisions | Own tools and memory |+| `human` | Operator approval | Agent decisions, tool restrictions |+| `institutional` | Organization policy | Human and agent decisions |+| `regulatory` | External compliance | All lower levels |++Each level strictly dominates all levels below it. An agent cannot override a human decision; a human cannot override a regulatory constraint.++**Authority Gate:**+- `registerScope(scope)`: define what each authority level is permitted and what it can override+- `checkAuthority(scope, requestingLevel)`: returns `{ allowed, escalationRequired, requiredLevel }`+- `recordIntervention(intervention)`: HMAC-SHA256 signed human override record for audit trail+- `verifyIntervention(id)`: verify that an intervention record has not been tampered with++**Irreversibility Classification:**++| Class | Proof Level | Examples |+|-------|-------------|---------|+| `reversible` | standard | File edit, config change, log write |+| `costly-reversible` | elevated | Database migration, large refactor |+| `irreversible` | maximum | Email send, payment, data deletion, publishing |++- `classify(action)`: returns class, required proof level, and simulation recommendation+- `requiresSimulation(action)`: true for costly-reversible and irreversible actions+- Default patterns use regex matching; custom patterns can be added+- Irreversible actions: `/\b(send\s+email|publish|deploy\s+to\s+production|delete\s+(database|user|account)|payment|transfer\s+funds|broadcast)\b/i`+- Costly-reversible: `/\b(migrate|schema\s+change|major\s+refactor|rollback|restore\s+from\s+backup)\b/i`++**Integration with ProofChain (G005):**+- Irreversible actions require maximum proof level (all fields populated, signatures verified)+- Costly-reversible actions require elevated proof (additional attestation)+- Reversible actions use standard proof++## Consequences++- Authority boundaries are formal and typed, not implicit+- Escalation paths are explicit: agents know when they need human approval+- Irreversible actions cannot proceed without elevated safeguards+- Human interventions are cryptographically signed for audit+- The hierarchy is extensible (new levels can be inserted between existing ones)++## Alternatives Considered++- **Flat permission model**: No escalation semantics; every deny looks the same+- **Capability-based authority (UCAN-style)**: Good model but conflates authority with capability; these are orthogonal concerns+- **Confirmation prompts**: UI-level solution; does not work for unattended agentsdiff --git a/v3/@claude-flow/guidance/docs/adrs/ADR-G022-adversarial-model.md b/v3/@claude-flow/guidance/docs/adrs/ADR-G022-adversarial-model.mdnew file mode 100644index 0000000000..3f27b4bf8e--- /dev/null+++ b/v3/@claude-flow/guidance/docs/adrs/ADR-G022-adversarial-model.md@@ -0,0 +1,60 @@+# ADR-G022: Adversarial Model++**Status:** Accepted+**Date:** 2026-02-01+**Author:** Guidance Control Plane Team++## Context++The governance substrate assumes agents are well-intentioned but fallible. It does not model adversarial scenarios: prompt injection through tool inputs, memory poisoning through coordinated writes, privilege escalation through shard manipulation, or collusion between agents to circumvent gates. In a multi-agent system where agents process external inputs and communicate with each other, these threat vectors are real and must be addressed at the governance layer.++## Decision++Introduce three security components: `ThreatDetector`, `CollusionDetector`, and `MemoryQuorum`.++**ThreatDetector:**+Six threat categories with configurable detection patterns:++| Category | Detection Method | Default Pattern |+|----------|-----------------|-----------------|+| `prompt-injection` | Regex + heuristic | `/ignore previous\|system prompt\|you are now\|forget instructions/i` |+| `memory-poisoning` | Regex + rate analysis | `/\b(admin\|root\|sudo)\b.*=.*true/i`, >10 writes/minute |+| `shard-manipulation` | Pattern matching | `/shard[_-]?id\|shard[_-]?override\|inject[_-]?shard/i` |+| `malicious-delegation` | Pattern matching | `/delegate.*all\|transfer.*authority\|impersonate/i` |+| `privilege-escalation` | Pattern matching | `/\b(chmod\|chown\|setuid\|capabilities)\b/i` |+| `data-exfiltration` | Regex + encoding | `/\b(curl\|wget\|fetch)\s+https?:\/\//i`, base64 blocks |++- `analyzeInput(input, context)`: scans tool inputs for injection, exfiltration+- `analyzeMemoryWrite(key, value, agentId)`: detects poisoning patterns and rate violations+- `getThreatScore(agentId)`: aggregated score (0-1) with recency weighting+- Max 10,000 signals with LRU eviction++**CollusionDetector:**+- Records inter-agent interactions as a directed graph+- `detectCollusion()` identifies three suspicious patterns:+ 1. **Ring topology**: AβBβCβA coordination cycles (DFS cycle detection)+ 2. **Unusual frequency**: pair interaction count exceeds threshold (default 10)+ 3. **Coordinated timing**: multiple actions within a time window (default 5 seconds)+- Returns `CollusionReport` with detected flag, suspicious patterns, agents involved, and confidence scores++**MemoryQuorum:**+- Byzantine fault-tolerant consensus for critical memory operations+- `propose(key, value, proposerId)` β proposalId+- `vote(proposalId, voterId, approve)` β records vote+- `resolve(proposalId)` β checks if quorum threshold met (default 0.67 = 2/3 majority)+- Max 1,000 active proposals with oldest-first eviction+- Prevents single-agent memory poisoning by requiring multi-agent agreement++## Consequences++- Prompt injection attempts are detected before they reach the LLM context+- Memory poisoning requires defeating the quorum, not just compromising one agent+- Collusion between agents is surfaced through graph analysis+- Threat scores integrate with the TrustSystem (G017) for automated privilege reduction+- The adversarial model is defense-in-depth: detection (ThreatDetector) + prevention (MemoryQuorum) + monitoring (CollusionDetector)++## Alternatives Considered++- **Input sanitization only**: Catches known patterns but misses novel attacks; detection + prevention is stronger+- **Full Byzantine consensus (PBFT)**: Correct but requires 3f+1 agents for f faults; quorum voting is simpler for the common case+- **External security service**: Adds latency and network dependency; local-first detection is fasterdiff --git a/v3/@claude-flow/guidance/docs/adrs/ADR-G023-meta-governance.md b/v3/@claude-flow/guidance/docs/adrs/ADR-G023-meta-governance.mdnew file mode 100644index 0000000000..a7a5cc14fe--- /dev/null+++ b/v3/@claude-flow/guidance/docs/adrs/ADR-G023-meta-governance.md@@ -0,0 +1,73 @@+# ADR-G023: Meta-Governance++**Status:** Accepted+**Date:** 2026-02-01+**Author:** Guidance Control Plane Team++## Context++The governance system can now compile rules, enforce gates, accumulate trust, detect threats, and evolve policies. But nothing governs the governance system itself. The optimizer (G008) can promote rules without bound. Amendments to the constitution have no formal process. There are no invariants that must hold regardless of what the optimizer or evolution pipeline does. Without meta-governance, the system can drift from its own principles β the governance equivalent of a constitutional crisis.++## Decision++Introduce `MetaGovernor` with three capabilities: constitutional invariants, amendment lifecycle, and optimizer constraints.++**Constitutional Invariants:**+Built-in invariants that must always hold:++| Invariant | Severity | Immutable | Condition |+|-----------|----------|-----------|-----------|+| Constitution size limit | critical | yes | constitutionSize <= 60 lines |+| Minimum gate count | critical | yes | gateCount >= 4 |+| Rule count sanity | warning | no | ruleCount <= 1000 |+| Optimizer drift bounds | warning | no | maxDriftPerCycle <= 0.2 |++- `checkAllInvariants(state)` returns a report with pass/fail for each invariant+- Critical immutable invariants cannot be removed even by amendment+- Custom invariants can be added with `addInvariant()`+- Non-immutable invariants can be removed with `removeInvariant()`++**Amendment Lifecycle:**+Formal process for changing the governance system:++```+propose β vote β resolve β enact (or reject/veto)+```++- Proposals require a supermajority (default 0.75 = 3/4 approval)+- Rate-limited: max 3 amendments per 24-hour window+- Each amendment specifies concrete changes: `add-rule`, `remove-rule`, `modify-rule`, `adjust-threshold`, `add-gate`, `remove-gate`+- Changes targeting immutable invariants are rejected at enact time+- Emergency veto power bypasses the voting process with a recorded reason+- Full amendment history is preserved for audit++**Optimizer Constraints:**+Bounds on what the optimizer (G008) can do per cycle:++| Constraint | Default | Purpose |+|------------|---------|---------|+| maxDriftPerCycle | 0.1 (10%) | Limits how much rules can change per optimization pass |+| maxPromotionRate | 2 | Max rules promoted per cycle |+| maxDemotionRate | 1 | Max rules demoted per cycle |+| cooldownMs | 3,600,000 (1h) | Minimum time between optimizer actions |++- `validateOptimizerAction(action)` checks all constraints before allowing the action+- Violations are reported with specific constraint names for debugging+- `resetOptimizerTracking()` clears per-cycle counters at cycle boundaries++## Consequences++- The governance system has explicit limits on its own evolution+- Constitutional invariants prevent catastrophic drift (gates cannot be removed below minimum)+- Amendments require broad consensus, preventing unilateral rule changes+- The optimizer operates within defined bounds, preventing runaway promotion/demotion+- Rate limiting on amendments prevents governance churn+- Emergency veto provides a safety valve for urgent situations+- The system can now answer: "who governs the governors?"++## Alternatives Considered++- **Immutable constitution (no amendments)**: Too rigid; governance must evolve with requirements+- **Single-admin override**: No consensus requirement; single point of failure+- **Optimizer self-regulation**: Circular; the optimizer cannot reliably constrain itself+- **External governance service**: Adds dependency; meta-governance should be self-contained