the-grid-cc 1.7.13 → 1.7.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.
@@ -0,0 +1,591 @@
1
+ # Research-First Architecture
2
+
3
+ **Technical Design Document**
4
+ **Version:** 1.0
5
+ **Author:** Program 4 (Research Swarm Executor)
6
+ **Date:** 2026-01-23
7
+
8
+ ---
9
+
10
+ ## Executive Summary
11
+
12
+ This document describes the **Research-First Architecture** for The Grid - a mandatory research swarm that runs BEFORE any planning phase. The architecture introduces two new agent types (Researcher and Scout) that gather context from external sources and existing codebases, enabling better-informed planning and execution.
13
+
14
+ ### Key Benefits
15
+ - **Informed Planning:** Planner receives structured context about best practices, patterns, and constraints
16
+ - **Reduced Rework:** Discovering constraints BEFORE building prevents costly pivots
17
+ - **Current Knowledge:** Web search brings 2024-2025 best practices beyond training cutoff
18
+ - **Faster Execution:** Cached research eliminates repeated searches
19
+ - **Parallel Intelligence:** Multiple researchers can gather context simultaneously
20
+
21
+ ---
22
+
23
+ ## Architecture Overview
24
+
25
+ ### Current Flow (Before)
26
+ ```
27
+ User Request → Planner → Executor → Recognizer
28
+ ```
29
+
30
+ ### New Flow (Research-First)
31
+ ```
32
+ User Request → Scout → Researcher(s) → Planner → Executor → Recognizer
33
+ ↓ ↓
34
+ Codebase External
35
+ Context Context
36
+ ```
37
+
38
+ ### Flow Decision Tree
39
+ ```
40
+ User Request
41
+
42
+
43
+ ┌─────────────────────┐
44
+ │ Quick Mode Check │
45
+ └─────────────────────┘
46
+ │ │
47
+ ≤5 files│ │ >5 files
48
+ ▼ ▼
49
+ ┌─────────┐ ┌─────────────────┐
50
+ │ /quick │ │ Research Phase │
51
+ └─────────┘ └─────────────────┘
52
+
53
+ ┌─────────────┴─────────────┐
54
+ ▼ ▼
55
+ ┌─────────┐ ┌───────────┐
56
+ │ Scout │ │ Researcher│
57
+ │(codebase)│ │ (external)│
58
+ └─────────┘ └───────────┘
59
+ │ │
60
+ └─────────────┬─────────────┘
61
+
62
+ ┌───────────────┐
63
+ │ Context Cache │
64
+ └───────────────┘
65
+
66
+
67
+ ┌───────────────┐
68
+ │ Planner │
69
+ │(with context) │
70
+ └───────────────┘
71
+
72
+
73
+ ┌───────────────┐
74
+ │ Executor │
75
+ └───────────────┘
76
+ ```
77
+
78
+ ---
79
+
80
+ ## Component Specifications
81
+
82
+ ### 1. Scout Agent (`grid-scout.md`)
83
+
84
+ **Purpose:** Rapid reconnaissance of existing codebase
85
+ **Time Budget:** < 2 minutes
86
+ **Output:** `.grid/scout/RECON_{timestamp}.md`
87
+
88
+ #### Capabilities
89
+ | Capability | Method | Time |
90
+ |------------|--------|------|
91
+ | Structure Scan | `find`, `glob` | 30s |
92
+ | Technology Detection | Package file analysis | 30s |
93
+ | Pattern Detection | Grep + file existence | 30s |
94
+ | Constraint Discovery | Schema + API analysis | 30s |
95
+
96
+ #### Key Outputs
97
+ ```yaml
98
+ scout_output:
99
+ technology_stack:
100
+ languages: [TypeScript, Python]
101
+ frameworks: [Next.js 14, FastAPI]
102
+ databases: [PostgreSQL via Prisma]
103
+
104
+ detected_patterns:
105
+ - name: "App Router"
106
+ confidence: HIGH
107
+ - name: "Server Components"
108
+ confidence: MEDIUM
109
+
110
+ constraints:
111
+ locked_dependencies: [react@18.2.0]
112
+ existing_schemas: [prisma/schema.prisma]
113
+ api_contracts: [src/app/api/*/route.ts]
114
+
115
+ conventions:
116
+ naming: "camelCase for files, PascalCase for components"
117
+ imports: "absolute imports from @/"
118
+ ```
119
+
120
+ #### Speed Optimizations
121
+ - Parallel file operations
122
+ - Early exit on pattern detection
123
+ - Depth limits on tree traversal
124
+ - Sample-based analysis (first N, not all)
125
+
126
+ ---
127
+
128
+ ### 2. Researcher Agent (`grid-researcher.md`)
129
+
130
+ **Purpose:** Gather external intelligence from web sources
131
+ **Time Budget:** 5-10 minutes (parallelizable)
132
+ **Output:** `.grid/research_cache/{topic}.md`
133
+
134
+ #### Mission Types
135
+ | Mission | Triggers | Output |
136
+ |---------|----------|--------|
137
+ | `technology` | New framework/library | Best practices, gotchas |
138
+ | `patterns` | Architecture decisions | Implementation guides |
139
+ | `similar_projects` | Novel project type | Reference architectures |
140
+ | `api_docs` | External integrations | API context, examples |
141
+
142
+ #### Search Tool Selection
143
+ | Need | Tool | Rationale |
144
+ |------|------|-----------|
145
+ | Best practices | `WebSearch` | Broad coverage |
146
+ | Code examples | `mcp__exa__get_code_context_exa` | Code-optimized |
147
+ | Company info | `mcp__exa__company_research_exa` | Structured data |
148
+ | Documentation | `WebFetch` | Direct access |
149
+ | GitHub repos | `gh` CLI | Precise queries |
150
+
151
+ #### Query Generation
152
+ ```python
153
+ def generate_queries(request: dict) -> list[str]:
154
+ queries = []
155
+
156
+ # Technology queries (3 per tech)
157
+ for tech in request.get('technologies', []):
158
+ queries.extend([
159
+ f"{tech} best practices 2024 2025",
160
+ f"{tech} production patterns",
161
+ f"{tech} common mistakes"
162
+ ])
163
+
164
+ # Pattern queries (3 per pattern)
165
+ for pattern in request.get('patterns', []):
166
+ queries.extend([
167
+ f"{pattern} implementation guide",
168
+ f"{pattern} real world examples",
169
+ f"when not to use {pattern}"
170
+ ])
171
+
172
+ return queries
173
+ ```
174
+
175
+ #### Confidence Assessment
176
+ | Level | Criteria |
177
+ |-------|----------|
178
+ | HIGH | 3+ corroborating sources, official docs |
179
+ | MEDIUM | 1-2 sources, reputable blogs |
180
+ | LOW | Single source, old content |
181
+
182
+ ---
183
+
184
+ ### 3. Research Cache
185
+
186
+ **Location:** `.grid/research_cache/`
187
+
188
+ #### Structure
189
+ ```
190
+ .grid/research_cache/
191
+ ├── index.json # Cache index
192
+ ├── nextjs-14-app-router.md # Cached research
193
+ ├── prisma-best-practices.md
194
+ ├── stripe-connect-api.md
195
+ └── archive/ # Expired entries
196
+ ```
197
+
198
+ #### Index Schema
199
+ ```json
200
+ {
201
+ "version": "1.0",
202
+ "entries": [
203
+ {
204
+ "key": "nextjs-14-app-router",
205
+ "queries": ["Next.js 14 best practices", "App Router patterns"],
206
+ "created": "2026-01-23T14:00:00Z",
207
+ "expires": "2026-01-24T14:00:00Z",
208
+ "file": "nextjs-14-app-router.md",
209
+ "hit_count": 3
210
+ }
211
+ ]
212
+ }
213
+ ```
214
+
215
+ #### Cache Policy
216
+ | Policy | Value | Rationale |
217
+ |--------|-------|-----------|
218
+ | Default TTL | 24 hours | Balance freshness/speed |
219
+ | Max entries | 50 | Prevent bloat |
220
+ | LRU eviction | On limit | Remove least used |
221
+ | Force refresh | User request | Override cache |
222
+
223
+ #### Cache Hit Algorithm
224
+ ```python
225
+ def check_cache(queries: list[str]) -> Optional[str]:
226
+ index = load_index()
227
+
228
+ for entry in index['entries']:
229
+ # Check query similarity (Jaccard > 0.7)
230
+ if jaccard_similarity(entry['queries'], queries) > 0.7:
231
+ if not is_expired(entry):
232
+ entry['hit_count'] += 1
233
+ save_index(index)
234
+ return read(entry['file'])
235
+
236
+ return None # Cache miss
237
+ ```
238
+
239
+ ---
240
+
241
+ ## Integration with Master Control
242
+
243
+ ### MC Research Phase Logic
244
+
245
+ ```python
246
+ def research_phase(user_request: str, project_root: str) -> dict:
247
+ """Execute research phase before planning."""
248
+
249
+ # Check if research should be skipped
250
+ if should_skip_research(user_request):
251
+ return {"skipped": True, "reason": "Quick mode eligible"}
252
+
253
+ context = {}
254
+
255
+ # Phase 1: Scout existing codebase (always, if exists)
256
+ if has_existing_code(project_root):
257
+ scout_result = Task(
258
+ prompt="""
259
+ First, read ~/.claude/agents/grid-scout.md for your role.
260
+
261
+ Scan the codebase at {project_root}.
262
+ Return structured scout report.
263
+ """,
264
+ subagent_type="general-purpose",
265
+ description="Scout codebase"
266
+ )
267
+ context['codebase'] = scout_result
268
+
269
+ # Phase 2: Extract research needs
270
+ research_needs = extract_research_needs(user_request, context.get('codebase'))
271
+
272
+ # Phase 3: Check cache for existing research
273
+ cached, needed = check_research_cache(research_needs)
274
+ context['cached_research'] = cached
275
+
276
+ # Phase 4: Spawn researchers for uncached needs (parallel)
277
+ if needed:
278
+ research_tasks = []
279
+ for need in needed:
280
+ task = Task(
281
+ prompt=f"""
282
+ First, read ~/.claude/agents/grid-researcher.md for your role.
283
+
284
+ <research_request>
285
+ {need}
286
+ </research_request>
287
+
288
+ Research and return structured context.
289
+ """,
290
+ subagent_type="general-purpose",
291
+ description=f"Research {need['topic']}"
292
+ )
293
+ research_tasks.append(task)
294
+
295
+ # All tasks execute in parallel
296
+ context['fresh_research'] = await_all(research_tasks)
297
+
298
+ return context
299
+ ```
300
+
301
+ ### Skip Conditions
302
+
303
+ Research is skipped when:
304
+ ```python
305
+ def should_skip_research(request: str) -> bool:
306
+ """Determine if research phase should be skipped."""
307
+
308
+ # Quick mode eligible = skip research
309
+ if quick_mode_eligible(request):
310
+ return True
311
+
312
+ # User explicitly skipped
313
+ if "skip research" in request.lower():
314
+ return True
315
+
316
+ # Known technology fully cached
317
+ if all_tech_cached(extract_technologies(request)):
318
+ return True
319
+
320
+ # Debug/fix mode
321
+ if is_debug_request(request):
322
+ return True
323
+
324
+ return False
325
+ ```
326
+
327
+ ---
328
+
329
+ ## Planner Integration
330
+
331
+ ### Planner Prompt Enhancement
332
+
333
+ ```python
334
+ def spawn_planner_with_research(user_request: str, research_context: dict):
335
+ """Spawn Planner with research context."""
336
+
337
+ prompt = f"""
338
+ First, read ~/.claude/agents/grid-planner.md for your role.
339
+
340
+ <codebase_context>
341
+ {research_context.get('codebase', 'Greenfield project - no existing code')}
342
+ </codebase_context>
343
+
344
+ <research_context>
345
+ {format_research(research_context.get('cached_research', []))}
346
+ {format_research(research_context.get('fresh_research', []))}
347
+ </research_context>
348
+
349
+ <user_request>
350
+ {user_request}
351
+ </user_request>
352
+
353
+ Create execution plan informed by:
354
+ 1. Codebase constraints (if existing code)
355
+ 2. Best practices from research
356
+ 3. Anti-patterns to avoid
357
+ 4. Recommended technologies
358
+
359
+ Your plan should respect existing patterns and leverage researched best practices.
360
+ """
361
+
362
+ return Task(
363
+ prompt=prompt,
364
+ subagent_type="general-purpose",
365
+ description="Plan with research context"
366
+ )
367
+ ```
368
+
369
+ ### Research-Informed Planning Rules
370
+
371
+ Planner applies research context as:
372
+ ```yaml
373
+ planning_rules:
374
+ # Constraints from Scout
375
+ must_preserve:
376
+ - existing_api_contracts
377
+ - database_schema_structure
378
+ - naming_conventions
379
+
380
+ # Patterns from Researcher
381
+ should_use:
382
+ - recommended_patterns
383
+ - best_practices_2024_2025
384
+
385
+ # Anti-patterns from Researcher
386
+ must_avoid:
387
+ - documented_anti_patterns
388
+ - deprecated_approaches
389
+
390
+ # Technology from Researcher
391
+ prefer:
392
+ - libraries_with_good_research
393
+ - patterns_with_code_examples
394
+ ```
395
+
396
+ ---
397
+
398
+ ## Performance Considerations
399
+
400
+ ### Time Budgets
401
+ | Phase | Target | Max |
402
+ |-------|--------|-----|
403
+ | Scout | 1 min | 2 min |
404
+ | Cache check | 1 sec | 5 sec |
405
+ | Single researcher | 3 min | 5 min |
406
+ | Parallel researchers | 3 min | 5 min |
407
+ | Total research phase | 4 min | 7 min |
408
+
409
+ ### Parallelization Strategy
410
+ ```
411
+ Sequential:
412
+ Scout (1 min) → Cache Check (1 sec) → [If cache miss] Research Phase
413
+
414
+ Research Phase (Parallel):
415
+ ├── Researcher 1: Framework docs (3 min)
416
+ ├── Researcher 2: Pattern research (3 min)
417
+ └── Researcher 3: API docs (3 min)
418
+ └── Total: 3 min (not 9 min)
419
+ ```
420
+
421
+ ### Context Budget
422
+ | Agent | Context Budget |
423
+ |-------|---------------|
424
+ | Scout | 10% max |
425
+ | Researcher | 20% per instance |
426
+ | Research output to Planner | 15% max |
427
+
428
+ Output compression ensures Planner receives concise, actionable context.
429
+
430
+ ---
431
+
432
+ ## Configuration
433
+
434
+ ### `.grid/config.json` Extensions
435
+ ```json
436
+ {
437
+ "research": {
438
+ "enabled": true,
439
+ "cache_ttl_hours": 24,
440
+ "max_researchers": 3,
441
+ "scout_timeout_seconds": 120,
442
+ "researcher_timeout_seconds": 300,
443
+ "skip_for_quick_mode": true
444
+ }
445
+ }
446
+ ```
447
+
448
+ ### User Controls
449
+ | Command | Effect |
450
+ |---------|--------|
451
+ | "skip research" | Bypass research phase |
452
+ | "fresh research" | Ignore cache, research anew |
453
+ | "research only" | Run research, don't plan |
454
+ | "deep research" | Extended time budget |
455
+
456
+ ---
457
+
458
+ ## Error Handling
459
+
460
+ ### Scout Failures
461
+ ```yaml
462
+ failure_modes:
463
+ timeout:
464
+ action: "Proceed with partial results"
465
+ fallback: "Manual constraint discovery"
466
+
467
+ permission_denied:
468
+ action: "Report inaccessible areas"
469
+ fallback: "User provides constraints"
470
+
471
+ empty_directory:
472
+ action: "Report greenfield"
473
+ fallback: "Standard patterns"
474
+ ```
475
+
476
+ ### Researcher Failures
477
+ ```yaml
478
+ failure_modes:
479
+ api_timeout:
480
+ action: "Retry once, then skip topic"
481
+ fallback: "Use training knowledge"
482
+
483
+ no_results:
484
+ action: "Report low confidence"
485
+ fallback: "Mark for manual review"
486
+
487
+ rate_limited:
488
+ action: "Queue for later"
489
+ fallback: "Proceed without"
490
+ ```
491
+
492
+ ---
493
+
494
+ ## Observability
495
+
496
+ ### Research Metrics
497
+ ```yaml
498
+ metrics:
499
+ scout:
500
+ - scan_duration_ms
501
+ - files_analyzed
502
+ - patterns_detected
503
+ - constraints_found
504
+
505
+ researcher:
506
+ - queries_executed
507
+ - sources_found
508
+ - cache_hit_rate
509
+ - avg_query_time_ms
510
+
511
+ overall:
512
+ - research_phase_duration_ms
513
+ - cache_hit_rate
514
+ - context_compression_ratio
515
+ ```
516
+
517
+ ### Logging
518
+ ```
519
+ .grid/logs/research/
520
+ ├── scout_2026-01-23T14:00:00.log
521
+ ├── researcher_nextjs_2026-01-23T14:01:00.log
522
+ └── researcher_prisma_2026-01-23T14:01:00.log
523
+ ```
524
+
525
+ ---
526
+
527
+ ## Migration Path
528
+
529
+ ### Phase 1: Scout Only (Week 1)
530
+ - Deploy Scout agent
531
+ - Add Scout to MC flow before Planner
532
+ - Measure planning improvement
533
+
534
+ ### Phase 2: Researcher Integration (Week 2)
535
+ - Deploy Researcher agent
536
+ - Add cache infrastructure
537
+ - Integrate with Planner prompts
538
+
539
+ ### Phase 3: Full Integration (Week 3)
540
+ - Parallel researcher spawning
541
+ - Cache optimization
542
+ - Metrics and observability
543
+
544
+ ### Backward Compatibility
545
+ - Research phase can be disabled via config
546
+ - Quick mode bypasses research by default
547
+ - Existing projects continue to work
548
+
549
+ ---
550
+
551
+ ## Security Considerations
552
+
553
+ ### Data Handling
554
+ - Research cache in `.grid/` (gitignored)
555
+ - No secrets in research output
556
+ - External queries sanitized
557
+
558
+ ### Rate Limiting
559
+ - Max 10 queries per researcher
560
+ - 2-second delay between web searches
561
+ - Respect API rate limits
562
+
563
+ ---
564
+
565
+ ## Future Enhancements
566
+
567
+ ### Planned
568
+ 1. **Semantic caching:** Match by meaning, not exact query
569
+ 2. **Learning loop:** Feed successful patterns back to research
570
+ 3. **Team knowledge:** Shared research cache across projects
571
+ 4. **Custom sources:** User-defined authoritative sources
572
+
573
+ ### Considered
574
+ - RAG over codebase for deep context
575
+ - ML-based pattern detection
576
+ - Automated research scheduling
577
+
578
+ ---
579
+
580
+ ## Summary
581
+
582
+ The Research-First Architecture introduces mandatory intelligence gathering before planning:
583
+
584
+ 1. **Scout** rapidly analyzes existing codebases (< 2 min)
585
+ 2. **Researcher** gathers external best practices (3-5 min, parallelizable)
586
+ 3. **Cache** prevents repeated searches (24h TTL)
587
+ 4. **Planner** receives structured context for informed planning
588
+
589
+ This architecture ensures The Grid builds on current knowledge and respects existing constraints, reducing rework and improving plan quality.
590
+
591
+ **End of Line.**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "the-grid-cc",
3
- "version": "1.7.13",
3
+ "version": "1.7.14",
4
4
  "description": "Agent orchestration for Claude Code. You talk to Master Control. Master Control handles the rest.",
5
5
  "main": "index.js",
6
6
  "bin": {