yats-toolkit 0.1.12 → 0.1.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +1 -1
  2. package/benchmark/README.md +54 -0
  3. package/benchmark/questions/csharp/Carter/01-modules.md +1 -0
  4. package/benchmark/questions/csharp/Carter/02-handlers.md +1 -0
  5. package/benchmark/questions/csharp/MediatR/01-pipeline.md +1 -0
  6. package/benchmark/questions/csharp/MediatR/02-dispatch.md +1 -0
  7. package/benchmark/questions/csharp/eShopOnWeb/01-repository.md +1 -0
  8. package/benchmark/questions/csharp/eShopOnWeb/02-architecture.md +1 -0
  9. package/benchmark/questions/go/gin/01-middleware.md +1 -0
  10. package/benchmark/questions/go/gin/02-routing.md +1 -0
  11. package/benchmark/questions/go/lab_hub/01-protocol-translation.md +1 -0
  12. package/benchmark/questions/go/lab_hub/02-bidirectional-flow.md +1 -0
  13. package/benchmark/questions/go/terraform/01-providers.md +1 -0
  14. package/benchmark/questions/go/terraform/02-graph.md +1 -0
  15. package/benchmark/questions/php/laravel/01-container.md +1 -0
  16. package/benchmark/questions/php/laravel/02-routing.md +1 -0
  17. package/benchmark/questions/php/symfony/01-dependency-injection.md +1 -0
  18. package/benchmark/questions/php/symfony/02-event-dispatcher.md +1 -0
  19. package/benchmark/questions/python/01-middleware.md +8 -0
  20. package/benchmark/questions/python/02-routing.md +9 -0
  21. package/benchmark/questions/python/django/01-middleware.md +1 -0
  22. package/benchmark/questions/python/django/01-orm.md +1 -0
  23. package/benchmark/questions/python/fastapi/01-middleware.md +1 -0
  24. package/benchmark/questions/python/fastapi/02-routing.md +1 -0
  25. package/benchmark/questions/typescript/nestjs/01-decorators.md +1 -0
  26. package/benchmark/questions/typescript/nestjs/02-modules.md +1 -0
  27. package/benchmark/questions/typescript/nextjs/01-rendering.md +1 -0
  28. package/benchmark/questions/typescript/nextjs/02-routing.md +1 -0
  29. package/benchmark/run.sh +288 -0
  30. package/benchmark/scripts/compare-codex-mcp.sh +94 -0
  31. package/benchmark/scripts/compare.py +42 -0
  32. package/benchmark/scripts/parse-copilot.sh +34 -0
  33. package/benchmark/scripts/report.py +123 -0
  34. package/benchmark/targets/repos.json +23 -0
  35. package/package.json +6 -2
  36. package/src/bridge.js +158 -75
  37. package/src/setup.js +3 -3
  38. package/src/watch.js +155 -0
  39. package/bin/setup.js +0 -80
package/README.md CHANGED
@@ -119,7 +119,7 @@ TypeScript, JavaScript, Python, Go, C#, PHP — plus universal fallback via Tree
119
119
 
120
120
  ## Architecture
121
121
 
