# loopgain - Doramagic AI Context Pack

> Positioning: a pre-install experience and judgment asset. It helps the host AI get off to a good start, but it does not mean the project has already been installed, run, or validated.

## Sufficiency Principle

- **Sufficiency over compression**: The AI Context Pack should be sufficient for the host AI to understand the project's value, capability boundaries, entrypoints, risks, and evidence sources before starting work; it may be layered, but it does not aim for the shortest possible summary.
- **Compression policy**: Compress only noise and duplication, never context that affects judgment or the quality of the work.

## How the Host AI Should Use This

You are reading the AI Context Pack that Doramagic compiled for loopgain. Treat it as pre-work context: help the user understand who it fits, what it can do, how to start, what must be verified after install, and where the risks are. Do not claim that you have already installed, run, or executed the target project.

## Claim Consumption Rules

- **Fact source**: Repo Evidence + Claim/Evidence Graph; the Human Wiki only supplies salience, terminology, and narrative structure.
- **Minimum status for a fact**: `supported`
- `supported`: May be used as a project fact, but the answer must cite the claim_id and evidence path.
- `weak`: Usable only as a low-confidence lead; the user must be asked to keep verifying.
- `inferred`: Usable only for risk notes or open questions; must not be packaged as a project fact.
- `unverified`: Must not be used as fact; state clearly that evidence is insufficient.
- `contradicted`: Must show the conflicting sources and must not force a single version on the user's behalf.

## Who It Fits Best

- **Developers already using host AIs such as Claude/Codex/Cursor/Gemini**: The README or plugin config mentions multiple host AIs. Evidence: `README.md` Claim: `clm_0002` supported 0.86

## What It Can Do

- **Command-Line Startup or Install Flow** (Verify after install): The project documentation contains runnable commands; real use requires running them in a local or host environment. Evidence: `README.md` Claim: `clm_0001` supported 0.86

## How to Start

- `pip install loopgain` Evidence: `README.md` Claim: `clm_0003` supported 0.86, `clm_0007` supported 0.86, `clm_0008` supported 0.86, `clm_0009` supported 0.86 et al.
- `/plugin marketplace add loopgain-ai/loopgain-plugin` Evidence: `README.md` Claim: `clm_0004` supported 0.86
- `/plugin install loopgain` Evidence: `README.md` Claim: `clm_0005` supported 0.86
- `pip install keyring` Evidence: `README.md` Claim: `clm_0006` supported 0.86
- `pip install 'loopgain[langgraph]'          # LangGraph` Evidence: `README.md` Claim: `clm_0007` supported 0.86
- `pip install 'loopgain[crewai]'             # CrewAI` Evidence: `README.md` Claim: `clm_0008` supported 0.86
- `pip install 'loopgain[autogen]'            # AutoGen v0.4+` Evidence: `README.md` Claim: `clm_0009` supported 0.86
- `pip install 'loopgain[langchain]'          # LangChain (create_agent / AgentExecutor)` Evidence: `README.md` Claim: `clm_0010` supported 0.86
- `pip install 'loopgain[openai-agents]'      # OpenAI Agents SDK` Evidence: `README.md` Claim: `clm_0011` supported 0.86
- `pip install 'loopgain[claude-agent-sdk]'   # Anthropic Claude Agent SDK` Evidence: `README.md` Claim: `clm_0012` supported 0.86

## Continue-or-Stop Decision Card

- **Current recommendation**: Needs admin / security approval
- **Why**: Continuing may involve secrets, accounts, external services, or sensitive context; get admin or security approval first.

### 30-Second Read

- **What to do now**: Needs admin / security approval
- **Minimum safe next step**: Run Prompt Preview first; if credentials or an enterprise environment are involved, get approval before trialing
- **Do not trust yet**: Real output quality cannot be trusted before install.
- **Continuing will touch**: Command execution, Local environment or project files, Environment variables / API keys

### What You Can Trust Now

- **Target-audience signal: Developers already using host AIs such as Claude/Codex/Cursor/Gemini** (supported): Backed by a supported claim or project evidence, but that still is not the same as real install results. Evidence: `README.md` Claim: `clm_0002` supported 0.86
- **Capability exists: Command-Line Startup or Install Flow** (supported): You can trust that the project contains signals of this capability; whether it fits your specific task still needs trial or after-install verification. Evidence: `README.md` Claim: `clm_0001` supported 0.86
- **There are Quick Start / install-command signals** (supported): You can trust that the docs mention a startup or install entrypoint; do not run it directly in your primary environment because of that. Evidence: `README.md` Claim: `clm_0003` supported 0.86, `clm_0007` supported 0.86, `clm_0008` supported 0.86, `clm_0009` supported 0.86

### What You Cannot Trust Yet

