Now I have all the information needed. Here is the thorough summary:
Thorough Summary of the iterate_loop.ts Codebase Context
1. Project Structure Around iterate_loop
There are two copies of iterate_loop.ts:
| Path | Lines | Package.json Script |
|---|
C:\Users\nicolas\Documents\GitHub\bballgenius\scripts\iterate_loop.ts | 2049 | Not referenced directly |
C:\Users\nicolas\Documents\GitHub\bballgenius\scripts\eval\iterate_loop.ts | 2049 | chatbot:iterate → bun run scripts/eval/iterate_loop.ts |
The two files appear to be duplicates -- both have the same header comment, identical NOTE: banner pointing to matrixHarness.ts, and the same import structure. The canonical version lives under scripts/eval/ (as wired in package.json).
Both files both have self-documenting headers noting that they are legacy/deprecated in favor of src/tabs/chatbot/eval/matrixHarness.ts:
* NOTE: For matrix-driven evaluation with three-way (agent/DB/basketball-reference)
* data-quality classification, prefer src/chatbot/eval/matrixHarness.ts
* (`bun run chatbot:matrix`). This script remains for broad multi-run loop testing.
Notably, both copies incorrectly reference src/chatbot/scripts/iterate_loop.ts in their usage instructions -- this path does not exist in the current directory layout (the file was moved to scripts/eval/).
scripts/ Directory Layout (28 entries)
scripts/
├── _write_temp.py
├── agent-smoke.sh
├── apply-branch-protection.sh
├── bbr/ # BBR crawl scripts (buildBbrUrlMap.sh, mergeBbrUrlMap.ts, etc.)
├── bbrMapObserveCycle.sh
├── bbrObservability.cjs
├── bbrPreflightCrawl.sh
├── bbrUrlUtils.cjs
├── bbrWaitMapThenCrawl.sh
├── build-ci-fixture.ts
├── buildBbrUrlMap.sh
├── capture-spans-dump.ts
├── chatbot-eval-multi-model.ts # Standalone multi-model eval
├── chatbot-smoke.ts # Standalone smoke test (older version?)
├── ci-guards.sh
├── ci/ # CI scripts
├── compareMapToTui.cjs
├── dev/ # Dev scripts (sync-keyboard-map.ts etc.)
├── eval/ # ** Eval scripts (iterate_loop, chatbot-smoke, etc.) **
│ ├── chatbot-eval-multi-model.ts
│ ├── chatbot-smoke.ts
│ ├── iterate_loop.ts # <-- canonical iterate_loop
│ ├── iteration-1-focused.ts
│ └── quick-test.ts
├── iterate_loop.ts # <-- root-level copy (duplicate)
├── iteration-1-focused.ts
├── mergeBbrUrlMap.ts
├── quick-test.ts
├── scrapeDepthSamples.cjs
├── sync-keyboard-map.ts
├── takeBbrScreenshots.cjs
├── takeBbrScreenshots.ts
└── verifyBbrScreenshots.cjs
2. APIs That iterate_loop.ts Depends On
The file imports from the chatbot module under a relative path ../agent/graph.js etc., meaning it expects to be run from within src/tabs/chatbot/ or similar. However, the actual file lives at scripts/eval/iterate_loop.ts, which means either:
- It is symlinked/copied from somewhere else, or
- The imports are actually
../../src/tabs/chatbot/agent/graph.js-style (but from the content read, they are ../agent/graph.js)
Looking more carefully at the imports from scripts/eval/iterate_loop.ts line 31-45, it uses:
import { resetGraph } from '../agent/graph.js';
import { streamQuery } from '../agent/streaming.js';
import { closeDb, initDb } from '../db.js';
import { getModel } from '../openrouter.js';
import { buildSystemPrompt } from '../systemPrompt.js';
This is the same import pattern as in src/tabs/chatbot/eval/matrixHarness.ts (which lives at src/tabs/chatbot/eval/matrixHarness.ts and correctly uses ../agent/graph.js). But scripts/eval/iterate_loop.ts is NOT inside src/tabs/chatbot/ -- it lives at the repo-root scripts/eval/. This means the imports as written would fail at runtime because there is no ../db.js relative to scripts/eval/. Either the file was originally in src/tabs/chatbot/scripts/ and moved, or the imports are relative to a different base.
The scripts/iterate_loop.ts (root) has the same relative imports -- same problem.
Actual API signatures consumed:
resetGraph() (from agent/graph.ts, line 316-318)
export function resetGraph() {
_graph = undefined;
invalidateSchemaCache();
}
- No arguments, no return value.
- Sets the cached compiled graph to
undefined, forcing getChatbotGraph() to rebuild it on next call.
- Also calls
invalidateSchemaCache() in db.ts to clear cached table/column metadata.
streamQuery() (from agent/streaming.ts, line 52-56)
export async function* streamQuery(
input: BaseMessage[],
threadId: string,
signal?: AbortSignal,
): AsyncGenerator<StreamEvent, void, undefined>
- Takes an array of
BaseMessage[], a string threadId, and an optional AbortSignal.
- Returns an
AsyncGenerator yielding StreamEvent union types:
{ type: 'token'; content: string } -- streaming LLM token
{ type: 'tool_start'; name: string; input: Record<string, unknown>; runId: string }
{ type: 'tool_end'; name: string; output: string; ... }
{ type: 'tool_error'; name: string; error: string; ... }
{ type: 'chain_stage'; stage: ChainStageName } -- node entry/exit
{ type: 'usage'; usage: TokenUsage } -- token counts
{ type: 'done'; messages: BaseMessage[] } -- graph finished
{ type: 'error'; message: string } -- exception caught
- Internally calls
getChatbotGraph() (singleton), sets recursionLimit: 40, uses graph.streamEvents() with version: 'v2'.
initDb() / closeDb() (from db.ts)
initDb(): Returns Promise<DuckDBConnection>. Singleton pattern -- reuses a cached connection if SELECT 1 succeeds, otherwise reconnects. Uses resolveDbPath() for the file path.
closeDb(): async void. Calls connection.disconnectSync() and nulls out instance/connection references.
getModel() (from openrouter.ts)
export function getModel(): string {
return currentModel; // defaults to process.env['MODEL'] || 'openai/gpt-oss-120b'
}
- Simple getter -- returns the model ID string.
setModel(id: string) lets the harness switch models at runtime.
buildSystemPrompt() (from systemPrompt.ts)
export async function buildSystemPrompt(): Promise<string>
- Dynamically discovers tables via
getTableRefs() and getColumns().
- Builds a comprehensive system prompt with: critical rules, tool descriptions, chain stages, schema listings, core table columns, example SQL queries, and source priority guide.
- Returns a single string prompt (no arguments).
3. Eval Infrastructure That Already Exists
The project has a rich, layered eval infrastructure:
src/tabs/chatbot/eval/ -- The Core Eval Layer
| File | Description |
|---|
matrixHarness.ts (490 lines) | Preferred eval harness. Three-way comparison: agent answer vs DB truth vs BBR truth. Produces verdicts like pass, data_quality, agent_bug, stale_test_expected, bbr_unverified, no_clarification, data_not_available, timeout, crash. Supports diacritic folding, numeric tolerance, per-question ground truth IDs. |
question-matrix.ts (341 lines) | Structured eval questions with tiers: simple, multi-step, vague, overly-specific. Each has expectedAnswer, groundTruthIds[], expectedClarification, maxToolCalls, tolerance. |
nba-100-queries.ts (530 lines) | 100 categorized NBA questions across 17 categories (career leaders, season leaders, awards, team seasons, cross-schema, games, shot charts, play-by-play, identity, draft, data quality, etc.). Used by chatbot-smoke.ts. |
bbrTruth.ts (213 lines) | Resolves ground truth IDs to BBR-scraped values from bbr-truth.json. Only verified: true entries count as authoritative fact. |
dbTruth.ts (200 lines) | Resolves ground truth IDs by running canonical SQL directly against DuckDB (not through the agent). One leg of the three-way comparison. |
bbrPlayerParser.ts | BBR HTML parsing utility. |
ground-truth.json | Legacy ground truth (explicitly distrusted by the new harness -- see note in bbrTruth.ts). |
bbr-truth.json | BBR-scraped truth values with asOf timestamp and verification flags. |
__fixtures__/ | bbr-jamesle01-totals.html, bbr-jordami01-totals.html for parser tests. |
__tests__/bbrPlayerParser.test.ts | Tests for the BBR HTML parser. |
scripts/eval/ -- The Script-Level Eval Layer
| File | Description |
|---|
iterate_loop.ts (2049 lines) | Legacy multi-run loop. Runs questions multiple times with RUNS_PER_QUESTION, timeout management, secret redaction, JSONL tracing, failure classification, summary CSV export. |
chatbot-smoke.ts (433 lines) | Smoke test. Loads fact-checked questions or the 100-query suite, validates answers against expected keywords. Supports DRY_RUN, CHATBOT_SMOKE_SUITE, CHATBOT_SMOKE_LIMIT. |
chatbot-eval-multi-model.ts (481 lines) | Multi-model eval. Tests multiple LLM models against the question matrix (MODELS array), iterates fixes up to ITERATION_MAX. |
iteration-1-focused.ts (149 lines) | Focused iteration test for detailed failure data collection across 2 models. |
quick-test.ts | Quick test script. |
4. Package.json Scripts Referencing iterate_loop
From package.json line 18:
"chatbot:iterate": "bun run scripts/eval/iterate_loop.ts"
There is no script referencing the root scripts/iterate_loop.ts. Only scripts/eval/iterate_loop.ts is wired.
Related eval scripts:
"chatbot:matrix": "bun run src/tabs/chatbot/eval/matrixHarness.ts",
"chatbot:smoke": "bun run scripts/eval/chatbot-smoke.ts",
"chatbot:smoke:100": "CHATBOT_SMOKE_SUITE=100 bun run scripts/eval/chatbot-smoke.ts",
"test:chatbot": "bun test src/tabs/chatbot/__tests__ src/tabs/chatbot/eval/__tests__ --concurrency=1",
5. How iterate_loop.ts Relates to the Broader Testing Strategy
The project has four layers of testing, and iterate_loop.ts sits at the intersection of two:
| Layer | Scope | Examples |
|---|
| Unit tests | Isolated modules, mocked LLM/DB | src/tabs/chatbot/__tests__/processQuestion.test.ts, executeSql.test.ts, retry.test.ts, streaming.test.ts |
| Eval unit | Parser/fixture verification | src/tabs/chatbot/eval/__tests__/bbrPlayerParser.test.ts |
| Smoke / Eval scripts | Real DuckDB + real API, end-to-end | chatbot:smoke, chatbot:matrix, chatbot:iterate, chatbot-eval-multi-model.ts |
| Hub integration | TUI rendering + golden snapshots | src/tests/tui_integration.test.ts, golden_snapshot.test.ts |
iterate_loop.ts is the oldest/legacy eval harness. It predates the three-way matrix harness and operates on a simpler model:
-
iterate_loop.ts (legacy): Runs each question 3x (configurable), compares agent answer to predetermined expected strings via keyword contains or numeric_contains matching. Has its own failure classification (sql_syntax, tool_loop, hallucination, wrong_answer, timeout, crash, etc.). Produces JSONL traces, raw logs, and CSV summaries with secret redaction. It appends a TEST_MODE_PROMPT_SUFFIX to the system prompt.
-
matrixHarness.ts (preferred): Three-way comparison (agent vs DB vs BBR). Distinguishes data_quality issues (DB wrong) from agent_bug (agent wrong) from stale_test_expected (expected answer wrong). Uses ground truth IDs, canonical SQL, and BBR-verified data. Has per-question tolerance, diacritic folding, and structured verdicts.
The iterate_loop.ts file itself acknowledges this in its header:
"For matrix-driven evaluation with three-way (agent/DB/basketball-reference) data-quality classification, prefer src/chatbot/eval/matrixHarness.ts (bun run chatbot:matrix). This script remains for broad multi-run loop testing."
Key relationship insight: The unit tests (under src/tabs/chatbot/__tests__/) use mock.module() to mock LangChain and the DB -- they never hit a real API. The eval scripts (iterate_loop.ts, matrixHarness.ts, chatbot-smoke.ts) hit both the real DuckDB and the real OpenRouter API, making them integration tests of the full graph + tool execution pipeline.
Notable Issues for Code Review
-
Duplicate files: scripts/iterate_loop.ts and scripts/eval/iterate_loop.ts appear to be identical copies. Only the scripts/eval/ one is wired in package.json. The root copy is dead code.
-
Stale import paths: Both copies of iterate_loop.ts use relative imports like ../agent/graph.js, which would only work if the file is run from within the chatbot module tree (e.g., src/tabs/chatbot/scripts/). But the file lives at scripts/eval/, which would resolve ../agent/graph.js to scripts/agent/graph.js -- a non-existent path. Compare with scripts/eval/chatbot-smoke.ts which correctly uses ../../src/tabs/chatbot/agent/graph.js.
-
Deprecated code maintained: At 2049 lines, iterate_loop.ts is a large script marked as legacy/deprecated in its own header. It has known TypeScript errors (referenced in be/ history -- TS4111 index signature access issues) that are treated as pre-existing and excluded during typechecking.