// SPDX-License-Identifier: CC-BY-SA-4.0
// Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) <j.d.a.jewell@open.ac.uk>
= ADR-002: Methodology Layer for AGENTIC.a2ml
:doctype: article
:toc: left
:sectnums:
:icons: font

== Status

Proposed (2026-03-23)

== Context

AGENTIC.a2ml currently defines **operational gating** — whether a permitted
action may proceed now. It covers entropy budgets, risk thresholds,
confirmation requirements, and decision recording.

What it does NOT cover is **how agents should approach work** — methodology
selection, constraint identification, coverage tracking, and divergent
invariant preservation. This gap has been measured:

* v2 meandering on ambientops used 296K tokens across 5 bots, found the
  critical constraint accidentally in wave 2, and visited only 21% of components
* v3 constraint-first on the same target used 89K tokens across 2 bots,
  identified the constraint in Phase 0, and achieved 100% component visibility
* A 70% token reduction with better outcomes

The methodology layer has been field-tested across 6+ sessions on 3 project
types (infrastructure, platform, formal verification) with consistent results.

=== Evidence: Cross-Project Validation

[options="header"]
|===
| Project | Type | Mode | Constraint Found | v3 Score

| ambientops | Infrastructure (Rust/Elixir/V) | Convergent | Evidence Envelope flow broken | 8/10
| burble | Platform (Elixir voice) | Convergent | Missing deps = silent fallbacks | 7/10
| proven | Research (Idris2 proofs) | Divergent | Build pipeline never verified | 8/10
|===

== Decision

Extend AGENTIC.a2ml with a `[methodology]` section that declares per-repo
methodology preferences, constraints, invariants, and session state. Add
`agent_instructions/` to `.machine_readable/` as the directory for
methodology-aware agent configuration.

== Specification

=== New AGENTIC.a2ml Section: `[methodology]`

[source,toml]
----
[methodology]
# Default mode for this project (convergent | divergent | hybrid)
# Agents infer if not set, but explicit is better
default-mode = "divergent"

# What makes this project unique (divergent mode guidance)
# Agents should deepen this, not broaden it
unique-strength = "Formal verification with dependent types — Idris2 proofs"

# Invariants that divergent mode must NOT violate
# These are the riverbanks — diverge within them, not across
divergent-invariants = [
  "Idris2 only for formal verification — no Lean4, Coq, Agda",
  "believe_me count must remain zero",
  "FFI architecture: Idris2 → RefC → Zig → C ABI (no shortcuts)",
]

# Constraint identification hints
# Help Phase 0 find the critical chain faster
known-constraints = [
  "End-to-end build (idris2 --build) has never been verified",
  "libproven.so does not exist yet — all bindings call stubs",
]

# Coverage tracking from last session
[methodology.coverage]
last-session = "2026-03-23"
visited = ["src/", "ffi/zig/", "bindings/rust/", "bindings/gleam/"]
skipped-with-musts = ["bindings/python/", "apps/"]
debt-file = "MEANDER-DEBT.md"
----

=== New Directory: `.machine_readable/agent_instructions/`

[source]
----
.machine_readable/
├── 6a2/                     # Existing: 6 A2ML checkpoint files
├── bot_directives/          # Existing: gitbot-fleet rules
├── agent_instructions/      # NEW: methodology-aware config
│   ├── methodology.a2ml     # Mode, invariants, constraints
│   ├── coverage.a2ml        # Session coverage tracking
│   └── debt.a2ml            # Meander debt from last session
----

==== methodology.a2ml

Declares the project's methodology preferences. Read by any AI agent
(Claude, Gemini, Copilot, etc.) at session start.

[source,toml]
----
[methodology]
version = "1.0.0"
default-mode = "divergent"  # convergent | divergent | hybrid
ring-ceiling = 2            # Hard ceiling for ring expansion (default: 2)
wave-cap = 2                # Max waves before requiring user "keep going" (default: 2)
spike-required = true       # Every session must ship code (default: true)

