@haposoft/cafekit 0.4.0 → 0.5.0

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.
package/bin/install.js CHANGED
@@ -17,6 +17,7 @@
17
17
  const fs = require('fs');
18
18
  const path = require('path');
19
19
  const readline = require('readline');
20
+ const { execSync } = require('child_process');
20
21
  const packageJson = require('../package.json');
21
22
 
22
23
  function validateManifestV2(manifest) {
@@ -487,8 +488,8 @@ function copyPlatformFiles(platformKey, results, options = {}) {
487
488
  if (platformKey === 'claude') {
488
489
  requiredSkills = CLAUDE_MIGRATION_MANIFEST?.skills?.required || [];
489
490
  } else if (platformKey === 'antigravity') {
490
- // Antigravity also needs impact-analysis skill
491
- requiredSkills = ['impact-analysis'];
491
+ // Antigravity also needs shared investigation and impact-analysis skills
492
+ requiredSkills = ['impact-analysis', 'debug'];
492
493
  }
493
494
 
494
495
  requiredSkills
@@ -768,6 +769,120 @@ function mergeClaudeSettings(platformKey, results, options = {}) {
768
769
  fs.writeFileSync(targetPath, JSON.stringify(mergedSettings, null, 2), 'utf8');
769
770
  }
770
771
 
772
+ // ═══════════════════════════════════════════════════════════
773
+ // GEMINI CLI SETUP
774
+ // ═══════════════════════════════════════════════════════════
775
+
776
+ function checkGeminiCLI() {
777
+ try {
778
+ execSync('which gemini', { stdio: 'ignore' });
779
+ return true;
780
+ } catch {
781
+ return false;
782
+ }
783
+ }
784
+
785
+ function installGeminiCLI() {
786
+ console.log('\n⚙ Installing gemini-cli...');
787
+ try {
788
+ execSync('npm install -g @google/generative-ai-cli', { stdio: 'inherit' });
789
+ console.log(' ✓ gemini-cli installed successfully');
790
+ return true;
791
+ } catch (error) {
792
+ console.log(' ✗ Failed to install gemini-cli automatically');
793
+ console.log(' Please run manually: npm install -g @google/generative-ai-cli');
794
+ return false;
795
+ }
796
+ }
797
+
798
+ async function promptInstallGemini() {
799
+ const rl = readline.createInterface({
800
+ input: process.stdin,
801
+ output: process.stdout
802
+ });
803
+
804
+ console.log('\n📦 Optional: Gemini CLI Installation');
805
+ console.log(' hapo:inspect with ext mode requires gemini-cli');
806
+ console.log(' • Install now: Auto-install and configure API key');
807
+ console.log(' • Skip: You can still use hapo:inspect in internal mode');
808
+ console.log();
809
+
810
+ return new Promise((resolve) => {
811
+ rl.question('Install gemini-cli? (Y/n): ', (answer) => {
812
+ rl.close();
813
+ const response = answer.trim().toLowerCase();
814
+ resolve(response === '' || response === 'y' || response === 'yes');
815
+ });
816
+ });
817
+ }
818
+
819
+ async function promptGeminiAPIKey() {
820
+ const rl = readline.createInterface({
821
+ input: process.stdin,
822
+ output: process.stdout
823
+ });
824
+
825
+ console.log('\n📝 Gemini API Key Configuration');
826
+ console.log(' Get your API key: https://aistudio.google.com/apikey');
827
+ console.log();
828
+
829
+ return new Promise((resolve) => {
830
+ rl.question('Enter your Gemini API key (or press Enter to skip): ', (answer) => {
831
+ rl.close();
832
+ resolve(answer.trim());
833
+ });
834
+ });
835
+ }
836
+
837
+ function configureGeminiKey(apiKey) {
838
+ try {
839
+ execSync(`gemini config set-key ${apiKey}`, { stdio: 'inherit' });
840
+ console.log(' ✓ Gemini API key configured successfully');
841
+ return true;
842
+ } catch (error) {
843
+ console.log(' ✗ Failed to configure Gemini API key');
844
+ console.log(' Please run manually: gemini config set-key YOUR_API_KEY');
845
+ return false;
846
+ }
847
+ }
848
+
849
+ async function setupGeminiCLI() {
850
+ const hasGemini = checkGeminiCLI();
851
+
852
+ if (hasGemini) {
853
+ console.log(' ✓ gemini-cli already installed');
854
+ return;
855
+ }
856
+
857
+ const shouldInstall = await promptInstallGemini();
858
+
859
+ if (!shouldInstall) {
860
+ console.log('\n ℹ Skipped gemini-cli installation');
861
+ console.log(' • hapo:inspect will work in internal mode (default)');
862
+ console.log(' • To install later: npm install -g @google/generative-ai-cli');
863
+ return;
864
+ }
865
+
866
+ console.log('\n⚙ Installing gemini-cli...');
867
+ const installed = installGeminiCLI();
868
+
869
+ if (installed) {
870
+ const apiKey = await promptGeminiAPIKey();
871
+
872
+ if (apiKey) {
873
+ configureGeminiKey(apiKey);
874
+ } else {
875
+ console.log('\n📝 Skipped API key configuration');
876
+ console.log(' Configure later with: gemini config set-key YOUR_API_KEY');
877
+ }
878
+ } else {
879
+ console.log('\n📝 Manual installation steps:');
880
+ console.log(' 1. npm install -g @google/generative-ai-cli');
881
+ console.log(' 2. Get API key: https://aistudio.google.com/apikey');
882
+ console.log(' 3. gemini config set-key YOUR_API_KEY');
883
+ }
884
+ }
885
+
771
886
  // ═══════════════════════════════════════════════════════════
772
887
  // MAIN
773
888
  // ═══════════════════════════════════════════════════════════
@@ -850,6 +965,9 @@ async function main() {
850
965
  console.log();
851
966
  }
852
967
 
968
+ // Setup Gemini CLI for hapo:inspect ext mode
969
+ setupGeminiCLI();
970
+
853
971
  // Note: CLAUDE.md and docs/ are generated via /docs init command
854
972
 
855
973
  // Summary
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@haposoft/cafekit",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Spec-Driven Development workflow for AI coding assistants. Supports Claude Code and Antigravity with spec-first workflows plus Claude Code hapo: skills.",
5
5
  "author": "Haposoft <nghialt@haposoft.com>",
6
6
  "license": "MIT",
@@ -1,11 +1,11 @@
1
1
  ---
2
2
  name: code-reviewer
3
- description: "Comprehensive code review with scout-based edge case detection. Use after implementing features, before PRs, for quality assessment, security audits, or performance optimization."
3
+ description: "Comprehensive code review with inspect-based edge case detection. Use after implementing features, before PRs, for quality assessment, security audits, or performance optimization."
4
4
  ---
5
5
 
6
6
  Senior software engineer specializing in code quality assessment. Expertise in TypeScript, JavaScript, Dart (Flutter), security, and performance.
7
7
 
8
- **IMPORTANT**: Ensure token efficiency. Use `scout` and `code-review` skills for protocols.
8
+ **IMPORTANT**: Ensure token efficiency. Use `hapo:inspector` and `code-review` protocols for edge-case discovery before review.
9
9
 
10
10
  ## Core Responsibilities
11
11
 
@@ -18,36 +18,37 @@ Senior software engineer specializing in code quality assessment. Expertise in T
18
18
 
19
19
  ## Review Process
20
20
 
21
- ### 1. Edge Case Scouting (NEW - Do First)
21
+ ### 1. Edge Case Inspection (NEW - Do First)
22
22
 
23
- Before reviewing, scout for edge cases the diff doesn't show:
23
+ Before reviewing, inspect for edge cases the diff doesn't show:
24
24
 
25
25
  ```bash
26
26
  git diff --name-only HEAD~1 # Get changed files
27
27
  ```
28
28
 
29
- Use `/scout` with edge-case-focused prompt:
29
+ Use `/hapo:inspector` with an edge-case-focused prompt:
30
30
  ```
31
- Scout edge cases for recent changes.
31
+ Inspect edge cases for recent changes.
32
+ Scope: {directories around changed files}
32
33
  Changed: {files}
33
34
  Find: affected dependents, data flow risks, boundary conditions, async races, state mutations
34
35
  ```
35
36
 
36
- Document scout findings for inclusion in review.
37
+ Document inspect findings for inclusion in review.
37
38
 
38
39
  ### 2. Initial Analysis
39
40
 
40
41
  - Read `.specs/<feature>/tasks.md` and related changed files
41
42
  - Focus on recently changed files (use `git diff`)
42
43
  - For full codebase: use `repomix` to compact, then analyze
43
- - Wait for scout results before proceeding
44
+ - Wait for inspect results before proceeding
44
45
 
45
46
  ### 3. Systematic Review
46
47
 
47
48
  | Area | Focus |
48
49
  |------|-------|
49
50
  | Structure | Organization, modularity |
50
- | Logic | Correctness, edge cases from scout |
51
+ | Logic | Correctness, edge cases from inspect |
51
52
  | Types | Safety, error handling |
52
53
  | Performance | Bottlenecks, inefficiencies |
53
54
  | Security | Vulnerabilities, data exposure |
@@ -79,7 +80,7 @@ Mark reviewed task status and add next steps in workflow handoff.
79
80
  - Files: [list]
80
81
  - LOC: [count]
81
82
  - Focus: [recent/specific/full]
82
- - Scout findings: [edge cases discovered]
83
+ - Inspect findings: [edge cases discovered]
83
84
 
84
85
  ### Overall Assessment
85
86
  [Brief quality overview]
@@ -96,8 +97,8 @@ Mark reviewed task status and add next steps in workflow handoff.
96
97
  ### Low Priority
97
98
  [Style, minor opts]
98
99
 
99
- ### Edge Cases Found by Scout
100
- [List issues from scouting phase]
100
+ ### Edge Cases Found by Inspect
101
+ [List issues from inspection phase]
101
102
 
102
103
  ### Positive Observations
103
104
  [Good practices noted]
@@ -122,7 +123,7 @@ Mark reviewed task status and add next steps in workflow handoff.
122
123
  - No AI attribution in code/commits
123
124
  - Security best practices priority
124
125
  - **Verify spec task checklist completion**
125
- - **Scout edge cases BEFORE reviewing**
126
+ - **Inspect edge cases BEFORE reviewing**
126
127
 
127
128
  ## Report Output
128
129
 
@@ -41,7 +41,7 @@ When investigating issues, you will:
41
41
  - **When you need to understand the project structure:**
42
42
  - Read `docs/codebase-summary.md` if it exists & up-to-date (less than 2 days old)
43
43
  - Otherwise, only use the `repomix` command to generate comprehensive codebase summary of the current project at `./repomix-output.xml` and create/update a codebase summary file at `./codebase-summary.md`
44
- - **IMPORTANT**: ONLY process this following step `codebase-summary.md` doesn't contain what you need: use `/scout:ext` (preferred) or `/scout` (fallback) slash command to search the codebase for files needed to complete the task
44
+ - **IMPORTANT**: ONLY process this following step `codebase-summary.md` doesn't contain what you need: use `/hapo:inspector ext` for scoped Gemini discovery or `/hapo:inspector` for scoped internal discovery to inspect only the relevant codebase scopes and find the files needed to complete the task
45
45
  - When you are given a Github repository URL, use `repomix --remote <github-repo-url>` bash command to generate a fresh codebase summary:
46
46
  ```bash
47
47
  # usage: repomix --remote <github-repo-url>
@@ -13,7 +13,7 @@ argument-hint: [scope-or-prompt]
13
13
 
14
14
  Main agent deeply analyzes the scope to LIST all potential edge cases FIRST:
15
15
  - Read `codebase-summary.md` for context
16
- - Use `/scout:ext` to find relevant files
16
+ - Use `/hapo:inspector ext` for scoped Gemini discovery; if external mode is unavailable or not appropriate, fall back to `/hapo:inspector` for scoped internal discovery
17
17
  - **Think exhaustively** about what could go wrong:
18
18
  - Null/undefined scenarios
19
19
  - Boundary conditions (off-by-one, empty, max values)
@@ -24,7 +24,7 @@ Think harder to scan the codebase and analyze it follow the Orchestration Protoc
24
24
 
25
25
  * Use 2 `researcher` subagents in parallel to search up to max 5 sources for the user's request, idea validation, best practices, challenges, and find the best possible solutions.
26
26
  * Keep every research markdown report concise (≤150 lines) while covering all requested topics and citations.
27
- * Use `/scout:ext` (preferred) or `/scout` (fallback) slash command to search the codebase for files needed to complete the task
27
+ * Use `/hapo:inspector ext` for scoped Gemini discovery or `/hapo:inspector` for scoped internal discovery to search the codebase for files needed to complete the task
28
28
 
29
29
  ### Code Review
30
30
 
@@ -34,7 +34,7 @@ Think harder to scan the codebase and analyze it follow the Orchestration Protoc
34
34
  * **IMPORTANT:** Sacrifice grammar for the sake of concision when writing outputs.
35
35
 
36
36
  ### Plan
37
- * Use `planner` subagent to analyze reports from `researcher` and `scout` subagents to create an improvement plan following the progressive disclosure structure:
37
+ * Use `planner` subagent to analyze reports from `researcher` and `hapo:inspector` discovery runs to create an improvement plan following the progressive disclosure structure:
38
38
  - Create a directory using naming pattern from `## Naming` section.
39
39
  - Save the overview access point at `plan.md`, keep it generic, under 80 lines, and list each phase with status/progress and links.
40
40
  - For each phase, add `phase-XX-phase-name.md` files containing sections (Context links, Overview with date/priority/statuses, Key Insights, Requirements, Architecture, Related code files, Implementation Steps, Todo list, Success Criteria, Risk Assessment, Security Considerations, Next steps).
@@ -21,6 +21,7 @@
21
21
  "required": [
22
22
  "specs",
23
23
  "impact-analysis",
24
+ "inspector",
24
25
  "spec-init",
25
26
  "spec-requirements",
26
27
  "spec-design",
@@ -46,6 +47,7 @@
46
47
  },
47
48
  "runtime": {
48
49
  "files": [
50
+ "runtime.json",
49
51
  "status.cjs",
50
52
  "hooks/session.cjs",
51
53
  "hooks/agent.cjs",
@@ -0,0 +1,5 @@
1
+ {
2
+ "gemini": {
3
+ "model": "gemini-3-flash-preview"
4
+ }
5
+ }
@@ -59,7 +59,7 @@ Load `references/change-detection.md` to:
59
59
  - Classify changes (backend/frontend/database)
60
60
  - Assess risk level
61
61
 
62
- ### 2. Scout Dependencies
62
+ ### 2. Inspect Dependencies
63
63
 
64
64
  Load `references/dependency-scouting.md` to:
65
65
  - Find files that import/use modified code
@@ -1,8 +1,8 @@
1
- # Dependency Scouting - Finding Affected Files
1
+ # Dependency Inspection - Finding Affected Files
2
2
 
3
3
  Methods for finding and analyzing dependencies to determine impact scope.
4
4
 
5
- ## Scouting Strategies
5
+ ## Inspection Strategies
6
6
 
7
7
  ### 1. Import Analysis (Direct Dependencies)
8
8
 
@@ -132,12 +132,17 @@ grep -r "as User" src/
132
132
  # src/components/UserCard.tsx: props: { user: User }
133
133
  ```
134
134
 
135
- ## Using /ck:scout for Parallel Scouting
135
+ ## Using /hapo:inspector for Dependency Inspection
136
136
 
137
- When multiple files change, use `/ck:scout` for parallel search:
137
+ When multiple files change, use `/hapo:inspector` for scoped discovery first:
138
138
 
139
139
  ```
140
- /ck:scout Scout dependencies for changes.
140
+ /hapo:inspector Inspect dependencies for these changes.
141
+
142
+ Scope:
143
+ - src/api/
144
+ - src/utils/
145
+ - prisma/
141
146
 
142
147
  Changed files:
143
148
  - src/api/auth.ts (authentication logic)
@@ -152,11 +157,7 @@ Find:
152
157
  5. Frontend components calling changed APIs
153
158
  6. Test files covering changed code
154
159
 
155
- Focus on:
156
- - Direct imports (import/require statements)
157
- - Function calls (grep for function names)
158
- - Type usage (TypeScript interfaces)
159
- - Integration points (API calls, DB queries)
160
+ Keep scope narrow. Do not scan repo root.
160
161
  ```
161
162
 
162
163
  ## Dependency Graph
@@ -236,15 +237,15 @@ grep -r "useContext.*{Context}" src/
236
237
  grep -r "use{Store}" src/
237
238
  ```
238
239
 
239
- ## Automated Scouting Script
240
+ ## Automated Inspection Script
240
241
 
241
242
  ```bash
242
243
  #!/bin/bash
243
- # scout-dependencies.sh
244
+ # inspect-dependencies.sh
244
245
 
245
246
  CHANGED_FILE=$1
246
247
 
247
- echo "=== Scouting Dependencies for: $CHANGED_FILE ==="
248
+ echo "=== Dependency inspection for: $CHANGED_FILE ==="
248
249
  echo ""
249
250
 
250
251
  # Extract module name
@@ -325,13 +326,13 @@ done
325
326
  ## Best Practices
326
327
 
327
328
  1. **Start with direct imports** - Easiest to find
328
- 2. **Use parallel scouting** - For multiple files
329
+ 2. **Use parallel inspection** - For multiple files
329
330
  3. **Check integration points** - APIs, events, state
330
331
  4. **Verify test coverage** - Find test files
331
332
  5. **Document findings** - For test scenario generation
332
333
 
333
334
  ## Next Steps
334
335
 
335
- After scouting, proceed to:
336
+ After inspection, proceed to:
336
337
  1. **Edge Case Identification** - Analyze risks in affected files
337
338
  2. **Test Scenario Generation** - Create tests for affected components
@@ -0,0 +1,161 @@
1
+ ---
2
+ name: hapo:inspector
3
+ description: "Fast codebase discovery using parallel agents. Use for file discovery, task context gathering, quick searches across directories. Supports internal (Explore) and external (Gemini) agents."
4
+ version: 2.0.0
5
+ argument-hint: "[search-target] [ext]"
6
+ ---
7
+
8
+ # Inspector
9
+
10
+ Fast, token-efficient codebase discovery using parallel agents to find files needed for tasks.
11
+
12
+ ## Arguments
13
+ - Default: Inspect using built-in Explore subagents in parallel (`./references/internal-inspection.md`)
14
+ - `ext`: Inspect using external Gemini CLI tool in parallel (`./references/external-gemini-inspection.md`)
15
+
16
+ ## When to Use
17
+
18
+ - Beginning work on feature spanning multiple directories
19
+ - User mentions needing to "find", "locate", or "search for" files
20
+ - Starting debugging session requiring file relationships understanding
21
+ - User asks about project structure or where functionality lives
22
+ - Before changes that might affect multiple codebase parts
23
+ - Before review/debug/impact-analysis when affected files are unclear
24
+
25
+ ## Preflight Scope Gate (MANDATORY - All Modes)
26
+
27
+ Before scanning with ANY mode (internal or external):
28
+ 1. Reject repo-root or root-wide scans such as `.`, `/`, `./`, `**/*`, `**/*.ts`, or similar broad patterns without a scoped directory.
29
+ 2. Require at least one concrete scope root such as `src/auth/`, `packages/spec/src/claude/`, or `tests/`.
30
+ 3. Prefer file-type or glob hints whenever possible.
31
+ 4. Apply the built-in no-scan lists below.
32
+ 5. If the request is still too broad, stop and return 2-4 narrower suggestions.
33
+
34
+ ## Built-in No-Scan Guidance
35
+
36
+ ### `NO_SCAN_PATHS`
37
+ - `.git/`
38
+ - `node_modules/`
39
+ - `dist/`
40
+ - `build/`
41
+ - `.next/`
42
+ - `coverage/`
43
+ - `tmp/`
44
+ - `temp/`
45
+ - `vendor/`
46
+ - `artifacts/`
47
+ - `secrets/`
48
+ - `private/`
49
+
50
+ ### `NO_SCAN_CONTENT_HINTS`
51
+ - private keys
52
+ - token dumps
53
+ - credential exports
54
+ - `.env` secrets
55
+ - generated bundles
56
+ - binary blobs
57
+
58
+ ## Configuration
59
+
60
+ Read from `.claude/runtime.json`:
61
+ ```json
62
+ {
63
+ "gemini": {
64
+ "model": "gemini-3-flash-preview"
65
+ }
66
+ }
67
+ ```
68
+
69
+ Default model: `gemini-3-flash-preview`
70
+
71
+ **Note:** This file is automatically installed when you run `npx @haposoft/cafekit`.
72
+
73
+ ## Workflow
74
+
75
+ ### 1. Analyze Task
76
+ - Parse user prompt for search targets
77
+ - Identify key directories, patterns, file types, lines of code
78
+ - Determine optimal SCALE value of subagents to spawn
79
+
80
+ **SCALE Calculation:**
81
+ ```
82
+ SCALE = ceil(estimated_files_to_scan / 50)
83
+ ```
84
+
85
+ Where:
86
+ - `estimated_files_to_scan` = rough count of files matching scope
87
+ - Minimum SCALE = 1 (single agent)
88
+ - Maximum SCALE = 10 (practical limit for coordination overhead)
89
+
90
+ **SCALE Thresholds:**
91
+ - SCALE 1-2: Simple, focused searches (< 100 files)
92
+ - SCALE 3-5: Medium scope, suitable for external Gemini CLI
93
+ - SCALE 6-10: Large scope, requires internal Explore agents
94
+
95
+ ### 2. Divide and Conquer
96
+ - Split codebase into logical segments per agent
97
+ - Assign each agent specific directories or patterns
98
+ - Ensure no overlap, maximize coverage
99
+
100
+ ### 3. Register Inspect Tasks
101
+ - **Skip if:** Agent count ≤ 2 (overhead exceeds benefit)
102
+ - `TaskList` first — check for existing inspector tasks in session
103
+ - If not found, `TaskCreate` per agent with scope metadata
104
+ - See `./references/internal-inspection.md` for patterns and examples
105
+
106
+ ### 4. Choose Mode
107
+
108
+ Decision table:
109
+ - **No `ext` argument** → Use internal Explore agents
110
+ - **`ext` argument + SCALE ≤ 5** → Use Gemini CLI (if scope gate passed and Gemini available)
111
+ - **`ext` argument + SCALE ≥ 6** → Use internal Explore agents (external not suitable for large scale)
112
+ - **Gemini unavailable or fails** → Fallback to internal Explore agents
113
+
114
+ Load appropriate reference:
115
+ - **Internal (Default):** `./references/internal-inspection.md` (Explore subagents)
116
+ - **External:** `./references/external-gemini-inspection.md` (Gemini CLI)
117
+
118
+ ### 5. Spawn Parallel Agents
119
+
120
+ **Notes:**
121
+ - `TaskUpdate` each task to `in_progress` before spawning its agent
122
+ - Prompt detailed instructions for each subagent with exact directories or files it should read
123
+ - Remember that each subagent has less than 200K tokens of context window
124
+ - Amount of subagents to-be-spawned depends on the current system resources available and amount of files to be scanned
125
+ - Each subagent must return a detailed summary report to a main agent
126
+
127
+ ### 6. Collect Results
128
+ - Timeout: 3 minutes per agent (skip non-responders)
129
+ - `TaskUpdate` completed tasks; log timed-out agents in report
130
+ - Aggregate findings into single report
131
+ - List unresolved questions at end
132
+
133
+ ## Report Format
134
+
135
+ ```markdown
136
+ # Inspector Report
137
+
138
+ ## Relevant Files
139
+ - `path/to/file.ts` - Brief description
140
+ - ...
141
+
142
+ ## Patterns
143
+ - Key patterns observed
144
+
145
+ ## Unresolved Questions
146
+ - Any gaps in findings
147
+ ```
148
+
149
+ ## Rules
150
+
151
+ - Keep scope narrow. Do not use `hapo:inspector` as a runtime policy engine.
152
+ - Prefer listing files first, then reading only the shortlisted files.
153
+ - Never encourage scanning ignored/generated/sensitive areas from the no-scan list.
154
+ - Keep reports concise and actionable.
155
+ - Ensure no overlap between agent scopes.
156
+ - Skip non-responding agents, do not retry.
157
+
158
+ ## References
159
+
160
+ - `./references/internal-inspection.md` - Using Explore subagents
161
+ - `./references/external-gemini-inspection.md` - Using Gemini CLI
@@ -0,0 +1,169 @@
1
+ # External Discovery with Gemini
2
+
3
+ Use external Gemini CLI for faster searches with large context windows (1M+ tokens) when SCALE ≤ 5.
4
+
5
+ ## Tool Selection
6
+
7
+ ```
8
+ SCALE ≤ 5 → gemini CLI
9
+ SCALE ≥ 6 → Use internal discovery instead
10
+ ```
11
+
12
+ ## Configuration
13
+
14
+ Read from `.claude/runtime.json`:
15
+ ```json
16
+ {
17
+ "gemini": {
18
+ "model": "gemini-3-flash-preview"
19
+ }
20
+ }
21
+ ```
22
+
23
+ Default model: `gemini-3-flash-preview`
24
+
25
+ **Note:** This file is automatically installed when you run `npx @haposoft/cafekit`.
26
+
27
+ ## When External Mode is Allowed
28
+
29
+ External Gemini inspection requires:
30
+
31
+ **Gemini-Specific Requirements:**
32
+ 1. The prompt explicitly includes `ext` argument
33
+ 2. SCALE ≤ 5 (calculated from estimated file count)
34
+
35
+ **General Preflight Gate (applies to all modes):**
36
+ 3. At least one concrete directory scope is present
37
+ 4. The request is not a repo-root or root-wide scan
38
+ 5. The built-in no-scan guidance has been applied
39
+
40
+ If any condition fails, use internal discovery instead.
41
+
42
+ ## Gemini CLI
43
+
44
+ ### Command
45
+ ```bash
46
+ gemini -y -m <model> "[prompt]"
47
+ ```
48
+
49
+ ### Example
50
+ ```bash
51
+ gemini -y -m gemini-3-flash-preview "Search src/ for authentication files. List paths with brief descriptions."
52
+ ```
53
+
54
+ ## Installation Check
55
+
56
+ Before using, verify Gemini CLI is installed:
57
+ ```bash
58
+ which gemini
59
+ ```
60
+
61
+ If not installed, ask user:
62
+ 1. **Yes** - Provide installation instructions (may need manual auth steps)
63
+ 2. **No** - Fall back to internal discovery (`internal-inspection.md`)
64
+
65
+ ## Spawning Parallel Bash Agents
66
+
67
+ Use `Agent` tool with `subagent_type: "Bash"` to spawn parallel agents:
68
+
69
+ ```
70
+ Agent 1: subagent_type="Bash", prompt="Run: gemini -y -m gemini-3-flash-preview '[prompt1]'"
71
+ Agent 2: subagent_type="Bash", prompt="Run: gemini -y -m gemini-3-flash-preview '[prompt2]'"
72
+ Agent 3: subagent_type="Bash", prompt="Run: gemini -y -m gemini-3-flash-preview '[prompt3]'"
73
+ ```
74
+
75
+ Spawn all in single message for parallel execution.
76
+
77
+ ## Prompt Guidelines
78
+
79
+ - Be specific about directories to search
80
+ - Request file paths with descriptions
81
+ - Set clear scope boundaries
82
+ - Ask for patterns/relationships if relevant
83
+ - Do not include no-scan paths
84
+ - Do not request secret material or generated bundles
85
+
86
+ ## Prompt Template
87
+
88
+ ```text
89
+ Inspect these scoped directories only:
90
+ - {dir-1}
91
+ - {dir-2}
92
+
93
+ Goal:
94
+ - {what to find}
95
+
96
+ Return:
97
+ 1. relevant file paths
98
+ 2. one-line description per file
99
+ 3. notable patterns or relationships
100
+ 4. unresolved questions
101
+
102
+ Do not inspect repo root, generated directories, or sensitive content.
103
+ Do not expand beyond the provided scope.
104
+ ```
105
+
106
+ ## Example Workflow
107
+
108
+ User: "Find database migration files" with `ext`
109
+
110
+ Spawn 3 parallel Bash agents via Agent tool:
111
+ ```
112
+ Agent 1 (Bash): "Run: gemini -y -m gemini-3-flash-preview 'Search db/, migrations/ for migration files'"
113
+ Agent 2 (Bash): "Run: gemini -y -m gemini-3-flash-preview 'Search lib/, src/ for database schema files'"
114
+ Agent 3 (Bash): "Run: gemini -y -m gemini-3-flash-preview 'Search config/ for database configuration'"
115
+ ```
116
+
117
+ ## Reading File Content
118
+
119
+ When needing to read file content, use chunking to stay within context limits (<150K tokens safe zone).
120
+
121
+ ### Step 1: Get Line Counts
122
+ Use Read tool to check file size before reading.
123
+
124
+ ### Step 2: Calculate Chunks
125
+ - **Target:** ~500 lines per chunk (safe for most files)
126
+ - **Max files per agent:** 3-5 small files OR 1 large file chunked
127
+
128
+ **Chunking formula:**
129
+ ```
130
+ chunks = ceil(total_lines / 500)
131
+ lines_per_chunk = ceil(total_lines / chunks)
132
+ ```
133
+
134
+ ### Step 3: Read Strategy
135
+
136
+ **Small files (<500 lines each):**
137
+ - Read entire file with Read tool
138
+
139
+ **Large file (>500 lines):**
140
+ - Use Read tool with offset/limit parameters
141
+ - Read in 500-line chunks
142
+
143
+ ### Chunking Decision Tree
144
+ ```
145
+ File < 500 lines → Read entire file
146
+ File 500-1500 lines → Split into 2-3 chunks
147
+ File > 1500 lines → Split into ceil(lines/500) chunks
148
+ ```
149
+
150
+ ## Timeout and Error Handling
151
+
152
+ - Set 3-minute timeout per bash call
153
+ - Skip timed-out agents
154
+ - Don't restart failed agents
155
+ - On persistent failures, fall back to internal discovery
156
+
157
+ ## Fallback Behavior
158
+
159
+ If Gemini is unavailable, misconfigured, or errors out:
160
+ 1. Stop external mode
161
+ 2. Continue with internal discovery
162
+ 3. Note the fallback in the final report
163
+
164
+ ## Expected Outcome
165
+
166
+ - Scoped Gemini discovery
167
+ - Concise file list with descriptions
168
+ - Patterns and relationships
169
+ - Fallback to internal mode if Gemini cannot run
@@ -0,0 +1,173 @@
1
+ # Internal Discovery with Explore Subagents
2
+
3
+ Use Explore subagents when SCALE >= 6 or external tools unavailable.
4
+
5
+ ## How It Works
6
+
7
+ Spawn multiple `Explore` subagents via `Agent` tool to search codebase in parallel.
8
+
9
+ ## Agent Tool Configuration
10
+
11
+ ```
12
+ subagent_type: "Explore"
13
+ ```
14
+
15
+ ## Prompt Template
16
+
17
+ ```
18
+ Quickly search {DIRECTORY} for files related to: {USER_PROMPT}
19
+
20
+ Instructions:
21
+ - Search for relevant files matching the task
22
+ - Use Glob/Grep for file discovery
23
+ - List files with brief descriptions
24
+ - Timeout: 3 minutes max
25
+ - Skip if timeout reached
26
+
27
+ Report format:
28
+ ## Found Files
29
+ - `path/file.ext` - description
30
+
31
+ ## Patterns
32
+ - Key patterns observed
33
+ ```
34
+
35
+ ## Spawning Strategy
36
+
37
+ ### Directory Division
38
+ Split codebase logically:
39
+ - `src/` - Source code
40
+ - `lib/` - Libraries
41
+ - `tests/` - Test files
42
+ - `config/` - Configuration
43
+ - `api/` - API routes
44
+ - `types/` - Type definitions
45
+
46
+ ### Parallel Execution
47
+ - Spawn all agents in single `Agent` tool call
48
+ - Each agent gets distinct directory scope
49
+ - No overlap between agents
50
+
51
+ ## Example
52
+
53
+ User prompt: "Find authentication-related files"
54
+
55
+ ```
56
+ Agent 1: Inspect src/auth/, src/middleware/ for auth files
57
+ Agent 2: Inspect src/api/, src/routes/ for auth endpoints
58
+ Agent 3: Inspect tests/ for auth tests
59
+ Agent 4: Inspect lib/, utils/ for auth utilities
60
+ Agent 5: Inspect config/ for auth configuration
61
+ Agent 6: Inspect types/, interfaces/ for auth types
62
+ ```
63
+
64
+ ## Task Registration (Optional)
65
+
66
+ ### When to Register Tasks
67
+
68
+ | Agents | Create Tasks? | Rationale |
69
+ |--------|--------------|-----------|
70
+ | ≤ 2 | No | Overhead exceeds benefit, finishes quickly |
71
+ | ≥ 3 | Yes | Meaningful coordination, progress monitoring |
72
+
73
+ ### Task Registration Flow
74
+
75
+ ```
76
+ TaskList() // Check for existing inspector tasks
77
+ → Found tasks? → Skip creation, reuse existing
78
+ → Empty? → TaskCreate per agent
79
+ ```
80
+
81
+ ### Task Metadata Pattern
82
+
83
+ ```
84
+ TaskCreate(
85
+ subject: "Inspect {directory} for {target}",
86
+ activeForm: "Searching {directory}",
87
+ description: "Search {directories} for {patterns}",
88
+ metadata: {
89
+ agentType: "Explore",
90
+ scope: "src/auth/,src/middleware/",
91
+ scale: 6,
92
+ agentIndex: 1,
93
+ totalAgents: 6,
94
+ toolMode: "internal",
95
+ priority: "P2",
96
+ effort: "3m"
97
+ }
98
+ )
99
+ ```
100
+
101
+ ### Task Lifecycle
102
+
103
+ ```
104
+ Step 3: TaskCreate per agent → status: pending
105
+ Step 4: Before spawning agent → TaskUpdate → status: in_progress
106
+ Step 5: Agent returns report → TaskUpdate → status: completed
107
+ Step 5: Agent times out (3m) → Keep in_progress, add error metadata
108
+ ```
109
+
110
+ ## Timeout Handling
111
+
112
+ - Set 3-minute timeout per agent
113
+ - Skip non-responding agents
114
+ - Don't restart timed-out agents
115
+ - Aggregate available results
116
+ - Log timeouts in final report's "Unresolved Questions" section
117
+
118
+ ## Reading File Content
119
+
120
+ When needing to read file content, use chunking to stay within context limits (<150K tokens safe zone).
121
+
122
+ ### Step 1: Get Line Counts
123
+ Use Read tool with limit/offset or check file size before reading.
124
+
125
+ ### Step 2: Calculate Chunks
126
+ - **Target:** ~500 lines per chunk (safe for most files)
127
+ - **Max files per agent:** 3-5 small files OR 1 large file chunked
128
+
129
+ **Chunking formula:**
130
+ ```
131
+ chunks = ceil(total_lines / 500)
132
+ lines_per_chunk = ceil(total_lines / chunks)
133
+ ```
134
+
135
+ ### Step 3: Read Strategy
136
+
137
+ **Small files (<500 lines each):**
138
+ - Read entire file with Read tool
139
+
140
+ **Large file (>500 lines):**
141
+ - Use Read tool with offset/limit parameters
142
+ - Read in 500-line chunks
143
+
144
+ ### Chunking Decision Tree
145
+ ```
146
+ File < 500 lines → Read entire file
147
+ File 500-1500 lines → Split into 2-3 chunks
148
+ File > 1500 lines → Split into ceil(lines/500) chunks
149
+ ```
150
+
151
+ ## Result Aggregation
152
+
153
+ Combine results from all agents:
154
+ 1. Deduplicate file paths
155
+ 2. Merge descriptions
156
+ 3. Note any gaps/timeouts
157
+ 4. List unresolved questions
158
+
159
+ ## Scope Discipline
160
+
161
+ - Start from concrete directories, not repo root
162
+ - Prefer scope like `packages/spec/src/common/skills/**/*.md` over `**/*.md`
163
+ - Skip `NO_SCAN_PATHS` from SKILL.md
164
+ - Avoid content matching `NO_SCAN_CONTENT_HINTS`
165
+ - If request still broad, stop and narrow before continuing
166
+
167
+ ## Output Contract
168
+
169
+ Return:
170
+ - file paths
171
+ - brief description per file
172
+ - notable relationships or repeated patterns
173
+ - unresolved questions