122
- See the [GitHub repository](https://github.com/fvinciarelli/yats) for the full architecture and source code.
122
+ See the [GitHub repository](https://github.com/fvinciarelli/yats.ai) for the full architecture and source code.
123
123
 
124
124
  ## CLI Reference
125
125
 
@@ -0,0 +1,54 @@
1
+ # YATS Benchmark
2
+
3
+ Measures how many tokens YATS saves when an AI agent answers questions about a codebase.
4
+
5
+ ## What it measures
6
+
7
+ For each question, the agent answers twice on a fresh LLM context:
8
+
9
+ | | Tools available |
10
+ |---|---|
11
+ | **Without YATS** | `read_file`, `grep` — reads source files directly |
12
+ | **With YATS** | `search_code`, `find_symbol`, `find_callers`, etc. — queries knowledge graph |
13
+
14
+ Metrics collected:
15
+ - **Time**: how long the agent took to answer
16
+ - **Input tokens**: tokens sent to the LLM
17
+ - **Output tokens**: tokens generated by the LLM
18
+ - **Savings**: percentage of tokens saved with YATS vs without
19
+
20
+ ## How to run
21
+
22
+ ```bash
23
+ # 1. Make sure YATS is running
24
+ yats status
25
+
26
+ # 2. Run the wizard
27
+ ./run.sh
28
+ ```
29
+
30
+ The wizard will:
31
+ 1. Let you pick an agent (Cursor, Claude CLI, Codex)
32
+ 2. Pick a language and repo (auto-cloned + indexed if needed)
33
+ 3. Pick which questions to run
34
+ 4. Run each question, measure everything
35
+ 5. Show a results table
36
+ 6. Save to `results/`
37
+
38
+ ## Results format
39
+
40
+ ```json
41
+ {
42
+ "agent": "cursor",
43
+ "repo": "fastapi/fastapi",
44
+ "language": "python",
45
+ "questions": [
46
+ {
47
+ "name": "01-middleware",
48
+ "without_yats": { "time_ms": 4500, "input_tokens": 8200, "output_tokens": 350 },
49
+ "with_yats": { "time_ms": 1200, "input_tokens": 800, "output_tokens": 280 },
50
+ "savings_pct": 89
51
+ }
52
+ ]
53
+ }
54
+ ```
@@ -0,0 +1 @@
1
+ How does Carter implement minimal API modules? Find ICarterModule and how routes are registered.
@@ -0,0 +1 @@
1
+ How does Carter handle request/response processing? Find the route handlers, binding, and response negotiation.
@@ -0,0 +1 @@
1
+ How does MediatR's request pipeline work? Find IRequestHandler and IPipelineBehavior interfaces and how they compose the pipeline.
@@ -0,0 +1 @@
1
+ How does MediatR dispatch requests to handlers? Find the IMediator interface, Send method, and how handlers are resolved.
@@ -0,0 +1 @@
1
+ How does eShopOnWeb implement the repository pattern? Find the Repository and Specification classes and their interfaces.
@@ -0,0 +1 @@
1
+ How does eShopOnWeb organize its architecture? Find Controllers, Services, Entities, and DTOs and how they depend on each other.
@@ -0,0 +1 @@
1
+ How does Gin handle middleware? Find the middleware chain implementation and how custom middleware is registered.
@@ -0,0 +1 @@
1
+ How does Gin's router work? Trace how HTTP verbs and path patterns are registered and how requests are dispatched to handlers.
@@ -0,0 +1 @@
1
+ How does Hub Lab identify instruments and translate their protocols? Trace the flow from receiving a raw ASTM/HL7/CSV message from an analyzer to delivering a normalized FHIR result to the LIS. What key components handle identification, translation, normalization, and delivery?
@@ -0,0 +1 @@
1
+ How does the bidirectional flow work in Hub Lab? Trace both paths: (1) orders from LIS to analyzer and (2) results from analyzer back to LIS. What are the key components and how do they handle the different protocols, validation, and the audit trail?
@@ -0,0 +1 @@
1
+ How does Terraform's provider system work? Find how providers are registered, configured, and how the plugin system operates.
@@ -0,0 +1 @@
1
+ How does Terraform build and walk the dependency graph? Find the graph construction and traversal algorithms.
@@ -0,0 +1 @@
1
+ How does Laravel's service container work? Find the binding resolution, contextual binding, and automatic injection.
@@ -0,0 +1 @@
1
+ How does Laravel handle HTTP routing? Find the route registration, middleware pipeline, and controller dispatch.
@@ -0,0 +1 @@
1
+ How does Symfony's dependency injection container work? Find the compiled container, service definitions, and autowiring.
@@ -0,0 +1 @@
1
+ How does Symfony's event dispatcher work? Find how events are registered, dispatched, and how listeners/subscribers are resolved.
@@ -0,0 +1,8 @@
1
+ ## Question: How does middleware work in FastAPI?
2
+
3
+ Find and explain the middleware stack: how middleware is registered, in what order it executes, and what built-in middleware FastAPI provides.
4
+
5
+ ### Expected answer should cover:
6
+ - The `build_middleware_stack` method in `fastapi/applications.py`
7
+ - Order: ServerErrorMiddleware → user middleware → ExceptionMiddleware → AsyncExitStackMiddleware
8
+ - How `@app.middleware("http")` registers custom middleware
@@ -0,0 +1,9 @@
1
+ ## Question: How is routing implemented in FastAPI?
2
+
3
+ Trace how HTTP routes are registered, stored, and dispatched. Find the key classes and methods involved.
4
+
5
+ ### Expected answer should cover:
6
+ - `APIRouter` class and its `add_api_route` method
7
+ - How decorators like `@app.get("/path")` register routes
8
+ - The relationship between `Route`, `APIRoute`, and path operations
9
+ - How dependencies are injected into route handlers
@@ -0,0 +1 @@
1
+ How does Django's middleware system work? Find the middleware chain and how request/response processing flows through it.
@@ -0,0 +1 @@
1
+ How does Django's ORM work? Trace how a model query like `User.objects.filter(name="John")` gets translated to SQL and executed.
@@ -0,0 +1 @@
1
+ How does middleware work in FastAPI? Trace the registration, ordering, and execution of the middleware stack.
@@ -0,0 +1 @@
1
+ How are HTTP routes registered and dispatched in FastAPI? Find the key classes responsible for routing.
@@ -0,0 +1 @@
1
+ How does NestJS use decorators for dependency injection and route registration? Find the key decorator implementations.
@@ -0,0 +1 @@
1
+ How does NestJS module system work? Trace how modules are defined, imported, and how providers are resolved across module boundaries.
@@ -0,0 +1 @@
1
+ How does Next.js handle server-side rendering vs static generation? Find the key functions and components involved.
@@ -0,0 +1 @@
1
+ How does Next.js file-based routing work? Find the routing implementation and how dynamic routes are resolved.
@@ -0,0 +1,288 @@
1
+ #!/usr/bin/env bash
2
+ set -e
3
+ # YATS Benchmark — Interactive wizard
4
+
5
+ B='\033[1m'; D='\033[2m'; R='\033[0m'
6
+ G='\033[32m'; Y='\033[33m'; C='\033[36m'; RED='\033[31m'
7
+
8
+ BENCH_DIR="$(cd "$(dirname "$0")" && pwd)"
9
+ AGENTS_DIR="$BENCH_DIR/agents"
10
+ QUESTIONS_DIR="$BENCH_DIR/questions"
11
+ RESULTS_DIR="$BENCH_DIR/results"
12
+ mkdir -p "$RESULTS_DIR"
13
+
14
+ echo -e ""
15
+ echo -e " ╔══════════════════════════════════════════════════════╗"
16
+ echo -e " ║ YATS Benchmark ║"
17
+ echo -e " ╚══════════════════════════════════════════════════════╝"
18
+ echo -e ""
19
+
20
+ # Step 1: Agent
21
+ echo -e " ${B}Step 1 — AI Agent${R}"
22
+ echo -e ""
23
+ agents=("cursor" "claude-cli" "copilot-cli" "codex" "gemini")
24
+ labels=("Cursor" "Claude CLI" "GitHub Copilot CLI" "VS Code Codex" "Gemini CLI")
25
+ for i in "${!labels[@]}"; do
26
+ echo -e " ${B}$((i+1))${R}. ${labels[$i]}"
27
+ done
28
+ echo -e ""
29
+ read -p " Pick [1-${#agents[@]}]: " c
30
+ AGENT="${agents[$((c-1))]}"
31
+ [ -z "$AGENT" ] && echo -e " ${RED}Invalid${R}" && exit 1
32
+ echo -e " ${G}✓${R} ${labels[$((c-1))]}"
33
+ echo -e ""
34
+
35
+ # Step 2: Language
36
+ echo -e " ${B}Step 2 — Language${R}"
37
+ echo -e ""
38
+ langs=($(ls -d "$QUESTIONS_DIR"/*/ | xargs -n1 basename))
39
+ for i in "${!langs[@]}"; do
40
+ echo -e " ${B}$((i+1))${R}. ${langs[$i]}"
41
+ done
42
+ echo -e ""
43
+ read -p " Pick [1-${#langs[@]}]: " c
44
+ LANG="${langs[$((c-1))]}"
45
+ [ -z "$LANG" ] && echo -e " ${RED}Invalid${R}" && exit 1
46
+ echo -e " ${G}✓${R} $LANG"
47
+ echo -e ""
48
+
49
+ # Step 3: Repo
50
+ echo -e " ${B}Step 3 — Repository${R}"
51
+ echo -e ""
52
+ repos=($(ls -d "$QUESTIONS_DIR/$LANG"/*/ | xargs -n1 basename))
53
+ for i in "${!repos[@]}"; do
54
+ echo -e " ${B}$((i+1))${R}. ${repos[$i]}"
55
+ done
56
+ echo -e ""
57
+ read -p " Pick [1-${#repos[@]}]: " c
58
+ REPO="${repos[$((c-1))]}"
59
+ [ -z "$REPO" ] && echo -e " ${RED}Invalid${R}" && exit 1
60
+ echo -e " ${G}✓${R} $REPO"
61
+ echo -e ""
62
+
63
+ # Step 3.5: Working directory for repo clone
64
+ echo -e " ${B}Step 3.5 — Working directory${R}"
65
+ echo -e " ${D}Directory where repos will be cloned for the agent to work on${R}"
66
+ echo -e ""
67
+ default_workdir="${YATS_BENCH_WORKDIR:-$HOME/yats-bench-repos}"
68
+ read -p " Path [${default_workdir}]: " workdir_input
69
+ WORKDIR="${workdir_input:-$default_workdir}"
70
+ mkdir -p "$WORKDIR"
71
+ echo -e " ${G}✓${R} $WORKDIR"
72
+ echo -e ""
73
+
74
+ # Clone repo if needed
75
+ REPO_DIR="$WORKDIR/$REPO"
76
+ REPO_URL=$(python3 -c "
77
+ import json
78
+ with open('$BENCH_DIR/targets/repos.json') as f:
79
+ data = json.load(f)
80
+ for r in data.get('$LANG', []):
81
+ if r['name'] == '$REPO':
82
+ print(r['url'])
83
+ break
84
+ " 2>/dev/null)
85
+
86
+ if [ ! -d "$REPO_DIR/.git" ]; then
87
+ if [ -n "$REPO_URL" ]; then
88
+ echo -e " ${D}Cloning $REPO from $REPO_URL...${R}"
89
+ git clone --depth 1 "$REPO_URL" "$REPO_DIR" 2>&1 | tail -1
90
+ echo -e " ${G}✓${R} Cloned to $REPO_DIR"
91
+ else
92
+ echo -e " ${Y}⚠ No URL in targets/repos.json — using existing $REPO_DIR if any${R}"
93
+ fi
94
+ else
95
+ echo -e " ${G}✓${R} Repo already exists at $REPO_DIR"
96
+ fi
97
+ echo -e ""
98
+
99
+ # Index repo in YATS if needed
100
+ YATS_HEALTH=$(curl -s -m 3 http://localhost:5555/health 2>/dev/null || echo '')
101
+ if [ -n "$YATS_HEALTH" ]; then
102
+ echo -e " ${D}Checking if $REPO is indexed...${R}"
103
+ if yats list 2>/dev/null | grep -q "^ $REPO "; then
104
+ echo -e " ${G}✓${R} Already indexed"
105
+ else
106
+ echo -e " ${D}Indexing $REPO (this may take a while)...${R}"
107
+ yats index "$REPO_DIR" 2>&1 | tail -3
108
+ echo -e " ${G}✓${R} Indexed as '$REPO'"
109
+ fi
110
+ else
111
+ echo -e " ${Y}⚠ YATS not running — skip indexing. Start with: yats start${R}"
112
+ fi
113
+ echo -e ""
114
+
115
+ # Export for run-agent.sh
116
+ export YATS_BENCH_REPO_DIR="$REPO_DIR"
117
+ export YATS_BENCH_REPO_NAME="$REPO"
118
+
119
+ # Step 4: Questions
120
+ echo -e " ${B}Step 4 — Questions${R}"
121
+ echo -e ""
122
+ questions=($(ls "$QUESTIONS_DIR/$LANG/$REPO"/*.md | sort))
123
+ selected=()
124
+ for i in "${!questions[@]}"; do
125
+ qname=$(basename "${questions[$i]}" .md)
126
+ read -p " Run ${qname}? [Y/n] " yn
127
+ if [ "$yn" != "n" ]; then
128
+ selected+=("${questions[$i]}")
129
+ echo -e " ${G}✓${R} $qname"
130
+ else
131
+ echo -e " ${D}✗${R} $qname"
132
+ fi
133
+ done
134
+ [ ${#selected[@]} -eq 0 ] && echo -e " ${RED}None selected${R}" && exit 1
135
+ echo -e ""
136
+
137
+ # Step 5: Confirm
138
+ echo -e " ${B}${#selected[@]} question(s) on $REPO${R}"
139
+ read -p " Proceed? [Y/n] " yn
140
+ [ "$yn" = "n" ] && echo -e " Cancelled." && exit 0
141
+
142
+ echo -e ""
143
+ echo -e " ${D}───────────────────────────────────────────────────────${R}"
144
+ echo -e ""
145
+
146
+ # Extract tokens from stream-json
147
+ extract_tokens_and_model() {
148
+ python3 -c "
149
+ import json
150
+ total = 0
151
+ nanoaiu = 0
152
+ model = ''
153
+ cost = 0
154
+ try:
155
+ with open('$1') as f:
156
+ for line in f:
157
+ line = line.strip()
158
+ if not line: continue
159
+ try: evt = json.loads(line)
160
+ except: continue
161
+ t = evt.get('type','')
162
+ # Capture model from first init/system event
163
+ if not model:
164
+ if t == 'init':
165
+ model = evt.get('model','')
166
+ elif t == 'system' and evt.get('subtype') == 'init':
167
+ model = evt.get('model','')
168
+ elif t == 'session.tools_updated':
169
+ model = evt.get('data',{}).get('model','')
170
+ elif t == 'tool.execution_start':
171
+ model = evt.get('data',{}).get('model','')
172
+ # Cursor/Claude: result events
173
+ if t in ('result','message'):
174
+ u = evt.get('usage',{})
175
+ total += u.get('input_tokens',0) + u.get('output_tokens',0) + u.get('cache_read_input_tokens',0) + u.get('cache_read_tokens',0)
176
+ # Codex: turn.completed events
177
+ if t == 'turn.completed':
178
+ u = evt.get('usage',{})
179
+ total += u.get('input_tokens',0) + u.get('cached_input_tokens',0) + u.get('output_tokens',0) + u.get('reasoning_output_tokens',0)
180
+ # Copilot: assistant.usage events OR nanoAiu from usage_checkpoint
181
+ if t == 'assistant.usage':
182
+ total += evt.get('inputTokens',0) + evt.get('outputTokens',0) + evt.get('cacheReadTokens',0)
183
+ if t == 'session.usage_checkpoint':
184
+ nanoaiu = evt.get('data',{}).get('totalNanoAiu', 0)
185
+ # Claude: total_cost_usd in wrapper events
186
+ if 'total_cost_usd' in evt:
187
+ cost = max(cost, evt.get('total_cost_usd', 0))
188
+ # Gemini: result events with stats
189
+ if t == 'result':
190
+ s = evt.get('stats',{})
191
+ total += s.get('input_tokens',0) + s.get('output_tokens',0)
192
+ if not model:
193
+ models = s.get('models',{})
194
+ if models:
195
+ model = list(models.keys())[0]
196
+ except: pass
197
+ # If Copilot, use nanoAiu as the metric (no token events)
198
+ if nanoaiu > 0 and total == 0:
199
+ total = nanoaiu
200
+ print(json.dumps({'tokens': total, 'model': model, 'cost': cost}))
201
+ " 2>/dev/null || echo '{"tokens":0,"model":""}'
202
+ }
203
+
204
+ TIMESTAMP=$(date +%Y-%m-%dT%H:%M:%S)
205
+ results_json="[]"
206
+
207
+ YATS_MCP="$AGENTS_DIR/yats-mcp.json"
208
+ # Gemini, Copilot, and Codex use stdio bridge; Cursor and Claude use HTTP
209
+ if [ "$AGENT" = "gemini" ] || [ "$AGENT" = "copilot-cli" ] || [ "$AGENT" = "codex" ]; then
210
+ cat > "$YATS_MCP" << 'MCPEOF'
211
+ {
212
+ "mcpServers": {
213
+ "yats": {
214
+ "command": "yats",
215
+ "args": ["bridge"],
216
+ "trust": true
217
+ }
218
+ }
219
+ }
220
+ MCPEOF
221
+ else
222
+ cat > "$YATS_MCP" << 'MCPEOF'
223
+ { "mcpServers": { "yats": { "url": "http://localhost:5555/mcp" } } }
224
+ MCPEOF
225
+ fi
226
+
227
+ for qfile in "${selected[@]}"; do
228
+ qname=$(basename "$qfile" .md)
229
+ echo -e " ${B}${qname}${R}"
230
+
231
+ # Without YATS
232
+ echo -ne " ${D}without YATS...${R} "
233
+ bash "$AGENTS_DIR/run-agent.sh" "$AGENT" "$qfile" "" > /tmp/yats-bench-without.jsonl 2>/dev/null || true
234
+ without_result=$(extract_tokens_and_model /tmp/yats-bench-without.jsonl)
235
+ without_total=$(echo "$without_result" | python3 -c "import json,sys; print(json.load(sys.stdin)['tokens'])" 2>/dev/null || echo 0)
236
+ without_model=$(echo "$without_result" | python3 -c "import json,sys; print(json.load(sys.stdin).get('model',''))" 2>/dev/null || echo "")
237
+
238
+ # With YATS
239
+ echo -ne "${D}with YATS...${R} "
240
+ bash "$AGENTS_DIR/run-agent.sh" "$AGENT" "$qfile" "$YATS_MCP" > /tmp/yats-bench-with.jsonl 2>/dev/null || true
241
+ with_result=$(extract_tokens_and_model /tmp/yats-bench-with.jsonl)
242
+ with_total=$(echo "$with_result" | python3 -c "import json,sys; print(json.load(sys.stdin)['tokens'])" 2>/dev/null || echo 0)
243
+ with_model=$(echo "$with_result" | python3 -c "import json,sys; print(json.load(sys.stdin).get('model',''))" 2>/dev/null || echo "")
244
+ without_cost=$(echo "$without_result" | python3 -c "import json,sys; print(json.load(sys.stdin).get('cost',0))" 2>/dev/null || echo 0)
245
+ with_cost=$(echo "$with_result" | python3 -c "import json,sys; print(json.load(sys.stdin).get('cost',0))" 2>/dev/null || echo 0)
246
+
247
+ if [ "$without_total" -gt 0 ]; then
248
+ savings=$((100 - (with_total * 100 / without_total)))
249
+ else
250
+ savings=0
251
+ fi
252
+
253
+ echo -e "${G}${savings}% saved${R} (${without_total} → ${with_total} tokens)"
254
+
255
+ result=$(python3 -c "
256
+ import json
257
+ r = {'question':'$qname','without_tokens':$without_total,'with_tokens':$with_total,'savings_pct':$savings,'model':'$with_model' if '$with_model' else '$without_model','without_cost':$without_cost,'with_cost':$with_cost}
258
+ print(json.dumps(r))
259
+ " 2>/dev/null)
260
+ results_json=$(python3 -c "import json; r=json.loads('$results_json'); r.append($result); print(json.dumps(r))" 2>/dev/null)
261
+ echo -e ""
262
+ done
263
+
264
+ # Save
265
+ output="$RESULTS_DIR/${LANG}_${REPO}_${AGENT}_${TIMESTAMP}.json"
266
+ python3 -c "
267
+ import json
268
+ data = {'agent':'$AGENT','repo':'$REPO','language':'$LANG','timestamp':'$TIMESTAMP','questions':json.loads('$results_json')}
269
+ with open('$output','w') as f: json.dump(data, f, indent=2)
270
+ " 2>/dev/null
271
+
272
+ # Table
273
+ echo -e " ${D}───────────────────────────────────────────────────────${R}"
274
+ echo -e ""
275
+ echo -e " ${B}Results${R}"
276
+ echo -e ""
277
+ python3 -c "
278
+ import json
279
+ data = json.loads('$results_json')
280
+ print(' ┌────────────────────────┬──────────┬──────────┬──────────┬──────────────────────┐')
281
+ print(' │ Question │ W/o YATS │ With YATS│ Savings │ Model │')
282
+ print(' ├────────────────────────┼──────────┼──────────┼──────────┼──────────────────────┤')
283
+ for q in data:
284
+ print(f\" │ {q['question'][:22]:<22} │ {q['without_tokens']:>5}t │ {q['with_tokens']:>5}t │ {q['savings_pct']:>3}% │\")
285
+ print(' └────────────────────────┴──────────┴──────────┴──────────┴──────────────────────┘')
286
+ print(f\"\\n Saved to $output\")
287
+ " 2>/dev/null
288
+ echo -e ""
@@ -0,0 +1,94 @@
1
+ #!/usr/bin/env bash
2
+
3
+ # Compare the same Codex prompt with YATS enabled and disabled.
4
+ # Run from the repository root:
5
+ # ./scripts/compare-codex-mcp.sh
6
+ # Or provide a different prompt:
7
+ # ./scripts/compare-codex-mcp.sh 'Explain the authentication flow in FastAPI.'
8
+
9
+ set -euo pipefail
10
+
11
+ readonly SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
12
+ # The benchmark script lives under .plans/, so its parent is not the repository root.
13
+ # Git finds the actual project root regardless of the script's location inside it.
14
+ readonly REPOSITORY_ROOT="$(git -C "$SCRIPT_DIR" rev-parse --show-toplevel)"
15
+ readonly RUN_ID="$(date +%Y%m%dT%H%M%S)"
16
+ readonly OUTPUT_DIR="${OUTPUT_DIR:-$REPOSITORY_ROOT/artifacts/codex-mcp-comparison/$RUN_ID}"
17
+ readonly DEFAULT_PROMPT='Explain how FastAPI resolves dependency injection. If YATS is available, consult it before answering. Mention get_dependant, Dependant, and solve_dependencies. Do not modify files. Maximum 200 words.'
18
+ readonly PROMPT="${1:-$DEFAULT_PROMPT}"
19
+
20
+ require_command() {
21
+ command -v "$1" >/dev/null 2>&1 || {
22
+ echo "Required command not found: $1" >&2
23
+ exit 127
24
+ }
25
+ }
26
+
27
+ require_command codex
28
+ require_command jq
29
+
30
+ if [[ ! -f "$REPOSITORY_ROOT/.codex/config.toml" ]] || ! grep -q '^\[mcp_servers\.yats\]' "$REPOSITORY_ROOT/.codex/config.toml"; then
31
+ echo "YATS is not configured in $REPOSITORY_ROOT/.codex/config.toml" >&2
32
+ exit 2
33
+ fi
34
+
35
+ mkdir -p "$OUTPUT_DIR"
36
+
37
+ write_summary_header() {
38
+ printf 'case\texit_code\telapsed_ms\tinput_tokens\tcached_input_tokens\toutput_tokens\treasoning_output_tokens\tmcp_tool_events\n' > "$OUTPUT_DIR/summary.tsv"
39
+ }
40
+
41
+ append_summary() {
42
+ local case_name="$1"
43
+ local exit_code="$2"
44
+ local elapsed_ms="$3"
45
+ local jsonl_file="$4"
46
+ local usage
47
+ local mcp_tool_events
48
+
49
+ usage="$(jq -r 'select(.type == "turn.completed") | [.usage.input_tokens // 0, .usage.cached_input_tokens // 0, .usage.output_tokens // 0, .usage.reasoning_output_tokens // 0] | @tsv' "$jsonl_file" | tail -n 1)"
50
+ usage="${usage:-$'0\t0\t0\t0'}"
51
+ mcp_tool_events="$(grep -c '"mcp_tool_call"' "$jsonl_file" || true)"
52
+
53
+ printf '%s\t%s\t%s\t%s\t%s\n' "$case_name" "$exit_code" "$elapsed_ms" "$usage" "$mcp_tool_events" >> "$OUTPUT_DIR/summary.tsv"
54
+ }
55
+
56
+ run_case() {
57
+ local case_name="$1"
58
+ shift
59
+
60
+ local jsonl_file="$OUTPUT_DIR/$case_name.jsonl"
61
+ local answer_file="$OUTPUT_DIR/$case_name.md"
62
+ local stderr_file="$OUTPUT_DIR/$case_name.stderr.log"
63
+ local start_ns
64
+ local end_ns
65
+ local elapsed_ms
66
+ local exit_code
67
+
68
+ start_ns="$(date +%s%N)"
69
+ set +e
70
+ (
71
+ cd "$REPOSITORY_ROOT"
72
+ codex exec "$@" --json --output-last-message "$answer_file" "$PROMPT"
73
+ ) > "$jsonl_file" 2> "$stderr_file"
74
+ exit_code=$?
75
+ set -e
76
+ end_ns="$(date +%s%N)"
77
+ elapsed_ms=$(( (end_ns - start_ns) / 1000000 ))
78
+
79
+ append_summary "$case_name" "$exit_code" "$elapsed_ms" "$jsonl_file"
80
+ printf '%s finished in %sms (exit %s)\n' "$case_name" "$elapsed_ms" "$exit_code"
81
+ }
82
+
83
+ write_summary_header
84
+
85
+ run_case with-mcp \
86
+ -c 'mcp_servers.yats.enabled=true' \
87
+ -c 'mcp_servers.yats.required=true'
88
+
89
+ run_case without-mcp \
90
+ -c 'mcp_servers.yats.enabled=false'
91
+
92
+ echo
93
+ echo "Results: $OUTPUT_DIR"
94
+ column -t -s $'\t' "$OUTPUT_DIR/summary.tsv" 2>/dev/null || cat "$OUTPUT_DIR/summary.tsv"
@@ -0,0 +1,42 @@
1
+ #!/usr/bin/env python3
2
+ """Compare two benchmark runs and show savings."""
3
+ import json, sys
4
+
5
+ b1_path = sys.argv[1] # baseline
6
+ b2_path = sys.argv[2] # yats
7
+
8
+ with open(b1_path) as f: b1 = json.load(f)
9
+ with open(b2_path) as f: b2 = json.load(f)
10
+
11
+ t1 = b1["total_tokens"]
12
+ t2 = b2["total_tokens"]
13
+ c1 = b1["cost_usd"]
14
+ c2 = b2["cost_usd"]
15
+ token_save = (1 - t2/t1) * 100 if t1 else 0
16
+ cost_save = (1 - c2/c1) * 100 if c1 else 0
17
+
18
+ print(f"""
19
+ ╔═══════════════════════════════════════════════════════════╗
20
+ ║ YATS BENCHMARK ║
21
+ ╠═══════════════════════════════════════════════════════════╣
22
+ ║ ║
23
+ ║ {'':10s} {'BASELINE':>15s} {'YATS':>15s} {'SAVINGS':>12s} ║
24
+ ║ {'─'*58} ║
25
+ ║ {'Tokens':10s} {t1:>15,d} {t2:>15,d} {token_save:>+11.1f}% ║
26
+ ║ {'Cost':10s} {'$'+str(round(c1,4)):>15s} {'$'+str(round(c2,4)):>15s} {cost_save:>+11.1f}% ║
27
+ ║ {'─'*58} ║
28
+ ║ {'Strategy':10s} {'':>15s} {'':>15s} {'':>12s} ║
29
+ ║ {'YATS queries':10s} {b1['strategy']['yats_queries']:>15} {b2['strategy']['yats_queries']:>15} {'':>12s} ║
30
+ ║ {'File reads':10s} {b1['strategy']['file_reads']:>15} {b2['strategy']['file_reads']:>15} {(((1 - b2['strategy']['file_reads']/b1['strategy']['file_reads'])*100) if b1['strategy']['file_reads'] else 0):>+11.1f}% ║
31
+ ║ {'Bash cmds':10s} {b1['strategy']['bash_commands']:>15} {b2['strategy']['bash_commands']:>15} {(((1 - b2['strategy']['bash_commands']/b1['strategy']['bash_commands'])*100) if b1['strategy']['bash_commands'] else 0):>+11.1f}% ║
32
+ ║ {'Agent spawns':10s} {b1['strategy']['agent_spawns']:>15} {b2['strategy']['agent_spawns']:>15} {'':>12s} ║
33
+ ║ {'Content':10s} {b1['content_chars']:>15,} {b2['content_chars']:>15,} {(((1 - b2['content_chars']/b1['content_chars'])*100) if b1['content_chars'] else 0):>+11.1f}% ║
34
+ ║ {'─'*58} ║
35
+ ║ {'Tokens':10s} {'':>15s} {'':>15s} {'':>12s} ║
36
+ ║ {' Input':10s} {b1['tokens']['input_tokens']:>15,d} {b2['tokens']['input_tokens']:>15,d} {'':>12s} ║
37
+ ║ {' Output':10s} {b1['tokens']['output_tokens']:>15,d} {b2['tokens']['output_tokens']:>15,d} {'← mas caro':>12s} ║
38
+ ║ {' Cache R':10s} {b1['tokens']['cache_read_input_tokens']:>15,d} {b2['tokens']['cache_read_input_tokens']:>15,d} {'← barato':>12s} ║
39
+ ║ {' Cache W':10s} {b1['tokens']['cache_creation_input_tokens']:>15,d} {b2['tokens']['cache_creation_input_tokens']:>15,d} {'← caro':>12s} ║
40
+ ║ ║
41
+ ╚═══════════════════════════════════════════════════════════╝
42
+ """)
@@ -0,0 +1,34 @@
1
+ #!/bin/bash
2
+ # YATS Benchmark — Copilot-specific token & tool extractor
3
+ # Usage: parse-copilot.sh <output_file>
4
+
5
+ file="$1"
6
+
7
+ # Count MCP tool calls
8
+ mcp_calls=$(grep -c "(MCP: yats)" "$file" 2>/dev/null || echo 0)
9
+
10
+ # Extract tokens and credits from last summary line
11
+ summary=$(grep "Tokens" "$file" | tail -1)
12
+ credits=$(echo "$summary" | grep -oP 'AI Credits \K[\d.]+' || echo 0)
13
+ time_s=$(echo "$summary" | grep -oP '\(\K\d+' | head -1 || echo 0)
14
+
15
+ # Token breakdown
16
+ tokens_total=$(echo "$summary" | grep -oP '↑ \K[\d.]+k' | head -1 | sed 's/k//' || echo 0)
17
+ cached=$(echo "$summary" | grep -oP '[\d.]+k cached' | head -1 | grep -oP '[\d.]+' || echo 0)
18
+ written=$(echo "$summary" | grep -oP '[\d.]+k written' | head -1 | grep -oP '[\d.]+' || echo 0)
19
+
20
+ # Count file reads (non-MCP reads)
21
+ file_reads=$(grep -c "● Read" "$file" 2>/dev/null || echo 0)
22
+
23
+ python3 -c "
24
+ import json
25
+ print(json.dumps({
26
+ 'mcp_calls': $mcp_calls,
27
+ 'file_reads': $file_reads,
28
+ 'credits': $credits,
29
+ 'time_s': $time_s,
30
+ 'tokens_total': '${tokens_total}k',
31
+ 'tokens_cached': '${cached}k',
32
+ 'tokens_written': '${written}k',
33
+ 'savings': 'MCP tool calls replace grep/file scanning'
34
+ }))" 2>/dev/null