claude-code-pilot 3.0.0 → 3.1.1

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 (124) hide show
  1. package/README.md +76 -97
  2. package/bin/install.js +14 -14
  3. package/manifest.json +1 -1
  4. package/package.json +17 -5
  5. package/src/agents/doc-updater.md +1 -1
  6. package/src/agents/gan-evaluator.md +209 -0
  7. package/src/agents/gan-generator.md +131 -0
  8. package/src/agents/gan-planner.md +99 -0
  9. package/src/agents/harness-optimizer.md +35 -0
  10. package/src/agents/loop-operator.md +36 -0
  11. package/src/agents/opensource-forker.md +198 -0
  12. package/src/agents/opensource-packager.md +249 -0
  13. package/src/agents/opensource-sanitizer.md +188 -0
  14. package/src/agents/performance-optimizer.md +446 -0
  15. package/src/available-rules/README.md +1 -1
  16. package/src/commands/{aside.md → ccp/aside.md} +14 -13
  17. package/src/commands/{build-fix.md → ccp/build-fix.md} +5 -0
  18. package/src/commands/{checkpoint.md → ccp/checkpoint.md} +12 -7
  19. package/src/commands/{code-review.md → ccp/code-review.md} +5 -0
  20. package/src/commands/{context-budget.md → ccp/context-budget.md} +2 -1
  21. package/src/commands/{cpp-build.md → ccp/cpp-build.md} +6 -5
  22. package/src/commands/{cpp-review.md → ccp/cpp-review.md} +7 -6
  23. package/src/commands/{cpp-test.md → ccp/cpp-test.md} +6 -5
  24. package/src/commands/ccp/docs-update.md +48 -0
  25. package/src/commands/{docs.md → ccp/docs.md} +4 -3
  26. package/src/commands/{e2e.md → ccp/e2e.md} +7 -6
  27. package/src/commands/{eval.md → ccp/eval.md} +10 -5
  28. package/src/commands/{evolve.md → ccp/evolve.md} +3 -3
  29. package/src/commands/{go-build.md → ccp/go-build.md} +6 -5
  30. package/src/commands/{go-review.md → ccp/go-review.md} +7 -6
  31. package/src/commands/{go-test.md → ccp/go-test.md} +6 -5
  32. package/src/commands/{gradle-build.md → ccp/gradle-build.md} +1 -0
  33. package/src/commands/{harness-audit.md → ccp/harness-audit.md} +6 -1
  34. package/src/commands/{kotlin-build.md → ccp/kotlin-build.md} +6 -5
  35. package/src/commands/{kotlin-review.md → ccp/kotlin-review.md} +7 -6
  36. package/src/commands/{kotlin-test.md → ccp/kotlin-test.md} +6 -5
  37. package/src/commands/{learn.md → ccp/learn.md} +7 -2
  38. package/src/commands/{model-route.md → ccp/model-route.md} +6 -1
  39. package/src/commands/{orchestrate.md → ccp/orchestrate.md} +4 -3
  40. package/src/commands/{plan.md → ccp/plan.md} +6 -5
  41. package/src/commands/ccp/profile-user.md +46 -0
  42. package/src/commands/{prompt-optimize.md → ccp/prompt-optimize.md} +3 -2
  43. package/src/commands/{prune.md → ccp/prune.md} +4 -4
  44. package/src/commands/{python-review.md → ccp/python-review.md} +7 -6
  45. package/src/commands/{quality-gate.md → ccp/quality-gate.md} +6 -1
  46. package/src/commands/{refactor-clean.md → ccp/refactor-clean.md} +5 -0
  47. package/src/commands/{resume-session.md → ccp/resume-session.md} +9 -8
  48. package/src/commands/ccp/review.md +37 -0
  49. package/src/commands/{rules-distill.md → ccp/rules-distill.md} +2 -1
  50. package/src/commands/{rust-build.md → ccp/rust-build.md} +6 -5
  51. package/src/commands/{rust-review.md → ccp/rust-review.md} +7 -6
  52. package/src/commands/{rust-test.md → ccp/rust-test.md} +6 -5
  53. package/src/commands/{save-session.md → ccp/save-session.md} +2 -1
  54. package/src/commands/ccp/secure-phase.md +35 -0
  55. package/src/commands/{sessions.md → ccp/sessions.md} +29 -24
  56. package/src/commands/{setup-pm.md → ccp/setup-pm.md} +1 -0
  57. package/src/commands/{setup-refresh.md → ccp/setup-refresh.md} +4 -3
  58. package/src/commands/{setup.md → ccp/setup.md} +24 -23
  59. package/src/commands/{skill-create.md → ccp/skill-create.md} +8 -8
  60. package/src/commands/{skill-health.md → ccp/skill-health.md} +5 -5
  61. package/src/commands/{tdd.md → ccp/tdd.md} +9 -8
  62. package/src/commands/{test-coverage.md → ccp/test-coverage.md} +5 -0
  63. package/src/commands/{tool-guide.md → ccp/tool-guide.md} +2 -1
  64. package/src/commands/{update-codemaps.md → ccp/update-codemaps.md} +5 -0
  65. package/src/commands/{update-docs.md → ccp/update-docs.md} +5 -0
  66. package/src/commands/{verify.md → ccp/verify.md} +5 -0
  67. package/src/commands/ccp/workstreams.md +68 -0
  68. package/src/examples/CLAUDE.md +4 -4
  69. package/src/examples/django-api-CLAUDE.md +5 -5
  70. package/src/examples/go-microservice-CLAUDE.md +6 -6
  71. package/src/examples/rust-api-CLAUDE.md +4 -4
  72. package/src/examples/saas-nextjs-CLAUDE.md +8 -8
  73. package/src/hooks/session-start.js +1 -1
  74. package/src/pilot/references/mcp-servers.json +1 -1
  75. package/src/pilot/workflows/docs-update.md +1165 -0
  76. package/src/pilot/workflows/help.md +48 -56
  77. package/src/pilot/workflows/profile-user.md +452 -0
  78. package/src/pilot/workflows/review.md +244 -0
  79. package/src/pilot/workflows/secure-phase.md +164 -0
  80. package/src/rules/common/code-review.md +124 -0
  81. package/src/rules/zh/README.md +108 -0
  82. package/src/rules/zh/agents.md +50 -0
  83. package/src/rules/zh/code-review.md +124 -0
  84. package/src/rules/zh/coding-style.md +48 -0
  85. package/src/rules/zh/development-workflow.md +44 -0
  86. package/src/rules/zh/git-workflow.md +24 -0
  87. package/src/rules/zh/hooks.md +30 -0
  88. package/src/rules/zh/patterns.md +31 -0
  89. package/src/rules/zh/performance.md +55 -0
  90. package/src/rules/zh/security.md +29 -0
  91. package/src/rules/zh/testing.md +29 -0
  92. package/src/skills/autonomous-agent-harness/SKILL.md +267 -0
  93. package/src/skills/autonomous-loops/SKILL.md +610 -0
  94. package/src/skills/bun-runtime/SKILL.md +84 -0
  95. package/src/skills/content-hash-cache-pattern/SKILL.md +161 -0
  96. package/src/skills/context-budget/SKILL.md +3 -3
  97. package/src/skills/continuous-learning-v2/SKILL.md +4 -4
  98. package/src/skills/continuous-learning-v2/agents/observer.md +1 -1
  99. package/src/skills/cost-aware-llm-pipeline/SKILL.md +183 -0
  100. package/src/skills/design-system/SKILL.md +82 -0
  101. package/src/skills/eval-harness/SKILL.md +270 -0
  102. package/src/skills/flutter-dart-code-review/SKILL.md +435 -0
  103. package/src/skills/gan-style-harness/SKILL.md +278 -0
  104. package/src/skills/git-workflow/SKILL.md +715 -0
  105. package/src/skills/hexagonal-architecture/SKILL.md +276 -0
  106. package/src/skills/iterative-retrieval/SKILL.md +211 -0
  107. package/src/skills/laravel-plugin-discovery/SKILL.md +229 -0
  108. package/src/skills/nextjs-turbopack/SKILL.md +44 -0
  109. package/src/skills/nuxt4-patterns/SKILL.md +100 -0
  110. package/src/skills/opensource-pipeline/SKILL.md +255 -0
  111. package/src/skills/perl-security/SKILL.md +503 -0
  112. package/src/skills/project-flow-ops/SKILL.md +111 -0
  113. package/src/skills/project-guidelines-example/SKILL.md +349 -0
  114. package/src/skills/prompt-optimizer/SKILL.md +38 -38
  115. package/src/skills/pytorch-patterns/SKILL.md +396 -0
  116. package/src/skills/regex-vs-llm-structured-text/SKILL.md +220 -0
  117. package/src/skills/repo-scan/SKILL.md +78 -0
  118. package/src/skills/rules-distill/SKILL.md +264 -0
  119. package/src/skills/rules-distill/scripts/scan-rules.sh +58 -0
  120. package/src/skills/rules-distill/scripts/scan-skills.sh +129 -0
  121. package/src/skills/swift-concurrency-6-2/SKILL.md +216 -0
  122. package/src/skills/token-budget-advisor/SKILL.md +133 -0
  123. package/src/skills/verification-loop/SKILL.md +1 -1
  124. package/src/skills/workspace-surface-audit/SKILL.md +125 -0