[methodology.priority-weights]
must = 3
should = 2
could = 1

[methodology.unique-strength]
description = "Formal verification with dependent types"
deepen-not-broaden = true
language-invariant = "idris2"  # Only this language for the core strength

[methodology.divergent-invariants]
# These constraints survive divergent mode
rules = [
  "No additional proof languages (Lean4, Coq, Agda)",
  "believe_me count must remain zero",
  "assert_total count must remain zero",
  "FFI architecture: Idris2 → RefC → Zig → C ABI",
]

[methodology.convergent-budget]
structural = 70   # % of budget for structural work
corrective = 20   # % for bug fixes
perfective = 10   # % for docs, formatting, style
----

==== coverage.a2ml

Persists coverage state across sessions. Updated at session end.

[source,toml]
----
[coverage]
version = "1.0.0"
last-session = "2026-03-23"
total-components = 29
visited-components = 6
coverage-percent = 21

[coverage.visited]
# Component → session date + ring reached
"emergency-room" = { date = "2026-03-23", ring = 2 }
"hardware-crash-team" = { date = "2026-03-23", ring = 2 }
"observatory" = { date = "2026-03-23", ring = 2 }

[coverage.skipped-musts]
# Components with known MUSTs that were not visited
"session-sentinel" = "P0: 56 SIGABRTs, D-Bus race"
"nano-aider" = "P1: wrong author email"
"panoptes" = "P1: MIT license, should be PMPL"
----

==== debt.a2ml

Meander debt list persisted between sessions.

[source,toml]
----
[debt]
version = "1.0.0"
last-updated = "2026-03-23"

[[debt.should]]
component = "system-tools/monitoring/observatory"
issue = "Stale duplicate of root observatory/"
effort = "easy"
impact = "medium"

[[debt.could]]
component = "cicada"
issue = "RSR_OUTLINE.adoc references banned AGPL-3.0"
effort = "easy"
impact = "low"
----

=== Relationship to Existing AGENTIC.a2ml Sections

[options="header"]
|===
| Existing Section | New Section | Relationship

| `[agent-permissions]`
| `[methodology]`
| Permissions say WHAT agents can do. Methodology says HOW.

