{"id":51682694,"url":"https://github.com/srdjan/two-loops","last_synced_at":"2026-07-15T15:04:07.966Z","repository":{"id":339616013,"uuid":"1161276787","full_name":"srdjan/two-loops","owner":"srdjan","description":"Ralph and RLM Loops + one-shot and 2 Models battling","archived":false,"fork":false,"pushed_at":"2026-02-20T19:56:22.000Z","size":104,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-04-08T12:35:30.514Z","etag":null,"topics":["agent","ax","deno","ralph-loop","rlm"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/srdjan.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-02-18T23:34:32.000Z","updated_at":"2026-02-21T13:58:20.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/srdjan/two-loops","commit_stats":null,"previous_names":["srdjan/ax-ralph-rlm","srdjan/two-loops"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/srdjan/two-loops","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/srdjan%2Ftwo-loops","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/srdjan%2Ftwo-loops/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/srdjan%2Ftwo-loops/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/srdjan%2Ftwo-loops/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/srdjan","download_url":"https://codeload.github.com/srdjan/two-loops/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/srdjan%2Ftwo-loops/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":35509502,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-07-15T02:00:06.706Z","response_time":131,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["agent","ax","deno","ralph-loop","rlm"],"created_at":"2026-07-15T15:04:04.397Z","updated_at":"2026-07-15T15:04:07.958Z","avatar_url":"https://github.com/srdjan.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Ralph Loop + RLM (Deno)\n\nA Deno proof-of-concept demonstrating two nested LLM loops for grounded,\nevidence-backed document analysis:\n\n- **Ralph loop** (outer quality loop): generate, validate, feedback, retry\n- **RLM mode** (inner long-context pattern): load a document into a sandboxed\n  Deno Worker and query slices via `llmQuery` rather than stuffing the full text\n  into the context window\n- **Two-model split**: Claude (Anthropic) for generation, GPT (OpenAI) for\n  validation\n\nThe system uses `@anthropic-ai/sdk` and `openai` directly - no framework\nintermediary.\n\n---\n\n## Prerequisites\n\n- **Deno** (v2.0+)\n- API keys:\n  - `ANTHROPIC_APIKEY` for Claude generation\n  - `OPENAI_APIKEY` for GPT validation\n\n## Setup\n\n```bash\ncp .env.example .env\n# fill in OPENAI_APIKEY and ANTHROPIC_APIKEY\n```\n\n## Modes\n\nThe system supports two modes: **QA** (question-answering with evidence) and\n**Task** (general task completion with iterative reasoning).\n\n### QA mode\n\nGenerates a structured answer with verbatim evidence quotes from a document.\n\n```bash\ndeno task demo -- --mode qa --query \"Explain Ralph loop and RLM\" --doc docs/long.txt\n```\n\nOutput: `answer` (3-7 bullet lines) + `evidence` (3-8 verbatim quotes that must\nappear in the document).\n\n### Task mode (default)\n\nReads a document, reasons about a task, and iteratively improves the output\nusing accumulated memory.\n\n```bash\ndeno task demo -- --query \"Summarize the key architectural decisions\" --doc docs/long.txt\n```\n\nOutput: `output` (task completion) + `memoryUpdate` (findings persisted across\niterations).\n\n### Full flag set\n\n```bash\ndeno task demo -- \\\n  --mode qa \\\n  --query \"...\" \\\n  --doc docs/long.txt \\\n  --maxIters 6 \\\n  --out out \\\n  --progressMs 5000 \\\n  --memFile out/context.md\n```\n\n---\n\n## How the QA loop works\n\n1. **Generate (Claude + RLM)**: the worker agent loads the document into a\n   sandboxed JS runtime. It explores the document using code execution and\n   `llmQuery` sub-calls, then produces bullet-point answers with verbatim\n   evidence quotes.\n\n2. **Validate**:\n   - **Hard checks (local):** format, bullet count (3-7), evidence count (3-8),\n     quote length (\u003c= 160 chars), no duplicates, each quote is a verbatim\n     substring of the document.\n   - **Semantic judge (GPT):** checks whether each bullet is supported by the\n     provided evidence contexts (220-char windows around each cited quote).\n\n3. **Feedback + retry**: validation failures become explicit constraints\n   appended to the next generation request, up to `maxIters` attempts.\n\n## How the Task loop works\n\n1. **DocReader (Claude + RLM)**: extracts and summarizes relevant information\n   from the document and accumulated memory into a compact brief.\n\n2. **TaskReasoner (Claude)**: reasons about the brief to complete the task and\n   produces findings for memory.\n\n3. **Validate**:\n   - **Hard checks (local):** output and memoryUpdate must be non-empty and meet\n     minimum length thresholds.\n   - **TaskJudge (GPT):** evaluates whether the output substantively completes\n     the task given the available brief and memory.\n\n4. **Memory + retry**: the reasoner's `memoryUpdate` is appended to a persistent\n   memory file. Failures produce feedback constraints for the next iteration.\n\n---\n\n## Architecture\n\n```\nsrc/\n  main.ts                    CLI entry point, wires both modes\n  lib/\n    llm_client.ts            Unified LLMClient interface + Anthropic/OpenAI implementations\n    ai.ts                    Client factories with model validation\n    agent.ts                 Non-RLM agent: tool-based structured output loop\n    rlm_agent.ts             RLM agent: sandbox + llmQuery + code execution loop\n    rlm_runtime.ts           Deno Worker sandbox host side\n    rlm_worker_script.ts     Worker script (runs inside sandbox)\n    rlm_prompt.ts            RLM system prompt builder\n    worker.ts                QA worker agent config (RLM)\n    doc_reader.ts            Task-mode document reader agent config (RLM)\n    judge.ts                 QA semantic judge agent config\n    task_reasoner.ts         Task-mode reasoning agent config\n    task_judge.ts            Task-mode validation judge config\n    ralph.ts                 QA outer loop orchestration\n    task_loop.ts             Task-mode outer loop orchestration\n    hard_validate.ts         Deterministic QA validation rules\n    task_validate.ts         Deterministic task validation rules\n    loop_helpers.ts          Shared loop utilities (heartbeat, error classification)\n    types.ts                 Shared type definitions\n    env.ts                   Environment variable helpers\n    memory.ts                Persistent memory read/write with budget trimming\n    git_memory.ts            Session trace indexing and archival\n```\n\n### LLM client layer\n\n`llm_client.ts` defines a `LLMClient` type that both Anthropic and OpenAI\nimplementations satisfy. It handles message format translation (Anthropic\nseparates system messages, uses content blocks for tool_use; OpenAI uses\nfunction_calling), tool definition mapping, and token usage extraction.\n\n### Agent layer\n\nNon-RLM agents (`agent.ts`) run a simple loop: send messages with a structured\noutput tool, parse the tool call response, retry up to `maxSteps`. Used by the\njudge, task reasoner, and task judge.\n\nRLM agents (`rlm_agent.ts`) extend this with a persistent Deno Worker sandbox.\nThe LLM emits `javascriptCode` to execute in the sandbox and `resultReady: true`\nwhen done. The sandbox proxies `llmQuery` calls back to the host for semantic\nsub-queries. A fallback extractor attempts to salvage partial results if the\nstep budget is exhausted.\n\n### Sandbox\n\n`rlm_runtime.ts` spawns a Deno Worker from `rlm_worker_script.ts`. The worker\nuses sloppy-mode eval so `var` declarations persist across execution calls.\nConsole output is captured as the execution result. Async function proxying (for\n`llmQuery`) uses a message-based protocol: the worker posts `fn-call`, the host\nresolves it and posts `fn-result` back.\n\n---\n\n## Trace output\n\n- Per-iteration traces: `out/iter-XX.json`\n- Session archives: `out/sessions/\u003csession-id\u003e/iter-XX.json`\n- Session index: `out/session-index.json`\n\nQuery traces programmatically:\n\n```ts\nimport { querySessionTraces } from \"./src/lib/git_memory.ts\";\nconst traces = await querySessionTraces(\"2026-02-20/ralph-d8eb40c5\");\n```\n\n---\n\n## Environment variables\n\n| Variable                   | Default                    | Description                              |\n| -------------------------- | -------------------------- | ---------------------------------------- |\n| `ANTHROPIC_APIKEY`         | (required)                 | Anthropic API key                        |\n| `OPENAI_APIKEY`            | (required)                 | OpenAI API key                           |\n| `GENERATE_MODEL`        | `claude-sonnet-4-20250514` | Claude model for generation              |\n| `VALIDATE_MODEL`        | `gpt-4o-mini`              | OpenAI model for validation              |\n| `MAX_ITERS`             | `4`                        | Max outer loop iterations                |\n| `WORKER_MAX_STEPS`      | `80`                       | Max RLM agent steps per iteration        |\n| `WORKER_MAX_LLM_CALLS`  | `60`                       | Max llmQuery sub-calls per iteration     |\n| `PROGRESS_HEARTBEAT_MS` | `8000`                     | Progress log interval during long phases |\n| `OUT_DIR`               | `out`                      | Output directory for traces              |\n\n## Troubleshooting\n\n- **Worker step-budget errors**: increase `WORKER_MAX_STEPS` (try doubling)\n  and `WORKER_MAX_LLM_CALLS` proportionally.\n- **Long silent pauses**: reduce `PROGRESS_HEARTBEAT_MS` or pass\n  `--progressMs 3000`.\n- **Model not recognized**: check the allowed model sets in `src/lib/ai.ts`. The\n  system falls back to defaults for unrecognized model names.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsrdjan%2Ftwo-loops","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsrdjan%2Ftwo-loops","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsrdjan%2Ftwo-loops/lists"}