@@ -0,0 +1,276 @@
1
+ ---
2
+ name: hexagonal-architecture
3
+ description: Design, implement, and refactor Ports & Adapters systems with clear domain boundaries, dependency inversion, and testable use-case orchestration across TypeScript, Java, Kotlin, and Go services.
4
+ origin: ECC
5
+ ---
6
+
7
+ # Hexagonal Architecture
8
+
9
+ Hexagonal architecture (Ports and Adapters) keeps business logic independent from frameworks, transport, and persistence details. The core app depends on abstract ports, and adapters implement those ports at the edges.
10
+
11
+ ## When to Use
12
+
13
+ - Building new features where long-term maintainability and testability matter.
14
+ - Refactoring layered or framework-heavy code where domain logic is mixed with I/O concerns.
15
+ - Supporting multiple interfaces for the same use case (HTTP, CLI, queue workers, cron jobs).
16
+ - Replacing infrastructure (database, external APIs, message bus) without rewriting business rules.
17
+
18
+ Use this skill when the request involves boundaries, domain-centric design, refactoring tightly coupled services, or decoupling application logic from specific libraries.
19
+
20
+ ## Core Concepts
21
+
22
+ - **Domain model**: Business rules and entities/value objects. No framework imports.
23
+ - **Use cases (application layer)**: Orchestrate domain behavior and workflow steps.
24
+ - **Inbound ports**: Contracts describing what the application can do (commands/queries/use-case interfaces).
25
+ - **Outbound ports**: Contracts for dependencies the application needs (repositories, gateways, event publishers, clock, UUID, etc.).
26
+ - **Adapters**: Infrastructure and delivery implementations of ports (HTTP controllers, DB repositories, queue consumers, SDK wrappers).
27
+ - **Composition root**: Single wiring location where concrete adapters are bound to use cases.
28
+
29
+ Outbound port interfaces usually live in the application layer (or in domain only when the abstraction is truly domain-level), while infrastructure adapters implement them.
30
+
31
+ Dependency direction is always inward:
32
+
33
+ - Adapters -> application/domain
34
+ - Application -> port interfaces (inbound/outbound contracts)
35
+ - Domain -> domain-only abstractions (no framework or infrastructure dependencies)
36
+ - Domain -> nothing external
37
+
38
+ ## How It Works
39
+
40
+ ### Step 1: Model a use case boundary
41
+
42
+ Define a single use case with a clear input and output DTO. Keep transport details (Express `req`, GraphQL `context`, job payload wrappers) outside this boundary.
43
+
44
+ ### Step 2: Define outbound ports first
45
+
46
+ Identify every side effect as a port:
47
+
48
+ - persistence (`UserRepositoryPort`)
49
+ - external calls (`BillingGatewayPort`)
50
+ - cross-cutting (`LoggerPort`, `ClockPort`)
51
+
52
+ Ports should model capabilities, not technologies.
53
+
54
+ ### Step 3: Implement the use case with pure orchestration
55
+
56
+ Use case class/function receives ports via constructor/arguments. It validates application-level invariants, coordinates domain rules, and returns plain data structures.
57
+
58
+ ### Step 4: Build adapters at the edge
59
+
60
+ - Inbound adapter converts protocol input to use-case input.
61
+ - Outbound adapter maps app contracts to concrete APIs/ORM/query builders.
62
+ - Mapping stays in adapters, not inside use cases.
63
+
64
+ ### Step 5: Wire everything in a composition root
65
+
66
+ Instantiate adapters, then inject them into use cases. Keep this wiring centralized to avoid hidden service-locator behavior.
67
+
68
+ ### Step 6: Test per boundary
69
+
70
+ - Unit test use cases with fake ports.
71
+ - Integration test adapters with real infra dependencies.
72
+ - E2E test user-facing flows through inbound adapters.
73
+
74
+ ## Architecture Diagram
75
+
76
+ ```mermaid
77
+ flowchart LR
78
+ Client["Client (HTTP/CLI/Worker)"] --> InboundAdapter["Inbound Adapter"]
79
+ InboundAdapter -->|"calls"| UseCase["UseCase (Application Layer)"]
80
+ UseCase -->|"uses"| OutboundPort["OutboundPort (Interface)"]
81
+ OutboundAdapter["Outbound Adapter"] -->|"implements"| OutboundPort
82
+ OutboundAdapter --> ExternalSystem["DB/API/Queue"]
83
+ UseCase --> DomainModel["DomainModel"]
84
+ ```
85
+
86
+ ## Suggested Module Layout
87
+
88
+ Use feature-first organization with explicit boundaries:
89
+
90
+ ```text
91
+ src/
92
+ features/
93
+ orders/
94
+ domain/
95
+ Order.ts
96
+ OrderPolicy.ts
97
+ application/
98
+ ports/
99
+ inbound/
100
+ CreateOrder.ts
101
+ outbound/
102
+ OrderRepositoryPort.ts
103
+ PaymentGatewayPort.ts
104
+ use-cases/
105
+ CreateOrderUseCase.ts
106
+ adapters/
107
+ inbound/
108
+ http/
109
+ createOrderRoute.ts
110
+ outbound/
111
+ postgres/
112
+ PostgresOrderRepository.ts
113
+ stripe/
114
+ StripePaymentGateway.ts
115
+ composition/
116
+ ordersContainer.ts
117
+ ```
118
+
119
+ ## TypeScript Example
120
+
121
+ ### Port definitions
122
+
123
+ ```typescript
124
+ export interface OrderRepositoryPort {
125
+ save(order: Order): Promise<void>;
126
+ findById(orderId: string): Promise<Order | null>;
127
+ }
128
+
129
+ export interface PaymentGatewayPort {
130
+ authorize(input: { orderId: string; amountCents: number }): Promise<{ authorizationId: string }>;
131
+ }
132
+ ```
133
+
134
+ ### Use case
135
+
136
+ ```typescript
137
+ type CreateOrderInput = {
138
+ orderId: string;
139
+ amountCents: number;
140
+ };
141
+
142
+ type CreateOrderOutput = {
143
+ orderId: string;
144
+ authorizationId: string;
145
+ };
146
+
147
+ export class CreateOrderUseCase {
148
+ constructor(
149
+ private readonly orderRepository: OrderRepositoryPort,
150
+ private readonly paymentGateway: PaymentGatewayPort
151
+ ) {}
152
+
153
+ async execute(input: CreateOrderInput): Promise<CreateOrderOutput> {
154
+ const order = Order.create({ id: input.orderId, amountCents: input.amountCents });
155
+
156
+ const auth = await this.paymentGateway.authorize({
157
+ orderId: order.id,
158
+ amountCents: order.amountCents,
159
+ });
160
+
161
+ // markAuthorized returns a new Order instance; it does not mutate in place.
162
+ const authorizedOrder = order.markAuthorized(auth.authorizationId);
163
+ await this.orderRepository.save(authorizedOrder);
164
+
165
+ return {
166
+ orderId: order.id,
167
+ authorizationId: auth.authorizationId,
168
+ };
169
+ }
170
+ }
171
+ ```
172
+
173
+ ### Outbound adapter
174
+
175
+ ```typescript
176
+ export class PostgresOrderRepository implements OrderRepositoryPort {
177
+ constructor(private readonly db: SqlClient) {}
178
+
179
+ async save(order: Order): Promise<void> {
180
+ await this.db.query(
181
+ "insert into orders (id, amount_cents, status, authorization_id) values ($1, $2, $3, $4)",
182
+ [order.id, order.amountCents, order.status, order.authorizationId]
183
+ );
184
+ }
185
+
186
+ async findById(orderId: string): Promise<Order | null> {
187
+ const row = await this.db.oneOrNone("select * from orders where id = $1", [orderId]);
188
+ return row ? Order.rehydrate(row) : null;
189
+ }
190
+ }
191
+ ```
192
+
193
+ ### Composition root
194
+
195
+ ```typescript
196
+ export const buildCreateOrderUseCase = (deps: { db: SqlClient; stripe: StripeClient }) => {
197
+ const orderRepository = new PostgresOrderRepository(deps.db);
198
+ const paymentGateway = new StripePaymentGateway(deps.stripe);
199
+
200
+ return new CreateOrderUseCase(orderRepository, paymentGateway);
201
+ };
202
+ ```
203
+
204
+ ## Multi-Language Mapping
205
+
206
+ Use the same boundary rules across ecosystems; only syntax and wiring style change.
207
+
208
+ - **TypeScript/JavaScript**
209
+ - Ports: `application/ports/*` as interfaces/types.
210
+ - Use cases: classes/functions with constructor/argument injection.
211
+ - Adapters: `adapters/inbound/*`, `adapters/outbound/*`.
212
+ - Composition: explicit factory/container module (no hidden globals).
213
+ - **Java**
214
+ - Packages: `domain`, `application.port.in`, `application.port.out`, `application.usecase`, `adapter.in`, `adapter.out`.
215
+ - Ports: interfaces in `application.port.*`.
216
+ - Use cases: plain classes (Spring `@Service` is optional, not required).
217
+ - Composition: Spring config or manual wiring class; keep wiring out of domain/use-case classes.
218
+ - **Kotlin**
219
+ - Modules/packages mirror the Java split (`domain`, `application.port`, `application.usecase`, `adapter`).
220
+ - Ports: Kotlin interfaces.
221
+ - Use cases: classes with constructor injection (Koin/Dagger/Spring/manual).
222
+ - Composition: module definitions or dedicated composition functions; avoid service locator patterns.
223
+ - **Go**
224
+ - Packages: `internal/<feature>/domain`, `application`, `ports`, `adapters/inbound`, `adapters/outbound`.
225
+ - Ports: small interfaces owned by the consuming application package.
226
+ - Use cases: structs with interface fields plus explicit `New...` constructors.
227
+ - Composition: wire in `cmd/<app>/main.go` (or dedicated wiring package), keep constructors explicit.
228
+
229
+ ## Anti-Patterns to Avoid
230
+
231
+ - Domain entities importing ORM models, web framework types, or SDK clients.
232
+ - Use cases reading directly from `req`, `res`, or queue metadata.
233
+ - Returning database rows directly from use cases without domain/application mapping.
234
+ - Letting adapters call each other directly instead of flowing through use-case ports.
235
+ - Spreading dependency wiring across many files with hidden global singletons.
236
+
237
+ ## Migration Playbook
238
+
239
+ 1. Pick one vertical slice (single endpoint/job) with frequent change pain.
240
+ 2. Extract a use-case boundary with explicit input/output types.
241
+ 3. Introduce outbound ports around existing infrastructure calls.
242
+ 4. Move orchestration logic from controllers/services into the use case.
243
+ 5. Keep old adapters, but make them delegate to the new use case.
244
+ 6. Add tests around the new boundary (unit + adapter integration).
245
+ 7. Repeat slice-by-slice; avoid full rewrites.
246
+
247
+ ### Refactoring Existing Systems
248
+
249
+ - **Strangler approach**: keep current endpoints, route one use case at a time through new ports/adapters.
250
+ - **No big-bang rewrites**: migrate per feature slice and preserve behavior with characterization tests.
251
+ - **Facade first**: wrap legacy services behind outbound ports before replacing internals.
252
+ - **Composition freeze**: centralize wiring early so new dependencies do not leak into domain/use-case layers.
253
+ - **Slice selection rule**: prioritize high-churn, low-blast-radius flows first.
254
+ - **Rollback path**: keep a reversible toggle or route switch per migrated slice until production behavior is verified.
255
+
256
+ ## Testing Guidance (Same Hexagonal Boundaries)
257
+
258
+ - **Domain tests**: test entities/value objects as pure business rules (no mocks, no framework setup).
259
+ - **Use-case unit tests**: test orchestration with fakes/stubs for outbound ports; assert business outcomes and port interactions.
260
+ - **Outbound adapter contract tests**: define shared contract suites at port level and run them against each adapter implementation.
261
+ - **Inbound adapter tests**: verify protocol mapping (HTTP/CLI/queue payload to use-case input and output/error mapping back to protocol).
262
+ - **Adapter integration tests**: run against real infrastructure (DB/API/queue) for serialization, schema/query behavior, retries, and timeouts.
263
+ - **End-to-end tests**: cover critical user journeys through inbound adapter -> use case -> outbound adapter.
264
+ - **Refactor safety**: add characterization tests before extraction; keep them until new boundary behavior is stable and equivalent.
265
+
266
+ ## Best Practices Checklist
267
+
268
+ - Domain and use-case layers import only internal types and ports.
269
+ - Every external dependency is represented by an outbound port.
270
+ - Validation occurs at boundaries (inbound adapter + use-case invariants).
271
+ - Use immutable transformations (return new values/entities instead of mutating shared state).
272
+ - Errors are translated across boundaries (infra errors -> application/domain errors).
273
+ - Composition root is explicit and easy to audit.
274
+ - Use cases are testable with simple in-memory fakes for ports.
275
+ - Refactoring starts from one vertical slice with behavior-preserving tests.
276
+ - Language/framework specifics stay in adapters, never in domain rules.
@@ -0,0 +1,211 @@
1
+ ---
2
+ name: iterative-retrieval
3
+ description: Pattern for progressively refining context retrieval to solve the subagent context problem
4
+ origin: ECC
5
+ ---
6
+
7
+ # Iterative Retrieval Pattern
8
+
9
+ Solves the "context problem" in multi-agent workflows where subagents don't know what context they need until they start working.
10
+
11
+ ## When to Activate
12
+
13
+ - Spawning subagents that need codebase context they cannot predict upfront
14
+ - Building multi-agent workflows where context is progressively refined
15
+ - Encountering "context too large" or "missing context" failures in agent tasks
16
+ - Designing RAG-like retrieval pipelines for code exploration
17
+ - Optimizing token usage in agent orchestration
18
+
19
+ ## The Problem
20
+
21
+ Subagents are spawned with limited context. They don't know:
22
+ - Which files contain relevant code
23
+ - What patterns exist in the codebase
24
+ - What terminology the project uses
25
+
26
+ Standard approaches fail:
27
+ - **Send everything**: Exceeds context limits
28
+ - **Send nothing**: Agent lacks critical information
29
+ - **Guess what's needed**: Often wrong
30
+
31
+ ## The Solution: Iterative Retrieval
32
+
33
+ A 4-phase loop that progressively refines context:
34
+
35
+ ```
36
+ ┌─────────────────────────────────────────────┐
37
+ │ │
38
+ │ ┌──────────┐ ┌──────────┐ │
39
+ │ │ DISPATCH │─────│ EVALUATE │ │
40
+ │ └──────────┘ └──────────┘ │
41
+ │ ▲ │ │
42
+ │ │ ▼ │
43
+ │ ┌──────────┐ ┌──────────┐ │
44
+ │ │ LOOP │─────│ REFINE │ │
45
+ │ └──────────┘ └──────────┘ │
46
+ │ │
47
+ │ Max 3 cycles, then proceed │
48
+ └─────────────────────────────────────────────┘
49
+ ```
50
+
51
+ ### Phase 1: DISPATCH
52
+
53
+ Initial broad query to gather candidate files:
54
+
55
+ ```javascript
56
+ // Start with high-level intent
57
+ const initialQuery = {
58
+ patterns: ['src/**/*.ts', 'lib/**/*.ts'],
59
+ keywords: ['authentication', 'user', 'session'],
60
+ excludes: ['*.test.ts', '*.spec.ts']
61
+ };
62
+
63
+ // Dispatch to retrieval agent
64
+ const candidates = await retrieveFiles(initialQuery);
65
+ ```
66
+
67
+ ### Phase 2: EVALUATE
68
+
69
+ Assess retrieved content for relevance:
70
+
71
+ ```javascript
72
+ function evaluateRelevance(files, task) {
73
+ return files.map(file => ({
74
+ path: file.path,
75
+ relevance: scoreRelevance(file.content, task),
76
+ reason: explainRelevance(file.content, task),
77
+ missingContext: identifyGaps(file.content, task)
78
+ }));
79
+ }
80
+ ```
81
+
82
+ Scoring criteria:
83
+ - **High (0.8-1.0)**: Directly implements target functionality
84
+ - **Medium (0.5-0.7)**: Contains related patterns or types
85
+ - **Low (0.2-0.4)**: Tangentially related
86
+ - **None (0-0.2)**: Not relevant, exclude
87
+
88
+ ### Phase 3: REFINE
89
+
90
+ Update search criteria based on evaluation:
91
+
92
+ ```javascript
93
+ function refineQuery(evaluation, previousQuery) {
94
+ return {
95
+ // Add new patterns discovered in high-relevance files
96
+ patterns: [...previousQuery.patterns, ...extractPatterns(evaluation)],
97
+
98
+ // Add terminology found in codebase
99
+ keywords: [...previousQuery.keywords, ...extractKeywords(evaluation)],
100
+
101
+ // Exclude confirmed irrelevant paths
102
+ excludes: [...previousQuery.excludes, ...evaluation
103
+ .filter(e => e.relevance < 0.2)
104
+ .map(e => e.path)
105
+ ],
106
+
107
+ // Target specific gaps
108
+ focusAreas: evaluation
109
+ .flatMap(e => e.missingContext)
110
+ .filter(unique)
111
+ };
112
+ }
113
+ ```
114
+
115
+ ### Phase 4: LOOP
116
+
117
+ Repeat with refined criteria (max 3 cycles):
118
+
119
+ ```javascript
120
+ async function iterativeRetrieve(task, maxCycles = 3) {
121
+ let query = createInitialQuery(task);
122
+ let bestContext = [];
123
+
124
+ for (let cycle = 0; cycle < maxCycles; cycle++) {
125
+ const candidates = await retrieveFiles(query);
126
+ const evaluation = evaluateRelevance(candidates, task);
127
+
128
+ // Check if we have sufficient context
129
+ const highRelevance = evaluation.filter(e => e.relevance >= 0.7);
130
+ if (highRelevance.length >= 3 && !hasCriticalGaps(evaluation)) {
131
+ return highRelevance;
132
+ }
133
+
134
+ // Refine and continue
135
+ query = refineQuery(evaluation, query);
136
+ bestContext = mergeContext(bestContext, highRelevance);
137
+ }
138
+
139
+ return bestContext;
140
+ }
141
+ ```
142
+
143
+ ## Practical Examples
144
+
145
+ ### Example 1: Bug Fix Context
146
+
147
+ ```
148
+ Task: "Fix the authentication token expiry bug"
149
+
150
+ Cycle 1:
151
+ DISPATCH: Search for "token", "auth", "expiry" in src/**
152
+ EVALUATE: Found auth.ts (0.9), tokens.ts (0.8), user.ts (0.3)
153
+ REFINE: Add "refresh", "jwt" keywords; exclude user.ts
154
+
155
+ Cycle 2:
156
+ DISPATCH: Search refined terms
157
+ EVALUATE: Found session-manager.ts (0.95), jwt-utils.ts (0.85)
158
+ REFINE: Sufficient context (2 high-relevance files)
159
+
160
+ Result: auth.ts, tokens.ts, session-manager.ts, jwt-utils.ts
161
+ ```
162
+
163
+ ### Example 2: Feature Implementation
164
+
165
+ ```
166
+ Task: "Add rate limiting to API endpoints"
167
+
168
+ Cycle 1:
169
+ DISPATCH: Search "rate", "limit", "api" in routes/**
170
+ EVALUATE: No matches - codebase uses "throttle" terminology
171
+ REFINE: Add "throttle", "middleware" keywords
172
+
173
+ Cycle 2:
174
+ DISPATCH: Search refined terms
175
+ EVALUATE: Found throttle.ts (0.9), middleware/index.ts (0.7)
176
+ REFINE: Need router patterns
177
+
178
+ Cycle 3:
179
+ DISPATCH: Search "router", "express" patterns
180
+ EVALUATE: Found router-setup.ts (0.8)
181
+ REFINE: Sufficient context
182
+
183
+ Result: throttle.ts, middleware/index.ts, router-setup.ts
184
+ ```
185
+
186
+ ## Integration with Agents
187
+
188
+ Use in agent prompts:
189
+
190
+ ```markdown
191
+ When retrieving context for this task:
192
+ 1. Start with broad keyword search
193
+ 2. Evaluate each file's relevance (0-1 scale)
194
+ 3. Identify what context is still missing
195
+ 4. Refine search criteria and repeat (max 3 cycles)
196
+ 5. Return files with relevance >= 0.7
197
+ ```
198
+
199
+ ## Best Practices
200
+
201
+ 1. **Start broad, narrow progressively** - Don't over-specify initial queries
202
+ 2. **Learn codebase terminology** - First cycle often reveals naming conventions
203
+ 3. **Track what's missing** - Explicit gap identification drives refinement
204
+ 4. **Stop at "good enough"** - 3 high-relevance files beats 10 mediocre ones
205
+ 5. **Exclude confidently** - Low-relevance files won't become relevant
206
+
207
+ ## Related
208
+
209
+ - [The Longform Guide](https://x.com/affaanmustafa/status/2014040193557471352) - Subagent orchestration section
210
+ - `continuous-learning` skill - For patterns that improve over time
211
+ - Agent definitions bundled with ECC (manual install path: `agents/`)