- **Real output quality cannot be trusted before install.** (unverified): Prompt Preview can only show how it guides you; it cannot prove result quality in the real project.
- **Host AI version compatibility cannot be trusted before install.** (unverified): Host loading rules and version differences across Claude, Cursor, Codex, Gemini, and others must be verified in a real environment.
- **That it will not pollute your existing host AI's behavior cannot be trusted directly.** (inferred): Skill, plugin, and AGENTS/CLAUDE/GEMINI instructions may change the host AI's default behavior.
- **Safe rollback cannot be assumed by default.** (unverified): Unless the project clearly provides uninstall and recovery instructions, verify in an isolated environment first.
- **After a real install, is it compatible with the user's current host AI version?** (unverified): Compatibility can only be verified in the actual host environment.
- **Does the project's output quality meet the user's specific task?** (unverified): The pre-install preview can only show flow and boundaries; it cannot replace real evaluation.
- **Do the install commands require network access, permissions, or global writes?** (unverified): This affects install risk in both enterprise and personal environments. Evidence: `README.md`

### What Continuing Will Touch

- **Command execution**: Package managers, network downloads, the local plugin directory, project config, or the user's home directory. Why: Running the very first command can already change your environment; decide whether it is worth running first. Evidence: `README.md`
- **Local environment or project files**: Install results, plugin caches, project config, or local dependency directories. Why: The write scope and rollback path cannot be proven before install and need isolated verification. Evidence: `README.md`
- **Environment variables / API keys**: Project entry docs explicitly showing API key, token, secret, or account credential configuration. Why: If a real install needs credentials, use test credentials first and go through a permission/compliance review. Evidence: `README.md`, `examples/README.md`, `examples/_common.py`, `loopgain/telemetry.py`
- **Host AI context**: The AI Context Pack, Prompt Preview, Skill routing, risk rules, and project facts. Why: Importing context affects the host AI's later judgment, so avoid packaging unverified items as facts.

### Minimum Safe Next Steps

- **Run Prompt Preview first**: Use a pre-install interactive trial to judge whether the way of working fits; it needs no authorization or environment change. (applies when: Applies to any project, especially when output quality is unknown.)
- **Trial-install only in an isolated directory or a test account**: Avoid letting install commands pollute your primary host AI, real projects, or home directory. (applies when: When there are signals of command execution, plugin config, or local writes.)
- **Do not use real production credentials**: Once an environment variable / API key enters the host or toolchain, it can create account and compliance risk. (applies when: When environment signals like API, TOKEN, KEY, or SECRET appear.)
- **After install, verify just one minimal task**: Verify loading, compatibility, output quality, and rollback first, then decide whether to use it deeply. (applies when: When moving from a trial into a real workflow.)

### Exit Plan

- **Preserve the pre-install state**: Record the original host config and project state so you can later judge whether it is recoverable.
- **Record the install commands and written paths**: Without clear uninstall instructions, you at least need to know which directories or configs to clean up manually.
- **Be ready to revoke test API keys or tokens**: If test credentials leak or are misused, you can cut losses quickly.
- **If there is no rollback path, do not enter your primary environment**: No rollback is a blocker before continuing; do not proceed on trust or luck.

## What Can Only Be Previewed

- Explain who the project fits and what it can do
- Demonstrate a typical conversation flow based on project docs
- Help the user decide whether it is worth installing or researching further

## What Must Be Verified After Install

- Actually installing the Skill, plugin, or CLI
- Running scripts, modifying local files, or accessing external services
- Verifying real output quality, performance, and compatibility

## Boundary & Risk Decision Card

- **Mistaking the pre-install preview for a real run**: The user may overestimate how much configuration, permission, and compatibility verification the project has already done. Mitigation: Clearly separate prompt_preview_can_do from runtime_required. Claim: `clm_0014` inferred 0.45
- **Command execution will modify the local environment**: Install commands may write to the user's home directory, the host plugin directory, or project configuration. Mitigation: Run in an isolated environment or a test account first. Evidence: `README.md` Claim: `clm_0015` supported 0.86
- **To confirm**: After a real install, is it compatible with the user's current host AI version?. Why: Compatibility can only be verified in the actual host environment.
- **To confirm**: Does the project's output quality meet the user's specific task?. Why: The pre-install preview can only show flow and boundaries; it cannot replace real evaluation.
- **To confirm**: Do the install commands require network access, permissions, or global writes?. Why: This affects install risk in both enterprise and personal environments.

## Pre-Work Working Context

### Loading Order

- First read how_to_use.host_ai_instruction to establish the boundaries of this pre-install judgment asset.
- Read claim_graph_summary to confirm facts come from the Claim/Evidence Graph, not the Human Wiki narrative.
- Then read intended_users, capabilities, and quick_start_candidates to judge whether the user is a match.
- When you need to carry out a concrete task, check role_skill_index first, then evidence_index.
- For real install, file modification, network access, performance, or compatibility questions, turn to risk_card and boundaries.runtime_required.

### Task Routes

- **Command-Line Startup or Install Flow**: State that this is an after-install capability first, then give a pre-install checklist. Boundary: Must be verified after a real install or run. Evidence: `README.md` Claim: `clm_0001` supported 0.86

