From 84301acc54f4f2c55609a23b95079866008f5ee2 Mon Sep 17 00:00:00 2001 From: Mike Date: Mon, 1 Jun 2026 22:40:33 -0400 Subject: [PATCH 1/4] [Claude] fix: require session close before branch merge (closes #2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds an explicit branch ordering rule to the protocol: session-close artifacts must be written on the feature branch before the PR is opened, not after merge. Changes: - PROTOCOL_RULES.md §P3: new "Branch ordering rule" subsection + new checklist item in handoff schema (v1.9.1 → v1.9.2) - modules/git-substrate.md: new §M-git-5 with git-specific enforcement and reviewer signal (v1.0.0 → v1.1.0) - template/: same changes replicated to the distributable template - README.md: version history entry for v1.9.2 (per §M-git-3) Co-Authored-By: Claude Sonnet 4.6 --- .agents/PROTOCOL_RULES.md | 328 +++++++--------------- .agents/modules/git-substrate.md | 34 ++- README.md | 274 +++--------------- template/.agents/PROTOCOL_RULES.md | 315 +++++++++++++++++++++ template/.agents/modules/git-substrate.md | 74 +++++ 5 files changed, 540 insertions(+), 485 deletions(-) create mode 100644 template/.agents/PROTOCOL_RULES.md create mode 100644 template/.agents/modules/git-substrate.md diff --git a/.agents/PROTOCOL_RULES.md b/.agents/PROTOCOL_RULES.md index faf498e..1e90234 100644 --- a/.agents/PROTOCOL_RULES.md +++ b/.agents/PROTOCOL_RULES.md @@ -1,6 +1,6 @@ # PROTOCOL_RULES.md — Lead Protocol framework rules (generic) -> Version: 2.0.0 | Updated: 2026-04-21 +> Version: 1.9.2 | Updated: 2026-06-01 > Scope: Substrate-agnostic kernel. Opt-in modules live in `modules/` and are activated via `PROJECT_RULES.md §J8`. > This file contains no project-specific content — that lives in `PROJECT_RULES.md`. @@ -9,8 +9,8 @@ ## §P1 — Versioning | File type | Format | Example | When to bump | -|---|---|---|---| -| Agent operation files (`CORE_RULES.md`, `PROTOCOL_RULES.md`, `PROJECT_RULES.md`, `handoff.md`) | `X.Y.Z` | `2.0.0` | Patch (Z) for clarifications/text fixes; Minor (Y) for new sections/rules; Major (X) for structural rewrites | +|---|---|---|---------| +| Agent operation files (`CORE_RULES.md`, `PROTOCOL_RULES.md`, `PROJECT_RULES.md`, `handoff.md`) | `X.Y.Z` | `1.4.0` | Patch (Z) for clarifications/text fixes; Minor (Y) for new sections/rules; Major (X) for structural rewrites | | Module files (`modules/*.md`) | `X.Y.Z` | `1.0.0` | Same rules as agent operation files. Each module versions independently from the kernel. | Projects that adopt Lead Protocol may use any versioning scheme for their own product releases — the Lead Protocol versioning rules apply only to the agent operation files and module files listed above. @@ -21,7 +21,7 @@ Meta-repos that develop the protocol itself see `modules/meta-repo.md §M-meta-1 1. `PROTOCOL_RULES.md` (framework kernel) 2. Active modules listed in `PROJECT_RULES.md §J8` (in declaration order) -3. `local///handoff.md` (current state for this actor × agent pair — may temporarily override stale rules if the project owner defines a temporary directive) +3. `handoff.md` (current state — may temporarily override stale rules if the project owner defines a temporary directive) 4. `PROJECT_RULES.md` (business context) 5. `README.md` (public surface — kept synced to the kernel per the active substrate module if any; kernel wins on conflict) 6. Project reference files (brand, product, channel, etc.) @@ -30,82 +30,11 @@ Meta-repos that develop the protocol itself see `modules/meta-repo.md §M-meta-1 A module cannot contradict the kernel — it can only add rules specific to a substrate, scope, or role. Where a module cites a kernel anchor, the qualifier `PROTOCOL_RULES §Px` makes the cross-file reference explicit. -The kernel (`PROTOCOL_RULES.md`) is canonical. When `CORE_RULES.md` and the kernel disagree, the kernel wins — `CORE_RULES.md` is an index into this file and cannot introduce new authority. See `§P-Access` for the CORE/PROTOCOL division rationale. - Meta-repos maintaining two copies of the framework see `modules/meta-repo.md §M-meta-2`. -## §P3 — State model and multi-agent coordination - -### Three-layer state model *(v2.0.0+)* - -Lead Protocol state is partitioned into three layers with distinct owners and lifecycles. Every file under `.agents/` belongs to exactly one layer. - -| Layer | Owner | Lifecycle | Shared across contributors? | Canonical location | -|---|---|---|---|---| -| **Framework** | Upstream Lead Protocol release | Changes with framework version | Yes — ships in the release ZIP, identical for every project | `.agents/CORE_RULES.md`, `.agents/PROTOCOL_RULES.md`, `.agents/modules/`, `.agents/schemas/`, `.agents/scripts/` | -| **Project** | The consuming project | Changes with project evolution | Yes — versioned with the project repo | `.agents/PROJECT_RULES.md`, `.agents/JOURNAL.md`, `.agents/LESSONS.md`, `.agents/decisions.jsonl`, `.agents/AGENTS_MAP.md`, `.agents/checkpoints/`, `.agents/sessions/` | -| **Actor × Agent** | One human operator running one AI agent | Changes every session | No — isolated per `(actor, agent)` pair, never committed | `.agents/local///handoff.md`, `.agents/local///tasks/TASK.md`, `.agents/local///activity.log`, `.agents/local///lessons.md` | - -### Why the volatile unit is `(actor, agent)`, not `actor` alone - -The primary use case the protocol exists to serve is **multi-agent interchange on the same machine, same user, same project** — e.g., Marco running Claude Code, Codex, Gemini, and Cursor on the same codebase. Keying volatile state only by the human actor would put all four agents on the same `handoff.md` and destroy the very interchange the protocol promises. The smallest unit of concurrency in practice is the pair, not the user. - -Two agents operated by the same actor have independent `handoff.md`, `tasks/TASK.md`, `activity.log`, and personal `lessons.md`. Cross-agent coordination happens through the **shared project layer** — specifically, checkpoints in `.agents/checkpoints/` — never by overwriting a peer's volatile state. - -### Identifying the pair `(actor, agent)` - -**``** — the human operator. Resolution by precedence: - -1. `LEAD_PROTOCOL_ACTOR_ID` (environment variable) — first-class override. Primary use: CI pipelines, DevContainers, Codespaces. -2. `.agents/local/WHOAMI.txt` — persistent per-project override. Nomads who want continuity across machines drop the `@host` suffix by writing just the user here. -3. Ephemeral-environment detection — if `CI`, `GITHUB_ACTIONS`, `CODESPACES`, or `DEVCONTAINER` is set, fall back to `@ephemeral` to avoid writing to a hostname that will not exist tomorrow. -4. Default — `@` derived from `$USERNAME`/`$USER` plus `$COMPUTERNAME`/`hostname`. - -**``** — the AI agent in runtime. Resolution by precedence (no circularity — no source below depends on already knowing ``): - -1. `LEAD_PROTOCOL_AGENT_ID` (environment variable) — explicit override. Recommended in every master prompt where the IDE vendor is known. Canonical when present. -2. `.agents/AGENTS_MAP.md` — project-level shared map of tool signatures to agent slugs. The agent reads its own tool signature (User-Agent, process name, or IDE-exposed tool name) and looks up the slug. -3. Direct self-identification — if the tool signature is not mapped but the agent has a confident self-reported name (e.g., Claude Code exposing its own identifier), use it directly, and **propose** adding the missing mapping to `AGENTS_MAP.md` via an explicit message to the user. The agent never edits `AGENTS_MAP.md` on its own; see *`AGENTS_MAP.md` governance* below. -4. Fallback — `unknown-agent-` under `local//`, with `agent_identity: unresolved` flagged in the handoff. - -**Bootstrap invariant:** `` resolution never reads from `local///` — that path only exists *after* `` is known. Every source in the precedence chain lives in a deterministic location that does not depend on the pair path. - -**Fallback is intentionally unstable.** Every unresolved session from the same tool creates a new `unknown-agent-/` folder, fragmenting continuity. This is deliberate — the fragmentation is a social signal that pushes the user to normalize identity via environment variable or a new `AGENTS_MAP.md` entry. Fallback is a safety valve, not an operating mode. - -### `AGENTS_MAP.md` governance *(v2.0.0+)* - -`.agents/AGENTS_MAP.md` is shared project state, versioned with the project repo, **and maintainer-managed**: - -- The agent never edits `AGENTS_MAP.md` autonomously. When direct self-identification succeeds but the tool signature is not mapped, the agent proposes the addition to the user (`"detected unmapped signature 'X'; add 'X = ' to AGENTS_MAP.md?"`) and waits for explicit confirmation. The human or maintainer commits the change through the normal project channel (git commit, OneDrive sync, etc.). -- Rationale: autonomous mutation of shared versioned state creates silent conflicts and opaque audit trails. Orchestration of agents operates on **explicit commands**, not on inferred state. -- Interaction with the fallback: if the user ignores the proposal, the agent keeps operating under `unknown-agent-/` for every new session. The accumulating folders are the signal — no other nag is needed. - -Not to be confused with the repository-root `AGENTS.md`, which is a universal pointer file for agents (Cursor, Claude Code, Antigravity, etc.) and serves a different purpose — hence the `_MAP` suffix on this file. - -### Resolved path +## §P3 — Multi-agent coordination -Once `` and `` are resolved, volatile state for this session lives under: - -``` -.agents/local///handoff.md -.agents/local///tasks/TASK.md -.agents/local///activity.log -.agents/local///lessons.md -``` - -`.agents/local/` is always gitignored (see the template `.gitignore`). It never travels between contributors. - -### Append-at-tail rule (concurrency-safe writes) - -Every shared project-layer file that grows over time — `JOURNAL.md`, `LESSONS.md`, `decisions.jsonl`, and each actor's personal `activity.log` — is **append-only at the end of the file**. Prepending (adding at the top) requires reading and rewriting the full file, which corrupts under simultaneous writes on a synced folder (OneDrive, Google Drive). Append at the tail is the only operation that is reasonably safe across every supported substrate (git, cloud-sync, local-only). - -Consequences: - -- `JOURNAL.md` reads oldest-first, newest-last. Agents consult recent entries via `tail -n N` or the functional equivalent, not `head`. There is no top-of-file index to drift. -- `LESSONS.md` has no top-of-file table of contents. Queries go through `grep` over inline tags (`grep -A 10 "tags:.*rate-limit" LESSONS.md`). -- `decisions.jsonl` is JSON Lines, one object per line (see *Decisions log* below), not a JSON array — a JSON array cannot be appended to atomically. - -### Handoff schema (`local///handoff.md`) — strict, always overwritten +### Handoff schema (`agent_log/handoff.md`) — strict, always overwritten ```markdown # handoff.md — Current operational state @@ -120,19 +49,17 @@ Consequences: **Open Threads:** **Session close checklist (self-verified):** -- [ ] `activity.log` contains an entry for this session -- [ ] `decisions.jsonl` appended (if any decision was made) -- [ ] `local///lessons.md` appended (if a personal lesson emerged) -- [ ] `LESSONS.md` appended (if a project-level lesson emerged) -- [ ] `JOURNAL.md` appended (if the session produced a structurally significant delivery) +- [ ] `activity_YYYY-MM.md` contains an entry for this session +- [ ] `decisions.json` appended (if any decision was made) +- [ ] `agent_lessons.md` appended (if an agent-level lesson emerged) +- [ ] `tasks/lessons.md` appended (if a project-level lesson emerged) - [ ] Commit(s) follow `[Agent] : ` convention - [ ] Version bumps applied to any rules file whose content changed - [ ] `active_sessions.md` row for this session removed (if registry is in use) +- [ ] Session-close state written on the feature branch before the PR is opened (when substrate uses pull requests — see §M-git-5) ``` -Schema is immutable — no agent may add sections, tables, or free paragraphs. Timestamp must include HH:MM. The session close checklist is **part of the schema**; each box is self-verified by the agent before closing. Unchecked boxes signal incomplete close to the next agent. - -Each pair `(actor, agent)` has its own `handoff.md` — agents operated by the same actor never compete for writes on the same file. When the owner wants to hand context from one agent to another, the path is **publishing a checkpoint in `.agents/checkpoints/`**, not overwriting the peer's handoff. +Schema is immutable — no agent may add sections, tables, or free paragraphs. Timestamp must include HH:MM. The session close checklist is **part of the schema** (added in Lead Protocol v1.5.0; `active_sessions.md` entry added in v1.6.0) — each box is self-verified by the agent before closing. Unchecked boxes signal incomplete close to the next agent. Projects that distribute pristine handoff templates (placeholder-populated, not yet in use) see `modules/meta-repo.md §M-meta-4`. @@ -140,40 +67,37 @@ Projects that distribute pristine handoff templates (placeholder-populated, not | Condition | Behavior | |---|---| -| Timestamp **< 30 min ago** AND no peer session live in `active_sessions.md` for the same `(actor, agent)` pair | Do not proceed. Assume prior agent is still active. | -| Timestamp **< 30 min ago** AND a different pair is live in `active_sessions.md` | Two pairs are legitimately concurrent. Do NOT take over — see *Concurrent sessions* below. | -| Timestamp **≥ 30 min ago** | Assume interrupted. Record takeover in `decisions.jsonl` with rationale `"Takeover: previous session assumed interrupted (>30min)"`. Run recovery mode before proceeding. | +| Timestamp **< 30 min ago** AND no peer session live in `active_sessions.md` | Do not proceed. Assume prior agent is still active. | +| Timestamp **< 30 min ago** AND a different session is live in `active_sessions.md` | Two sessions are legitimately concurrent. Do NOT take over — see §P3 concurrent sessions. | +| Timestamp **≥ 30 min ago** | Assume interrupted. Record takeover in `decisions.json` with rationale `"Takeover: previous session assumed interrupted (>30min)"`. Run recovery mode before proceeding. | | Timestamp **< 30 min** + explicit human override | Proceed. Rationale: `"Forced takeover: human override"`. | -Takeover is scoped to the `(actor, agent)` pair's own `handoff.md`. A peer pair's recent activity never triggers a takeover of your own handoff. - ### Recovery mode Before continuing a prior `Pending Step`: - -1. Read the last entry in `.agents/decisions.jsonl` (tail the file; `decisions.jsonl` is append-only). +1. Read the last entry in `decisions.json`. 2. Spot-check files listed in `files_affected`. 3. If state is inconsistent (missing headers, version conflicts, half-written content): fix or revert first — never build on corrupted state. -4. Log the recovery action in `decisions.jsonl`. - -Meta-repos with two `decisions.jsonl` files (IDE vs. template) see `modules/meta-repo.md §M-meta-3`. - -### Decisions log (`.agents/decisions.jsonl`) — append-only, immutable - -`decisions.jsonl` is **JSON Lines** — one JSON object per line, no enclosing array, no comma between entries. The canonical schema for a single entry is `schemas/decisions.entry.schema.json` (introduced in v2.0.0). The pre-v2 array-form `decisions.schema.json` is removed, not kept as a legacy alias, so there is no ambiguity about which schema is authoritative. - -```jsonl -{"timestamp":"2026-04-21T15:30:00","agent":"[Claude Code / claude-opus-4-7]","decision":"Short imperative","rationale":"Why","files_affected":["path/to/file.md"],"status":"completed"} -{"timestamp":"2026-04-21T16:05:00","agent":"[Codex / GPT-5.4]","decision":"...","rationale":"...","files_affected":[],"status":"completed"} +4. Log the recovery action in `decisions.json`. + +Meta-repos with two `decisions.json` files (IDE vs. template) see `modules/meta-repo.md §M-meta-3`. + +### Decisions log (`agent_log/decisions.json`) — append-only, immutable + +```json +[ + { + "timestamp": "2026-04-17T15:30:00", + "agent": "[Claude Code / claude-opus-4-6]", + "decision": "Short imperative", + "rationale": "Why", + "files_affected": ["path/to/file.md"], + "status": "completed" + } +] ``` -Why JSONL, not a JSON array: - -1. **Atomic append.** Adding a decision is writing one line at the end — no read, parse, re-serialize, rewrite. Two contributors appending from a synced folder in the worst case reorder lines; the file remains structurally valid. -2. **Cheap line-by-line query.** Agents grep or filter line-by-line without loading the full file — consistent with the demand-load contract in `§P-Access`. -3. **Scales past the point a JSON array becomes an anti-pattern.** A 200-entry JSON array is unreadable without tooling; 200 JSONL lines are trivially filterable. - -Never edit past entries. If the file is corrupted (a line is not valid JSON), the recovery agent fixes the structure before appending new entries. +Never edit past entries. If the JSON is corrupted, the recovery agent fixes structure before appending. ### Commit convention @@ -183,72 +107,81 @@ Never edit past entries. If the file is corrupted (a line is not valid JSON), th Where `[Agent]` is `[Claude]`, `[Cursor]`, `[Codex]`, etc., and `` is `feat|fix|refactor|docs|ops|chore`. This convention is substrate-neutral — it applies whether the underlying system is git, a cloud-sync folder, or any other change-tracked substrate. Substrate-specific workflows (branching, pull requests, CI) live in substrate modules such as `modules/git-substrate.md`. -### Session close ritual *(v1.5.0+, updated in v2.0.0)* +### Session close ritual *(v1.5.0+)* A **"non-trivial session"** is one where any of the following occurred: - A change was committed (by the active substrate's commit mechanism) - A review/approval artifact was opened, updated, or merged (when a substrate module defines one) -- A file outside `.agents/local///` was modified +- A file outside `agent_log/` was modified - A product, strategy, or architectural decision was made -- A user-facing deliverable was shipped +- A user-facing deliverable was shipped (listing, pin, copy, export) At the end of a non-trivial session, the agent **must** update every applicable artifact below **and** check the corresponding box in the `handoff.md` session close checklist: | Artifact | Mandatory trigger | Skip if | |---|---|---| -| `local///handoff.md` | Always | Never skipped | -| `local///activity.log` | Any session activity worth remembering locally | Pure read-only Q&A that produced nothing reusable | -| `.agents/decisions.jsonl` | A decision was made, a file was created/renamed/deleted, or a version was bumped | No decisions and no file state changed | -| `local///lessons.md` | A **personal** lesson emerged (about how this actor × agent pair works) | No personal lesson emerged | -| `.agents/LESSONS.md` | A **project-level** lesson emerged (applies to any actor working here) | No project-level lesson emerged | -| `.agents/JOURNAL.md` | The session produced a **structurally significant delivery** (see promotion rule below) | Routine activity, small fixes, exploration | -| `.agents/sessions/active_sessions.md` | Registry is in use and this session has an open row | Registry not in use, or no open row | +| `handoff.md` | Always | Never skipped | +| `decisions.json` | A decision was made, a file was created/renamed/deleted, or a version was bumped | No decisions and no file state changed | +| `activity_YYYY-MM.md` | A commit, review artifact, or major artifact change occurred | Pure reads / inspection / Q&A sessions | +| `agent_lessons.md` | An **agent-level** lesson emerged (format drift, tool failure, recovery incident, cross-agent coordination pattern) | No new agent-level lesson | +| `tasks/lessons.md` | A **project-level** lesson emerged (bug pattern, process flaw, systemic decision criterion) | No new project-level lesson | +| `active_sessions.md` | Registry is in use and this session has an open row | Registry not in use, or no open row | + +### Branch ordering rule *(v1.9.2+)* -**JOURNAL promotion — procedural, not heuristic.** At session close, the agent asks the user exactly one procedural question: *"Did this session produce a structurally significant delivery? If yes, promote to JOURNAL."* The user replies with one word. No background detection, no heuristic guessing — orchestration of agents operates on **explicit commands**, never on state inference. The criterion for a "yes" is the six-month test: *if a new contributor arriving in six months would still benefit from seeing this entry, it belongs in JOURNAL; otherwise it belongs only in the actor's personal `activity.log`*. +Session close is the **final operational step on the feature branch**. Complete all session-close artifacts — handoff, decisions, lessons, and journal updates — before opening or merging the pull request. + +**Why this order matters:** if session-close state is written on the default branch after merge, protected-branch settings may block the write or force a follow-up PR for state files only. This creates unnecessary review overhead and an audit gap where the handoff describes work that is not yet in the branch history. + +**Implementation rule:** the session-close checklist in `handoff.md` is complete (all boxes checked) when the pull request is **opened**, not after it merges. Agents must not mark the session closed and then create a separate follow-up PR to write state files. + +This rule is substrate-neutral. Git-specific enforcement and rationale live in the active substrate module (see `modules/git-substrate.md §M-git-5`). **Verification step (mandatory before closing):** -Before the final response of the session, the agent verifies that each *applicable* artifact carries today's date. The implementation is substrate-agnostic — shell grep, file tooling with date filtering, or a direct read-and-check — whichever is cheapest in the active environment. If an applicable artifact does not carry today's date, the update was skipped — fix before closing. +Before the final response of the session, the agent runs: + +```bash +grep -l "YYYY-MM-DD" .agents/agent_log/*.md .agents/agent_log/*.json tasks/*.md +``` + +(substituting `YYYY-MM-DD` with today's date) and confirms that each *applicable* artifact appears in the output. If an applicable artifact does not appear, the update was skipped — fix before closing. -**Personal vs project-level lessons — decision rule:** +**Agent-level vs project-level lessons — decision rule:** -- `local///lessons.md` captures lessons **about how this specific pair operates**: this agent's tool-failure modes with this actor's workflow, recovery protocols specific to the IDE, format drift noticed by this agent, cross-agent coordination patterns. Example: *"Marco tends to forget to run migrations before testing — remind next session"*. -- `.agents/LESSONS.md` captures lessons **about the project or domain**: any actor working on this project needs to know this. Systemic mistakes, decision criteria, recurring bug patterns, process fixes. Example: *"External API Z rate-limits aggressively in staging (5 req/s vs 50 req/s in prod); set a 30s timeout"*. +- `agent_lessons.md` captures lessons **about how agents operate**: format drift, tool failure modes, recovery protocols, cross-agent coordination patterns. Examples: "the file-reader cache got confused after a rename", "I took an attribute dropdown value as ground truth without cross-checking". +- `tasks/lessons.md` captures lessons **about the project or domain**: systemic mistakes, decision criteria, recurring bug patterns, process fixes. Examples: "anchor election from local sales data underweights cross-shop demand", "lessons about customer behavior, pricing elasticity, or category positioning". -When in doubt, a lesson is project-level if removing the specific pair would still leave the lesson valid. If the lesson is about *how this agent or this actor works*, it is personal. +When in doubt, a lesson is project-level if removing the specific agent would still leave the lesson valid. If the lesson is about *how the agent failed as an agent*, it is agent-level. -### Concurrent sessions and mid-session checkpoints *(v1.6.0+, updated in v2.0.0)* +### Concurrent sessions and mid-session checkpoints *(v1.6.0+)* -Real-world tooling (multiple IDEs, multiple agents, multiple terminals rooted at the same repo) routinely runs more than one session live at a time — indeed, this is the primary use case for the protocol. Two mechanisms keep concurrent sessions legible without breaking any schema. +The v1.5 takeover rule assumes at most one session is live per repo at any time. Real-world tooling (multiple IDEs, multiple agents, multiple terminals rooted at the same repo) routinely breaks this assumption. Two additions address concurrent sessions and mid-session cross-agent consultation without breaking any existing schema. -**Active sessions registry** — `.agents/sessions/active_sessions.md` +**Active sessions registry** — `.agents/agent_log/sessions/active_sessions.md` -A flat markdown table, one row per live session. The agent appends its row on session start and removes the row on session close (session close checklist item). +Optional but recommended when more than one agent may operate on the repo. A flat markdown table, one row per live session. The agent appends its row on session start and removes the row on session close (session close checklist item). Schema — immutable columns: ```markdown # active_sessions.md — Sessions currently live > Append row on session start. Remove row on session close. -> Stale rows (>24h with no checkpoint update) may be removed by any next agent with a decisions.jsonl log. +> Stale rows (>24h with no checkpoint update) may be removed by any next agent with a decisions.json log. | Session ID | Agent | Started | Topic | Last checkpoint | |---|---|---|---|---| -| 2026-04-21-1310-claude | [Claude Code / claude-opus-4-7] | 2026-04-21 13:10 | <1-line topic> | | +| 2026-04-19-1310-claude | [Claude Code / claude-opus-4-7] | 2026-04-19 13:10 | <1-line topic> | | ``` **Session ID format:** `YYYY-MM-DD-HHMM-`. The `` suffix (`claude`, `gemini`, `cursor`, `codex`, etc.) prevents ID collision when two agents boot in the same minute. -**Effect on takeover rule:** when `active_sessions.md` exists and holds a row for a peer session whose Started timestamp is within the last 30 minutes OR whose Last checkpoint is within the last 30 minutes, the current agent MUST NOT take over the peer's own pair state. Concurrent sessions are legitimate — append a new row for the current session instead. Takeover of your own handoff, gated by the 30-minute rule, continues to apply. - -**Mid-session checkpoints** — `.agents/checkpoints/YYYY-MM-DDTHHMMSS__.md` - -A checkpoint is a pre-execution snapshot written voluntarily by the agent at the owner's request (or proactively when the agent is about to take an action that would benefit from a second opinion). Checkpoints are ephemeral working notes — authoritative state lives in `handoff.md`, `decisions.jsonl`, and project files. +**Effect on takeover rule:** when `active_sessions.md` exists and holds a row for a peer session whose Started timestamp is within the last 30 minutes OR whose Last checkpoint is within the last 30 minutes, the current agent MUST NOT take over. Concurrent sessions are legitimate — append a new row for the current session instead. The `handoff.md` 30-minute takeover rule remains in effect only when `active_sessions.md` is absent or empty. -Checkpoints remain at the **project layer**, shared, not inside `local/`. The whole point of a checkpoint is that any peer agent in the repository can find and read it; moving checkpoints into per-pair private space would defeat the multi-agent consultation pattern that justifies the protocol in the first place. +**Mid-session checkpoints** — `.agents/agent_log/checkpoints/YYYY-MM-DD-HHMM-.md` -**Unique name convention:** `YYYY-MM-DDTHHMMSS__.md`. Timestamp at second precision plus the `` slug guarantee uniqueness even when two agents checkpoint the same topic on the same day. The title slug is a human-readable affix; uniqueness comes from timestamp plus agent, not from the slug. +A checkpoint is a pre-execution snapshot written voluntarily by the agent at the owner's request (or proactively when the agent is about to take an action that would benefit from a second opinion). Checkpoints are ephemeral working notes — authoritative state lives in `handoff.md`, `decisions.json`, and project files. Template — content must be self-contained so a peer agent reads it without the conversation transcript: @@ -271,115 +204,38 @@ Template — content must be self-contained so a peer agent reads it without the ``` -**Usage pattern:** when the owner asks for a second opinion from a peer agent, the current agent writes the checkpoint and updates the `Last checkpoint` column of its row in `active_sessions.md`. The owner opens the peer agent in another window; the peer agent boots per `§P5`, sees the fresh checkpoint referenced in `active_sessions.md`, reads it, and responds with contrarian input. No copy-paste required. +**Usage pattern:** when the owner asks for a second opinion from a peer agent, the current agent writes the checkpoint and updates the `Last checkpoint` column of its row in `active_sessions.md`. The owner opens the peer agent in another window; the peer agent boots per §P5, sees the fresh checkpoint referenced in `active_sessions.md`, reads it, and responds with contrarian input. No copy-paste required. -**Retention:** no automatic retention policy. Checkpoints accumulate as an audit trail. If `.agents/checkpoints/` grows beyond practical limits, the project may adopt a retention rule in `PROJECT_RULES.md §J8`. +**Retention:** no automatic retention policy. Checkpoints accumulate as an audit trail. If the `checkpoints/` directory grows beyond practical limits, the project may adopt a retention rule in `PROJECT_RULES.md §J8`. **Scope limits:** - - The registry is advisory, not a lock. It does not prevent two agents from editing the same file concurrently — resolve conflicts per the active substrate module. -- Checkpoints do not replace `handoff.md`. They coexist: checkpoint = live snapshot of an in-progress decision; handoff = authoritative state at session close for one pair. -- Neither the registry nor checkpoints are required when only one agent ever operates on the repo. Single-pair projects may leave `active_sessions.md` empty and never write a checkpoint. - -## §P-Access — Load-on-demand access protocol *(v2.0.0+)* - -Every session that boots an agent pays a token cost proportional to what it reads. Real-world Lead Protocol usage involves many sessions per day per project. A naive "read everything to be safe" policy multiplies that cost by the size of the historical record and makes the protocol unviable at scale. `§P-Access` specifies what the agent reads up front, what it reads on demand, and how to keep baseline cost bounded. - -### Division of authority between CORE and PROTOCOL - -For the baseline to stay light without creating a split-brain of governance, the two framework files divide responsibilities by **level of detail**, not by authority: - -- **`CORE_RULES.md`** — what the agent **must know to operate correctly at every session start**. Protocol index, essential contracts (three-layer state model, `(actor, agent)` identification, append-at-tail, checkpoints as shared coordination), pointers to the detailed sections in this file. Size budget: **under 5k tokens**. Mandatory in the baseline load. -- **`PROTOCOL_RULES.md`** — detail, schemas, recovery procedures, edge cases, threat model, cross-repo semantics. Consulted **on demand**, when the agent hits a situation whose handling CORE points here for. - -**Governance invariant:** `CORE` does not repeat `PROTOCOL` — it references. If the agent finds a conflict between `CORE` and `PROTOCOL`, `PROTOCOL` wins (see `§P2`). The split is editorial, not authoritative. - -### Baseline load (every session, budget ~5–8k tokens) - -Read order matters: the `(actor, agent)` pair must be resolved *before* the pair-specific handoff path can be formed. That forces `AGENTS_MAP.md` to precede the handoff in the boot sequence. - -1. `.agents/CORE_RULES.md` — index plus essential contracts. -2. `.agents/PROJECT_RULES.md` — project identity. -3. `.agents/modules/.md` — for each scope listed in `§J8 Active modules` (in declaration order). -4. `.agents/AGENTS_MAP.md` — tool-signature → agent-slug map. Required to resolve `` before the handoff path can be formed. -5. `.agents/sessions/active_sessions.md` — concurrent-session awareness, needed before any write to the pair's handoff. -6. `.agents/local///handoff.md` — state of this pair. Only accessible once `` is resolved. -7. Listing (not reading) of `.agents/checkpoints/` — the agent knows which checkpoints exist and reads individual files on demand when they become relevant. - -### On-demand load contract (substrate-agnostic) - -The protocol prescribes **behavior** ("do not process more than is necessary to answer the current question"), not tooling. The agent picks the cheapest implementation available in its environment. A refined implementation (native offset reads) costs fewer tokens; a minimal implementation (load whole file, filter in-prompt) still satisfies the contract — it pays more, but semantics are identical. Whatever the substrate, the following access pattern applies: - -| Artifact | Pattern | -|---|---| -| `JOURNAL.md`, `local///activity.log` | Read the **last N lines** (files are append-at-tail, recent entries at the end). Implementation: offset-from-end read, `tail -n`, or equivalent. | -| `LESSONS.md` | **Grep on inline tags** (e.g., `grep -A 10 "tags:.*rate-limit" LESSONS.md`). There is no manual top-of-file index. Sequential tail reading only when no specific tag is known. | -| `decisions.jsonl` | Filter by topic / actor / date. Implementation: line-level grep, `jq`, or in-memory filter. | -| `PROTOCOL_RULES.md` | Only when invoked explicitly by reference from `CORE_RULES.md`. Not loaded up front. | -| `.agents/checkpoints/.md` | Read on demand by specific filename (typically listed in `active_sessions.md → Last checkpoint` or recommended by the owner). Never load the whole directory preemptively. | - -**Absolute rule:** never load a historical file in full without a specific justification tied to the current question. *"My tooling has no offset read"* is not a justification — it is an implementation limitation to work around via shell (`tail`, `grep`) or in-memory filter. If the agent cannot do better than a full load, it pays the cost explicitly once and does not let that pattern become the default. - -### File-size targets - -- `JOURNAL.md` active file: **< ~500 lines**. Move older entries into `archive/JOURNAL-.md` when exceeded. -- `LESSONS.md` active file: **< ~300 lines**. Move older entries into `archive/LESSONS-.md` when exceeded. -- `activity.log`: no hard limit — the agent reads only the last N lines. Monthly rotation into `activity_YYYY-MM.log` is optional. - -### Where to find more - -Detailed schemas for the state files listed above live in `.agents/schemas/` (when the project ships that directory). Substrate-specific access additions — e.g., a meta-repo's dual-copy layout or a git-substrate's PR-triggered validation — live in the corresponding module files under `.agents/modules/`. - -## §P-Threat — Threat model *(v2.0.0+)* - -The protocol is narrow about what it guarantees. Overselling guarantees is how agents and humans misplace trust. - -### The protocol guarantees - -- **Isolation of session state per `(actor, agent)` pair.** `handoff.md`, `TASK.md`, `activity.log`, and personal `lessons.md` of a pair are never overwritten by another pair — even on the same machine, even for the same human actor. -- **No leak of personal state through a shared git repository** when the template's `.gitignore` (which excludes `.agents/local/`) is respected. -- **Best-effort append-at-tail safety for shared files.** `JOURNAL.md`, `LESSONS.md`, `decisions.jsonl`, and activity logs are appended only at the end. This minimizes the concurrent-write window and prevents structural corruption (truncated arrays, overwritten headers). Individual lines may be lost if two writes coincide on the exact same instant in a synced folder, but the file remains valid and readable. - -### The protocol does NOT guarantee - -- **Zero line loss under simultaneous writes on a cloud-sync folder.** OneDrive, Google Drive, and similar substrates can drop one of two lines written in the same instant. Mitigations: unique names for per-file artifacts (checkpoints never collide), social coordination for shared append-only files, and the actor's own `activity.log` as a personal fallback trace. -- **Confidentiality between actors who voluntarily share a folder.** A OneDrive folder shared between Marco and João is technically visible to both; the protocol isolates state at the file level (no overwrite) but not at the content level (no hidden files from a folder sibling). That is IT hygiene, not protocol design. -- **Encryption of state files.** -- **Granular per-file access control.** -- **Read auditing.** -- **Distributed locking or automatic conflict resolution.** - -### Deployment recommendations from the threat model - -- **One actor, many agents** (primary product use case): any substrate works well — OneDrive, standalone folder, GitHub. -- **Many actors, active simultaneous development**: GitHub is the recommended substrate. OneDrive is feasible with social coordination on append-only files. -- **Strict isolation between actors required** (confidentiality, compliance): use separate Git repositories or enforce access at the IT layer. Lead Protocol does not implement this level of isolation. +- Checkpoints do not replace `handoff.md`. They coexist: checkpoint = live snapshot of an in-progress decision; handoff = authoritative state at session close. +- Neither the registry nor checkpoints are required when only one agent operates on the repo. Projects may opt into v1.6 features via `PROJECT_RULES.md §J8`. ## §P4 — Generic quality checklist Before closing any significant action: - - [ ] Persona/agent signature present in every recorded change and in `handoff.md` -- [ ] `local///handoff.md` overwritten with current state (Status, Timestamp HH:MM, Last Action, Pending Step, session close checklist) -- [ ] `.agents/decisions.jsonl` appended with rationale and files_affected (if applicable per `§P3` session close ritual) -- [ ] `local///activity.log` appended with one line per logical action (if applicable per `§P3` session close ritual) -- [ ] If a new **personal** pattern/bug learned → append to `local///lessons.md` -- [ ] If a new **project-level** pattern/bug learned → append to `.agents/LESSONS.md` -- [ ] JOURNAL promotion question asked; if user says yes → append to `.agents/JOURNAL.md` -- [ ] Commit record follows `[Agent] : ` convention (`§P3`) +- [ ] `handoff.md` overwritten with current state (Status, Timestamp HH:MM, Last Action, Pending Step, session close checklist) +- [ ] `decisions.json` appended with rationale and files_affected (if applicable per §P3 session close ritual) +- [ ] `activity_YYYY-MM.md` appended with one line per logical action (if applicable per §P3 session close ritual) +- [ ] If a new **agent-level** pattern/bug learned → append to `agent_log/agent_lessons.md` +- [ ] If a new **project-level** pattern/bug learned → append to `tasks/lessons.md` +- [ ] Commit record follows `[Agent] : ` convention (§P3) - [ ] Version bumps applied to any rules file or module whose content changed -- [ ] Session close checklist in `handoff.md` fully verified (today-date verification per `§P3`) -- [ ] If `.agents/sessions/active_sessions.md` is in use, the row for this session has been removed +- [ ] Session close checklist in `handoff.md` fully verified (`grep` confirmed entries exist per §P3) +- [ ] If `active_sessions.md` is in use, the row for this session has been removed (per §P3 concurrent sessions) - [ ] Any additional checks required by an active module have been satisfied ## §P5 — Operational model (generic) -- Every agent reads, on session start, in order: `CORE_RULES.md` → `PROJECT_RULES.md` → each active module → `AGENTS_MAP.md` → `sessions/active_sessions.md` → `local///handoff.md`. See `§P-Access` for the full baseline load. +- Every agent reads `CORE_RULES.md` → `PROTOCOL_RULES.md` (kernel) → `PROJECT_RULES.md` → each module file listed in `§J8 Active modules` (in declaration order) → `handoff.md` on session start. +- Additionally (v1.6.0+), when `agent_log/sessions/active_sessions.md` exists, the agent reads it to detect concurrent peer sessions. If a peer session has a Last checkpoint referenced, the agent reads the latest checkpoint in `agent_log/checkpoints/` before responding to the owner. - The active Session Protocol level (1/2/3), the active substrate, and the list of active modules are declared in `PROJECT_RULES.md §J8`. - Edits to framework files (`PROTOCOL_RULES.md` kernel, any module file) only happen via methodology upgrade — never ad-hoc. - Edits to business files (`PROJECT_RULES.md`, project reference docs) happen per project rules in `§J8`. -- `.agents/AGENTS_MAP.md` is maintainer-managed. Agents propose additions; humans commit them. See `§P3` *`AGENTS_MAP.md` governance*. -- Language: operational files (`CORE_RULES`, `PROTOCOL_RULES`, `PROJECT_RULES`, module files, `handoff`, `decisions.jsonl`, `JOURNAL`, `LESSONS`, `activity.log`, `AGENTS_MAP`, `active_sessions`, checkpoints) are always EN-US. +- Language: operational files (`CORE_RULES`, `PROTOCOL_RULES`, `PROJECT_RULES`, module files, `handoff`, `decisions`, `agent_lessons`, `activity`, `active_sessions`, `checkpoints`) are always EN-US. - Additional module-specific boot steps may apply — see each active module's header. ## §P6 — Cross-repository references @@ -412,7 +268,7 @@ Both tiers are **optional** — projects without sensitive context at the corres 1. **Private context repo** lives separately from any repo shared with a wider audience. Owner-level private context lives in a personal private repo (e.g., `owner/private-context`); organizational-level confidential context lives in a directors-only repo (e.g., `org/business-vault`). 2. **Consuming repos** (team-shared project repos, documentation repos) reference the private repo only by name in `§J6`, with explicit rule: `"Never copy content from this repo into [consuming repo] or any repo with a wider audience."` 3. **Harness local memory** (e.g., `~/.claude/projects/*/memory/`) may contain a lightweight summary + pointer to the private repo. Never the full content — avoid duplication and drift. -4. **The private repo** must follow the full Lead Protocol (`.agents/`, `PROTOCOL_RULES.md`, `PROJECT_RULES.md`, `handoff.md`, `decisions.jsonl`) like any other project. +4. **The private repo** must follow the full Lead Protocol (`.agents/`, `PROTOCOL_RULES.md`, `PROJECT_RULES.md`, `handoff.md`, `decisions.json`) like any other project. 5. **Content that belongs in the personal private repo (`private-context`):** owner's identity, personal strategic goals, permanent personal decisions, personal lessons learned, personal digital presence, family/health/financial context. 6. **Content that belongs in the organizational private repo (`business-vault`):** company financials, strategic plans not yet public, personnel and compensation, legal matters under privilege. 7. **Content that belongs in the team-shared repo:** methodology, system architecture, runbooks, product technical decisions, team operational context. @@ -426,7 +282,7 @@ The kernel above is substrate-agnostic and role-agnostic. Substrate-specific and - `.agents/modules/.md` — one file per module; `` is lowercase kebab-case. - `.agents/modules/README.md` — one-paragraph index listing available modules. -- Each module file carries its own `> Version: X.Y.Z` header and bumps per `§P1` independently of the kernel. +- Each module file carries its own `> Version: X.Y.Z` header and bumps per §P1 independently of the kernel. ### Anchor convention @@ -445,7 +301,7 @@ A module is in effect if and only if its scope appears in `Active modules`. Acti ### Boot -Agents read active modules after `PROJECT_RULES.md` and before `AGENTS_MAP.md` / `sessions/active_sessions.md` / `handoff.md`, in the order listed in `§J8 Active modules`. See `§P-Access` for the full baseline load sequence. +Agents read active modules after `PROJECT_RULES.md` and before `handoff.md`, in the order listed in `§J8 Active modules`. See §P5 for the full boot sequence. ### Authoring rules @@ -453,3 +309,7 @@ Agents read active modules after `PROJECT_RULES.md` and before `AGENTS_MAP.md` / - When a module cites a kernel anchor, use the fully qualified form `PROTOCOL_RULES §Px` to mark the module→kernel crossing explicitly. - A module may depend on another module only if it declares the dependency in its header. - Module CI/tooling (if any) must include a top-of-file comment identifying the module it enforces, so consumer repos that do not list the module know not to copy the tooling. + +### Relation to earlier opt-in language + +The field historically called `Active optional modules` in `PROJECT_RULES.md §J8` (introduced v1.6 for the concurrent-session registry feature flag) is renamed to `Active modules` in v1.9.0. The semantic shift is deliberate: v1.6 used the field to toggle a kernel-internal feature; v1.9 uses the field to activate external rule files. Projects upgrading from v1.8 or earlier move any v1.6 feature-flag values into the new `Active modules` field, or drop them if the feature is now part of the kernel by default. diff --git a/.agents/modules/git-substrate.md b/.agents/modules/git-substrate.md index 414420d..a2932d1 100644 --- a/.agents/modules/git-substrate.md +++ b/.agents/modules/git-substrate.md @@ -1,6 +1,6 @@ # modules/git-substrate.md — Git / pull-request substrate rules -> Version: 1.1.0 | Updated: 2026-04-21 | Protocol: Lead Protocol v2.0.0+ +> Version: 1.1.0 | Updated: 2026-06-01 | Protocol: Lead Protocol v1.9.2+ > Scope: Opt-in module. Activate via `PROJECT_RULES.md §J8 Active modules: git-substrate`. > Applies to: repositories hosted on a git platform with pull-request support (GitHub, GitLab, Bitbucket, etc.). @@ -14,11 +14,9 @@ This module extends `PROTOCOL_RULES.md` with rules specific to projects whose su |---|---| | Executable code (`.py`, `.js`, `.ts`, `.html`, `.css`) | Yes | | Agent configuration (`CORE_RULES.md`, `CLAUDE.md`, `AGENTS.md`, workflow YAML) | Yes | -| Framework files (`PROTOCOL_RULES.md`, `modules/*.md`, `schemas/*`, `scripts/*`) | Yes | -| `AGENTS_MAP.md` (shared, maintainer-managed) | Yes | -| Documentation, logs | No — direct commit allowed | -| Project state files (`JOURNAL.md`, `LESSONS.md`, `decisions.jsonl`, `checkpoints/*`, `sessions/active_sessions.md`) | No — operational project state, direct commit | -| Per-pair state (`local///*`) | **Never committed** — gitignored per the template `.gitignore` | +| Framework files (`PROTOCOL_RULES.md`, `modules/*.md`) | Yes | +| Documentation, logs, operational data | No — direct commit allowed | +| `handoff.md`, `decisions.json`, activity logs, `active_sessions.md`, checkpoints | No — operational state, direct commit | Branch names follow the project's convention declared in `PROJECT_RULES.md §J8` (e.g., `claude/` for AI-authored work, `feat/` / `fix/` for human work). @@ -30,11 +28,11 @@ Expected flow: `branch → commit → push → PR → merge via platform → del This rule does not apply to: -- Changes with direct commit allowed per §M-git-1 (project state files, docs). -- Repositories without a remote. -- Repositories whose hosting platform does not support pull requests (for those, drop this module from `§J8`). +- Changes with direct commit allowed per §M-git-1 (handoff, decisions, docs, activity logs, active_sessions, checkpoints) +- Repositories without a remote +- Repositories whose hosting platform does not support pull requests (for those, drop this module from `§J8`) -**Platform branch protection overrides this clause.** When the hosting platform enforces branch protection requiring a pull request for *all* changes to the default branch (including project state files), the platform rule wins — open a short-lived PR even for JOURNAL/decisions updates. The §M-git-1 risk-based table is the module's recommendation, not a hard override of platform policy. +**Platform branch protection overrides this clause.** When the hosting platform enforces branch protection requiring a pull request for *all* changes to the default branch (including state files), the platform rule wins — open a short-lived PR even for handoff/decisions updates. The §M-git-1 risk-based table is the module's recommendation, not a hard override of platform policy. ## §M-git-3 — Public-facing documentation sync @@ -50,10 +48,6 @@ Scope: this rule applies only to `.agents/PROTOCOL_RULES.md`. Changes to `PROJEC The `PROTOCOL_RULES §P3` commit convention (`[Agent] : `) applies verbatim in git. No substrate-specific additions. -## §M-git-5 — `.gitignore` baseline - -The template ships a `.gitignore` that ignores `.agents/local/`. This is non-negotiable for git-substrate projects: committing per-pair state leaks personal context and creates spurious merge conflicts on every session. If a project using this module lacks the line `.agents/local/` in its `.gitignore`, treat the omission as a bug and fix it before any session close that would commit state. - ## Optional tooling that ships with the template These files are included in the template as conveniences for projects whose substrate is `git+github` and that use common Python-ecosystem tooling. They are **opt-in** — deleting them breaks nothing in the kernel or in this module's rules: @@ -61,7 +55,17 @@ These files are included in the template as conveniences for projects whose subs - `.pre-commit-config.yaml` (at template root) — pre-commit.com scaffold that wires `validate_state.py` as a pre-commit hook. Safe to delete if you use a different hook manager (husky, lefthook) or no hook manager. - `.agents/scripts/.pre-commit-hooks.yaml` — hook manifest for publishing this repo as a reusable pre-commit source (so downstream projects can `- repo: https://github.com/…/lead-protocol`). Safe to delete if you are not distributing hooks. -The framework validator itself (`.agents/scripts/validate_state.py`) is **not** opt-in — it is part of the framework and runs independently of any hook tooling (e.g., invoked manually or from CI). The migration script `.agents/scripts/migrate_to_v2.py` is also part of the framework (one-time v1.x → v2.0.0 upgrade tool) and not opt-in. +The framework validator itself (`.agents/scripts/validate_state.py`) is **not** opt-in — it is part of the framework and runs independently of any hook tooling (e.g., invoked manually or from CI). + +## §M-git-5 — Session close ordering before PR merge *(v1.1.0+)* + +All session-close state — handoff, decisions, activity, lessons — must be committed on the **feature branch** before the pull request is opened. Writing operational state to the default branch after merge is not permitted. + +**Rationale:** the default branch is typically protected (all writes require a PR). State committed after merge requires a follow-up PR for files that carry no meaningful code diff, splitting the audit trail from the work it documents and creating noise in the review history. + +**Agent rule:** the session-close checklist in `handoff.md` must be fully checked before the PR is opened — not after. The last commit on the feature branch before `git push` should include the updated `handoff.md` and any `decisions.json` / `activity` entries for the session. See PROTOCOL_RULES §P3 branch ordering rule for the substrate-neutral statement. + +**Reviewer signal:** if a PR modifies only operational state files (`handoff.md`, `decisions.json`, `activity_*.md`) and the description explains it as a post-merge closeout, flag the PR. The correct fix is to revert, re-open the original branch, add the state there, and re-merge. ## Relationship to the kernel diff --git a/README.md b/README.md index bdcc248..f766eb2 100644 --- a/README.md +++ b/README.md @@ -1,89 +1,38 @@ # Lead Protocol -**A shift-change logbook for your AI coding assistants.** +**Operational continuity protocol for AI agents** — vendor-agnostic, file-based, git-native. -When one AI session ends, it writes down what it did, what's left, and why it made the calls it made. The next session — even a different tool, even days later — reads that and picks up where the last one stopped. Nothing forgotten, nothing re-explained. +> The missing layer between agent instructions (AGENTS.md) and agent memory (mem0). -> Current version: **2.0.3** +> Current version: **1.8.3** (template) / **1.7.1** (IDE) — see [`template/.agents/PROTOCOL_RULES.md`](template/.agents/PROTOCOL_RULES.md). The development environment at the repo root runs the previous stable version used to build the next release, governed by §P8 (meta-repo promotion lifecycle). --- ## The problem -You've probably hit this: you spend an afternoon working through a problem with an AI assistant, close the chat, and the next day it remembers none of it. Open a different tool — Claude Code instead of Cursor — and you start from zero again. Ask it later *why* it made some change, and there's no record. +When multiple AI agents (Claude Code, Cursor, Codex, Antigravity, Windsurf) work on the same codebase — across different sessions, tools, and LLMs — there is no standard way to: -When more than one AI assistant works on the same project — across different days, tools, and people — there's no shared place for them to leave notes for each other. So context gets lost, decisions go unexplained, and interrupted work is hard to resume. +- **Hand off state** from one agent session to the next +- **Audit decisions** made by agents with rationale +- **Recover from interrupted sessions** without losing context +- **Coordinate concurrent agents** operating on the same repo +- **Consult a peer agent mid-session** without copy-pasting context -Lead Protocol gives every assistant the same simple habit: **read the notes before you start, leave notes before you stop.** - -
-For developers: where this sits relative to AGENTS.md, mem0, and LangGraph - -Phrased technically, the gap is the *operational state layer* — what was done, what's pending, who decided what, who is live right now, and how to recover. Existing tools solve adjacent problems, not this one: +Existing solutions solve adjacent problems: - **AGENTS.md / spec-kit** tell agents *what to know* about a project (instructions layer) - **mem0 / engram** remember *what happened* in the past (memory layer, DB-backed) - **LangGraph / CrewAI** orchestrate agents *in real time* (runtime layer) -Lead Protocol is vendor-agnostic, file-based, and git-native: the state lives as plain files committed alongside your code, so it is diffable, reviewable, and auditable like any other part of the repo. - -
+**Nobody solves the operational state layer** — what was done, what's pending, who decided what, who is live right now, and how to recover. ## The solution -Lead Protocol is a set of structured files committed to your git repository: - -- **`handoff.md`** — current state: what's done, what's in progress, what's blocked -- **`decisions.jsonl`** — append-only audit trail: why each important decision was made -- **`JOURNAL.md`** — curated timeline of structurally significant deliveries -- **`LESSONS.md`** — mistakes not to repeat, searchable by tag - -Any agent that can read text files can use it. No runtime, no database, no API keys — it's just files in your git repo. A CLI and MCP server are on the roadmap, but you never need them to use Lead Protocol today. - -In practice, the whole protocol is a single folder of markdown and JSON files dropped into your repository: - -``` -your-project/ -├── .agents/ -│ ├── CORE_RULES.md # Rules index + essential contracts (read first) -│ ├── PROTOCOL_RULES.md # Framework kernel (substrate-agnostic, upgradable) -│ ├── PROJECT_RULES.md # Your project's identity and context — edit this -│ ├── JOURNAL.md # Curated timeline of structurally significant deliveries -│ ├── LESSONS.md # Project-level lessons (append-at-tail, grep by tag) -│ ├── decisions.jsonl # Append-only audit trail (one JSON object per line) -│ ├── AGENTS_MAP.md # Tool-signature → agent-slug map (maintainer-managed) -│ ├── modules/ # Opt-in extension rule files -│ │ ├── README.md # Index of available modules -│ │ ├── git-substrate.md # Branching + PR + README-sync + .gitignore baseline -│ │ └── meta-repo.md # IDE/template duality + promotion lifecycle -│ ├── schemas/ -│ │ ├── handoff.schema.json # Validates parsed handoff.md -│ │ └── decisions.entry.schema.json # Validates one decisions.jsonl line -│ ├── scripts/ -│ │ ├── validate_state.py # Schema validator -│ │ ├── migrate_to_v2.py # v1.x → v2.0.0 migration tool -│ │ ├── conftest.py # Pytest config -│ │ └── test_validate_state.py # Validator tests -│ ├── checkpoints/ # Cross-agent coordination snapshots (shared) -│ ├── sessions/ -│ │ └── active_sessions.md # Concurrent session registry -│ └── local/ # ← gitignored — per (actor, agent) state -│ └── // -│ ├── handoff.md # Current operational state for this pair -│ ├── tasks/TASK.md # TODO for the active session -│ ├── activity.log # Per-pair raw activity log -│ └── lessons.md # Personal lessons for this pair -├── .gitignore # Ignores .agents/local/ -├── CLAUDE.md # Pointer for Claude Code -└── AGENTS.md # Pointer for other agents -``` - -The bundled Python scripts are validation and migration helpers — you do not need them to get started. +Lead Protocol defines a set of structured files committed to your git repository — a `handoff.md` with a strict schema, an append-only `decisions.json` audit trail, rules for takeover and recovery, a concurrent-session registry, and framework/project separation. Any agent that can read text files can use it. No runtime, no API, no vendor dependency. -
-For developers: where Lead Protocol sits in the agent stack +The full structure, schemas, and operational details live in the [operational manual](template/README.md). -Lead Protocol fills the operational-state slot in the broader agent stack: +## Where it fits ``` ┌─────────────────────────────────────────────┐ @@ -103,187 +52,40 @@ Lead Protocol fills the operational-state slot in the broader agent stack: └─────────────────────────────────────────────┘ ``` -
- ## Quick start -```bash -# Clone the latest stable release -# Check https://github.com/mmilanez/lead-protocol/releases for the current version number -git clone --branch v2.0.3 --depth 1 https://github.com/mmilanez/lead-protocol.git /tmp/lp - -# Copy the scaffold into your project -cp -R /tmp/lp/.agents your-project/.agents -cp /tmp/lp/CLAUDE.md your-project/CLAUDE.md -cp /tmp/lp/AGENTS.md your-project/AGENTS.md - -# Set your project's identity -$EDITOR your-project/.agents/PROJECT_RULES.md - -# Verify the scaffold state -cd your-project -python .agents/scripts/validate_state.py -``` - -**Windows (PowerShell):** - -```powershell -# Clone the latest stable release -# Check https://github.com/mmilanez/lead-protocol/releases for the current version number -git clone --branch v2.0.3 --depth 1 https://github.com/mmilanez/lead-protocol.git $env:TEMP\lp - -# Copy the scaffold into your project -Copy-Item -Recurse $env:TEMP\lp\.agents your-project\.agents -Copy-Item $env:TEMP\lp\CLAUDE.md your-project\CLAUDE.md -Copy-Item $env:TEMP\lp\AGENTS.md your-project\AGENTS.md - -# Set your project's identity -code your-project\.agents\PROJECT_RULES.md - -# Verify the scaffold state -Set-Location your-project -python .agents/scripts/validate_state.py -``` - -That's it. Read the sections below or browse [`.agents/CORE_RULES.md`](.agents/CORE_RULES.md) to understand how agents use the protocol inside your project. - -## Installing a specific version - -`main` is the development branch and may contain in-progress work. **Do not install directly from `main`.** Always install from a published release. - -Available versions are listed on the [Releases page](https://github.com/mmilanez/lead-protocol/releases). Versions follow [SemVer](https://semver.org): - -- **`vX.Y.Z`** (no suffix) — stable release, recommended for production use -- **`vX.Y.Z-alpha.N` / `-beta.N` / `-rc.N`** — pre-releases, for preview and testing only - -### Alternative — download the release archive - -On the [Releases page](https://github.com/mmilanez/lead-protocol/releases), pick a version and download the `Source code (zip)` or `(tar.gz)` asset. Extract and copy the files into your project as shown in Quick start. - -For Windows PowerShell, use equivalent `Copy-Item` commands and run the same validator command from the target project root. - -### Checking which version you have - -`.agents/PROTOCOL_RULES.md` records the **kernel** version (the framework rules). A patch release may leave the kernel untouched — for example, release `2.0.1` ships kernel `2.0.0` because it only fixed tooling and docs. So the kernel version is a floor, not the release number. The exact release you installed is the one named in the top entry of [`CHANGELOG.md`](CHANGELOG.md); compare it against the [Version history](#version-history) table below. - -### Release notes and migration - -- **Changelog:** [`CHANGELOG.md`](CHANGELOG.md) — release-by-release summary of what changed. -- **v1.x → v2.0.0 migration:** [`docs/MIGRATION-v2.md`](docs/MIGRATION-v2.md) — required reading for consumer repos upgrading from any `v1.x` release. - ---- - -## Three-layer state model - -Every file under `.agents/` belongs to exactly one of three layers: - -| Layer | Owner | Lifecycle | Shared? | -|---|---|---|---| -| **Framework** | Upstream Lead Protocol | Changes with framework version | Yes — ships in the release | -| **Project** | Your project | Changes with project evolution | Yes — versioned with the repo | -| **Actor × Agent** | One human operator running one AI agent | Changes every session | **No** — gitignored, one folder per pair | - -
-Why the pair (actor × agent) is the unit of concurrency - -The smallest unit that owns volatile state is the pair `(actor, agent)`, not the actor alone. Claude Code, Codex, Gemini, and Cursor operated by the same human each get their own `local///`. That is what makes cross-agent interchange in the same project viable — agents never overwrite each other's handoff. - -Full detail: `.agents/PROTOCOL_RULES.md §P3 — Three-layer state model`. - -
- ---- - -## How agents boot in your project - -> You don't run these steps — your AI agent does, automatically, the moment it reads `CLAUDE.md`. This section explains what's happening under the hood. - -Every compliant agent reads, in order: - -1. `.agents/CORE_RULES.md` — index + essential contracts. -2. `.agents/PROJECT_RULES.md` — your project's identity, language rules, tone, operational preferences. Read `§J8 Active modules` first. -3. `.agents/modules/.md` — for each scope listed in `§J8 Active modules`, in declaration order. -4. `.agents/AGENTS_MAP.md` — resolve this agent's own `` slug from its tool signature. -5. `.agents/sessions/active_sessions.md` — concurrent-session awareness. -6. `.agents/local///handoff.md` — current state of this pair. - -`PROTOCOL_RULES.md` itself is read **on demand**, not in the baseline — `CORE_RULES.md` points agents there when needed. This keeps baseline cost bounded. See `PROTOCOL_RULES.md §P-Access` for the full load contract. - -Pointer files `CLAUDE.md` and `AGENTS.md` at the project root exist so each vendor-specific agent tool discovers `.agents/` without custom configuration. - ---- - -## Upgrading - -### Upgrading from v1.x to v2.0.0 (structural — state layout changed) - -v2.0.0 introduces the three-layer state model with an actor × agent sub-dimension. The old `agent_log/` layout is gone. Run the migration tool: +Only the `template/` directory is meant to be copied into your project — everything else in this repo is the development environment of the Lead Protocol itself. ```bash -python .agents/scripts/migrate_to_v2.py # dry-run first -python .agents/scripts/migrate_to_v2.py --apply # then mutate +cp -R lead-protocol/template/.agents your-project/.agents +cp lead-protocol/template/CLAUDE.md your-project/CLAUDE.md +cp lead-protocol/template/AGENTS.md your-project/AGENTS.md +$EDITOR your-project/.agents/PROJECT_RULES.md # set your project's identity ``` -Full consumer migration guide: [`docs/MIGRATION-v2.md`](docs/MIGRATION-v2.md). - -### Upgrading between v2.Y patches/minors +That's it. Read the [operational manual](template/README.md) to understand how agents will use the protocol inside your project. -Replace framework files verbatim (`CORE_RULES.md`, `PROTOCOL_RULES.md`, `modules/`, `schemas/`, `scripts/`). Do not replace `PROJECT_RULES.md`, project-layer state, or per-pair state. Append a decision entry to `decisions.jsonl` recording the upgrade. +## Why `template/` only? -Patch bumps (Z) never break anything. Minor bumps (Y) may introduce new features but preserve backward compatibility. Major bumps (X) may require migration — the release notes will say so explicitly and typically ship a migration script. - ---- +This repository dogfoods its own protocol. Its root `.agents/` records the real decisions, lessons, and history of developing the protocol itself — that would be noise in a consumer repo. The `template/` folder is the clean, versioned baseline that ships. Think of the repo like an IDE: `template/` is the distributable program; the rest is the workshop. ## Version history | Version | Highlights | |---|---| -| **2.0.3** | Security patch: `migrate_to_v2.py` now validates `--actor` / `--agent` values against path traversal (rejects `..`, `/`, `\`, absolute paths, drive letters). README Quick Start updated to current release with PowerShell copy block added. `SECURITY.md` and `CONTRIBUTING.md` scope corrected (CLI/MCP are roadmap, not shipped). CI workflow permissions hardened. No kernel or schema changes. | -| **2.0.2** | Documentation and release infrastructure fixes. README version references corrected. No kernel or schema changes. | -| **2.0.1** | Patch from first external consumer feedback. `migrate_to_v2.py --dry-run` now accepted; pristine `LESSONS.md` scaffold no longer false-positives the rerun-safety guard; `docs/MIGRATION-v2.md` Step 3 rewritten with agent-driven callout and `--agent` slug warning. No kernel or schema changes. | -| **2.0.0** | **Three-layer state model (Framework / Project / Actor × Agent).** New files: `JOURNAL.md`, `LESSONS.md`, `AGENTS_MAP.md`. `decisions.json` replaced by `decisions.jsonl` (append-only). `handoff.md` relocates to `local///handoff.md`. New `migrate_to_v2.py` migration tool. Six-step baseline boot order. | - -
-Earlier versions (v1.0.0 – v1.9.1) - -| Version | Highlights | -|---|---| -| **1.9.1** | Template cosmetic pass — clarifies opt-in nature of pre-commit tooling, adds `scripts/README.md`, reframes validation section so local ad-hoc validation is the default path. No framework rules changed. | -| **1.9.0** | **Substrate-agnostic kernel + opt-in modules.** `PROTOCOL_RULES.md` rewritten as kernel (§P1–§P7, new §P9 module contract); git/PR/README-sync rules extracted to `modules/git-substrate.md`; meta-repo promotion (former §P8) relocated to `modules/meta-repo.md`. | -| **1.8.3** | CI state validation workflow — GitHub Action that runs `validate_state.py` on every PR. | -| **1.8.2** | Pre-commit hook integration — Python validator enforces JSON Schemas against `handoff.md` and `decisions.json`. | -| **1.8.1** | Formal JSON Schemas (`handoff.schema.json`, `decisions.schema.json`). | -| **1.8.0** | **Meta-repo promotion lifecycle (§P8).** Formalizes IDE↔template dual-copy model: version invariant, when/how to promote, anti-patterns. | -| **1.7.1** | Clarifications across §P1–§P5; branch-protection override note; pristine-vs-populated handoff distinction. | -| **1.7.0** | Public-facing documentation sync rule + CI enforcement; §P7 dual-tier private context. | -| **1.6.0** | Concurrent session registry (`active_sessions.md`) + mid-session checkpoints. | -| **1.5.0** | Session close ritual + embedded self-verification checklist in `handoff.md`. | -| **1.4.0** | SemVer for rules files + pull-request-required rule. | -| **1.3.0** | §P6 cross-repo references + §P7 private vs shared context separation. | -| **1.0.0** | Initial protocol: handoff, decisions, takeover, recovery, authority hierarchy. | - -
- -## Roadmap - -| Priority | Component | Status | -|---|---|---| -| **P1** | CLI (`lead-protocol init / handoff / validate`) | Planned | -| **P1** | JSON Schemas for `handoff.md` and `decisions.jsonl` | ✅ Shipped in v1.8.1 | -| **P1** | Pre-commit hook for schema enforcement | ✅ Shipped in v1.8.2 | -| **P2** | MCP Server (protocol operations as MCP tools) | Planned | -| **P2** | GitHub Action for CI validation | ✅ Shipped in v1.8.3 | -| **P3** | Decisions dashboard (web UI) | Planned | -| **P3** | Template marketplace (`PROJECT_RULES.md` by industry) | Planned | - -## Contributing - -Contributions welcome. See [CONTRIBUTING.md](CONTRIBUTING.md) for details. - -## License - -[Apache 2.0](LICENSE) — see also [`NOTICE`](NOTICE) for required attribution. - ---- - -*Built by [mmilanez](https://github.com/mmilanez) — born from managing AI agents across 100+ repositories.* +| **1.9.2** | **Branch ordering rule for session close.** Adds an explicit rule (PROTOCOL_RULES §P3) requiring session-close artifacts — handoff, decisions, lessons — to be committed on the feature branch before the PR is opened, not after merge. Adds corresponding git-substrate enforcement (§M-git-5) with reviewer signal for post-merge closeout PRs. Adds one checklist item to the handoff schema. Fixes #2. | +| **1.9.1** | Template cosmetic pass — clarifies opt-in nature of pre-commit tooling (header comment + cross-reference in `modules/git-substrate.md`), adds `template/.agents/scripts/README.md` distinguishing framework files (validator, tests) from distribution files (pre-commit hook manifest), and reframes the "Validating state files" section so local ad-hoc validation is the default path, with pre-commit (requires pre-commit.com) and CI (requires GitHub Actions) presented as opt-in layers. Closed via #36. No framework rules changed. Promoted to IDE on 2026-04-20. | +| **1.9.0** | **Substrate-agnostic kernel + opt-in modules.** PROTOCOL_RULES rewritten as kernel (§P1–§P7, new §P9 module contract); git/GitHub/PR/README-sync concerns extracted to `.agents/modules/git-substrate.md` (§M-git-1..4); meta-repo promotion (former §P8) relocated to `.agents/modules/meta-repo.md` (§M-meta-1..6). PROJECT_RULES §J8 gains `Active substrate` + `Active modules` fields (field previously `Active optional modules`). Promotion copy list expanded to include `modules/`. Promoted to IDE on 2026-04-20. | +| **1.8.3** | CI state validation workflow — GitHub Action that runs `validate_state.py` on every PR that touches state, schemas, or scripts. Two jobs: one for the IDE root state, one for the template's pristine baseline. | +| **1.8.2** | Pre-commit hook integration — Python validator (`validate_state.py`) that enforces the JSON Schemas against `handoff.md` and `decisions.json`. Ships as `.pre-commit-hooks.yaml` for external adoption and a ready `.pre-commit-config.yaml` scaffold in the template. §P8 copy list expanded to include `scripts/`. | +| **1.8.1** | Formal JSON Schemas (`handoff.schema.json`, `decisions.schema.json`) for the two state files — source of truth for the upcoming CLI, pre-commit hook, and CI validator. §P8 promotion procedure updated to treat `schemas/` as framework (copied verbatim on promotion). | +| **1.8.0** | **§P8 — Meta-repo promotion lifecycle.** Formalizes the IDE↔template dual-copy model introduced in PR #17: version invariant (template ≥ IDE), when/how to promote a tested template version into the IDE, anti-patterns (no ad-hoc IDE edits, no multi-minor gaps), and scope (§P8 governs meta-repos only, not consumer repos). Complements the README split (PR #21) and CI dual-sync (PR #22). | +| **1.7.1** | Clarifications across §P1–§P5 reflecting the IDE-vs-template separation (PR #17); branch-protection override note in §P3; pristine-vs-populated handoff distinction; README added to authority hierarchy in §P2 | +| **1.7.0** | Public-facing documentation sync rule + CI enforcement (README ↔ PROTOCOL_RULES); §P7 dual-tier (`private-context` + `business-vault`) with opt-in framing | +| **1.6.0** | Concurrent session registry (`active_sessions.md`) + mid-session checkpoints | +| **1.5.0** | Session close ritual + self-verification checklist in `handoff.md` | +| **1.4.0** | `decisions.json` format stabilized; `agent_lessons.md` introduced | +| **1.3.0** | §P6 (portable cross-repo identifiers) + §P7 (private context separation) | +| **1.2.0** | Recovery mode + takeover rule | +| **1.1.0** | Commit convention (`[Agent] : `) | +| **1.0.0** | Initial release: handoff schema, decisions log, session protocol levels | diff --git a/template/.agents/PROTOCOL_RULES.md b/template/.agents/PROTOCOL_RULES.md new file mode 100644 index 0000000..1e90234 --- /dev/null +++ b/template/.agents/PROTOCOL_RULES.md @@ -0,0 +1,315 @@ +# PROTOCOL_RULES.md — Lead Protocol framework rules (generic) + +> Version: 1.9.2 | Updated: 2026-06-01 +> Scope: Substrate-agnostic kernel. Opt-in modules live in `modules/` and are activated via `PROJECT_RULES.md §J8`. +> This file contains no project-specific content — that lives in `PROJECT_RULES.md`. + +--- + +## §P1 — Versioning + +| File type | Format | Example | When to bump | +|---|---|---|---------| +| Agent operation files (`CORE_RULES.md`, `PROTOCOL_RULES.md`, `PROJECT_RULES.md`, `handoff.md`) | `X.Y.Z` | `1.4.0` | Patch (Z) for clarifications/text fixes; Minor (Y) for new sections/rules; Major (X) for structural rewrites | +| Module files (`modules/*.md`) | `X.Y.Z` | `1.0.0` | Same rules as agent operation files. Each module versions independently from the kernel. | + +Projects that adopt Lead Protocol may use any versioning scheme for their own product releases — the Lead Protocol versioning rules apply only to the agent operation files and module files listed above. + +Meta-repos that develop the protocol itself see `modules/meta-repo.md §M-meta-1`. + +## §P2 — Authority hierarchy (framework tier) + +1. `PROTOCOL_RULES.md` (framework kernel) +2. Active modules listed in `PROJECT_RULES.md §J8` (in declaration order) +3. `handoff.md` (current state — may temporarily override stale rules if the project owner defines a temporary directive) +4. `PROJECT_RULES.md` (business context) +5. `README.md` (public surface — kept synced to the kernel per the active substrate module if any; kernel wins on conflict) +6. Project reference files (brand, product, channel, etc.) +7. Official platform policies +8. General best practices + +A module cannot contradict the kernel — it can only add rules specific to a substrate, scope, or role. Where a module cites a kernel anchor, the qualifier `PROTOCOL_RULES §Px` makes the cross-file reference explicit. + +Meta-repos maintaining two copies of the framework see `modules/meta-repo.md §M-meta-2`. + +## §P3 — Multi-agent coordination + +### Handoff schema (`agent_log/handoff.md`) — strict, always overwritten + +```markdown +# handoff.md — Current operational state +> Version: X.Y | Updated: YYYY-MM-DD + +**Last Agent:** [Agent signature] +**Timestamp:** YYYY-MM-DD HH:MM +**Status:** STABLE | BLOCKED | IN_PROGRESS +**Last Action:** <1 sentence> +**Pending Step:** +**Blockers/Context:** +**Open Threads:** + +**Session close checklist (self-verified):** +- [ ] `activity_YYYY-MM.md` contains an entry for this session +- [ ] `decisions.json` appended (if any decision was made) +- [ ] `agent_lessons.md` appended (if an agent-level lesson emerged) +- [ ] `tasks/lessons.md` appended (if a project-level lesson emerged) +- [ ] Commit(s) follow `[Agent] : ` convention +- [ ] Version bumps applied to any rules file whose content changed +- [ ] `active_sessions.md` row for this session removed (if registry is in use) +- [ ] Session-close state written on the feature branch before the PR is opened (when substrate uses pull requests — see §M-git-5) +``` + +Schema is immutable — no agent may add sections, tables, or free paragraphs. Timestamp must include HH:MM. The session close checklist is **part of the schema** (added in Lead Protocol v1.5.0; `active_sessions.md` entry added in v1.6.0) — each box is self-verified by the agent before closing. Unchecked boxes signal incomplete close to the next agent. + +Projects that distribute pristine handoff templates (placeholder-populated, not yet in use) see `modules/meta-repo.md §M-meta-4`. + +### Takeover rule + +| Condition | Behavior | +|---|---| +| Timestamp **< 30 min ago** AND no peer session live in `active_sessions.md` | Do not proceed. Assume prior agent is still active. | +| Timestamp **< 30 min ago** AND a different session is live in `active_sessions.md` | Two sessions are legitimately concurrent. Do NOT take over — see §P3 concurrent sessions. | +| Timestamp **≥ 30 min ago** | Assume interrupted. Record takeover in `decisions.json` with rationale `"Takeover: previous session assumed interrupted (>30min)"`. Run recovery mode before proceeding. | +| Timestamp **< 30 min** + explicit human override | Proceed. Rationale: `"Forced takeover: human override"`. | + +### Recovery mode + +Before continuing a prior `Pending Step`: +1. Read the last entry in `decisions.json`. +2. Spot-check files listed in `files_affected`. +3. If state is inconsistent (missing headers, version conflicts, half-written content): fix or revert first — never build on corrupted state. +4. Log the recovery action in `decisions.json`. + +Meta-repos with two `decisions.json` files (IDE vs. template) see `modules/meta-repo.md §M-meta-3`. + +### Decisions log (`agent_log/decisions.json`) — append-only, immutable + +```json +[ + { + "timestamp": "2026-04-17T15:30:00", + "agent": "[Claude Code / claude-opus-4-6]", + "decision": "Short imperative", + "rationale": "Why", + "files_affected": ["path/to/file.md"], + "status": "completed" + } +] +``` + +Never edit past entries. If the JSON is corrupted, the recovery agent fixes structure before appending. + +### Commit convention + +``` +[Agent] : +``` + +Where `[Agent]` is `[Claude]`, `[Cursor]`, `[Codex]`, etc., and `` is `feat|fix|refactor|docs|ops|chore`. This convention is substrate-neutral — it applies whether the underlying system is git, a cloud-sync folder, or any other change-tracked substrate. Substrate-specific workflows (branching, pull requests, CI) live in substrate modules such as `modules/git-substrate.md`. + +### Session close ritual *(v1.5.0+)* + +A **"non-trivial session"** is one where any of the following occurred: + +- A change was committed (by the active substrate's commit mechanism) +- A review/approval artifact was opened, updated, or merged (when a substrate module defines one) +- A file outside `agent_log/` was modified +- A product, strategy, or architectural decision was made +- A user-facing deliverable was shipped (listing, pin, copy, export) + +At the end of a non-trivial session, the agent **must** update every applicable artifact below **and** check the corresponding box in the `handoff.md` session close checklist: + +| Artifact | Mandatory trigger | Skip if | +|---|---|---| +| `handoff.md` | Always | Never skipped | +| `decisions.json` | A decision was made, a file was created/renamed/deleted, or a version was bumped | No decisions and no file state changed | +| `activity_YYYY-MM.md` | A commit, review artifact, or major artifact change occurred | Pure reads / inspection / Q&A sessions | +| `agent_lessons.md` | An **agent-level** lesson emerged (format drift, tool failure, recovery incident, cross-agent coordination pattern) | No new agent-level lesson | +| `tasks/lessons.md` | A **project-level** lesson emerged (bug pattern, process flaw, systemic decision criterion) | No new project-level lesson | +| `active_sessions.md` | Registry is in use and this session has an open row | Registry not in use, or no open row | + +### Branch ordering rule *(v1.9.2+)* + +Session close is the **final operational step on the feature branch**. Complete all session-close artifacts — handoff, decisions, lessons, and journal updates — before opening or merging the pull request. + +**Why this order matters:** if session-close state is written on the default branch after merge, protected-branch settings may block the write or force a follow-up PR for state files only. This creates unnecessary review overhead and an audit gap where the handoff describes work that is not yet in the branch history. + +**Implementation rule:** the session-close checklist in `handoff.md` is complete (all boxes checked) when the pull request is **opened**, not after it merges. Agents must not mark the session closed and then create a separate follow-up PR to write state files. + +This rule is substrate-neutral. Git-specific enforcement and rationale live in the active substrate module (see `modules/git-substrate.md §M-git-5`). + +**Verification step (mandatory before closing):** + +Before the final response of the session, the agent runs: + +```bash +grep -l "YYYY-MM-DD" .agents/agent_log/*.md .agents/agent_log/*.json tasks/*.md +``` + +(substituting `YYYY-MM-DD` with today's date) and confirms that each *applicable* artifact appears in the output. If an applicable artifact does not appear, the update was skipped — fix before closing. + +**Agent-level vs project-level lessons — decision rule:** + +- `agent_lessons.md` captures lessons **about how agents operate**: format drift, tool failure modes, recovery protocols, cross-agent coordination patterns. Examples: "the file-reader cache got confused after a rename", "I took an attribute dropdown value as ground truth without cross-checking". +- `tasks/lessons.md` captures lessons **about the project or domain**: systemic mistakes, decision criteria, recurring bug patterns, process fixes. Examples: "anchor election from local sales data underweights cross-shop demand", "lessons about customer behavior, pricing elasticity, or category positioning". + +When in doubt, a lesson is project-level if removing the specific agent would still leave the lesson valid. If the lesson is about *how the agent failed as an agent*, it is agent-level. + +### Concurrent sessions and mid-session checkpoints *(v1.6.0+)* + +The v1.5 takeover rule assumes at most one session is live per repo at any time. Real-world tooling (multiple IDEs, multiple agents, multiple terminals rooted at the same repo) routinely breaks this assumption. Two additions address concurrent sessions and mid-session cross-agent consultation without breaking any existing schema. + +**Active sessions registry** — `.agents/agent_log/sessions/active_sessions.md` + +Optional but recommended when more than one agent may operate on the repo. A flat markdown table, one row per live session. The agent appends its row on session start and removes the row on session close (session close checklist item). + +Schema — immutable columns: + +```markdown +# active_sessions.md — Sessions currently live +> Append row on session start. Remove row on session close. +> Stale rows (>24h with no checkpoint update) may be removed by any next agent with a decisions.json log. + +| Session ID | Agent | Started | Topic | Last checkpoint | +|---|---|---|---|---| +| 2026-04-19-1310-claude | [Claude Code / claude-opus-4-7] | 2026-04-19 13:10 | <1-line topic> | | +``` + +**Session ID format:** `YYYY-MM-DD-HHMM-`. The `` suffix (`claude`, `gemini`, `cursor`, `codex`, etc.) prevents ID collision when two agents boot in the same minute. + +**Effect on takeover rule:** when `active_sessions.md` exists and holds a row for a peer session whose Started timestamp is within the last 30 minutes OR whose Last checkpoint is within the last 30 minutes, the current agent MUST NOT take over. Concurrent sessions are legitimate — append a new row for the current session instead. The `handoff.md` 30-minute takeover rule remains in effect only when `active_sessions.md` is absent or empty. + +**Mid-session checkpoints** — `.agents/agent_log/checkpoints/YYYY-MM-DD-HHMM-.md` + +A checkpoint is a pre-execution snapshot written voluntarily by the agent at the owner's request (or proactively when the agent is about to take an action that would benefit from a second opinion). Checkpoints are ephemeral working notes — authoritative state lives in `handoff.md`, `decisions.json`, and project files. + +Template — content must be self-contained so a peer agent reads it without the conversation transcript: + +```markdown +# Checkpoint — +> Session: +> Timestamp: YYYY-MM-DD HH:MM +> Author: [Agent signature] + +## Open question + + +## Data gathered + + +## Current recommendation + + +## What specifically needs second-opinion + +``` + +**Usage pattern:** when the owner asks for a second opinion from a peer agent, the current agent writes the checkpoint and updates the `Last checkpoint` column of its row in `active_sessions.md`. The owner opens the peer agent in another window; the peer agent boots per §P5, sees the fresh checkpoint referenced in `active_sessions.md`, reads it, and responds with contrarian input. No copy-paste required. + +**Retention:** no automatic retention policy. Checkpoints accumulate as an audit trail. If the `checkpoints/` directory grows beyond practical limits, the project may adopt a retention rule in `PROJECT_RULES.md §J8`. + +**Scope limits:** +- The registry is advisory, not a lock. It does not prevent two agents from editing the same file concurrently — resolve conflicts per the active substrate module. +- Checkpoints do not replace `handoff.md`. They coexist: checkpoint = live snapshot of an in-progress decision; handoff = authoritative state at session close. +- Neither the registry nor checkpoints are required when only one agent operates on the repo. Projects may opt into v1.6 features via `PROJECT_RULES.md §J8`. + +## §P4 — Generic quality checklist + +Before closing any significant action: +- [ ] Persona/agent signature present in every recorded change and in `handoff.md` +- [ ] `handoff.md` overwritten with current state (Status, Timestamp HH:MM, Last Action, Pending Step, session close checklist) +- [ ] `decisions.json` appended with rationale and files_affected (if applicable per §P3 session close ritual) +- [ ] `activity_YYYY-MM.md` appended with one line per logical action (if applicable per §P3 session close ritual) +- [ ] If a new **agent-level** pattern/bug learned → append to `agent_log/agent_lessons.md` +- [ ] If a new **project-level** pattern/bug learned → append to `tasks/lessons.md` +- [ ] Commit record follows `[Agent] : ` convention (§P3) +- [ ] Version bumps applied to any rules file or module whose content changed +- [ ] Session close checklist in `handoff.md` fully verified (`grep` confirmed entries exist per §P3) +- [ ] If `active_sessions.md` is in use, the row for this session has been removed (per §P3 concurrent sessions) +- [ ] Any additional checks required by an active module have been satisfied + +## §P5 — Operational model (generic) + +- Every agent reads `CORE_RULES.md` → `PROTOCOL_RULES.md` (kernel) → `PROJECT_RULES.md` → each module file listed in `§J8 Active modules` (in declaration order) → `handoff.md` on session start. +- Additionally (v1.6.0+), when `agent_log/sessions/active_sessions.md` exists, the agent reads it to detect concurrent peer sessions. If a peer session has a Last checkpoint referenced, the agent reads the latest checkpoint in `agent_log/checkpoints/` before responding to the owner. +- The active Session Protocol level (1/2/3), the active substrate, and the list of active modules are declared in `PROJECT_RULES.md §J8`. +- Edits to framework files (`PROTOCOL_RULES.md` kernel, any module file) only happen via methodology upgrade — never ad-hoc. +- Edits to business files (`PROJECT_RULES.md`, project reference docs) happen per project rules in `§J8`. +- Language: operational files (`CORE_RULES`, `PROTOCOL_RULES`, `PROJECT_RULES`, module files, `handoff`, `decisions`, `agent_lessons`, `activity`, `active_sessions`, `checkpoints`) are always EN-US. +- Additional module-specific boot steps may apply — see each active module's header. + +## §P6 — Cross-repository references + +When a project references resources in other repositories (personal context, external specs, sibling repos): + +1. **Portable identifiers** — Always use `org/repo` (e.g., `acme/private-context`). Never use local machine paths (e.g., `C:\Dados\...` or `/home/user/...`). Local paths break on other machines and are not traceable. +2. **Pointer, not copy** — When information exists in a canonical repo, other locations must contain only pointers (`§J6` with repo reference). Never duplicate full content. If duplicated, reduce the copy to a summary + pointer. +3. **Deduplication** — Before recording information in more than one location (local memory, repo A, repo B), check: does this information already have a canonical home? If yes, pointer. If no, elect a home and point the rest. +4. **Reference format in `§J6`** — For external repos, use format: `Repo 'org/repo' (private|public) — path/to/file.md`. Include visibility flag so agents know if authentication is required. + +## §P7 — Private vs shared context separation + +**Problem:** Context relevant to an AI agent may be sensitive enough that it must not leak into repos shared more widely. This applies in two analogous tiers: + +- **Personal tier:** an individual owner's context (identity, finances, strategic goals, private decisions) that must not leak into repos shared with a team. +- **Organizational tier:** a company's confidential context (financials, strategic plans not yet public, compensation, privileged legal matters) that must not leak into repos shared beyond the director/C-level circle. + +**Rule:** isolate sensitive context in a dedicated private repo, and reference it by name from the less-private repos that consume it. The pattern is the same in both tiers — only the audience and the repo name differ. + +| Context tier | Canonical private repo | Consumers | +|---|---|---| +| Personal | `owner/private-context` (owner-only) | Owner's personal project repos | +| Organizational | `org/business-vault` (directors/C-level only) | Team-shared company repos | + +Both tiers are **optional** — projects without sensitive context at the corresponding tier simply don't have a `private-context` or `business-vault` repo. The rules below apply wherever the pattern is used. + +**Rules:** + +1. **Private context repo** lives separately from any repo shared with a wider audience. Owner-level private context lives in a personal private repo (e.g., `owner/private-context`); organizational-level confidential context lives in a directors-only repo (e.g., `org/business-vault`). +2. **Consuming repos** (team-shared project repos, documentation repos) reference the private repo only by name in `§J6`, with explicit rule: `"Never copy content from this repo into [consuming repo] or any repo with a wider audience."` +3. **Harness local memory** (e.g., `~/.claude/projects/*/memory/`) may contain a lightweight summary + pointer to the private repo. Never the full content — avoid duplication and drift. +4. **The private repo** must follow the full Lead Protocol (`.agents/`, `PROTOCOL_RULES.md`, `PROJECT_RULES.md`, `handoff.md`, `decisions.json`) like any other project. +5. **Content that belongs in the personal private repo (`private-context`):** owner's identity, personal strategic goals, permanent personal decisions, personal lessons learned, personal digital presence, family/health/financial context. +6. **Content that belongs in the organizational private repo (`business-vault`):** company financials, strategic plans not yet public, personnel and compensation, legal matters under privilege. +7. **Content that belongs in the team-shared repo:** methodology, system architecture, runbooks, product technical decisions, team operational context. +8. **Opt-in activation:** projects without sensitive context at a given tier do not need to create a corresponding private repo. The rule activates only when such context exists and needs a home. + +## §P9 — Modules architecture *(v1.9.0+)* + +The kernel above is substrate-agnostic and role-agnostic. Substrate-specific and role-specific rules live in opt-in module files under `.agents/modules/`. This section defines the module contract. + +### File layout + +- `.agents/modules/.md` — one file per module; `` is lowercase kebab-case. +- `.agents/modules/README.md` — one-paragraph index listing available modules. +- Each module file carries its own `> Version: X.Y.Z` header and bumps per §P1 independently of the kernel. + +### Anchor convention + +Sections inside a module use anchors of the form `§M--N`. Examples: `§M-git-1`, `§M-meta-3`. The `§M-` prefix disambiguates module anchors from kernel `§P` anchors and project `§J` anchors. + +### Activation + +A project declares its active substrate and active modules in `PROJECT_RULES.md §J8`: + +```markdown +- **Active substrate:** git+github | git | local | cloud-sync | other +- **Active modules:** +``` + +A module is in effect if and only if its scope appears in `Active modules`. Activation order determines precedence between modules (earlier entries win conflicts between modules). The kernel always outranks any module. + +### Boot + +Agents read active modules after `PROJECT_RULES.md` and before `handoff.md`, in the order listed in `§J8 Active modules`. See §P5 for the full boot sequence. + +### Authoring rules + +- A module cannot contradict the kernel. It can only add substrate-specific or role-specific rules. +- When a module cites a kernel anchor, use the fully qualified form `PROTOCOL_RULES §Px` to mark the module→kernel crossing explicitly. +- A module may depend on another module only if it declares the dependency in its header. +- Module CI/tooling (if any) must include a top-of-file comment identifying the module it enforces, so consumer repos that do not list the module know not to copy the tooling. + +### Relation to earlier opt-in language + +The field historically called `Active optional modules` in `PROJECT_RULES.md §J8` (introduced v1.6 for the concurrent-session registry feature flag) is renamed to `Active modules` in v1.9.0. The semantic shift is deliberate: v1.6 used the field to toggle a kernel-internal feature; v1.9 uses the field to activate external rule files. Projects upgrading from v1.8 or earlier move any v1.6 feature-flag values into the new `Active modules` field, or drop them if the feature is now part of the kernel by default. diff --git a/template/.agents/modules/git-substrate.md b/template/.agents/modules/git-substrate.md new file mode 100644 index 0000000..a2932d1 --- /dev/null +++ b/template/.agents/modules/git-substrate.md @@ -0,0 +1,74 @@ +# modules/git-substrate.md — Git / pull-request substrate rules + +> Version: 1.1.0 | Updated: 2026-06-01 | Protocol: Lead Protocol v1.9.2+ +> Scope: Opt-in module. Activate via `PROJECT_RULES.md §J8 Active modules: git-substrate`. +> Applies to: repositories hosted on a git platform with pull-request support (GitHub, GitLab, Bitbucket, etc.). + +--- + +This module extends `PROTOCOL_RULES.md` with rules specific to projects whose substrate is git and whose review/approval surface is a pull-request platform. A project that is not on git, or is on git but has no remote, or is on a git remote without PR support, should **not** list this module in `§J8 Active modules`. + +## §M-git-1 — Branching (risk-based) + +| File type | Branch required? | +|---|---| +| Executable code (`.py`, `.js`, `.ts`, `.html`, `.css`) | Yes | +| Agent configuration (`CORE_RULES.md`, `CLAUDE.md`, `AGENTS.md`, workflow YAML) | Yes | +| Framework files (`PROTOCOL_RULES.md`, `modules/*.md`) | Yes | +| Documentation, logs, operational data | No — direct commit allowed | +| `handoff.md`, `decisions.json`, activity logs, `active_sessions.md`, checkpoints | No — operational state, direct commit | + +Branch names follow the project's convention declared in `PROJECT_RULES.md §J8` (e.g., `claude/` for AI-authored work, `feat/` / `fix/` for human work). + +## §M-git-2 — Pull request required + +All changes that require branching per §M-git-1 **must use the platform's pull-request workflow**. Direct local merges to the default branch are not allowed for branched work. + +Expected flow: `branch → commit → push → PR → merge via platform → delete branch`. + +This rule does not apply to: + +- Changes with direct commit allowed per §M-git-1 (handoff, decisions, docs, activity logs, active_sessions, checkpoints) +- Repositories without a remote +- Repositories whose hosting platform does not support pull requests (for those, drop this module from `§J8`) + +**Platform branch protection overrides this clause.** When the hosting platform enforces branch protection requiring a pull request for *all* changes to the default branch (including state files), the platform rule wins — open a short-lived PR even for handoff/decisions updates. The §M-git-1 risk-based table is the module's recommendation, not a hard override of platform policy. + +## §M-git-3 — Public-facing documentation sync + +When a pull request modifies `.agents/PROTOCOL_RULES.md` (the kernel that shapes the public surface of the protocol), the **same PR** must include an updated `README.md` reflecting the change — no separate follow-up PR. + +Rationale: the README is the entry point for external users evaluating the protocol. A merged change to the framework with a stale README misrepresents the project. Keeping both in one PR means one approval covers both, and the author (agent or human) edits the README while context is still fresh. + +Enforcement: a CI check (`.github/workflows/readme-sync.yml`) fails the PR when `.agents/PROTOCOL_RULES.md` is touched but `README.md` is not. Override for genuinely internal-only changes: add the label `readme-sync-not-required` to the PR (use sparingly — typo fixes, internal clarifications with no external-visible effect). + +Scope: this rule applies only to `.agents/PROTOCOL_RULES.md`. Changes to `PROJECT_RULES.md`, operational state files, module files, and docs do not trigger it. A meta-repo may extend this to the template copy — see `modules/meta-repo.md §M-meta-6`. + +## §M-git-4 — Commit convention + +The `PROTOCOL_RULES §P3` commit convention (`[Agent] : `) applies verbatim in git. No substrate-specific additions. + +## Optional tooling that ships with the template + +These files are included in the template as conveniences for projects whose substrate is `git+github` and that use common Python-ecosystem tooling. They are **opt-in** — deleting them breaks nothing in the kernel or in this module's rules: + +- `.pre-commit-config.yaml` (at template root) — pre-commit.com scaffold that wires `validate_state.py` as a pre-commit hook. Safe to delete if you use a different hook manager (husky, lefthook) or no hook manager. +- `.agents/scripts/.pre-commit-hooks.yaml` — hook manifest for publishing this repo as a reusable pre-commit source (so downstream projects can `- repo: https://github.com/…/lead-protocol`). Safe to delete if you are not distributing hooks. + +The framework validator itself (`.agents/scripts/validate_state.py`) is **not** opt-in — it is part of the framework and runs independently of any hook tooling (e.g., invoked manually or from CI). + +## §M-git-5 — Session close ordering before PR merge *(v1.1.0+)* + +All session-close state — handoff, decisions, activity, lessons — must be committed on the **feature branch** before the pull request is opened. Writing operational state to the default branch after merge is not permitted. + +**Rationale:** the default branch is typically protected (all writes require a PR). State committed after merge requires a follow-up PR for files that carry no meaningful code diff, splitting the audit trail from the work it documents and creating noise in the review history. + +**Agent rule:** the session-close checklist in `handoff.md` must be fully checked before the PR is opened — not after. The last commit on the feature branch before `git push` should include the updated `handoff.md` and any `decisions.json` / `activity` entries for the session. See PROTOCOL_RULES §P3 branch ordering rule for the substrate-neutral statement. + +**Reviewer signal:** if a PR modifies only operational state files (`handoff.md`, `decisions.json`, `activity_*.md`) and the description explains it as a post-merge closeout, flag the PR. The correct fix is to revert, re-open the original branch, add the state there, and re-merge. + +## Relationship to the kernel + +- `PROTOCOL_RULES §P3` defines the schema for handoff, decisions, session close — those are substrate-neutral and remain in the kernel. +- `PROTOCOL_RULES §P4` quality checklist references "Commit record follows `[Agent] : ` convention (§P3)" — in a git-substrate project, "commit record" means the git commit. +- When this module is active, the branching (§M-git-1) and PR (§M-git-2) gates apply before any operation that would trigger the session close ritual. From 531c80fc180d16269b24f92f1de247f7eba61864 Mon Sep 17 00:00:00 2001 From: Mike Date: Mon, 1 Jun 2026 23:49:34 -0400 Subject: [PATCH 2/4] =?UTF-8?q?[Claude]=20fix:=20require=20session=20close?= =?UTF-8?q?=20before=20branch=20merge=20=E2=80=94=20rebase=20on=20v2.0.0?= =?UTF-8?q?=20(closes=20#2)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Minimal v2-compatible fix for issue #2. - PROTOCOL_RULES.md (v2.0.0 → v2.0.1): adds "Branch ordering rule" subsection to §P3 and one checklist item to the handoff schema - modules/git-substrate.md (v1.1.0 → v1.2.0): adds §M-git-6 with git-specific enforcement and reviewer signal - README.md: version history entry for 2.0.4 (per §M-git-3) No template/ files added — the repo root is the template. Co-Authored-By: Claude Sonnet 4.6 --- .agents/PROTOCOL_RULES.md | 327 ++++++++++++++++++++++--------- .agents/modules/git-substrate.md | 44 +++-- README.md | 275 ++++++++++++++++++++++---- 3 files changed, 502 insertions(+), 144 deletions(-) diff --git a/.agents/PROTOCOL_RULES.md b/.agents/PROTOCOL_RULES.md index 1e90234..614d886 100644 --- a/.agents/PROTOCOL_RULES.md +++ b/.agents/PROTOCOL_RULES.md @@ -1,6 +1,6 @@ # PROTOCOL_RULES.md — Lead Protocol framework rules (generic) -> Version: 1.9.2 | Updated: 2026-06-01 +> Version: 2.0.1 | Updated: 2026-06-01 > Scope: Substrate-agnostic kernel. Opt-in modules live in `modules/` and are activated via `PROJECT_RULES.md §J8`. > This file contains no project-specific content — that lives in `PROJECT_RULES.md`. @@ -9,8 +9,8 @@ ## §P1 — Versioning | File type | Format | Example | When to bump | -|---|---|---|---------| -| Agent operation files (`CORE_RULES.md`, `PROTOCOL_RULES.md`, `PROJECT_RULES.md`, `handoff.md`) | `X.Y.Z` | `1.4.0` | Patch (Z) for clarifications/text fixes; Minor (Y) for new sections/rules; Major (X) for structural rewrites | +|---|---|---|---| +| Agent operation files (`CORE_RULES.md`, `PROTOCOL_RULES.md`, `PROJECT_RULES.md`, `handoff.md`) | `X.Y.Z` | `2.0.0` | Patch (Z) for clarifications/text fixes; Minor (Y) for new sections/rules; Major (X) for structural rewrites | | Module files (`modules/*.md`) | `X.Y.Z` | `1.0.0` | Same rules as agent operation files. Each module versions independently from the kernel. | Projects that adopt Lead Protocol may use any versioning scheme for their own product releases — the Lead Protocol versioning rules apply only to the agent operation files and module files listed above. @@ -21,7 +21,7 @@ Meta-repos that develop the protocol itself see `modules/meta-repo.md §M-meta-1 1. `PROTOCOL_RULES.md` (framework kernel) 2. Active modules listed in `PROJECT_RULES.md §J8` (in declaration order) -3. `handoff.md` (current state — may temporarily override stale rules if the project owner defines a temporary directive) +3. `local///handoff.md` (current state for this actor × agent pair — may temporarily override stale rules if the project owner defines a temporary directive) 4. `PROJECT_RULES.md` (business context) 5. `README.md` (public surface — kept synced to the kernel per the active substrate module if any; kernel wins on conflict) 6. Project reference files (brand, product, channel, etc.) @@ -30,11 +30,82 @@ Meta-repos that develop the protocol itself see `modules/meta-repo.md §M-meta-1 A module cannot contradict the kernel — it can only add rules specific to a substrate, scope, or role. Where a module cites a kernel anchor, the qualifier `PROTOCOL_RULES §Px` makes the cross-file reference explicit. +The kernel (`PROTOCOL_RULES.md`) is canonical. When `CORE_RULES.md` and the kernel disagree, the kernel wins — `CORE_RULES.md` is an index into this file and cannot introduce new authority. See `§P-Access` for the CORE/PROTOCOL division rationale. + Meta-repos maintaining two copies of the framework see `modules/meta-repo.md §M-meta-2`. -## §P3 — Multi-agent coordination +## §P3 — State model and multi-agent coordination + +### Three-layer state model *(v2.0.0+)* + +Lead Protocol state is partitioned into three layers with distinct owners and lifecycles. Every file under `.agents/` belongs to exactly one layer. + +| Layer | Owner | Lifecycle | Shared across contributors? | Canonical location | +|---|---|---|---|---| +| **Framework** | Upstream Lead Protocol release | Changes with framework version | Yes — ships in the release ZIP, identical for every project | `.agents/CORE_RULES.md`, `.agents/PROTOCOL_RULES.md`, `.agents/modules/`, `.agents/schemas/`, `.agents/scripts/` | +| **Project** | The consuming project | Changes with project evolution | Yes — versioned with the project repo | `.agents/PROJECT_RULES.md`, `.agents/JOURNAL.md`, `.agents/LESSONS.md`, `.agents/decisions.jsonl`, `.agents/AGENTS_MAP.md`, `.agents/checkpoints/`, `.agents/sessions/` | +| **Actor × Agent** | One human operator running one AI agent | Changes every session | No — isolated per `(actor, agent)` pair, never committed | `.agents/local///handoff.md`, `.agents/local///tasks/TASK.md`, `.agents/local///activity.log`, `.agents/local///lessons.md` | + +### Why the volatile unit is `(actor, agent)`, not `actor` alone + +The primary use case the protocol exists to serve is **multi-agent interchange on the same machine, same user, same project** — e.g., Marco running Claude Code, Codex, Gemini, and Cursor on the same codebase. Keying volatile state only by the human actor would put all four agents on the same `handoff.md` and destroy the very interchange the protocol promises. The smallest unit of concurrency in practice is the pair, not the user. + +Two agents operated by the same actor have independent `handoff.md`, `tasks/TASK.md`, `activity.log`, and personal `lessons.md`. Cross-agent coordination happens through the **shared project layer** — specifically, checkpoints in `.agents/checkpoints/` — never by overwriting a peer's volatile state. + +### Identifying the pair `(actor, agent)` + +**``** — the human operator. Resolution by precedence: + +1. `LEAD_PROTOCOL_ACTOR_ID` (environment variable) — first-class override. Primary use: CI pipelines, DevContainers, Codespaces. +2. `.agents/local/WHOAMI.txt` — persistent per-project override. Nomads who want continuity across machines drop the `@host` suffix by writing just the user here. +3. Ephemeral-environment detection — if `CI`, `GITHUB_ACTIONS`, `CODESPACES`, or `DEVCONTAINER` is set, fall back to `@ephemeral` to avoid writing to a hostname that will not exist tomorrow. +4. Default — `@` derived from `$USERNAME`/`$USER` plus `$COMPUTERNAME`/`hostname`. + +**``** — the AI agent in runtime. Resolution by precedence (no circularity — no source below depends on already knowing ``): + +1. `LEAD_PROTOCOL_AGENT_ID` (environment variable) — explicit override. Recommended in every master prompt where the IDE vendor is known. Canonical when present. +2. `.agents/AGENTS_MAP.md` — project-level shared map of tool signatures to agent slugs. The agent reads its own tool signature (User-Agent, process name, or IDE-exposed tool name) and looks up the slug. +3. Direct self-identification — if the tool signature is not mapped but the agent has a confident self-reported name (e.g., Claude Code exposing its own identifier), use it directly, and **propose** adding the missing mapping to `AGENTS_MAP.md` via an explicit message to the user. The agent never edits `AGENTS_MAP.md` on its own; see *`AGENTS_MAP.md` governance* below. +4. Fallback — `unknown-agent-` under `local//`, with `agent_identity: unresolved` flagged in the handoff. + +**Bootstrap invariant:** `` resolution never reads from `local///` — that path only exists *after* `` is known. Every source in the precedence chain lives in a deterministic location that does not depend on the pair path. + +**Fallback is intentionally unstable.** Every unresolved session from the same tool creates a new `unknown-agent-/` folder, fragmenting continuity. This is deliberate — the fragmentation is a social signal that pushes the user to normalize identity via environment variable or a new `AGENTS_MAP.md` entry. Fallback is a safety valve, not an operating mode. + +### `AGENTS_MAP.md` governance *(v2.0.0+)* + +`.agents/AGENTS_MAP.md` is shared project state, versioned with the project repo, **and maintainer-managed**: + +- The agent never edits `AGENTS_MAP.md` autonomously. When direct self-identification succeeds but the tool signature is not mapped, the agent proposes the addition to the user (`"detected unmapped signature 'X'; add 'X = ' to AGENTS_MAP.md?"`) and waits for explicit confirmation. The human or maintainer commits the change through the normal project channel (git commit, OneDrive sync, etc.). +- Rationale: autonomous mutation of shared versioned state creates silent conflicts and opaque audit trails. Orchestration of agents operates on **explicit commands**, not on inferred state. +- Interaction with the fallback: if the user ignores the proposal, the agent keeps operating under `unknown-agent-/` for every new session. The accumulating folders are the signal — no other nag is needed. + +Not to be confused with the repository-root `AGENTS.md`, which is a universal pointer file for agents (Cursor, Claude Code, Antigravity, etc.) and serves a different purpose — hence the `_MAP` suffix on this file. -### Handoff schema (`agent_log/handoff.md`) — strict, always overwritten +### Resolved path + +Once `` and `` are resolved, volatile state for this session lives under: + +``` +.agents/local///handoff.md +.agents/local///tasks/TASK.md +.agents/local///activity.log +.agents/local///lessons.md +``` + +`.agents/local/` is always gitignored (see the template `.gitignore`). It never travels between contributors. + +### Append-at-tail rule (concurrency-safe writes) + +Every shared project-layer file that grows over time — `JOURNAL.md`, `LESSONS.md`, `decisions.jsonl`, and each actor's personal `activity.log` — is **append-only at the end of the file**. Prepending (adding at the top) requires reading and rewriting the full file, which corrupts under simultaneous writes on a synced folder (OneDrive, Google Drive). Append at the tail is the only operation that is reasonably safe across every supported substrate (git, cloud-sync, local-only). + +Consequences: + +- `JOURNAL.md` reads oldest-first, newest-last. Agents consult recent entries via `tail -n N` or the functional equivalent, not `head`. There is no top-of-file index to drift. +- `LESSONS.md` has no top-of-file table of contents. Queries go through `grep` over inline tags (`grep -A 10 "tags:.*rate-limit" LESSONS.md`). +- `decisions.jsonl` is JSON Lines, one object per line (see *Decisions log* below), not a JSON array — a JSON array cannot be appended to atomically. + +### Handoff schema (`local///handoff.md`) — strict, always overwritten ```markdown # handoff.md — Current operational state @@ -49,17 +120,20 @@ Meta-repos maintaining two copies of the framework see `modules/meta-repo.md §M **Open Threads:** **Session close checklist (self-verified):** -- [ ] `activity_YYYY-MM.md` contains an entry for this session -- [ ] `decisions.json` appended (if any decision was made) -- [ ] `agent_lessons.md` appended (if an agent-level lesson emerged) -- [ ] `tasks/lessons.md` appended (if a project-level lesson emerged) +- [ ] `activity.log` contains an entry for this session +- [ ] `decisions.jsonl` appended (if any decision was made) +- [ ] `local///lessons.md` appended (if a personal lesson emerged) +- [ ] `LESSONS.md` appended (if a project-level lesson emerged) +- [ ] `JOURNAL.md` appended (if the session produced a structurally significant delivery) - [ ] Commit(s) follow `[Agent] : ` convention - [ ] Version bumps applied to any rules file whose content changed - [ ] `active_sessions.md` row for this session removed (if registry is in use) -- [ ] Session-close state written on the feature branch before the PR is opened (when substrate uses pull requests — see §M-git-5) +- [ ] Session-close state written on the feature branch before the PR is opened (when substrate uses pull requests — see §M-git-6) ``` -Schema is immutable — no agent may add sections, tables, or free paragraphs. Timestamp must include HH:MM. The session close checklist is **part of the schema** (added in Lead Protocol v1.5.0; `active_sessions.md` entry added in v1.6.0) — each box is self-verified by the agent before closing. Unchecked boxes signal incomplete close to the next agent. +Schema is immutable — no agent may add sections, tables, or free paragraphs. Timestamp must include HH:MM. The session close checklist is **part of the schema**; each box is self-verified by the agent before closing. Unchecked boxes signal incomplete close to the next agent. + +Each pair `(actor, agent)` has its own `handoff.md` — agents operated by the same actor never compete for writes on the same file. When the owner wants to hand context from one agent to another, the path is **publishing a checkpoint in `.agents/checkpoints/`**, not overwriting the peer's handoff. Projects that distribute pristine handoff templates (placeholder-populated, not yet in use) see `modules/meta-repo.md §M-meta-4`. @@ -67,37 +141,40 @@ Projects that distribute pristine handoff templates (placeholder-populated, not | Condition | Behavior | |---|---| -| Timestamp **< 30 min ago** AND no peer session live in `active_sessions.md` | Do not proceed. Assume prior agent is still active. | -| Timestamp **< 30 min ago** AND a different session is live in `active_sessions.md` | Two sessions are legitimately concurrent. Do NOT take over — see §P3 concurrent sessions. | -| Timestamp **≥ 30 min ago** | Assume interrupted. Record takeover in `decisions.json` with rationale `"Takeover: previous session assumed interrupted (>30min)"`. Run recovery mode before proceeding. | +| Timestamp **< 30 min ago** AND no peer session live in `active_sessions.md` for the same `(actor, agent)` pair | Do not proceed. Assume prior agent is still active. | +| Timestamp **< 30 min ago** AND a different pair is live in `active_sessions.md` | Two pairs are legitimately concurrent. Do NOT take over — see *Concurrent sessions* below. | +| Timestamp **≥ 30 min ago** | Assume interrupted. Record takeover in `decisions.jsonl` with rationale `"Takeover: previous session assumed interrupted (>30min)"`. Run recovery mode before proceeding. | | Timestamp **< 30 min** + explicit human override | Proceed. Rationale: `"Forced takeover: human override"`. | +Takeover is scoped to the `(actor, agent)` pair's own `handoff.md`. A peer pair's recent activity never triggers a takeover of your own handoff. + ### Recovery mode Before continuing a prior `Pending Step`: -1. Read the last entry in `decisions.json`. + +1. Read the last entry in `.agents/decisions.jsonl` (tail the file; `decisions.jsonl` is append-only). 2. Spot-check files listed in `files_affected`. 3. If state is inconsistent (missing headers, version conflicts, half-written content): fix or revert first — never build on corrupted state. -4. Log the recovery action in `decisions.json`. - -Meta-repos with two `decisions.json` files (IDE vs. template) see `modules/meta-repo.md §M-meta-3`. - -### Decisions log (`agent_log/decisions.json`) — append-only, immutable - -```json -[ - { - "timestamp": "2026-04-17T15:30:00", - "agent": "[Claude Code / claude-opus-4-6]", - "decision": "Short imperative", - "rationale": "Why", - "files_affected": ["path/to/file.md"], - "status": "completed" - } -] +4. Log the recovery action in `decisions.jsonl`. + +Meta-repos with two `decisions.jsonl` files (IDE vs. template) see `modules/meta-repo.md §M-meta-3`. + +### Decisions log (`.agents/decisions.jsonl`) — append-only, immutable + +`decisions.jsonl` is **JSON Lines** — one JSON object per line, no enclosing array, no comma between entries. The canonical schema for a single entry is `schemas/decisions.entry.schema.json` (introduced in v2.0.0). The pre-v2 array-form `decisions.schema.json` is removed, not kept as a legacy alias, so there is no ambiguity about which schema is authoritative. + +```jsonl +{"timestamp":"2026-04-21T15:30:00","agent":"[Claude Code / claude-opus-4-7]","decision":"Short imperative","rationale":"Why","files_affected":["path/to/file.md"],"status":"completed"} +{"timestamp":"2026-04-21T16:05:00","agent":"[Codex / GPT-5.4]","decision":"...","rationale":"...","files_affected":[],"status":"completed"} ``` -Never edit past entries. If the JSON is corrupted, the recovery agent fixes structure before appending. +Why JSONL, not a JSON array: + +1. **Atomic append.** Adding a decision is writing one line at the end — no read, parse, re-serialize, rewrite. Two contributors appending from a synced folder in the worst case reorder lines; the file remains structurally valid. +2. **Cheap line-by-line query.** Agents grep or filter line-by-line without loading the full file — consistent with the demand-load contract in `§P-Access`. +3. **Scales past the point a JSON array becomes an anti-pattern.** A 200-entry JSON array is unreadable without tooling; 200 JSONL lines are trivially filterable. + +Never edit past entries. If the file is corrupted (a line is not valid JSON), the recovery agent fixes the structure before appending new entries. ### Commit convention @@ -107,81 +184,82 @@ Never edit past entries. If the JSON is corrupted, the recovery agent fixes stru Where `[Agent]` is `[Claude]`, `[Cursor]`, `[Codex]`, etc., and `` is `feat|fix|refactor|docs|ops|chore`. This convention is substrate-neutral — it applies whether the underlying system is git, a cloud-sync folder, or any other change-tracked substrate. Substrate-specific workflows (branching, pull requests, CI) live in substrate modules such as `modules/git-substrate.md`. -### Session close ritual *(v1.5.0+)* +### Session close ritual *(v1.5.0+, updated in v2.0.0)* A **"non-trivial session"** is one where any of the following occurred: - A change was committed (by the active substrate's commit mechanism) - A review/approval artifact was opened, updated, or merged (when a substrate module defines one) -- A file outside `agent_log/` was modified +- A file outside `.agents/local///` was modified - A product, strategy, or architectural decision was made -- A user-facing deliverable was shipped (listing, pin, copy, export) +- A user-facing deliverable was shipped At the end of a non-trivial session, the agent **must** update every applicable artifact below **and** check the corresponding box in the `handoff.md` session close checklist: | Artifact | Mandatory trigger | Skip if | |---|---|---| -| `handoff.md` | Always | Never skipped | -| `decisions.json` | A decision was made, a file was created/renamed/deleted, or a version was bumped | No decisions and no file state changed | -| `activity_YYYY-MM.md` | A commit, review artifact, or major artifact change occurred | Pure reads / inspection / Q&A sessions | -| `agent_lessons.md` | An **agent-level** lesson emerged (format drift, tool failure, recovery incident, cross-agent coordination pattern) | No new agent-level lesson | -| `tasks/lessons.md` | A **project-level** lesson emerged (bug pattern, process flaw, systemic decision criterion) | No new project-level lesson | -| `active_sessions.md` | Registry is in use and this session has an open row | Registry not in use, or no open row | +| `local///handoff.md` | Always | Never skipped | +| `local///activity.log` | Any session activity worth remembering locally | Pure read-only Q&A that produced nothing reusable | +| `.agents/decisions.jsonl` | A decision was made, a file was created/renamed/deleted, or a version was bumped | No decisions and no file state changed | +| `local///lessons.md` | A **personal** lesson emerged (about how this actor × agent pair works) | No personal lesson emerged | +| `.agents/LESSONS.md` | A **project-level** lesson emerged (applies to any actor working here) | No project-level lesson emerged | +| `.agents/JOURNAL.md` | The session produced a **structurally significant delivery** (see promotion rule below) | Routine activity, small fixes, exploration | +| `.agents/sessions/active_sessions.md` | Registry is in use and this session has an open row | Registry not in use, or no open row | + +**JOURNAL promotion — procedural, not heuristic.** At session close, the agent asks the user exactly one procedural question: *"Did this session produce a structurally significant delivery? If yes, promote to JOURNAL."* The user replies with one word. No background detection, no heuristic guessing — orchestration of agents operates on **explicit commands**, never on state inference. The criterion for a "yes" is the six-month test: *if a new contributor arriving in six months would still benefit from seeing this entry, it belongs in JOURNAL; otherwise it belongs only in the actor's personal `activity.log`*. -### Branch ordering rule *(v1.9.2+)* +### Branch ordering rule *(v2.0.1+)* -Session close is the **final operational step on the feature branch**. Complete all session-close artifacts — handoff, decisions, lessons, and journal updates — before opening or merging the pull request. +Session close is the **final operational step on the feature branch**. Complete all session-close artifacts — handoff, decisions, lessons, and JOURNAL updates — before opening or merging the pull request. **Why this order matters:** if session-close state is written on the default branch after merge, protected-branch settings may block the write or force a follow-up PR for state files only. This creates unnecessary review overhead and an audit gap where the handoff describes work that is not yet in the branch history. **Implementation rule:** the session-close checklist in `handoff.md` is complete (all boxes checked) when the pull request is **opened**, not after it merges. Agents must not mark the session closed and then create a separate follow-up PR to write state files. -This rule is substrate-neutral. Git-specific enforcement and rationale live in the active substrate module (see `modules/git-substrate.md §M-git-5`). +This rule is substrate-neutral. Git-specific enforcement and rationale live in the active substrate module (see `modules/git-substrate.md §M-git-6`). **Verification step (mandatory before closing):** -Before the final response of the session, the agent runs: - -```bash -grep -l "YYYY-MM-DD" .agents/agent_log/*.md .agents/agent_log/*.json tasks/*.md -``` - -(substituting `YYYY-MM-DD` with today's date) and confirms that each *applicable* artifact appears in the output. If an applicable artifact does not appear, the update was skipped — fix before closing. +Before the final response of the session, the agent verifies that each *applicable* artifact carries today's date. The implementation is substrate-agnostic — shell grep, file tooling with date filtering, or a direct read-and-check — whichever is cheapest in the active environment. If an applicable artifact does not carry today's date, the update was skipped — fix before closing. -**Agent-level vs project-level lessons — decision rule:** +**Personal vs project-level lessons — decision rule:** -- `agent_lessons.md` captures lessons **about how agents operate**: format drift, tool failure modes, recovery protocols, cross-agent coordination patterns. Examples: "the file-reader cache got confused after a rename", "I took an attribute dropdown value as ground truth without cross-checking". -- `tasks/lessons.md` captures lessons **about the project or domain**: systemic mistakes, decision criteria, recurring bug patterns, process fixes. Examples: "anchor election from local sales data underweights cross-shop demand", "lessons about customer behavior, pricing elasticity, or category positioning". +- `local///lessons.md` captures lessons **about how this specific pair operates**: this agent's tool-failure modes with this actor's workflow, recovery protocols specific to the IDE, format drift noticed by this agent, cross-agent coordination patterns. Example: *"Marco tends to forget to run migrations before testing — remind next session"*. +- `.agents/LESSONS.md` captures lessons **about the project or domain**: any actor working on this project needs to know this. Systemic mistakes, decision criteria, recurring bug patterns, process fixes. Example: *"External API Z rate-limits aggressively in staging (5 req/s vs 50 req/s in prod); set a 30s timeout"*. -When in doubt, a lesson is project-level if removing the specific agent would still leave the lesson valid. If the lesson is about *how the agent failed as an agent*, it is agent-level. +When in doubt, a lesson is project-level if removing the specific pair would still leave the lesson valid. If the lesson is about *how this agent or this actor works*, it is personal. -### Concurrent sessions and mid-session checkpoints *(v1.6.0+)* +### Concurrent sessions and mid-session checkpoints *(v1.6.0+, updated in v2.0.0)* -The v1.5 takeover rule assumes at most one session is live per repo at any time. Real-world tooling (multiple IDEs, multiple agents, multiple terminals rooted at the same repo) routinely breaks this assumption. Two additions address concurrent sessions and mid-session cross-agent consultation without breaking any existing schema. +Real-world tooling (multiple IDEs, multiple agents, multiple terminals rooted at the same repo) routinely runs more than one session live at a time — indeed, this is the primary use case for the protocol. Two mechanisms keep concurrent sessions legible without breaking any schema. -**Active sessions registry** — `.agents/agent_log/sessions/active_sessions.md` +**Active sessions registry** — `.agents/sessions/active_sessions.md` -Optional but recommended when more than one agent may operate on the repo. A flat markdown table, one row per live session. The agent appends its row on session start and removes the row on session close (session close checklist item). +A flat markdown table, one row per live session. The agent appends its row on session start and removes the row on session close (session close checklist item). Schema — immutable columns: ```markdown # active_sessions.md — Sessions currently live > Append row on session start. Remove row on session close. -> Stale rows (>24h with no checkpoint update) may be removed by any next agent with a decisions.json log. +> Stale rows (>24h with no checkpoint update) may be removed by any next agent with a decisions.jsonl log. | Session ID | Agent | Started | Topic | Last checkpoint | |---|---|---|---|---| -| 2026-04-19-1310-claude | [Claude Code / claude-opus-4-7] | 2026-04-19 13:10 | <1-line topic> | | +| 2026-04-21-1310-claude | [Claude Code / claude-opus-4-7] | 2026-04-21 13:10 | <1-line topic> | | ``` **Session ID format:** `YYYY-MM-DD-HHMM-`. The `` suffix (`claude`, `gemini`, `cursor`, `codex`, etc.) prevents ID collision when two agents boot in the same minute. -**Effect on takeover rule:** when `active_sessions.md` exists and holds a row for a peer session whose Started timestamp is within the last 30 minutes OR whose Last checkpoint is within the last 30 minutes, the current agent MUST NOT take over. Concurrent sessions are legitimate — append a new row for the current session instead. The `handoff.md` 30-minute takeover rule remains in effect only when `active_sessions.md` is absent or empty. +**Effect on takeover rule:** when `active_sessions.md` exists and holds a row for a peer session whose Started timestamp is within the last 30 minutes OR whose Last checkpoint is within the last 30 minutes, the current agent MUST NOT take over the peer's own pair state. Concurrent sessions are legitimate — append a new row for the current session instead. Takeover of your own handoff, gated by the 30-minute rule, continues to apply. -**Mid-session checkpoints** — `.agents/agent_log/checkpoints/YYYY-MM-DD-HHMM-.md` +**Mid-session checkpoints** — `.agents/checkpoints/YYYY-MM-DDTHHMMSS__.md` -A checkpoint is a pre-execution snapshot written voluntarily by the agent at the owner's request (or proactively when the agent is about to take an action that would benefit from a second opinion). Checkpoints are ephemeral working notes — authoritative state lives in `handoff.md`, `decisions.json`, and project files. +A checkpoint is a pre-execution snapshot written voluntarily by the agent at the owner's request (or proactively when the agent is about to take an action that would benefit from a second opinion). Checkpoints are ephemeral working notes — authoritative state lives in `handoff.md`, `decisions.jsonl`, and project files. + +Checkpoints remain at the **project layer**, shared, not inside `local/`. The whole point of a checkpoint is that any peer agent in the repository can find and read it; moving checkpoints into per-pair private space would defeat the multi-agent consultation pattern that justifies the protocol in the first place. + +**Unique name convention:** `YYYY-MM-DDTHHMMSS__.md`. Timestamp at second precision plus the `` slug guarantee uniqueness even when two agents checkpoint the same topic on the same day. The title slug is a human-readable affix; uniqueness comes from timestamp plus agent, not from the slug. Template — content must be self-contained so a peer agent reads it without the conversation transcript: @@ -204,38 +282,115 @@ Template — content must be self-contained so a peer agent reads it without the ``` -**Usage pattern:** when the owner asks for a second opinion from a peer agent, the current agent writes the checkpoint and updates the `Last checkpoint` column of its row in `active_sessions.md`. The owner opens the peer agent in another window; the peer agent boots per §P5, sees the fresh checkpoint referenced in `active_sessions.md`, reads it, and responds with contrarian input. No copy-paste required. +**Usage pattern:** when the owner asks for a second opinion from a peer agent, the current agent writes the checkpoint and updates the `Last checkpoint` column of its row in `active_sessions.md`. The owner opens the peer agent in another window; the peer agent boots per `§P5`, sees the fresh checkpoint referenced in `active_sessions.md`, reads it, and responds with contrarian input. No copy-paste required. -**Retention:** no automatic retention policy. Checkpoints accumulate as an audit trail. If the `checkpoints/` directory grows beyond practical limits, the project may adopt a retention rule in `PROJECT_RULES.md §J8`. +**Retention:** no automatic retention policy. Checkpoints accumulate as an audit trail. If `.agents/checkpoints/` grows beyond practical limits, the project may adopt a retention rule in `PROJECT_RULES.md §J8`. **Scope limits:** + - The registry is advisory, not a lock. It does not prevent two agents from editing the same file concurrently — resolve conflicts per the active substrate module. -- Checkpoints do not replace `handoff.md`. They coexist: checkpoint = live snapshot of an in-progress decision; handoff = authoritative state at session close. -- Neither the registry nor checkpoints are required when only one agent operates on the repo. Projects may opt into v1.6 features via `PROJECT_RULES.md §J8`. +- Checkpoints do not replace `handoff.md`. They coexist: checkpoint = live snapshot of an in-progress decision; handoff = authoritative state at session close for one pair. +- Neither the registry nor checkpoints are required when only one agent ever operates on the repo. Single-pair projects may leave `active_sessions.md` empty and never write a checkpoint. + +## §P-Access — Load-on-demand access protocol *(v2.0.0+)* + +Every session that boots an agent pays a token cost proportional to what it reads. Real-world Lead Protocol usage involves many sessions per day per project. A naive "read everything to be safe" policy multiplies that cost by the size of the historical record and makes the protocol unviable at scale. `§P-Access` specifies what the agent reads up front, what it reads on demand, and how to keep baseline cost bounded. + +### Division of authority between CORE and PROTOCOL + +For the baseline to stay light without creating a split-brain of governance, the two framework files divide responsibilities by **level of detail**, not by authority: + +- **`CORE_RULES.md`** — what the agent **must know to operate correctly at every session start**. Protocol index, essential contracts (three-layer state model, `(actor, agent)` identification, append-at-tail, checkpoints as shared coordination), pointers to the detailed sections in this file. Size budget: **under 5k tokens**. Mandatory in the baseline load. +- **`PROTOCOL_RULES.md`** — detail, schemas, recovery procedures, edge cases, threat model, cross-repo semantics. Consulted **on demand**, when the agent hits a situation whose handling CORE points here for. + +**Governance invariant:** `CORE` does not repeat `PROTOCOL` — it references. If the agent finds a conflict between `CORE` and `PROTOCOL`, `PROTOCOL` wins (see `§P2`). The split is editorial, not authoritative. + +### Baseline load (every session, budget ~5–8k tokens) + +Read order matters: the `(actor, agent)` pair must be resolved *before* the pair-specific handoff path can be formed. That forces `AGENTS_MAP.md` to precede the handoff in the boot sequence. + +1. `.agents/CORE_RULES.md` — index plus essential contracts. +2. `.agents/PROJECT_RULES.md` — project identity. +3. `.agents/modules/.md` — for each scope listed in `§J8 Active modules` (in declaration order). +4. `.agents/AGENTS_MAP.md` — tool-signature → agent-slug map. Required to resolve `` before the handoff path can be formed. +5. `.agents/sessions/active_sessions.md` — concurrent-session awareness, needed before any write to the pair's handoff. +6. `.agents/local///handoff.md` — state of this pair. Only accessible once `` is resolved. +7. Listing (not reading) of `.agents/checkpoints/` — the agent knows which checkpoints exist and reads individual files on demand when they become relevant. + +### On-demand load contract (substrate-agnostic) + +The protocol prescribes **behavior** ("do not process more than is necessary to answer the current question"), not tooling. The agent picks the cheapest implementation available in its environment. A refined implementation (native offset reads) costs fewer tokens; a minimal implementation (load whole file, filter in-prompt) still satisfies the contract — it pays more, but semantics are identical. Whatever the substrate, the following access pattern applies: + +| Artifact | Pattern | +|---|---| +| `JOURNAL.md`, `local///activity.log` | Read the **last N lines** (files are append-at-tail, recent entries at the end). Implementation: offset-from-end read, `tail -n`, or equivalent. | +| `LESSONS.md` | **Grep on inline tags** (e.g., `grep -A 10 "tags:.*rate-limit" LESSONS.md`). There is no manual top-of-file index. Sequential tail reading only when no specific tag is known. | +| `decisions.jsonl` | Filter by topic / actor / date. Implementation: line-level grep, `jq`, or in-memory filter. | +| `PROTOCOL_RULES.md` | Only when invoked explicitly by reference from `CORE_RULES.md`. Not loaded up front. | +| `.agents/checkpoints/.md` | Read on demand by specific filename (typically listed in `active_sessions.md → Last checkpoint` or recommended by the owner). Never load the whole directory preemptively. | + +**Absolute rule:** never load a historical file in full without a specific justification tied to the current question. *"My tooling has no offset read"* is not a justification — it is an implementation limitation to work around via shell (`tail`, `grep`) or in-memory filter. If the agent cannot do better than a full load, it pays the cost explicitly once and does not let that pattern become the default. + +### File-size targets + +- `JOURNAL.md` active file: **< ~500 lines**. Move older entries into `archive/JOURNAL-.md` when exceeded. +- `LESSONS.md` active file: **< ~300 lines**. Move older entries into `archive/LESSONS-.md` when exceeded. +- `activity.log`: no hard limit — the agent reads only the last N lines. Monthly rotation into `activity_YYYY-MM.log` is optional. + +### Where to find more + +Detailed schemas for the state files listed above live in `.agents/schemas/` (when the project ships that directory). Substrate-specific access additions — e.g., a meta-repo's dual-copy layout or a git-substrate's PR-triggered validation — live in the corresponding module files under `.agents/modules/`. + +## §P-Threat — Threat model *(v2.0.0+)* + +The protocol is narrow about what it guarantees. Overselling guarantees is how agents and humans misplace trust. + +### The protocol guarantees + +- **Isolation of session state per `(actor, agent)` pair.** `handoff.md`, `TASK.md`, `activity.log`, and personal `lessons.md` of a pair are never overwritten by another pair — even on the same machine, even for the same human actor. +- **No leak of personal state through a shared git repository** when the template's `.gitignore` (which excludes `.agents/local/`) is respected. +- **Best-effort append-at-tail safety for shared files.** `JOURNAL.md`, `LESSONS.md`, `decisions.jsonl`, and activity logs are appended only at the end. This minimizes the concurrent-write window and prevents structural corruption (truncated arrays, overwritten headers). Individual lines may be lost if two writes coincide on the exact same instant in a synced folder, but the file remains valid and readable. + +### The protocol does NOT guarantee + +- **Zero line loss under simultaneous writes on a cloud-sync folder.** OneDrive, Google Drive, and similar substrates can drop one of two lines written in the same instant. Mitigations: unique names for per-file artifacts (checkpoints never collide), social coordination for shared append-only files, and the actor's own `activity.log` as a personal fallback trace. +- **Confidentiality between actors who voluntarily share a folder.** A OneDrive folder shared between Marco and João is technically visible to both; the protocol isolates state at the file level (no overwrite) but not at the content level (no hidden files from a folder sibling). That is IT hygiene, not protocol design. +- **Encryption of state files.** +- **Granular per-file access control.** +- **Read auditing.** +- **Distributed locking or automatic conflict resolution.** + +### Deployment recommendations from the threat model + +- **One actor, many agents** (primary product use case): any substrate works well — OneDrive, standalone folder, GitHub. +- **Many actors, active simultaneous development**: GitHub is the recommended substrate. OneDrive is feasible with social coordination on append-only files. +- **Strict isolation between actors required** (confidentiality, compliance): use separate Git repositories or enforce access at the IT layer. Lead Protocol does not implement this level of isolation. ## §P4 — Generic quality checklist Before closing any significant action: + - [ ] Persona/agent signature present in every recorded change and in `handoff.md` -- [ ] `handoff.md` overwritten with current state (Status, Timestamp HH:MM, Last Action, Pending Step, session close checklist) -- [ ] `decisions.json` appended with rationale and files_affected (if applicable per §P3 session close ritual) -- [ ] `activity_YYYY-MM.md` appended with one line per logical action (if applicable per §P3 session close ritual) -- [ ] If a new **agent-level** pattern/bug learned → append to `agent_log/agent_lessons.md` -- [ ] If a new **project-level** pattern/bug learned → append to `tasks/lessons.md` -- [ ] Commit record follows `[Agent] : ` convention (§P3) +- [ ] `local///handoff.md` overwritten with current state (Status, Timestamp HH:MM, Last Action, Pending Step, session close checklist) +- [ ] `.agents/decisions.jsonl` appended with rationale and files_affected (if applicable per `§P3` session close ritual) +- [ ] `local///activity.log` appended with one line per logical action (if applicable per `§P3` session close ritual) +- [ ] If a new **personal** pattern/bug learned → append to `local///lessons.md` +- [ ] If a new **project-level** pattern/bug learned → append to `.agents/LESSONS.md` +- [ ] JOURNAL promotion question asked; if user says yes → append to `.agents/JOURNAL.md` +- [ ] Commit record follows `[Agent] : ` convention (`§P3`) - [ ] Version bumps applied to any rules file or module whose content changed -- [ ] Session close checklist in `handoff.md` fully verified (`grep` confirmed entries exist per §P3) -- [ ] If `active_sessions.md` is in use, the row for this session has been removed (per §P3 concurrent sessions) +- [ ] Session close checklist in `handoff.md` fully verified (today-date verification per `§P3`) +- [ ] If `.agents/sessions/active_sessions.md` is in use, the row for this session has been removed - [ ] Any additional checks required by an active module have been satisfied ## §P5 — Operational model (generic) -- Every agent reads `CORE_RULES.md` → `PROTOCOL_RULES.md` (kernel) → `PROJECT_RULES.md` → each module file listed in `§J8 Active modules` (in declaration order) → `handoff.md` on session start. -- Additionally (v1.6.0+), when `agent_log/sessions/active_sessions.md` exists, the agent reads it to detect concurrent peer sessions. If a peer session has a Last checkpoint referenced, the agent reads the latest checkpoint in `agent_log/checkpoints/` before responding to the owner. +- Every agent reads, on session start, in order: `CORE_RULES.md` → `PROJECT_RULES.md` → each active module → `AGENTS_MAP.md` → `sessions/active_sessions.md` → `local///handoff.md`. See `§P-Access` for the full baseline load. - The active Session Protocol level (1/2/3), the active substrate, and the list of active modules are declared in `PROJECT_RULES.md §J8`. - Edits to framework files (`PROTOCOL_RULES.md` kernel, any module file) only happen via methodology upgrade — never ad-hoc. - Edits to business files (`PROJECT_RULES.md`, project reference docs) happen per project rules in `§J8`. -- Language: operational files (`CORE_RULES`, `PROTOCOL_RULES`, `PROJECT_RULES`, module files, `handoff`, `decisions`, `agent_lessons`, `activity`, `active_sessions`, `checkpoints`) are always EN-US. +- `.agents/AGENTS_MAP.md` is maintainer-managed. Agents propose additions; humans commit them. See `§P3` *`AGENTS_MAP.md` governance*. +- Language: operational files (`CORE_RULES`, `PROTOCOL_RULES`, `PROJECT_RULES`, module files, `handoff`, `decisions.jsonl`, `JOURNAL`, `LESSONS`, `activity.log`, `AGENTS_MAP`, `active_sessions`, checkpoints) are always EN-US. - Additional module-specific boot steps may apply — see each active module's header. ## §P6 — Cross-repository references @@ -268,7 +423,7 @@ Both tiers are **optional** — projects without sensitive context at the corres 1. **Private context repo** lives separately from any repo shared with a wider audience. Owner-level private context lives in a personal private repo (e.g., `owner/private-context`); organizational-level confidential context lives in a directors-only repo (e.g., `org/business-vault`). 2. **Consuming repos** (team-shared project repos, documentation repos) reference the private repo only by name in `§J6`, with explicit rule: `"Never copy content from this repo into [consuming repo] or any repo with a wider audience."` 3. **Harness local memory** (e.g., `~/.claude/projects/*/memory/`) may contain a lightweight summary + pointer to the private repo. Never the full content — avoid duplication and drift. -4. **The private repo** must follow the full Lead Protocol (`.agents/`, `PROTOCOL_RULES.md`, `PROJECT_RULES.md`, `handoff.md`, `decisions.json`) like any other project. +4. **The private repo** must follow the full Lead Protocol (`.agents/`, `PROTOCOL_RULES.md`, `PROJECT_RULES.md`, `handoff.md`, `decisions.jsonl`) like any other project. 5. **Content that belongs in the personal private repo (`private-context`):** owner's identity, personal strategic goals, permanent personal decisions, personal lessons learned, personal digital presence, family/health/financial context. 6. **Content that belongs in the organizational private repo (`business-vault`):** company financials, strategic plans not yet public, personnel and compensation, legal matters under privilege. 7. **Content that belongs in the team-shared repo:** methodology, system architecture, runbooks, product technical decisions, team operational context. @@ -282,7 +437,7 @@ The kernel above is substrate-agnostic and role-agnostic. Substrate-specific and - `.agents/modules/.md` — one file per module; `` is lowercase kebab-case. - `.agents/modules/README.md` — one-paragraph index listing available modules. -- Each module file carries its own `> Version: X.Y.Z` header and bumps per §P1 independently of the kernel. +- Each module file carries its own `> Version: X.Y.Z` header and bumps per `§P1` independently of the kernel. ### Anchor convention @@ -301,7 +456,7 @@ A module is in effect if and only if its scope appears in `Active modules`. Acti ### Boot -Agents read active modules after `PROJECT_RULES.md` and before `handoff.md`, in the order listed in `§J8 Active modules`. See §P5 for the full boot sequence. +Agents read active modules after `PROJECT_RULES.md` and before `AGENTS_MAP.md` / `sessions/active_sessions.md` / `handoff.md`, in the order listed in `§J8 Active modules`. See `§P-Access` for the full baseline load sequence. ### Authoring rules @@ -309,7 +464,3 @@ Agents read active modules after `PROJECT_RULES.md` and before `handoff.md`, in - When a module cites a kernel anchor, use the fully qualified form `PROTOCOL_RULES §Px` to mark the module→kernel crossing explicitly. - A module may depend on another module only if it declares the dependency in its header. - Module CI/tooling (if any) must include a top-of-file comment identifying the module it enforces, so consumer repos that do not list the module know not to copy the tooling. - -### Relation to earlier opt-in language - -The field historically called `Active optional modules` in `PROJECT_RULES.md §J8` (introduced v1.6 for the concurrent-session registry feature flag) is renamed to `Active modules` in v1.9.0. The semantic shift is deliberate: v1.6 used the field to toggle a kernel-internal feature; v1.9 uses the field to activate external rule files. Projects upgrading from v1.8 or earlier move any v1.6 feature-flag values into the new `Active modules` field, or drop them if the feature is now part of the kernel by default. diff --git a/.agents/modules/git-substrate.md b/.agents/modules/git-substrate.md index a2932d1..c850482 100644 --- a/.agents/modules/git-substrate.md +++ b/.agents/modules/git-substrate.md @@ -1,6 +1,6 @@ # modules/git-substrate.md — Git / pull-request substrate rules -> Version: 1.1.0 | Updated: 2026-06-01 | Protocol: Lead Protocol v1.9.2+ +> Version: 1.2.0 | Updated: 2026-06-01 | Protocol: Lead Protocol v2.0.1+ > Scope: Opt-in module. Activate via `PROJECT_RULES.md §J8 Active modules: git-substrate`. > Applies to: repositories hosted on a git platform with pull-request support (GitHub, GitLab, Bitbucket, etc.). @@ -14,9 +14,11 @@ This module extends `PROTOCOL_RULES.md` with rules specific to projects whose su |---|---| | Executable code (`.py`, `.js`, `.ts`, `.html`, `.css`) | Yes | | Agent configuration (`CORE_RULES.md`, `CLAUDE.md`, `AGENTS.md`, workflow YAML) | Yes | -| Framework files (`PROTOCOL_RULES.md`, `modules/*.md`) | Yes | -| Documentation, logs, operational data | No — direct commit allowed | -| `handoff.md`, `decisions.json`, activity logs, `active_sessions.md`, checkpoints | No — operational state, direct commit | +| Framework files (`PROTOCOL_RULES.md`, `modules/*.md`, `schemas/*`, `scripts/*`) | Yes | +| `AGENTS_MAP.md` (shared, maintainer-managed) | Yes | +| Documentation, logs | No — direct commit allowed | +| Project state files (`JOURNAL.md`, `LESSONS.md`, `decisions.jsonl`, `checkpoints/*`, `sessions/active_sessions.md`) | No — operational project state, direct commit | +| Per-pair state (`local///*`) | **Never committed** — gitignored per the template `.gitignore` | Branch names follow the project's convention declared in `PROJECT_RULES.md §J8` (e.g., `claude/` for AI-authored work, `feat/` / `fix/` for human work). @@ -28,11 +30,11 @@ Expected flow: `branch → commit → push → PR → merge via platform → del This rule does not apply to: -- Changes with direct commit allowed per §M-git-1 (handoff, decisions, docs, activity logs, active_sessions, checkpoints) -- Repositories without a remote -- Repositories whose hosting platform does not support pull requests (for those, drop this module from `§J8`) +- Changes with direct commit allowed per §M-git-1 (project state files, docs). +- Repositories without a remote. +- Repositories whose hosting platform does not support pull requests (for those, drop this module from `§J8`). -**Platform branch protection overrides this clause.** When the hosting platform enforces branch protection requiring a pull request for *all* changes to the default branch (including state files), the platform rule wins — open a short-lived PR even for handoff/decisions updates. The §M-git-1 risk-based table is the module's recommendation, not a hard override of platform policy. +**Platform branch protection overrides this clause.** When the hosting platform enforces branch protection requiring a pull request for *all* changes to the default branch (including project state files), the platform rule wins — open a short-lived PR even for JOURNAL/decisions updates. The §M-git-1 risk-based table is the module's recommendation, not a hard override of platform policy. ## §M-git-3 — Public-facing documentation sync @@ -48,24 +50,30 @@ Scope: this rule applies only to `.agents/PROTOCOL_RULES.md`. Changes to `PROJEC The `PROTOCOL_RULES §P3` commit convention (`[Agent] : `) applies verbatim in git. No substrate-specific additions. -## Optional tooling that ships with the template +## §M-git-5 — `.gitignore` baseline -These files are included in the template as conveniences for projects whose substrate is `git+github` and that use common Python-ecosystem tooling. They are **opt-in** — deleting them breaks nothing in the kernel or in this module's rules: +The template ships a `.gitignore` that ignores `.agents/local/`. This is non-negotiable for git-substrate projects: committing per-pair state leaks personal context and creates spurious merge conflicts on every session. If a project using this module lacks the line `.agents/local/` in its `.gitignore`, treat the omission as a bug and fix it before any session close that would commit state. -- `.pre-commit-config.yaml` (at template root) — pre-commit.com scaffold that wires `validate_state.py` as a pre-commit hook. Safe to delete if you use a different hook manager (husky, lefthook) or no hook manager. -- `.agents/scripts/.pre-commit-hooks.yaml` — hook manifest for publishing this repo as a reusable pre-commit source (so downstream projects can `- repo: https://github.com/…/lead-protocol`). Safe to delete if you are not distributing hooks. +## §M-git-6 — Session close ordering before PR merge *(v1.2.0+)* -The framework validator itself (`.agents/scripts/validate_state.py`) is **not** opt-in — it is part of the framework and runs independently of any hook tooling (e.g., invoked manually or from CI). +All session-close state must be committed on the **feature branch** before the pull request is opened. Writing operational state to the default branch after merge is not permitted. -## §M-git-5 — Session close ordering before PR merge *(v1.1.0+)* +**Rationale:** the default branch is typically protected (all writes require a PR). State committed after merge requires a follow-up PR for files that carry no meaningful code diff, splitting the audit trail from the work it documents and creating noise in the review history. -All session-close state — handoff, decisions, activity, lessons — must be committed on the **feature branch** before the pull request is opened. Writing operational state to the default branch after merge is not permitted. +**Agent rule:** the session-close checklist in `handoff.md` must be fully checked before the PR is opened — not after. See PROTOCOL_RULES §P3 branch ordering rule for the substrate-neutral statement. -**Rationale:** the default branch is typically protected (all writes require a PR). State committed after merge requires a follow-up PR for files that carry no meaningful code diff, splitting the audit trail from the work it documents and creating noise in the review history. +**Reviewer signal:** if a PR modifies only project-layer state files (`JOURNAL.md`, `LESSONS.md`, `decisions.jsonl`) and the description explains it as a post-merge closeout, flag the PR. The correct fix is to reopen the feature branch with the state files included and re-merge. + +**Interaction with §M-git-1:** project-layer state files (`JOURNAL.md`, `LESSONS.md`, `decisions.jsonl`) normally allow direct commit without branching. §M-git-6 does not override that — it restricts **when** that direct commit may happen relative to PR lifecycle. When a PR is open for branched work, write your state to the feature branch before merge, not directly to the default branch after. -**Agent rule:** the session-close checklist in `handoff.md` must be fully checked before the PR is opened — not after. The last commit on the feature branch before `git push` should include the updated `handoff.md` and any `decisions.json` / `activity` entries for the session. See PROTOCOL_RULES §P3 branch ordering rule for the substrate-neutral statement. +## Optional tooling that ships with the template + +These files are included in the template as conveniences for projects whose substrate is `git+github` and that use common Python-ecosystem tooling. They are **opt-in** — deleting them breaks nothing in the kernel or in this module's rules: + +- `.pre-commit-config.yaml` (at template root) — pre-commit.com scaffold that wires `validate_state.py` as a pre-commit hook. Safe to delete if you use a different hook manager (husky, lefthook) or no hook manager. +- `.agents/scripts/.pre-commit-hooks.yaml` — hook manifest for publishing this repo as a reusable pre-commit source (so downstream projects can `- repo: https://github.com/…/lead-protocol`). Safe to delete if you are not distributing hooks. -**Reviewer signal:** if a PR modifies only operational state files (`handoff.md`, `decisions.json`, `activity_*.md`) and the description explains it as a post-merge closeout, flag the PR. The correct fix is to revert, re-open the original branch, add the state there, and re-merge. +The framework validator itself (`.agents/scripts/validate_state.py`) is **not** opt-in — it is part of the framework and runs independently of any hook tooling (e.g., invoked manually or from CI). The migration script `.agents/scripts/migrate_to_v2.py` is also part of the framework (one-time v1.x → v2.0.0 upgrade tool) and not opt-in. ## Relationship to the kernel diff --git a/README.md b/README.md index f766eb2..bcd8514 100644 --- a/README.md +++ b/README.md @@ -1,38 +1,89 @@ # Lead Protocol -**Operational continuity protocol for AI agents** — vendor-agnostic, file-based, git-native. +**A shift-change logbook for your AI coding assistants.** -> The missing layer between agent instructions (AGENTS.md) and agent memory (mem0). +When one AI session ends, it writes down what it did, what's left, and why it made the calls it made. The next session — even a different tool, even days later — reads that and picks up where the last one stopped. Nothing forgotten, nothing re-explained. -> Current version: **1.8.3** (template) / **1.7.1** (IDE) — see [`template/.agents/PROTOCOL_RULES.md`](template/.agents/PROTOCOL_RULES.md). The development environment at the repo root runs the previous stable version used to build the next release, governed by §P8 (meta-repo promotion lifecycle). +> Current version: **2.0.4** --- ## The problem -When multiple AI agents (Claude Code, Cursor, Codex, Antigravity, Windsurf) work on the same codebase — across different sessions, tools, and LLMs — there is no standard way to: +You've probably hit this: you spend an afternoon working through a problem with an AI assistant, close the chat, and the next day it remembers none of it. Open a different tool — Claude Code instead of Cursor — and you start from zero again. Ask it later *why* it made some change, and there's no record. -- **Hand off state** from one agent session to the next -- **Audit decisions** made by agents with rationale -- **Recover from interrupted sessions** without losing context -- **Coordinate concurrent agents** operating on the same repo -- **Consult a peer agent mid-session** without copy-pasting context +When more than one AI assistant works on the same project — across different days, tools, and people — there's no shared place for them to leave notes for each other. So context gets lost, decisions go unexplained, and interrupted work is hard to resume. -Existing solutions solve adjacent problems: +Lead Protocol gives every assistant the same simple habit: **read the notes before you start, leave notes before you stop.** + +
+For developers: where this sits relative to AGENTS.md, mem0, and LangGraph + +Phrased technically, the gap is the *operational state layer* — what was done, what's pending, who decided what, who is live right now, and how to recover. Existing tools solve adjacent problems, not this one: - **AGENTS.md / spec-kit** tell agents *what to know* about a project (instructions layer) - **mem0 / engram** remember *what happened* in the past (memory layer, DB-backed) - **LangGraph / CrewAI** orchestrate agents *in real time* (runtime layer) -**Nobody solves the operational state layer** — what was done, what's pending, who decided what, who is live right now, and how to recover. +Lead Protocol is vendor-agnostic, file-based, and git-native: the state lives as plain files committed alongside your code, so it is diffable, reviewable, and auditable like any other part of the repo. + +
## The solution -Lead Protocol defines a set of structured files committed to your git repository — a `handoff.md` with a strict schema, an append-only `decisions.json` audit trail, rules for takeover and recovery, a concurrent-session registry, and framework/project separation. Any agent that can read text files can use it. No runtime, no API, no vendor dependency. +Lead Protocol is a set of structured files committed to your git repository: + +- **`handoff.md`** — current state: what's done, what's in progress, what's blocked +- **`decisions.jsonl`** — append-only audit trail: why each important decision was made +- **`JOURNAL.md`** — curated timeline of structurally significant deliveries +- **`LESSONS.md`** — mistakes not to repeat, searchable by tag + +Any agent that can read text files can use it. No runtime, no database, no API keys — it's just files in your git repo. A CLI and MCP server are on the roadmap, but you never need them to use Lead Protocol today. + +In practice, the whole protocol is a single folder of markdown and JSON files dropped into your repository: + +``` +your-project/ +├── .agents/ +│ ├── CORE_RULES.md # Rules index + essential contracts (read first) +│ ├── PROTOCOL_RULES.md # Framework kernel (substrate-agnostic, upgradable) +│ ├── PROJECT_RULES.md # Your project's identity and context — edit this +│ ├── JOURNAL.md # Curated timeline of structurally significant deliveries +│ ├── LESSONS.md # Project-level lessons (append-at-tail, grep by tag) +│ ├── decisions.jsonl # Append-only audit trail (one JSON object per line) +│ ├── AGENTS_MAP.md # Tool-signature → agent-slug map (maintainer-managed) +│ ├── modules/ # Opt-in extension rule files +│ │ ├── README.md # Index of available modules +│ │ ├── git-substrate.md # Branching + PR + README-sync + .gitignore baseline +│ │ └── meta-repo.md # IDE/template duality + promotion lifecycle +│ ├── schemas/ +│ │ ├── handoff.schema.json # Validates parsed handoff.md +│ │ └── decisions.entry.schema.json # Validates one decisions.jsonl line +│ ├── scripts/ +│ │ ├── validate_state.py # Schema validator +│ │ ├── migrate_to_v2.py # v1.x → v2.0.0 migration tool +│ │ ├── conftest.py # Pytest config +│ │ └── test_validate_state.py # Validator tests +│ ├── checkpoints/ # Cross-agent coordination snapshots (shared) +│ ├── sessions/ +│ │ └── active_sessions.md # Concurrent session registry +│ └── local/ # ← gitignored — per (actor, agent) state +│ └── // +│ ├── handoff.md # Current operational state for this pair +│ ├── tasks/TASK.md # TODO for the active session +│ ├── activity.log # Per-pair raw activity log +│ └── lessons.md # Personal lessons for this pair +├── .gitignore # Ignores .agents/local/ +├── CLAUDE.md # Pointer for Claude Code +└── AGENTS.md # Pointer for other agents +``` + +The bundled Python scripts are validation and migration helpers — you do not need them to get started. -The full structure, schemas, and operational details live in the [operational manual](template/README.md). +
+For developers: where Lead Protocol sits in the agent stack -## Where it fits +Lead Protocol fills the operational-state slot in the broader agent stack: ``` ┌─────────────────────────────────────────────┐ @@ -52,40 +103,188 @@ The full structure, schemas, and operational details live in the [operational ma └─────────────────────────────────────────────┘ ``` +
+ ## Quick start -Only the `template/` directory is meant to be copied into your project — everything else in this repo is the development environment of the Lead Protocol itself. +```bash +# Clone the latest stable release +# Check https://github.com/mmilanez/lead-protocol/releases for the current version number +git clone --branch v2.0.4 --depth 1 https://github.com/mmilanez/lead-protocol.git /tmp/lp + +# Copy the scaffold into your project +cp -R /tmp/lp/.agents your-project/.agents +cp /tmp/lp/CLAUDE.md your-project/CLAUDE.md +cp /tmp/lp/AGENTS.md your-project/AGENTS.md + +# Set your project's identity +$EDITOR your-project/.agents/PROJECT_RULES.md + +# Verify the scaffold state +cd your-project +python .agents/scripts/validate_state.py +``` + +**Windows (PowerShell):** + +```powershell +# Clone the latest stable release +# Check https://github.com/mmilanez/lead-protocol/releases for the current version number +git clone --branch v2.0.4 --depth 1 https://github.com/mmilanez/lead-protocol.git $env:TEMP\lp + +# Copy the scaffold into your project +Copy-Item -Recurse $env:TEMP\lp\.agents your-project\.agents +Copy-Item $env:TEMP\lp\CLAUDE.md your-project\CLAUDE.md +Copy-Item $env:TEMP\lp\AGENTS.md your-project\AGENTS.md + +# Set your project's identity +code your-project\.agents\PROJECT_RULES.md + +# Verify the scaffold state +Set-Location your-project +python .agents/scripts/validate_state.py +``` + +That's it. Read the sections below or browse [`.agents/CORE_RULES.md`](.agents/CORE_RULES.md) to understand how agents use the protocol inside your project. + +## Installing a specific version + +`main` is the development branch and may contain in-progress work. **Do not install directly from `main`.** Always install from a published release. + +Available versions are listed on the [Releases page](https://github.com/mmilanez/lead-protocol/releases). Versions follow [SemVer](https://semver.org): + +- **`vX.Y.Z`** (no suffix) — stable release, recommended for production use +- **`vX.Y.Z-alpha.N` / `-beta.N` / `-rc.N`** — pre-releases, for preview and testing only + +### Alternative — download the release archive + +On the [Releases page](https://github.com/mmilanez/lead-protocol/releases), pick a version and download the `Source code (zip)` or `(tar.gz)` asset. Extract and copy the files into your project as shown in Quick start. + +For Windows PowerShell, use equivalent `Copy-Item` commands and run the same validator command from the target project root. + +### Checking which version you have + +`.agents/PROTOCOL_RULES.md` records the **kernel** version (the framework rules). A patch release may leave the kernel untouched — for example, release `2.0.1` ships kernel `2.0.0` because it only fixed tooling and docs. So the kernel version is a floor, not the release number. The exact release you installed is the one named in the top entry of [`CHANGELOG.md`](CHANGELOG.md); compare it against the [Version history](#version-history) table below. + +### Release notes and migration + +- **Changelog:** [`CHANGELOG.md`](CHANGELOG.md) — release-by-release summary of what changed. +- **v1.x → v2.0.0 migration:** [`docs/MIGRATION-v2.md`](docs/MIGRATION-v2.md) — required reading for consumer repos upgrading from any `v1.x` release. + +--- + +## Three-layer state model + +Every file under `.agents/` belongs to exactly one of three layers: + +| Layer | Owner | Lifecycle | Shared? | +|---|---|---|---| +| **Framework** | Upstream Lead Protocol | Changes with framework version | Yes — ships in the release | +| **Project** | Your project | Changes with project evolution | Yes — versioned with the repo | +| **Actor × Agent** | One human operator running one AI agent | Changes every session | **No** — gitignored, one folder per pair | + +
+Why the pair (actor × agent) is the unit of concurrency + +The smallest unit that owns volatile state is the pair `(actor, agent)`, not the actor alone. Claude Code, Codex, Gemini, and Cursor operated by the same human each get their own `local///`. That is what makes cross-agent interchange in the same project viable — agents never overwrite each other's handoff. + +Full detail: `.agents/PROTOCOL_RULES.md §P3 — Three-layer state model`. + +
+ +--- + +## How agents boot in your project + +> You don't run these steps — your AI agent does, automatically, the moment it reads `CLAUDE.md`. This section explains what's happening under the hood. + +Every compliant agent reads, in order: + +1. `.agents/CORE_RULES.md` — index + essential contracts. +2. `.agents/PROJECT_RULES.md` — your project's identity, language rules, tone, operational preferences. Read `§J8 Active modules` first. +3. `.agents/modules/.md` — for each scope listed in `§J8 Active modules`, in declaration order. +4. `.agents/AGENTS_MAP.md` — resolve this agent's own `` slug from its tool signature. +5. `.agents/sessions/active_sessions.md` — concurrent-session awareness. +6. `.agents/local///handoff.md` — current state of this pair. + +`PROTOCOL_RULES.md` itself is read **on demand**, not in the baseline — `CORE_RULES.md` points agents there when needed. This keeps baseline cost bounded. See `PROTOCOL_RULES.md §P-Access` for the full load contract. + +Pointer files `CLAUDE.md` and `AGENTS.md` at the project root exist so each vendor-specific agent tool discovers `.agents/` without custom configuration. + +--- + +## Upgrading + +### Upgrading from v1.x to v2.0.0 (structural — state layout changed) + +v2.0.0 introduces the three-layer state model with an actor × agent sub-dimension. The old `agent_log/` layout is gone. Run the migration tool: ```bash -cp -R lead-protocol/template/.agents your-project/.agents -cp lead-protocol/template/CLAUDE.md your-project/CLAUDE.md -cp lead-protocol/template/AGENTS.md your-project/AGENTS.md -$EDITOR your-project/.agents/PROJECT_RULES.md # set your project's identity +python .agents/scripts/migrate_to_v2.py # dry-run first +python .agents/scripts/migrate_to_v2.py --apply # then mutate ``` -That's it. Read the [operational manual](template/README.md) to understand how agents will use the protocol inside your project. +Full consumer migration guide: [`docs/MIGRATION-v2.md`](docs/MIGRATION-v2.md). + +### Upgrading between v2.Y patches/minors -## Why `template/` only? +Replace framework files verbatim (`CORE_RULES.md`, `PROTOCOL_RULES.md`, `modules/`, `schemas/`, `scripts/`). Do not replace `PROJECT_RULES.md`, project-layer state, or per-pair state. Append a decision entry to `decisions.jsonl` recording the upgrade. -This repository dogfoods its own protocol. Its root `.agents/` records the real decisions, lessons, and history of developing the protocol itself — that would be noise in a consumer repo. The `template/` folder is the clean, versioned baseline that ships. Think of the repo like an IDE: `template/` is the distributable program; the rest is the workshop. +Patch bumps (Z) never break anything. Minor bumps (Y) may introduce new features but preserve backward compatibility. Major bumps (X) may require migration — the release notes will say so explicitly and typically ship a migration script. + +--- ## Version history | Version | Highlights | |---|---| -| **1.9.2** | **Branch ordering rule for session close.** Adds an explicit rule (PROTOCOL_RULES §P3) requiring session-close artifacts — handoff, decisions, lessons — to be committed on the feature branch before the PR is opened, not after merge. Adds corresponding git-substrate enforcement (§M-git-5) with reviewer signal for post-merge closeout PRs. Adds one checklist item to the handoff schema. Fixes #2. | -| **1.9.1** | Template cosmetic pass — clarifies opt-in nature of pre-commit tooling (header comment + cross-reference in `modules/git-substrate.md`), adds `template/.agents/scripts/README.md` distinguishing framework files (validator, tests) from distribution files (pre-commit hook manifest), and reframes the "Validating state files" section so local ad-hoc validation is the default path, with pre-commit (requires pre-commit.com) and CI (requires GitHub Actions) presented as opt-in layers. Closed via #36. No framework rules changed. Promoted to IDE on 2026-04-20. | -| **1.9.0** | **Substrate-agnostic kernel + opt-in modules.** PROTOCOL_RULES rewritten as kernel (§P1–§P7, new §P9 module contract); git/GitHub/PR/README-sync concerns extracted to `.agents/modules/git-substrate.md` (§M-git-1..4); meta-repo promotion (former §P8) relocated to `.agents/modules/meta-repo.md` (§M-meta-1..6). PROJECT_RULES §J8 gains `Active substrate` + `Active modules` fields (field previously `Active optional modules`). Promotion copy list expanded to include `modules/`. Promoted to IDE on 2026-04-20. | -| **1.8.3** | CI state validation workflow — GitHub Action that runs `validate_state.py` on every PR that touches state, schemas, or scripts. Two jobs: one for the IDE root state, one for the template's pristine baseline. | -| **1.8.2** | Pre-commit hook integration — Python validator (`validate_state.py`) that enforces the JSON Schemas against `handoff.md` and `decisions.json`. Ships as `.pre-commit-hooks.yaml` for external adoption and a ready `.pre-commit-config.yaml` scaffold in the template. §P8 copy list expanded to include `scripts/`. | -| **1.8.1** | Formal JSON Schemas (`handoff.schema.json`, `decisions.schema.json`) for the two state files — source of truth for the upcoming CLI, pre-commit hook, and CI validator. §P8 promotion procedure updated to treat `schemas/` as framework (copied verbatim on promotion). | -| **1.8.0** | **§P8 — Meta-repo promotion lifecycle.** Formalizes the IDE↔template dual-copy model introduced in PR #17: version invariant (template ≥ IDE), when/how to promote a tested template version into the IDE, anti-patterns (no ad-hoc IDE edits, no multi-minor gaps), and scope (§P8 governs meta-repos only, not consumer repos). Complements the README split (PR #21) and CI dual-sync (PR #22). | -| **1.7.1** | Clarifications across §P1–§P5 reflecting the IDE-vs-template separation (PR #17); branch-protection override note in §P3; pristine-vs-populated handoff distinction; README added to authority hierarchy in §P2 | -| **1.7.0** | Public-facing documentation sync rule + CI enforcement (README ↔ PROTOCOL_RULES); §P7 dual-tier (`private-context` + `business-vault`) with opt-in framing | -| **1.6.0** | Concurrent session registry (`active_sessions.md`) + mid-session checkpoints | -| **1.5.0** | Session close ritual + self-verification checklist in `handoff.md` | -| **1.4.0** | `decisions.json` format stabilized; `agent_lessons.md` introduced | -| **1.3.0** | §P6 (portable cross-repo identifiers) + §P7 (private context separation) | -| **1.2.0** | Recovery mode + takeover rule | -| **1.1.0** | Commit convention (`[Agent] : `) | -| **1.0.0** | Initial release: handoff schema, decisions log, session protocol levels | +| **2.0.4** | **Branch ordering rule (kernel 2.0.1).** Adds an explicit rule (PROTOCOL_RULES §P3) requiring session-close state to be committed on the feature branch before the PR is opened, not written to the default branch after merge. Adds §M-git-6 to `git-substrate.md` with git-specific enforcement and a reviewer signal for post-merge closeout PRs. Adds one checklist item to the handoff schema. Fixes #2. | +| **2.0.3** | Security patch: `migrate_to_v2.py` now validates `--actor` / `--agent` values against path traversal (rejects `..`, `/`, `\`, absolute paths, drive letters). README Quick Start updated to current release with PowerShell copy block added. `SECURITY.md` and `CONTRIBUTING.md` scope corrected (CLI/MCP are roadmap, not shipped). CI workflow permissions hardened. No kernel or schema changes. | +| **2.0.2** | Documentation and release infrastructure fixes. README version references corrected. No kernel or schema changes. | +| **2.0.1** | Patch from first external consumer feedback. `migrate_to_v2.py --dry-run` now accepted; pristine `LESSONS.md` scaffold no longer false-positives the rerun-safety guard; `docs/MIGRATION-v2.md` Step 3 rewritten with agent-driven callout and `--agent` slug warning. No kernel or schema changes. | +| **2.0.0** | **Three-layer state model (Framework / Project / Actor × Agent).** New files: `JOURNAL.md`, `LESSONS.md`, `AGENTS_MAP.md`. `decisions.json` replaced by `decisions.jsonl` (append-only). `handoff.md` relocates to `local///handoff.md`. New `migrate_to_v2.py` migration tool. Six-step baseline boot order. | + +
+Earlier versions (v1.0.0 – v1.9.1) + +| Version | Highlights | +|---|---| +| **1.9.1** | Template cosmetic pass — clarifies opt-in nature of pre-commit tooling, adds `scripts/README.md`, reframes validation section so local ad-hoc validation is the default path. No framework rules changed. | +| **1.9.0** | **Substrate-agnostic kernel + opt-in modules.** `PROTOCOL_RULES.md` rewritten as kernel (§P1–§P7, new §P9 module contract); git/PR/README-sync rules extracted to `modules/git-substrate.md`; meta-repo promotion (former §P8) relocated to `modules/meta-repo.md`. | +| **1.8.3** | CI state validation workflow — GitHub Action that runs `validate_state.py` on every PR. | +| **1.8.2** | Pre-commit hook integration — Python validator enforces JSON Schemas against `handoff.md` and `decisions.json`. | +| **1.8.1** | Formal JSON Schemas (`handoff.schema.json`, `decisions.schema.json`). | +| **1.8.0** | **Meta-repo promotion lifecycle (§P8).** Formalizes IDE↔template dual-copy model: version invariant, when/how to promote, anti-patterns. | +| **1.7.1** | Clarifications across §P1–§P5; branch-protection override note; pristine-vs-populated handoff distinction. | +| **1.7.0** | Public-facing documentation sync rule + CI enforcement; §P7 dual-tier private context. | +| **1.6.0** | Concurrent session registry (`active_sessions.md`) + mid-session checkpoints. | +| **1.5.0** | Session close ritual + embedded self-verification checklist in `handoff.md`. | +| **1.4.0** | SemVer for rules files + pull-request-required rule. | +| **1.3.0** | §P6 cross-repo references + §P7 private vs shared context separation. | +| **1.0.0** | Initial protocol: handoff, decisions, takeover, recovery, authority hierarchy. | + +
+ +## Roadmap + +| Priority | Component | Status | +|---|---|---| +| **P1** | CLI (`lead-protocol init / handoff / validate`) | Planned | +| **P1** | JSON Schemas for `handoff.md` and `decisions.jsonl` | ✅ Shipped in v1.8.1 | +| **P1** | Pre-commit hook for schema enforcement | ✅ Shipped in v1.8.2 | +| **P2** | MCP Server (protocol operations as MCP tools) | Planned | +| **P2** | GitHub Action for CI validation | ✅ Shipped in v1.8.3 | +| **P3** | Decisions dashboard (web UI) | Planned | +| **P3** | Template marketplace (`PROJECT_RULES.md` by industry) | Planned | + +## Contributing + +Contributions welcome. See [CONTRIBUTING.md](CONTRIBUTING.md) for details. + +## License + +[Apache 2.0](LICENSE) — see also [`NOTICE`](NOTICE) for required attribution. + +--- + +*Built by [mmilanez](https://github.com/mmilanez) — born from managing AI agents across 100+ repositories.* From c0f5e1e9c076c6103f6ef76df9e59263f3d6fc22 Mon Sep 17 00:00:00 2001 From: Mike Date: Tue, 2 Jun 2026 00:22:22 -0400 Subject: [PATCH 3/4] chore: remove erroneous template/ files (repo root is the template) --- template/.agents/PROTOCOL_RULES.md | 315 ----------------------------- 1 file changed, 315 deletions(-) delete mode 100644 template/.agents/PROTOCOL_RULES.md diff --git a/template/.agents/PROTOCOL_RULES.md b/template/.agents/PROTOCOL_RULES.md deleted file mode 100644 index 1e90234..0000000 --- a/template/.agents/PROTOCOL_RULES.md +++ /dev/null @@ -1,315 +0,0 @@ -# PROTOCOL_RULES.md — Lead Protocol framework rules (generic) - -> Version: 1.9.2 | Updated: 2026-06-01 -> Scope: Substrate-agnostic kernel. Opt-in modules live in `modules/` and are activated via `PROJECT_RULES.md §J8`. -> This file contains no project-specific content — that lives in `PROJECT_RULES.md`. - ---- - -## §P1 — Versioning - -| File type | Format | Example | When to bump | -|---|---|---|---------| -| Agent operation files (`CORE_RULES.md`, `PROTOCOL_RULES.md`, `PROJECT_RULES.md`, `handoff.md`) | `X.Y.Z` | `1.4.0` | Patch (Z) for clarifications/text fixes; Minor (Y) for new sections/rules; Major (X) for structural rewrites | -| Module files (`modules/*.md`) | `X.Y.Z` | `1.0.0` | Same rules as agent operation files. Each module versions independently from the kernel. | - -Projects that adopt Lead Protocol may use any versioning scheme for their own product releases — the Lead Protocol versioning rules apply only to the agent operation files and module files listed above. - -Meta-repos that develop the protocol itself see `modules/meta-repo.md §M-meta-1`. - -## §P2 — Authority hierarchy (framework tier) - -1. `PROTOCOL_RULES.md` (framework kernel) -2. Active modules listed in `PROJECT_RULES.md §J8` (in declaration order) -3. `handoff.md` (current state — may temporarily override stale rules if the project owner defines a temporary directive) -4. `PROJECT_RULES.md` (business context) -5. `README.md` (public surface — kept synced to the kernel per the active substrate module if any; kernel wins on conflict) -6. Project reference files (brand, product, channel, etc.) -7. Official platform policies -8. General best practices - -A module cannot contradict the kernel — it can only add rules specific to a substrate, scope, or role. Where a module cites a kernel anchor, the qualifier `PROTOCOL_RULES §Px` makes the cross-file reference explicit. - -Meta-repos maintaining two copies of the framework see `modules/meta-repo.md §M-meta-2`. - -## §P3 — Multi-agent coordination - -### Handoff schema (`agent_log/handoff.md`) — strict, always overwritten - -```markdown -# handoff.md — Current operational state -> Version: X.Y | Updated: YYYY-MM-DD - -**Last Agent:** [Agent signature] -**Timestamp:** YYYY-MM-DD HH:MM -**Status:** STABLE | BLOCKED | IN_PROGRESS -**Last Action:** <1 sentence> -**Pending Step:** -**Blockers/Context:** -**Open Threads:** - -**Session close checklist (self-verified):** -- [ ] `activity_YYYY-MM.md` contains an entry for this session -- [ ] `decisions.json` appended (if any decision was made) -- [ ] `agent_lessons.md` appended (if an agent-level lesson emerged) -- [ ] `tasks/lessons.md` appended (if a project-level lesson emerged) -- [ ] Commit(s) follow `[Agent] : ` convention -- [ ] Version bumps applied to any rules file whose content changed -- [ ] `active_sessions.md` row for this session removed (if registry is in use) -- [ ] Session-close state written on the feature branch before the PR is opened (when substrate uses pull requests — see §M-git-5) -``` - -Schema is immutable — no agent may add sections, tables, or free paragraphs. Timestamp must include HH:MM. The session close checklist is **part of the schema** (added in Lead Protocol v1.5.0; `active_sessions.md` entry added in v1.6.0) — each box is self-verified by the agent before closing. Unchecked boxes signal incomplete close to the next agent. - -Projects that distribute pristine handoff templates (placeholder-populated, not yet in use) see `modules/meta-repo.md §M-meta-4`. - -### Takeover rule - -| Condition | Behavior | -|---|---| -| Timestamp **< 30 min ago** AND no peer session live in `active_sessions.md` | Do not proceed. Assume prior agent is still active. | -| Timestamp **< 30 min ago** AND a different session is live in `active_sessions.md` | Two sessions are legitimately concurrent. Do NOT take over — see §P3 concurrent sessions. | -| Timestamp **≥ 30 min ago** | Assume interrupted. Record takeover in `decisions.json` with rationale `"Takeover: previous session assumed interrupted (>30min)"`. Run recovery mode before proceeding. | -| Timestamp **< 30 min** + explicit human override | Proceed. Rationale: `"Forced takeover: human override"`. | - -### Recovery mode - -Before continuing a prior `Pending Step`: -1. Read the last entry in `decisions.json`. -2. Spot-check files listed in `files_affected`. -3. If state is inconsistent (missing headers, version conflicts, half-written content): fix or revert first — never build on corrupted state. -4. Log the recovery action in `decisions.json`. - -Meta-repos with two `decisions.json` files (IDE vs. template) see `modules/meta-repo.md §M-meta-3`. - -### Decisions log (`agent_log/decisions.json`) — append-only, immutable - -```json -[ - { - "timestamp": "2026-04-17T15:30:00", - "agent": "[Claude Code / claude-opus-4-6]", - "decision": "Short imperative", - "rationale": "Why", - "files_affected": ["path/to/file.md"], - "status": "completed" - } -] -``` - -Never edit past entries. If the JSON is corrupted, the recovery agent fixes structure before appending. - -### Commit convention - -``` -[Agent] : -``` - -Where `[Agent]` is `[Claude]`, `[Cursor]`, `[Codex]`, etc., and `` is `feat|fix|refactor|docs|ops|chore`. This convention is substrate-neutral — it applies whether the underlying system is git, a cloud-sync folder, or any other change-tracked substrate. Substrate-specific workflows (branching, pull requests, CI) live in substrate modules such as `modules/git-substrate.md`. - -### Session close ritual *(v1.5.0+)* - -A **"non-trivial session"** is one where any of the following occurred: - -- A change was committed (by the active substrate's commit mechanism) -- A review/approval artifact was opened, updated, or merged (when a substrate module defines one) -- A file outside `agent_log/` was modified -- A product, strategy, or architectural decision was made -- A user-facing deliverable was shipped (listing, pin, copy, export) - -At the end of a non-trivial session, the agent **must** update every applicable artifact below **and** check the corresponding box in the `handoff.md` session close checklist: - -| Artifact | Mandatory trigger | Skip if | -|---|---|---| -| `handoff.md` | Always | Never skipped | -| `decisions.json` | A decision was made, a file was created/renamed/deleted, or a version was bumped | No decisions and no file state changed | -| `activity_YYYY-MM.md` | A commit, review artifact, or major artifact change occurred | Pure reads / inspection / Q&A sessions | -| `agent_lessons.md` | An **agent-level** lesson emerged (format drift, tool failure, recovery incident, cross-agent coordination pattern) | No new agent-level lesson | -| `tasks/lessons.md` | A **project-level** lesson emerged (bug pattern, process flaw, systemic decision criterion) | No new project-level lesson | -| `active_sessions.md` | Registry is in use and this session has an open row | Registry not in use, or no open row | - -### Branch ordering rule *(v1.9.2+)* - -Session close is the **final operational step on the feature branch**. Complete all session-close artifacts — handoff, decisions, lessons, and journal updates — before opening or merging the pull request. - -**Why this order matters:** if session-close state is written on the default branch after merge, protected-branch settings may block the write or force a follow-up PR for state files only. This creates unnecessary review overhead and an audit gap where the handoff describes work that is not yet in the branch history. - -**Implementation rule:** the session-close checklist in `handoff.md` is complete (all boxes checked) when the pull request is **opened**, not after it merges. Agents must not mark the session closed and then create a separate follow-up PR to write state files. - -This rule is substrate-neutral. Git-specific enforcement and rationale live in the active substrate module (see `modules/git-substrate.md §M-git-5`). - -**Verification step (mandatory before closing):** - -Before the final response of the session, the agent runs: - -```bash -grep -l "YYYY-MM-DD" .agents/agent_log/*.md .agents/agent_log/*.json tasks/*.md -``` - -(substituting `YYYY-MM-DD` with today's date) and confirms that each *applicable* artifact appears in the output. If an applicable artifact does not appear, the update was skipped — fix before closing. - -**Agent-level vs project-level lessons — decision rule:** - -- `agent_lessons.md` captures lessons **about how agents operate**: format drift, tool failure modes, recovery protocols, cross-agent coordination patterns. Examples: "the file-reader cache got confused after a rename", "I took an attribute dropdown value as ground truth without cross-checking". -- `tasks/lessons.md` captures lessons **about the project or domain**: systemic mistakes, decision criteria, recurring bug patterns, process fixes. Examples: "anchor election from local sales data underweights cross-shop demand", "lessons about customer behavior, pricing elasticity, or category positioning". - -When in doubt, a lesson is project-level if removing the specific agent would still leave the lesson valid. If the lesson is about *how the agent failed as an agent*, it is agent-level. - -### Concurrent sessions and mid-session checkpoints *(v1.6.0+)* - -The v1.5 takeover rule assumes at most one session is live per repo at any time. Real-world tooling (multiple IDEs, multiple agents, multiple terminals rooted at the same repo) routinely breaks this assumption. Two additions address concurrent sessions and mid-session cross-agent consultation without breaking any existing schema. - -**Active sessions registry** — `.agents/agent_log/sessions/active_sessions.md` - -Optional but recommended when more than one agent may operate on the repo. A flat markdown table, one row per live session. The agent appends its row on session start and removes the row on session close (session close checklist item). - -Schema — immutable columns: - -```markdown -# active_sessions.md — Sessions currently live -> Append row on session start. Remove row on session close. -> Stale rows (>24h with no checkpoint update) may be removed by any next agent with a decisions.json log. - -| Session ID | Agent | Started | Topic | Last checkpoint | -|---|---|---|---|---| -| 2026-04-19-1310-claude | [Claude Code / claude-opus-4-7] | 2026-04-19 13:10 | <1-line topic> | | -``` - -**Session ID format:** `YYYY-MM-DD-HHMM-`. The `` suffix (`claude`, `gemini`, `cursor`, `codex`, etc.) prevents ID collision when two agents boot in the same minute. - -**Effect on takeover rule:** when `active_sessions.md` exists and holds a row for a peer session whose Started timestamp is within the last 30 minutes OR whose Last checkpoint is within the last 30 minutes, the current agent MUST NOT take over. Concurrent sessions are legitimate — append a new row for the current session instead. The `handoff.md` 30-minute takeover rule remains in effect only when `active_sessions.md` is absent or empty. - -**Mid-session checkpoints** — `.agents/agent_log/checkpoints/YYYY-MM-DD-HHMM-.md` - -A checkpoint is a pre-execution snapshot written voluntarily by the agent at the owner's request (or proactively when the agent is about to take an action that would benefit from a second opinion). Checkpoints are ephemeral working notes — authoritative state lives in `handoff.md`, `decisions.json`, and project files. - -Template — content must be self-contained so a peer agent reads it without the conversation transcript: - -```markdown -# Checkpoint — -> Session: -> Timestamp: YYYY-MM-DD HH:MM -> Author: [Agent signature] - -## Open question - - -## Data gathered - - -## Current recommendation - - -## What specifically needs second-opinion - -``` - -**Usage pattern:** when the owner asks for a second opinion from a peer agent, the current agent writes the checkpoint and updates the `Last checkpoint` column of its row in `active_sessions.md`. The owner opens the peer agent in another window; the peer agent boots per §P5, sees the fresh checkpoint referenced in `active_sessions.md`, reads it, and responds with contrarian input. No copy-paste required. - -**Retention:** no automatic retention policy. Checkpoints accumulate as an audit trail. If the `checkpoints/` directory grows beyond practical limits, the project may adopt a retention rule in `PROJECT_RULES.md §J8`. - -**Scope limits:** -- The registry is advisory, not a lock. It does not prevent two agents from editing the same file concurrently — resolve conflicts per the active substrate module. -- Checkpoints do not replace `handoff.md`. They coexist: checkpoint = live snapshot of an in-progress decision; handoff = authoritative state at session close. -- Neither the registry nor checkpoints are required when only one agent operates on the repo. Projects may opt into v1.6 features via `PROJECT_RULES.md §J8`. - -## §P4 — Generic quality checklist - -Before closing any significant action: -- [ ] Persona/agent signature present in every recorded change and in `handoff.md` -- [ ] `handoff.md` overwritten with current state (Status, Timestamp HH:MM, Last Action, Pending Step, session close checklist) -- [ ] `decisions.json` appended with rationale and files_affected (if applicable per §P3 session close ritual) -- [ ] `activity_YYYY-MM.md` appended with one line per logical action (if applicable per §P3 session close ritual) -- [ ] If a new **agent-level** pattern/bug learned → append to `agent_log/agent_lessons.md` -- [ ] If a new **project-level** pattern/bug learned → append to `tasks/lessons.md` -- [ ] Commit record follows `[Agent] : ` convention (§P3) -- [ ] Version bumps applied to any rules file or module whose content changed -- [ ] Session close checklist in `handoff.md` fully verified (`grep` confirmed entries exist per §P3) -- [ ] If `active_sessions.md` is in use, the row for this session has been removed (per §P3 concurrent sessions) -- [ ] Any additional checks required by an active module have been satisfied - -## §P5 — Operational model (generic) - -- Every agent reads `CORE_RULES.md` → `PROTOCOL_RULES.md` (kernel) → `PROJECT_RULES.md` → each module file listed in `§J8 Active modules` (in declaration order) → `handoff.md` on session start. -- Additionally (v1.6.0+), when `agent_log/sessions/active_sessions.md` exists, the agent reads it to detect concurrent peer sessions. If a peer session has a Last checkpoint referenced, the agent reads the latest checkpoint in `agent_log/checkpoints/` before responding to the owner. -- The active Session Protocol level (1/2/3), the active substrate, and the list of active modules are declared in `PROJECT_RULES.md §J8`. -- Edits to framework files (`PROTOCOL_RULES.md` kernel, any module file) only happen via methodology upgrade — never ad-hoc. -- Edits to business files (`PROJECT_RULES.md`, project reference docs) happen per project rules in `§J8`. -- Language: operational files (`CORE_RULES`, `PROTOCOL_RULES`, `PROJECT_RULES`, module files, `handoff`, `decisions`, `agent_lessons`, `activity`, `active_sessions`, `checkpoints`) are always EN-US. -- Additional module-specific boot steps may apply — see each active module's header. - -## §P6 — Cross-repository references - -When a project references resources in other repositories (personal context, external specs, sibling repos): - -1. **Portable identifiers** — Always use `org/repo` (e.g., `acme/private-context`). Never use local machine paths (e.g., `C:\Dados\...` or `/home/user/...`). Local paths break on other machines and are not traceable. -2. **Pointer, not copy** — When information exists in a canonical repo, other locations must contain only pointers (`§J6` with repo reference). Never duplicate full content. If duplicated, reduce the copy to a summary + pointer. -3. **Deduplication** — Before recording information in more than one location (local memory, repo A, repo B), check: does this information already have a canonical home? If yes, pointer. If no, elect a home and point the rest. -4. **Reference format in `§J6`** — For external repos, use format: `Repo 'org/repo' (private|public) — path/to/file.md`. Include visibility flag so agents know if authentication is required. - -## §P7 — Private vs shared context separation - -**Problem:** Context relevant to an AI agent may be sensitive enough that it must not leak into repos shared more widely. This applies in two analogous tiers: - -- **Personal tier:** an individual owner's context (identity, finances, strategic goals, private decisions) that must not leak into repos shared with a team. -- **Organizational tier:** a company's confidential context (financials, strategic plans not yet public, compensation, privileged legal matters) that must not leak into repos shared beyond the director/C-level circle. - -**Rule:** isolate sensitive context in a dedicated private repo, and reference it by name from the less-private repos that consume it. The pattern is the same in both tiers — only the audience and the repo name differ. - -| Context tier | Canonical private repo | Consumers | -|---|---|---| -| Personal | `owner/private-context` (owner-only) | Owner's personal project repos | -| Organizational | `org/business-vault` (directors/C-level only) | Team-shared company repos | - -Both tiers are **optional** — projects without sensitive context at the corresponding tier simply don't have a `private-context` or `business-vault` repo. The rules below apply wherever the pattern is used. - -**Rules:** - -1. **Private context repo** lives separately from any repo shared with a wider audience. Owner-level private context lives in a personal private repo (e.g., `owner/private-context`); organizational-level confidential context lives in a directors-only repo (e.g., `org/business-vault`). -2. **Consuming repos** (team-shared project repos, documentation repos) reference the private repo only by name in `§J6`, with explicit rule: `"Never copy content from this repo into [consuming repo] or any repo with a wider audience."` -3. **Harness local memory** (e.g., `~/.claude/projects/*/memory/`) may contain a lightweight summary + pointer to the private repo. Never the full content — avoid duplication and drift. -4. **The private repo** must follow the full Lead Protocol (`.agents/`, `PROTOCOL_RULES.md`, `PROJECT_RULES.md`, `handoff.md`, `decisions.json`) like any other project. -5. **Content that belongs in the personal private repo (`private-context`):** owner's identity, personal strategic goals, permanent personal decisions, personal lessons learned, personal digital presence, family/health/financial context. -6. **Content that belongs in the organizational private repo (`business-vault`):** company financials, strategic plans not yet public, personnel and compensation, legal matters under privilege. -7. **Content that belongs in the team-shared repo:** methodology, system architecture, runbooks, product technical decisions, team operational context. -8. **Opt-in activation:** projects without sensitive context at a given tier do not need to create a corresponding private repo. The rule activates only when such context exists and needs a home. - -## §P9 — Modules architecture *(v1.9.0+)* - -The kernel above is substrate-agnostic and role-agnostic. Substrate-specific and role-specific rules live in opt-in module files under `.agents/modules/`. This section defines the module contract. - -### File layout - -- `.agents/modules/.md` — one file per module; `` is lowercase kebab-case. -- `.agents/modules/README.md` — one-paragraph index listing available modules. -- Each module file carries its own `> Version: X.Y.Z` header and bumps per §P1 independently of the kernel. - -### Anchor convention - -Sections inside a module use anchors of the form `§M--N`. Examples: `§M-git-1`, `§M-meta-3`. The `§M-` prefix disambiguates module anchors from kernel `§P` anchors and project `§J` anchors. - -### Activation - -A project declares its active substrate and active modules in `PROJECT_RULES.md §J8`: - -```markdown -- **Active substrate:** git+github | git | local | cloud-sync | other -- **Active modules:** -``` - -A module is in effect if and only if its scope appears in `Active modules`. Activation order determines precedence between modules (earlier entries win conflicts between modules). The kernel always outranks any module. - -### Boot - -Agents read active modules after `PROJECT_RULES.md` and before `handoff.md`, in the order listed in `§J8 Active modules`. See §P5 for the full boot sequence. - -### Authoring rules - -- A module cannot contradict the kernel. It can only add substrate-specific or role-specific rules. -- When a module cites a kernel anchor, use the fully qualified form `PROTOCOL_RULES §Px` to mark the module→kernel crossing explicitly. -- A module may depend on another module only if it declares the dependency in its header. -- Module CI/tooling (if any) must include a top-of-file comment identifying the module it enforces, so consumer repos that do not list the module know not to copy the tooling. - -### Relation to earlier opt-in language - -The field historically called `Active optional modules` in `PROJECT_RULES.md §J8` (introduced v1.6 for the concurrent-session registry feature flag) is renamed to `Active modules` in v1.9.0. The semantic shift is deliberate: v1.6 used the field to toggle a kernel-internal feature; v1.9 uses the field to activate external rule files. Projects upgrading from v1.8 or earlier move any v1.6 feature-flag values into the new `Active modules` field, or drop them if the feature is now part of the kernel by default. From 25dac59b902dfa69a234b0ac5859c3a9cc7462ad Mon Sep 17 00:00:00 2001 From: Mike Date: Tue, 2 Jun 2026 00:22:27 -0400 Subject: [PATCH 4/4] chore: remove erroneous template/modules/ file (repo root is the template) --- template/.agents/modules/git-substrate.md | 74 ----------------------- 1 file changed, 74 deletions(-) delete mode 100644 template/.agents/modules/git-substrate.md diff --git a/template/.agents/modules/git-substrate.md b/template/.agents/modules/git-substrate.md deleted file mode 100644 index a2932d1..0000000 --- a/template/.agents/modules/git-substrate.md +++ /dev/null @@ -1,74 +0,0 @@ -# modules/git-substrate.md — Git / pull-request substrate rules - -> Version: 1.1.0 | Updated: 2026-06-01 | Protocol: Lead Protocol v1.9.2+ -> Scope: Opt-in module. Activate via `PROJECT_RULES.md §J8 Active modules: git-substrate`. -> Applies to: repositories hosted on a git platform with pull-request support (GitHub, GitLab, Bitbucket, etc.). - ---- - -This module extends `PROTOCOL_RULES.md` with rules specific to projects whose substrate is git and whose review/approval surface is a pull-request platform. A project that is not on git, or is on git but has no remote, or is on a git remote without PR support, should **not** list this module in `§J8 Active modules`. - -## §M-git-1 — Branching (risk-based) - -| File type | Branch required? | -|---|---| -| Executable code (`.py`, `.js`, `.ts`, `.html`, `.css`) | Yes | -| Agent configuration (`CORE_RULES.md`, `CLAUDE.md`, `AGENTS.md`, workflow YAML) | Yes | -| Framework files (`PROTOCOL_RULES.md`, `modules/*.md`) | Yes | -| Documentation, logs, operational data | No — direct commit allowed | -| `handoff.md`, `decisions.json`, activity logs, `active_sessions.md`, checkpoints | No — operational state, direct commit | - -Branch names follow the project's convention declared in `PROJECT_RULES.md §J8` (e.g., `claude/` for AI-authored work, `feat/` / `fix/` for human work). - -## §M-git-2 — Pull request required - -All changes that require branching per §M-git-1 **must use the platform's pull-request workflow**. Direct local merges to the default branch are not allowed for branched work. - -Expected flow: `branch → commit → push → PR → merge via platform → delete branch`. - -This rule does not apply to: - -- Changes with direct commit allowed per §M-git-1 (handoff, decisions, docs, activity logs, active_sessions, checkpoints) -- Repositories without a remote -- Repositories whose hosting platform does not support pull requests (for those, drop this module from `§J8`) - -**Platform branch protection overrides this clause.** When the hosting platform enforces branch protection requiring a pull request for *all* changes to the default branch (including state files), the platform rule wins — open a short-lived PR even for handoff/decisions updates. The §M-git-1 risk-based table is the module's recommendation, not a hard override of platform policy. - -## §M-git-3 — Public-facing documentation sync - -When a pull request modifies `.agents/PROTOCOL_RULES.md` (the kernel that shapes the public surface of the protocol), the **same PR** must include an updated `README.md` reflecting the change — no separate follow-up PR. - -Rationale: the README is the entry point for external users evaluating the protocol. A merged change to the framework with a stale README misrepresents the project. Keeping both in one PR means one approval covers both, and the author (agent or human) edits the README while context is still fresh. - -Enforcement: a CI check (`.github/workflows/readme-sync.yml`) fails the PR when `.agents/PROTOCOL_RULES.md` is touched but `README.md` is not. Override for genuinely internal-only changes: add the label `readme-sync-not-required` to the PR (use sparingly — typo fixes, internal clarifications with no external-visible effect). - -Scope: this rule applies only to `.agents/PROTOCOL_RULES.md`. Changes to `PROJECT_RULES.md`, operational state files, module files, and docs do not trigger it. A meta-repo may extend this to the template copy — see `modules/meta-repo.md §M-meta-6`. - -## §M-git-4 — Commit convention - -The `PROTOCOL_RULES §P3` commit convention (`[Agent] : `) applies verbatim in git. No substrate-specific additions. - -## Optional tooling that ships with the template - -These files are included in the template as conveniences for projects whose substrate is `git+github` and that use common Python-ecosystem tooling. They are **opt-in** — deleting them breaks nothing in the kernel or in this module's rules: - -- `.pre-commit-config.yaml` (at template root) — pre-commit.com scaffold that wires `validate_state.py` as a pre-commit hook. Safe to delete if you use a different hook manager (husky, lefthook) or no hook manager. -- `.agents/scripts/.pre-commit-hooks.yaml` — hook manifest for publishing this repo as a reusable pre-commit source (so downstream projects can `- repo: https://github.com/…/lead-protocol`). Safe to delete if you are not distributing hooks. - -The framework validator itself (`.agents/scripts/validate_state.py`) is **not** opt-in — it is part of the framework and runs independently of any hook tooling (e.g., invoked manually or from CI). - -## §M-git-5 — Session close ordering before PR merge *(v1.1.0+)* - -All session-close state — handoff, decisions, activity, lessons — must be committed on the **feature branch** before the pull request is opened. Writing operational state to the default branch after merge is not permitted. - -**Rationale:** the default branch is typically protected (all writes require a PR). State committed after merge requires a follow-up PR for files that carry no meaningful code diff, splitting the audit trail from the work it documents and creating noise in the review history. - -**Agent rule:** the session-close checklist in `handoff.md` must be fully checked before the PR is opened — not after. The last commit on the feature branch before `git push` should include the updated `handoff.md` and any `decisions.json` / `activity` entries for the session. See PROTOCOL_RULES §P3 branch ordering rule for the substrate-neutral statement. - -**Reviewer signal:** if a PR modifies only operational state files (`handoff.md`, `decisions.json`, `activity_*.md`) and the description explains it as a post-merge closeout, flag the PR. The correct fix is to revert, re-open the original branch, add the state there, and re-merge. - -## Relationship to the kernel - -- `PROTOCOL_RULES §P3` defines the schema for handoff, decisions, session close — those are substrate-neutral and remain in the kernel. -- `PROTOCOL_RULES §P4` quality checklist references "Commit record follows `[Agent] : ` convention (§P3)" — in a git-substrate project, "commit record" means the git commit. -- When this module is active, the branching (§M-git-1) and PR (§M-git-2) gates apply before any operation that would trigger the session close ritual.