| `[agent-constraints]`
| `[methodology.divergent-invariants]`
| Constraints are universal (never do X). Divergent invariants are
mode-specific (in divergent mode, don't broaden).

| `[entropy-budget]`
| `[methodology.convergent-budget]`
| Entropy budget tracks risk accumulation. Convergent budget tracks
effort allocation (70/20/10 structural/corrective/perfective).

| `[risk-thresholds]`
| `[methodology.priority-weights]`
| Risk classifies danger. Priority classifies importance (MUST 3x).
|===

=== How This Informs the Agentic Server

The agentic server is the runtime that reads and enforces these files.
Its architecture maps to the methodology framework:

[source]
----
Agentic Server Architecture:

  ┌─────────────────────────────────────────────────┐
  │  Agent Request ("work on this repo")            │
  └──────────────────┬──────────────────────────────┘
                     │
  ┌──────────────────▼──────────────────────────────┐
  │  1. READ: agent_instructions/methodology.a2ml   │
  │     → mode, invariants, ring ceiling, weights   │
  ├─────────────────────────────────────────────────┤
  │  2. READ: agent_instructions/coverage.a2ml      │
  │     → what was visited, what has MUSTs           │
  ├─────────────────────────────────────────────────┤
  │  3. READ: agent_instructions/debt.a2ml          │
  │     → carried debt from last session             │
  ├─────────────────────────────────────────────────┤
  │  4. READ: 6a2/STATE.a2ml                        │
  │     → P1 items, current phase, blockers          │
  │     ⚠ VALIDATE: not a template placeholder      │
  ├─────────────────────────────────────────────────┤
  │  5. IDENTIFY CONSTRAINT                         │
  │     → Build dependency graph from state + debt   │
  │     → Find critical chain                        │
  │     → Locate first unresolved link               │
  ├─────────────────────────────────────────────────┤
  │  6. SELECT AGENT ROLE(S)                        │
  │     ┌──────────────┐                            │
  │     │ convergent?  │→ Converge agent             │
  │     │ divergent?   │→ Diverge agent              │
  │     │ hybrid?      │→ TSDM navigator + worker    │
  │     │ complex?     │→ 3-agent (ADR-001)          │
  │     └──────────────┘                            │
  ├─────────────────────────────────────────────────┤
  │  7. ENFORCE AT RUNTIME                          │
  │     → Check divergent invariants before edits    │
  │     → Check convergent budget (70/20/10)         │
  │     → Check ring ceiling before expansion        │
  │     → Validate bot claims before commit          │
  ├─────────────────────────────────────────────────┤
  │  8. PERSIST                                     │
  │     → Update coverage.a2ml                       │
  │     → Update debt.a2ml                           │
  │     → Feed outcomes to Hypatia learning loop     │
  └─────────────────────────────────────────────────┘
----

=== Contractile Tightening

The contractile system (Mustfile/Trustfile/Dustfile/Intentfile/K9)
should enforce methodology constraints:

[source,toml]
----
# In Mustfile:
[methodology]
mode = "divergent"
language-invariant = "idris2"
believe-me-ceiling = 0
assert-total-ceiling = 0

# K9 validator:
# k9/methodology-guard.k9.ncl
# Checks that no commit introduces:
# - Files in languages violating the divergent invariant
# - believe_me or assert_total above the ceiling
# - Changes to agent_instructions/ without user approval
----

This turns methodology constraints from "things Claude reads in a prompt"
into "things any CI system can enforce."

=== State File Validation (from field testing)

Phase 0 reads STATE.a2ml first. Field testing found two failure modes:

1. **Template placeholder** (burble): STATE.a2ml was never customised from
   rsr-template-repo. Project name = "rsr-template-repo", completion = 95%.
   Agent would start with completely wrong data.

2. **Empty after migration** (proven): STATE.a2ml was migrated from .scm
   but the content didn't carry over. Completion = 0%, no tasks.

**Required validation before trusting STATE.a2ml:**

[source]
----
1. Check for {{PLACEHOLDER}} or {{PROJECT}} tokens → template, not real
2. Check project name matches repo name → not template default
3. Check last-updated is within 90 days → not stale
4. If validation fails → fall back to TODO.md, ROADMAP.adoc, README.adoc
5. Flag the broken STATE.a2ml as a P1 MUST in the audit
----

== Consequences

=== Positive

* Methodology becomes a protocol, not a prompt — any agent server can implement it
* Divergent invariants are machine-enforceable, not trust-based
* Coverage tracking persists across sessions — no more starting blind
* Meander debt survives session boundaries — nothing discovered is lost
* Contractile K9 validators can block invariant violations in CI
* Hypatia learning loop gets structured methodology outcome data

=== Negative

* More files in `.machine_readable/` (3 new files per repo)
* Initial setup cost: every repo needs methodology.a2ml configured
* Risk of over-specification — some projects don't need methodology config
* The agentic server is a new runtime to build and maintain

=== Mitigations

* `rsr-template-repo` provides sensible defaults (hybrid mode, standard weights)
* The `just init` recipe can generate methodology.a2ml from project type
* Repos without methodology.a2ml fall back to v3 defaults (hybrid, 3x/2x/1x, Ring 2 ceiling)
* The agentic server can start as a BoJ cartridge before becoming standalone

== References

* ADR-001: Three-Agent Architecture (Diverge/Converge/TSDM)
* Productive Meandering v3-v5 prompt (methodologies repo)
* AGENTIC-FORMAT-SPEC.adoc (this repo)
* Field reports: ambientops, burble, proven evaluations (methodologies repo)
* Hypatia learning loop: `hypatia/lib/learning_scheduler.ex`