### Context Scale

- Total files: 33
- Important-file coverage: 32/33
- Evidence index entries: 31
- Role / Skill entries: 6

### Handling Insufficient Evidence

- **missing_evidence**: State that evidence is insufficient and ask the user for the target file, a README section, or after-install verification records; do not fill in facts.
- **out_of_scope_request**: State that the task is beyond the current AI Context Pack's evidence scope and suggest the user check the Human Manual or verify after a real install.
- **runtime_request**: Provide a pre-install checklist and command sources, but do not run commands for the user or claim they have been run.
- **source_conflict**: Show the conflicting sources side by side, mark them as unverified, and do not force a single version.

## Prompt Recipes

### Fit assessment

- Goal: Judge whether this project fits the user's current task.
- Expected output: A fit conclusion, key reasons, evidence citations, what can be previewed before install, what must be verified after install, and a next-step recommendation.

```text
Based on the AI Context Pack for loopgain, ask me 3 necessary questions first, then judge whether it fits my task. The answer must cover: who it fits, what it can do, what it cannot do, whether it is worth installing, and where the evidence comes from. Every project fact must cite evidence_refs, source_paths, or a claim_id.
```

### Pre-install experience

- Goal: Let the user feel the core workflow before installing, while avoiding packaging the preview as real capability or a marketing promise.
- Expected output: An experience script with boundary labels, an after-install verification checklist, and a cautious recommendation; with no real-run promises or strong marketing language.

```text
Treat loopgain as a pre-install experience asset, not an already-installed tool or a real runtime environment.

Output exactly four parts:
1. Ask me 3 necessary questions first.
2. Give an "experience script": use the three labels [Previewable before install], [Must verify after install], and [Insufficient evidence] to show how it might guide the workflow.
3. Give an after-install verification checklist: list which capabilities can only be confirmed after a real install, real host loading, and a real project run.
4. Give a cautious recommendation: only "worth researching/trialing further", "add information before deciding", or "not recommended to continue"; do not endorse the project.

Hard boundaries:
- Do not claim you have installed, run, executed tests, modified files, or produced real results.
- Do not write promise-like phrasing such as "auto-adapts", "guarantees passing", "perfect fit", or "strongly recommend installing".
- If you describe how it works after install, you must use a conditional such as "if installed successfully and the host loads the Skill correctly, it might...".
- The experience script may only be written as "example lines / hypothetical flow": use "might ask / might suggest / might show", not "has written, has generated, has passed, is running, is generating".
- Prompt Preview does not hand out install commands; if the user is ready to trial, only prompt them to read Quick Start and the Risk Card first and to verify in an isolated environment.
- Every project fact must come from a supported claim, evidence_refs, or source_paths; inferred/unverified items can only be risks or open questions.

```

### Role / Skill selection

- Goal: Pick the best-matching asset from the project's roles or Skills.
- Expected output: A list of candidate roles or Skills, each with an applicable scenario, evidence paths, risk boundary, and whether after-install verification is needed.

```text
Read role_skill_index and recommend 3-5 of the most relevant roles or Skills for my target task. For each recommendation, state the applicable scenario, likely output, risk boundary, and evidence_refs.
```

### Risk pre-check

- Goal: Identify environment, permission, rule-conflict, and quality risks before installing or adopting.
- Expected output: A checklist of environment, permission, dependency, license, host-conflict, quality risk, and unknown items.

```text
Based on risk_card, boundaries, and quick_start_candidates, give me a pre-install risk pre-check list. Do not run commands for me; only explain what I should check, why, and what impact a failure would have.
```

### Host AI kickoff instruction

- Goal: Turn the project context into a host AI instruction for the start of a conversation.
- Expected output: A pre-work instruction with clear boundaries and clear evidence citations, suitable to copy to a host AI.

```text
Based on the AI Context Pack for loopgain, generate a pre-work instruction I can paste to my host AI. This instruction must obey not_runtime=true and must not claim the project has been installed, run, or produced real results.
```

## Role / Skill Index

- Indexed 6 role / Skill / project-doc entries.

- **LoopGain** (project_doc): An open-source cost controller for AI agent loops. Activation hint: Reference this when the user needs to understand the project's structure, install path, or boundaries. Evidence: `README.md`
- **LoopGain examples — real Claude loops, baseline vs LoopGain** (project_doc): LoopGain examples — real Claude loops, baseline vs LoopGain Activation hint: Reference this when the user needs to understand the project's structure, install path, or boundaries. Evidence: `examples/README.md`
- **LoopGain v2 Classifier — Pre-Registration** (project_doc): LoopGain v2 Classifier — Pre-Registration Activation hint: Reference this when the user needs to understand the project's structure, install path, or boundaries. Evidence: `PROTOCOL_v2_classifier.md`
- **LoopGain v0.2 Classifier — Validation Results** (project_doc): LoopGain v0.2 Classifier — Validation Results Activation hint: Reference this when the user needs to understand the project's structure, install path, or boundaries. Evidence: `RESULTS_v2_classifier.md`
- **Telemetry in loopgain** (project_doc): LoopGain has two completely separate telemetry paths. They serve different purposes, are configured differently, and never share data or code. This document is about the second one — anonymous funnel telemetry — and how to control it. Activation hint: Reference this when the user needs to understand the project's structure, install path, or boundaries. Evidence: `TELEMETRY.md`
- **Changelog** (project_doc): All notable changes to the loopgain library are recorded here. The format follows Keep a Changelog https://keepachangelog.com/en/1.1.0/ , and versions follow Semantic Versioning https://semver.org/ . Activation hint: Reference this when the user needs to understand the project's structure, install path, or boundaries. Evidence: `CHANGELOG.md`

## Evidence Index

- Indexed 31 evidence entries.

- **LoopGain** (documentation): An open-source cost controller for AI agent loops. Evidence: `README.md`
- **LoopGain examples — real Claude loops, baseline vs LoopGain** (documentation): LoopGain examples — real Claude loops, baseline vs LoopGain Evidence: `examples/README.md`
- **License** (source_file): Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ Evidence: `LICENSE`
- **LoopGain v2 Classifier — Pre-Registration** (documentation): LoopGain v2 Classifier — Pre-Registration Evidence: `PROTOCOL_v2_classifier.md`
- **LoopGain v0.2 Classifier — Validation Results** (documentation): LoopGain v0.2 Classifier — Validation Results Evidence: `RESULTS_v2_classifier.md`
- **Telemetry in loopgain** (documentation): LoopGain has two completely separate telemetry paths. They serve different purposes, are configured differently, and never share data or code. This document is about the second one — anonymous funnel telemetry — and how to control it. Evidence: `TELEMETRY.md`
- **01 Code Pytest** (source_file): WORKLOAD ID = "example-01-code-pytest" FIXED CAP = 5 ⋮---- SPEC = """\ ⋮---- TESTS = '''\ ⋮---- def strip code fences text: str - str ⋮---- fence = re.match r"^\s \s $", text, re.DOTALL ⋮---- def run pytest workdir: Path - tuple int, str ⋮---- proc = subprocess.run out = proc.stdout + proc.stderr m = re.search r" \d+ \s+failed", out failures = int m.group 1 if m else 0 ⋮---- failures = 15 collection/import error → worst-case signal ⋮---- def one iteration client, workdir: Path, prev code: str, prev failures: str ⋮---- """Single verify-revise step. Returns failing count, code, pytest output .""" ⋮---- prompt = SPEC ⋮---- prompt = code = strip code fences call claude client, prompt ⋮---- def… Evidence: `examples/01_code_pytest.py`
- **02 Json Extract** (source_file): WORKLOAD ID = "example-02-json-extract" FIXED CAP = 5 ⋮---- BLURB = """\ ⋮---- ISO DATE = re.compile r"^\d{4}-\d{2}-\d{2}$" HTTPS URL = re.compile r"^https?:// ^\s +$" ⋮---- SYSTEM = ⋮---- def validate doc - list str ⋮---- """Return a list of human-readable validation errors. Empty = valid.""" errs: list str = ⋮---- def need key, typ, path="$" ⋮---- v = doc "venue" ⋮---- def parse json text: str ⋮---- fence = re.search r" ", text, re.DOTALL payload = fence.group 1 if fence else text ⋮---- def one iteration client, prev json: str, prev errors: list str ⋮---- """Single extract → validate step. Returns err count, raw json, errors .""" ⋮---- prompt = ⋮---- raw = call claude client, prompt, syst… Evidence: `examples/02_json_extract.py`
- **03 Essay Critique** (source_file): WORKLOAD ID = "example-03-essay-critique" FIXED CAP = 6 ⋮---- TOPIC = ⋮---- JUDGE SYSTEM = ⋮---- def parse scores text: str ⋮---- fence = re.search r" ", text, re.DOTALL payload = fence.group 1 if fence else text ⋮---- d = json.loads payload ⋮---- keys = "clarity", "accuracy", "concision", "prose" ⋮---- def error from scores scores - float ⋮---- def one iteration client, prev essay: str, prev scores ⋮---- draft prompt = TOPIC ⋮---- crit = draft prompt = essay = call claude client, draft prompt, max tokens=400 ⋮---- judge reply = call claude scores = parse scores judge reply ⋮---- def baseline run client ⋮---- """No LoopGain: run FIXED CAP iterations unconditionally.""" ⋮---- avg = 10.0 - er… Evidence: `examples/03_essay_critique.py`
- **04 Sql Synth** (source_file): WORKLOAD ID = "example-04-sql-synth" FIXED CAP = 5 ⋮---- SCHEMA = """\ ⋮---- QUESTION = ⋮---- EXPECTED = ⋮---- def extract sql text: str - str ⋮---- fence = re.search r" ", text, re.DOTALL ⋮---- def run query conn: sqlite3.Connection, sql: str ⋮---- rows = conn.execute sql .fetchall ⋮---- got = tuple r for r in rows diff = set got .symmetric difference set EXPECTED ⋮---- def one iteration client, conn, prev sql: str, prev msg: str ⋮---- prompt = ⋮---- sql = extract sql call claude client, prompt ⋮---- def baseline run client, conn ⋮---- def loopgain run client, conn ⋮---- lg = LoopGain target error=0, max iterations=FIXED CAP ⋮---- first line = sql.splitlines 0 if sql else " no sql " previe… Evidence: `examples/04_sql_synth.py`
- **Tokens forbidden by constraint a — these are exactly the coroutine** (source_file): WORKLOAD ID = "example-05-unsolvable-stalls" FIXED CAP = 10 ⋮---- STARTER = '''\ ⋮---- SPEC = ⋮---- Tokens forbidden by constraint a — these are exactly the coroutine drivers that constraint c requires, so satisfying both is impossible. DRIVERS = DRIVER RE = re.compile " ".join DRIVERS ⋮---- def strip fences text: str - str ⋮---- m = re.match r"^\s \s $", text, re.DOTALL ⋮---- def evaluate code: str ⋮---- """Return error, reason . 0 is unreachable by construction. The spec is impossible, so every attempt fails at least one constraint and the error sits at 1 — the loop makes no forward progress no matter how many times it revises. A fixed cap keeps paying for that; LoopGain reads the flat tr… Evidence: `examples/05_unsolvable_stalls.py`
- **06 Diverges** (source_file): WORKLOAD ID = "example-06-diverges" FIXED CAP = 8 ⋮---- PASSAGE = ⋮---- FACTS = ⋮---- def count missing text: str ⋮---- lower = text or "" .lower missing = f for f in FACTS if f.lower not in lower ⋮---- def one iteration client, prev text: str, iteration: int ⋮---- prompt = ⋮---- revised = call claude client, prompt, max tokens=400 ⋮---- def baseline run client ⋮---- current = PASSAGE err = 0 ⋮---- wc = len current.split ⋮---- def loopgain run client ⋮---- lg = LoopGain target error=None, max iterations=FIXED CAP ⋮---- iteration = 0 ⋮---- preview = f"{wc}w; missing={err}/{len FACTS }: {missing :2 }" state = lg.observe err, output=current ⋮---- def main - None ⋮---- client = get client ⋮----… Evidence: `examples/06_diverges.py`
- **Init** (source_file): all = Evidence: `loopgain/__init__.py`
- **Classifier** (source_file): INIT = "INIT" FAST CONVERGE = "FAST CONVERGE" CONVERGING = "CONVERGING" STALLING = "STALLING" OSCILLATING = "OSCILLATING" DIVERGING = "DIVERGING" ⋮---- DEFAULT E RATIO FAST = 0.1 ⋮---- DEFAULT E RATIO CONV = 0.5 ⋮---- DEFAULT P SIG = 0.05 ⋮---- DEFAULT DIV MARGIN = 0.10 ⋮---- DEFAULT OSC STD THRESHOLD = 0.30 ⋮---- DEFAULT SLOPE TOL = 0.05 ⋮---- DEFAULT STALL PATIENCE = 3 ⋮---- EPS = 1e-12 ⋮---- @dataclass frozen=True class TrajectoryThresholds ⋮---- e ratio fast: float = DEFAULT E RATIO FAST e ratio conv: float = DEFAULT E RATIO CONV p sig: float = DEFAULT P SIG div margin: float = DEFAULT DIV MARGIN osc std threshold: float = DEFAULT OSC STD THRESHOLD slope tol: float = DEFAULT SLOPE TOL s… Evidence: `loopgain/classifier.py`
- **Cli** (source_file): def print status - None ⋮---- s = Funnel start background=False .status state = "ON" if s "enabled" else "OFF" ⋮---- def handle telemetry args: argparse.Namespace - int ⋮---- def handle doctor args: "argparse.Namespace" - int ⋮---- resolved = resolve telemetry config args.endpoint, args.token ⋮---- lg = LoopGain target error=0.1, max iterations=5 ⋮---- res = lg.result ⋮---- ok = lg.send telemetry ⋮---- def main argv: Optional Sequence str = None - int ⋮---- parser = argparse.ArgumentParser ⋮---- sub = parser.add subparsers dest="command" ⋮---- p tel = sub.add parser grp = p tel.add mutually exclusive group ⋮---- p doc = sub.add parser ⋮---- args = parser.parse args argv Evidence: `loopgain/cli.py`
- **Core** (source_file): DEFAULT FAST CONVERGE = 0.3 DEFAULT CONVERGING = 0.85 DEFAULT STALLING = 0.95 DEFAULT OSCILLATING UPPER = 1.05 ⋮---- DEFAULT MAX ITERATIONS = 50 ⋮---- INIT = "INIT" FAST CONVERGE = "FAST CONVERGE" CONVERGING = "CONVERGING" STALLING = "STALLING" OSCILLATING = "OSCILLATING" DIVERGING = "DIVERGING" TARGET MET = "TARGET MET" MAX ITERATIONS = "MAX ITERATIONS" ⋮---- @dataclass frozen=True class ThresholdBands ⋮---- fast converge: float = DEFAULT FAST CONVERGE converging: float = DEFAULT CONVERGING stalling: float = DEFAULT STALLING oscillating upper: float = DEFAULT OSCILLATING UPPER ⋮---- def state for self, ab smooth: float - str ⋮---- @dataclass class LoopGainResult ⋮---- outcome: str ⋮---- it… Evidence: `loopgain/core.py`
- **Map terminal LoopGain state names to the coarse outcome buckets we count.** (source_file): FUNNEL SCHEMA VERSION = 1 ⋮---- DEFAULT FUNNEL ENDPOINT = "https://telemetry.loopgain.ai/v1/funnel" ⋮---- TRUE = frozenset {"1", "true", "yes", "on", "enable", "enabled"} FALSE = frozenset {"0", "false", "no", "off", "disable", "disabled", ""} ⋮---- Map terminal LoopGain state names to the coarse outcome buckets we count. Anything unrecognized is bucketed as "other" so the distribution stays small ⋮---- STATE TO OUTCOME = { ⋮---- DISABLED = "disabled" UNDECIDED = "undecided" ENABLED = "enabled" ⋮---- NOTICE = ⋮---- def now hour clock: Callable , datetime - str ⋮---- class NoRedirectHandler urllib.request.HTTPRedirectHandler ⋮---- def http error 301 self, req, fp, code, msg, headers ⋮---- ht… Evidence: `loopgain/funnel.py`
- **Library version sourced from loopgain. version so there's exactly one** (source_file): def safe float x: Any - Any ⋮---- class NoRedirectHandler urllib.request.HTTPRedirectHandler ⋮---- def http error 301 self, req, fp, code, msg, headers ⋮---- http error 302 = http error 301 http error 303 = http error 301 http error 307 = http error 301 http error 308 = http error 301 ⋮---- NO REDIRECT OPENER = urllib.request.build opener NoRedirectHandler ⋮---- def open request req: urllib.request.Request, timeout: float - Any ⋮---- SCHEMA VERSION = 4 ⋮---- AGGREGATE PATH = "/v1/aggregate" ⋮---- ENDPOINT ENV = "LOOPGAIN TELEMETRY ENDPOINT" TOKEN ENV = "LOOPGAIN TELEMETRY TOKEN" ⋮---- ep = endpoint or os.environ.get ENDPOINT ENV or "" .strip tok = token or os.environ.get TOKEN ENV or "" .st… Evidence: `loopgain/telemetry.py`
- **Init** (source_file): all = ⋮---- def getattr name: str Evidence: `loopgain/integrations/__init__.py`
- **Autogen** (source_file): AsyncMessageErrorFn = Callable Any , Awaitable Optional float MessageErrorFn = Callable Any , Optional float ⋮---- class AutoGenAdapter ⋮---- framework name = "autogen" ⋮---- out: List Any = ⋮---- kwargs: dict str, Any = {"task": task} ⋮---- we cancelled = False iterator = team.run stream kwargs . aiter ⋮---- message = await iterator. anext ⋮---- source = getattr message, "source", None ⋮---- magnitude = self.error fn message ⋮---- magnitude = await magnitude ⋮---- cancel = getattr cancellation token, "cancel", None ⋮---- we cancelled = True Evidence: `loopgain/integrations/autogen.py`
- **Crewai** (source_file): CrewStepFn = Callable Any , Optional float CrewTaskFn = Callable Any , Optional float ⋮---- class CrewAIAdapter ⋮---- framework name = "crewai" ⋮---- def install self, crew: Any - None ⋮---- existing = getattr crew, "step callback" ⋮---- existing = getattr crew, "task callback" ⋮---- def uninstall self - None ⋮---- def enter self ⋮---- def exit self, exc info - None ⋮---- def on step self, step: Any - None ⋮---- magnitude = self.step error fn step ⋮---- def on task self, task output: Any - None ⋮---- magnitude = self.task error fn task output ⋮---- @staticmethod def chain existing: Optional Callable Any , None , ours: Callable Any , None - Callable Any , None ⋮---- def chained item: Any - N… Evidence: `loopgain/integrations/crewai.py`
- **Langchain** (source_file): ErrorFn = Callable Any , Optional float AsyncErrorFn = Callable Any , Awaitable Optional float ⋮---- class LangChainAdapter ⋮---- framework name = "langchain" ⋮---- last: Any = None ⋮---- last = item ⋮---- iterator = agent.stream input, stream kwargs ⋮---- magnitude = self.error fn item ⋮---- iterator = agent.astream input, stream kwargs ⋮---- magnitude: Optional float ⋮---- magnitude = await error fn item Evidence: `loopgain/integrations/langchain.py`
- **Langgraph** (source_file): ErrorFn = Callable Any , Optional float AsyncErrorFn = Callable Any , Awaitable Optional float ⋮---- class LangGraphAdapter ⋮---- framework name = "langgraph" ⋮---- last: Any = None ⋮---- last = item ⋮---- iterator = graph.stream ⋮---- magnitude = self.error fn item ⋮---- iterator = graph.astream ⋮---- magnitude: Optional float ⋮---- magnitude = await error fn item Evidence: `loopgain/integrations/langgraph.py`
- **Openai Agents** (source_file): EventErrorFn = Callable Any , Optional float AsyncEventErrorFn = Callable Any , Awaitable Optional float ⋮---- DEFAULT OBSERVE EVENT TYPES = frozenset {"run item stream event"} ⋮---- class OpenAIAgentsAdapter ⋮---- framework name = "openai-agents" ⋮---- result = Runner.run streamed agent, input, run kwargs ⋮---- async def drive self, result: Any - AsyncIterator Any ⋮---- cancelled = False ⋮---- event type = getattr event, "type", None ⋮---- magnitude = self.error fn event ⋮---- magnitude = await magnitude ⋮---- cancel = getattr result, "cancel", None ⋮---- cancelled = True Evidence: `loopgain/integrations/openai_agents.py`
- **Changelog** (documentation): All notable changes to the loopgain library are recorded here. The format follows Keep a Changelog https://keepachangelog.com/en/1.1.0/ , and versions follow Semantic Versioning https://semver.org/ . Evidence: `CHANGELOG.md`
- **Virtualenv** (source_file): pycache / .py cod $py.class .so .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ .egg-info/ .installed.cfg .egg Evidence: `.gitignore`
- **LoopGain developer Makefile.** (source_file): LoopGain developer Makefile. Targets here are for manual invocation by the maintainer. There is no CI integration for examples — running them costs real Anthropic API spend, so they should only fire when a human asks. Evidence: `Makefile`
- **07 Agentic Multistep** (source_file): WORKLOAD ID = "example-07-agentic-multistep" FIXED CAP = 5 ⋮---- PANTRY = { ALLOWED TECHNIQUES = {"searing", "braising", "roasting", "poaching"} GOAL = { ⋮---- SYSTEM = ⋮---- def render prompt prev plan: str, prev errors: list str - str ⋮---- pantry lines = "\n".join base = ⋮---- def parse plan text: str ⋮---- fence = re.search r" ", text, re.DOTALL payload = fence.group 1 if fence else text ⋮---- def verify plan - list str ⋮---- """Return the list of unmet constraints. Empty list = goal achieved.""" errs: list str = ⋮---- ings = plan.get "ingredients" ⋮---- ings = bad names = i.get "name" for i in ings if i.get "name" not in PANTRY ⋮---- n ings = len ings ⋮---- cost = 0.0 ⋮---- info = PANT… Evidence: `examples/07_agentic_multistep.py`
- **Common** (source_file): DEFAULT MODEL = os.environ.get "LOOPGAIN EXAMPLE MODEL", "claude-haiku-4-5" DEFAULT ENDPOINT = "https://telemetry.loopgain.ai/v1/aggregate" ⋮---- def get client ⋮---- kwargs = { ⋮---- msg = client.messages.create kwargs parts = b.text for b in msg.content if getattr b, "type", None == "text" ⋮---- def send telemetry lg, , workload id: str, loop type: str - None ⋮---- """POST aggregate telemetry to the receiver. No-op if token is unset.""" token = os.environ.get "LOOPGAIN TELEMETRY TOKEN" endpoint = os.environ.get "LOOPGAIN TELEMETRY ENDPOINT", DEFAULT ENDPOINT ⋮---- ok = lg.send telemetry ⋮---- def print iteration i: int, error: float, state: str, preview: str = "" - None ⋮---- """One-line… Evidence: `examples/_common.py`
- **Version** (source_file): version = "0.6.3" Evidence: `loopgain/_version.py`
- **Single source of truth: loopgain/ version.py read dynamically below .** (source_file): build-system requires = "setuptools =61.0" build-backend = "setuptools.build meta" Evidence: `pyproject.toml`

## Rules the Host AI Must Follow

- **Treat this asset as pre-work context, not a runtime environment.**: The AI Context Pack contains only an evidence-backed understanding of the project, not the project's executable state. Evidence: `README.md`, `examples/README.md`, `LICENSE`
- **When answering the user, distinguish what can be previewed from what can only be verified after install.**: The consumer value of the pre-install experience comes from reducing bad installs and misjudgments, not from pretending to be a real run. Evidence: `README.md`, `examples/README.md`, `LICENSE`

## Questions the User Should Answer First

- Which host AI or local environment do you plan to use it in?
- Do you just want to experience the workflow first, or are you ready to actually install?
- What matters most to you: install cost, output quality, or conflicts with your existing rules?

## Acceptance Checks

- Every capability claim can be traced back to a file path in evidence_refs.
- AI_CONTEXT_PACK.md does not package previews as a real run.
- The user can understand who it fits, what it can do, how to start, and the risk boundaries within 3 minutes.

---

## Doramagic Context Augmentation

The following sections strengthen the repository context for a host AI. Human Manual data is a reading route, and pitfall notes become operating constraints.

## Human Manual Outline

Usage rule: this is only a reading route and salience signal, not factual authority. Concrete claims must still return to repo evidence or Claim Graph.

Host AI hard rules:
- Do not treat page titles, section order, summaries, or importance values as factual project evidence.
- When explaining the Human Manual outline, state that it is only a reading route or salience signal.
- Capability, installation, compatibility, runtime state, and risk claims must cite repo evidence, source paths, or Claim Graph.

- **Core LoopGain Engine and Trajectory Classifier**: importance `high`
  - source_paths: loopgain/core.py, loopgain/classifier.py, loopgain/__init__.py, PROTOCOL_v2_classifier.md, RESULTS_v2_classifier.md
- **Funnel Telemetry: Lifecycle, Initialization, and Known Issues**: importance `high`
  - source_paths: loopgain/funnel.py, loopgain/telemetry.py, loopgain/cli.py, loopgain/__main__.py, TELEMETRY.md
- **Framework Adapters: Wiring LoopGain into Agent Stacks**: importance `high`
  - source_paths: loopgain/integrations/__init__.py, loopgain/integrations/langgraph.py, loopgain/integrations/crewai.py, loopgain/integrations/autogen.py, loopgain/integrations/langchain.py
- **Usage Examples, Error Signals, and Common Workflows**: importance `medium`
  - source_paths: examples/01_code_pytest.py, examples/02_json_extract.py, examples/03_essay_critique.py, examples/04_sql_synth.py, examples/05_unsolvable_stalls.py

## Repo Inspection Evidence

- repo_clone_verified: true
- repo_inspection_verified: true
- repo_commit: `2ee73af917c72c211d1744bad5aa81b12f83c88b`
- inspected_files: `README.md`, `pyproject.toml`, `examples/01_code_pytest.py`, `examples/02_json_extract.py`, `examples/03_essay_critique.py`, `examples/04_sql_synth.py`, `examples/05_unsolvable_stalls.py`, `examples/06_diverges.py`, `examples/07_agentic_multistep.py`, `examples/README.md`, `examples/_common.py`

Host AI hard rules:
- Without repo_clone_verified=true, do not claim that the source code has been read.
- Without repo_inspection_verified=true, do not write README, docs, or package-file conclusions as facts.
- Without quick_start_verified=true, do not claim that the Quick Start path has run successfully.

## Doramagic Pitfall Constraints

These rules come from Doramagic discovery, validation, or compilation findings. The host AI must treat them as operating constraints, not background notes.

### Constraint 1: Capability evidence risk requires verification

- Trigger: README/documentation is current enough for a first validation pass.
- Host AI rule: Reproduce the official install and quickstart path in an isolated environment.
- Why it matters: May increase setup, validation, or first-run risk for the user.
- Evidence: capability.assumptions | https://news.ycombinator.com/item?id=48919562
- Hard boundary: Do not present this pitfall as solved, verified, or ignorable unless later evidence explicitly closes it.

### Constraint 2: Security or permission risk requires verification

- Trigger: no_demo
- Host AI rule: Reproduce the official install and quickstart path in an isolated environment.
- Why it matters: May increase setup, validation, or first-run risk for the user.
- Evidence: downstream_validation.risk_items | https://news.ycombinator.com/item?id=48919562
- Hard boundary: Do not present this pitfall as solved, verified, or ignorable unless later evidence explicitly closes it.

### Constraint 3: Security or permission risk requires verification

- Trigger: no_demo
- Host AI rule: Reproduce the official install and quickstart path in an isolated environment.
- Why it matters: May increase setup, validation, or first-run risk for the user.
- Evidence: risks.scoring_risks | https://news.ycombinator.com/item?id=48919562
- Hard boundary: Do not present this pitfall as solved, verified, or ignorable unless later evidence explicitly closes it.

### Constraint 4: Maintenance risk requires verification

- Trigger: issue_or_pr_quality=unknown。
- Host AI rule: Reproduce the official install and quickstart path in an isolated environment.
- Why it matters: May increase setup, validation, or first-run risk for the user.
- Evidence: evidence.maintainer_signals | https://news.ycombinator.com/item?id=48919562
- Hard boundary: Do not present this pitfall as solved, verified, or ignorable unless later evidence explicitly closes it.

### Constraint 5: Maintenance risk requires verification

- Trigger: release_recency=unknown。
- Host AI rule: Reproduce the official install and quickstart path in an isolated environment.
- Why it matters: May increase setup, validation, or first-run risk for the user.
- Evidence: evidence.maintainer_signals | https://news.ycombinator.com/item?id=48919562
- Hard boundary: Do not present this pitfall as solved, verified, or ignorable unless later evidence explicitly closes it.
