@nebutra/next-unicorn-skill 1.0.4 → 1.0.5

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/README.md CHANGED
@@ -11,7 +11,7 @@
11
11
  <a href="https://www.npmjs.com/package/@nebutra/next-unicorn-skill"><img src="https://img.shields.io/npm/v/@nebutra/next-unicorn-skill.svg?color=blue" alt="npm version" /></a>
12
12
  <a href="./LICENSE"><img src="https://img.shields.io/badge/license-MIT-green.svg" alt="License" /></a>
13
13
  <a href="https://www.typescriptlang.org/"><img src="https://img.shields.io/badge/TypeScript-strict-blue.svg" alt="TypeScript" /></a>
14
- <a href="./tests/"><img src="https://img.shields.io/badge/tests-198%20passed-brightgreen.svg" alt="Tests" /></a>
14
+ <a href="./tests/"><img src="https://img.shields.io/badge/tests-210%20passed-brightgreen.svg" alt="Tests" /></a>
15
15
  <a href="./tests/"><img src="https://img.shields.io/badge/properties-29%20verified-purple.svg" alt="Property Tests" /></a>
16
16
  </p>
17
17
 
@@ -31,9 +31,9 @@
31
31
 
32
32
  Every codebase accumulates hand-rolled implementations that should be mature libraries. Custom date formatters, DIY loggers, bespoke state machines, ad-hoc i18n — **Vibe Coding debt**.
33
33
 
34
- Snyk, Dependabot, and Renovate manage your *existing* dependencies. They can't find code you wrote that *should become* a dependency.
34
+ Snyk, Dependabot, and Renovate manage your *existing* dependencies. They can't find code you wrote that *should become* a dependency — or capabilities your project is *missing entirely*.
35
35
 
36
- **Next-Unicorn does both** — and verifies every recommendation against real documentation via [Context7 MCP](https://context7.com).
36
+ **Next-Unicorn does all three** — replacement, gap analysis, and dependency management verified against real documentation via [Context7 MCP](https://context7.com).
37
37
 
38
38
  ## Quick Start
39
39
 
@@ -61,18 +61,36 @@ npm install @nebutra/next-unicorn-skill
61
61
 
62
62
  ```typescript
63
63
  import { analyze, scanCodebase } from '@nebutra/next-unicorn-skill';
64
- import type { Recommender } from '@nebutra/next-unicorn-skill';
65
-
66
- // The recommender function: AI agent decides which library fits each detection
67
- const recommender: Recommender = (detection) => {
68
- // AI agent uses its knowledge + project context to recommend
69
- // Return null to skip a detection (false positive, intentional custom code)
70
- return {
71
- library: 'zustand', // dynamically chosen, not hardcoded
72
- version: '^5.0.0', // verified via Context7
73
- license: 'MIT',
74
- };
75
- };
64
+ import type { Recommender, GapRecommendation } from '@nebutra/next-unicorn-skill';
65
+
66
+ // The recommender: AI agent decides which library fits each detection
67
+ const recommender: Recommender = (detection) => ({
68
+ library: '@lingui/core',
69
+ version: '^4.0.0',
70
+ license: 'MIT',
71
+ rationale: 'Compile-time i18n with near-zero runtime overhead',
72
+ ecosystem: [
73
+ { library: '@lingui/macro', version: '^4.0.0', role: 'Tagged templates' },
74
+ { library: '@lingui/cli', version: '^4.0.0', role: 'CI message extraction' },
75
+ ],
76
+ antiPatterns: ['Avoid i18next if bundle size matters — Lingui compiles away'],
77
+ alternatives: [
78
+ { library: 'next-intl', when: 'Next.js App Router with server components' },
79
+ ],
80
+ });
81
+
82
+ // Gap analysis: capabilities the project should have but doesn't
83
+ const gaps: GapRecommendation[] = [
84
+ {
85
+ domain: 'observability',
86
+ description: 'No structured logging detected',
87
+ recommendedLibrary: {
88
+ name: 'pino', version: '^9.0.0', license: 'MIT',
89
+ rationale: 'Fastest Node.js JSON logger with redaction and child loggers',
90
+ },
91
+ priority: 'critical',
92
+ },
93
+ ];
76
94
 
77
95
  const result = await analyze({
78
96
  input: {
@@ -83,27 +101,22 @@ const result = await analyze({
83
101
  currentLibraries: { react: '18.2.0', next: '14.1.0' },
84
102
  },
85
103
  optimizationGoals: ['reduce custom code', 'improve maintainability'],
86
- constraints: {
87
- licenseAllowlist: ['MIT', 'Apache-2.0', 'ISC'],
88
- },
104
+ constraints: { licenseAllowlist: ['MIT', 'Apache-2.0', 'ISC'] },
89
105
  priorityFocusAreas: ['i18n', 'observability', 'auth-security'],
90
106
  },
91
107
  context7Client: myContext7Client,
92
- recommender, // AI agent provides library recommendations
93
- // Optional Phase 2 clients:
94
- vulnClient: myOsvClient, // vulnerability scanning
95
- registryClient: myRegistryClient, // auto-update
96
- platformClient: myGitHubClient, // PR creation
97
- gitOps: myGitOperations, // PR creation
108
+ recommender,
109
+ gaps,
98
110
  });
99
111
 
100
112
  if (result.success) {
101
113
  console.log(result.prettyJson);
102
- // result.scanResult contains raw detections for further AI analysis
114
+ // result.scanResult raw detections + structural findings for AI analysis
115
+ // result.output.gapAnalysis — Context7-verified gap recommendations
103
116
  }
104
117
  ```
105
118
 
106
- Or use as an **MCP SKILL** — provide [`SKILL.md`](./SKILL.md) to your AI agent (Claude Code, Kiro, etc.).
119
+ Or use as an **MCP SKILL** — provide [`SKILL.md`](./SKILL.md) to your AI agent (Claude Code, Kiro, Cursor, etc.).
107
120
 
108
121
  ## Features
109
122
 
@@ -111,17 +124,19 @@ Or use as an **MCP SKILL** — provide [`SKILL.md`](./SKILL.md) to your AI agent
111
124
 
112
125
  | Feature | Description |
113
126
  |---------|-------------|
114
- | **Pattern-based scanning** | Detects hand-rolled code across 68 Vibe Coding Domains (ISO 25010-aligned) |
115
- | **Gap analysis** | AI agent identifies missing capabilities — not just hand-rolled code, but things you should have but don't (e.g., no error monitoring, no rate limiting, no event-driven workflows) |
116
- | **Ecosystem-level recommendations** | Solutions include rationale, companion packages, anti-patterns, and alternatives not just "use library X" |
117
- | **Context7 verification** | Every recommendation verified against real, version-correct documentation |
127
+ | **Pattern-based scanning** | Detects hand-rolled code across 30 domains with 40+ regex patterns (design-system, auth, state-management, etc.) |
128
+ | **Structural analysis** | Detects monorepo architecture gaps: missing token layers, dependency flow violations, hardcoded config values |
129
+ | **Gap analysis** | AI agent identifies missing capabilities — not just hand-rolled code, but things you should have but don't |
130
+ | **Ecosystem-level recommendations** | Solutions include rationale, companion packages, anti-patterns, and alternatives |
131
+ | **Context7 verification** | Every recommendation (replacements AND gaps) verified with exponential backoff retry |
118
132
  | **7-dimension impact scoring** | Scalability, performance, security, maintainability, feature richness, UX, UI aesthetics |
119
133
  | **Phased migration plans** | Low / medium / high risk phases with adapter strategies |
120
134
  | **Deletion checklists** | Every file and line range to remove, with estimated lines saved |
121
135
  | **UX completeness audit** | A11y, error/empty/loading states, form validation, design system alignment |
136
+ | **Design system support** | Two paths: scaffold from reference repos (Primer, Polaris, Supabase, Dub) or extract from existing code |
122
137
  | **Monorepo support** | Detects npm, pip, cargo, go workspaces independently |
123
138
 
124
- ### Dependency Management (v2.0)
139
+ ### Dependency Management
125
140
 
126
141
  | Feature | Description |
127
142
  |---------|-------------|
@@ -133,13 +148,14 @@ Or use as an **MCP SKILL** — provide [`SKILL.md`](./SKILL.md) to your AI agent
133
148
  ## How It Works
134
149
 
135
150
  ```
136
- Input ─> Validator ─> Scanner ─> Recommender (AI Agent) ─> Context7 Verifier
151
+ Input ─> Validator ─> Scanner + Structure Analyzer
152
+ ─> Gap Analysis (AI Agent) ─> Recommender (AI Agent) ─> Context7 Verifier
137
153
  ─> Impact Scorer ─> Conflict Detection ─> Vuln Scanner ─> License Filter
138
154
  ─> Migration Planner ─> UX Auditor ─> Auto-Updater
139
155
  ─> Serializer ─> PR Creator ─> Output
140
156
  ```
141
157
 
142
- **Key architecture**: The scanner detects WHAT is hand-rolled; the **Recommender** (AI agent or caller) decides WHAT library to use. No library recommendations are hardcoded — they are provided dynamically based on project context, ecosystem knowledge, and Context7 verification.
158
+ **Key architecture**: The scanner detects WHAT is hand-rolled; the structure analyzer detects architectural gaps; the **Recommender** (AI agent or caller) decides WHAT to use. No library recommendations are hardcoded — they are provided dynamically based on project context, ecosystem knowledge, and Context7 verification.
143
159
 
144
160
  Each stage is a pure function with structured I/O. All external dependencies (Context7, OSV, npm registry, GitHub API) are **injected via interfaces** for testability.
145
161
 
@@ -166,14 +182,14 @@ function t(key, locale) {
166
182
  <td>
167
183
 
168
184
  ```tsx
169
- // next-intl — Context7 verified, MIT
170
- // Impact: 9.2/10 composite
171
- // Migration risk: low | Effort: 8h
172
- import { useTranslations } from 'next-intl';
185
+ // @lingui/core — Context7 verified, MIT
186
+ // Ecosystem: @lingui/macro + @lingui/cli
187
+ // Impact: 9.2/10 | Risk: low | Effort: 8h
188
+ import { useLingui } from '@lingui/react';
173
189
 
174
190
  export default function Page() {
175
- const t = useTranslations('common');
176
- return <h1>{t('greeting')}</h1>;
191
+ const { t } = useLingui();
192
+ return <h1>{t`greeting`}</h1>;
177
193
  }
178
194
  ```
179
195
 
@@ -199,8 +215,8 @@ function logRequest(req) {
199
215
 
200
216
  ```typescript
201
217
  // pino — Context7 verified, MIT
202
- // Impact: 9.0/10 composite
203
- // Migration risk: low | Effort: 4h
218
+ // Gap analysis: "No structured logging detected"
219
+ // Priority: critical
204
220
  import pino from 'pino';
205
221
  const logger = pino({
206
222
  level: 'info',
@@ -217,11 +233,15 @@ const logger = pino({
217
233
  | Feature | Next-Unicorn | Snyk | Dependabot | Renovate |
218
234
  |---------|:---:|:---:|:---:|:---:|
219
235
  | Finds hand-rolled code to replace | **Yes** | | | |
236
+ | Identifies missing capabilities (gaps) | **Yes** | | | |
237
+ | Structural architecture analysis | **Yes** | | | |
220
238
  | Recommends new libraries | **Yes** | | | |
239
+ | Ecosystem-level solutions | **Yes** | | | |
221
240
  | 7-dimension impact scoring | **Yes** | | | |
222
241
  | Context7 doc verification | **Yes** | | | |
223
242
  | Phased migration plans | **Yes** | | | |
224
243
  | UX completeness audit | **Yes** | | | |
244
+ | Design system scaffold/extraction | **Yes** | | | |
225
245
  | Deletion checklists | **Yes** | | | |
226
246
  | Vulnerability scanning | **Yes** | Yes | Yes | |
227
247
  | Scans *recommended* libs for vulns | **Yes** | | | |
@@ -249,14 +269,18 @@ const logger = pino({
249
269
 
250
270
  ### `scanCodebase(input): Promise<ScanResult>`
251
271
 
252
- Standalone scanner — returns detections and workspace info without recommendations. AI agents can call this first, then provide recommendations via the `Recommender` callback.
272
+ Standalone scanner — returns detections, workspace info, and structural findings (design system layer analysis, dependency flow violations). AI agents can call this first, then provide recommendations via the `Recommender` callback.
273
+
274
+ ### `analyzeStructure(repoPath, workspaces): StructuralAnalysis`
275
+
276
+ Standalone structure analyzer — detects missing design system layers, dependency flow violations, hardcoded config values, and missing shared presets in monorepos.
253
277
 
254
278
  ### Output Structure
255
279
 
256
280
  ```jsonc
257
281
  {
258
282
  "recommendedChanges": [...], // Replacement recommendations with impact scores
259
- "gapAnalysis": [...], // (optional) Missing capabilities with prioritized recs
283
+ "gapAnalysis": [...], // (optional) Context7-verified gap recommendations
260
284
  "filesToDelete": [...], // Files to remove after migration
261
285
  "linesSavedEstimate": 1250, // Total lines saved
262
286
  "uxAudit": [...], // UX completeness (8 categories)
@@ -272,16 +296,16 @@ Standalone scanner — returns detections and workspace info without recommendat
272
296
 
273
297
  ## Vibe Coding Domains
274
298
 
275
- 68 domains across 11 categories, aligned with ISO/IEC 25010:
299
+ 68 domains across 11 categories, aligned with ISO/IEC 25010. 30 domains have scanner patterns; the rest are covered by AI agent gap analysis.
276
300
 
277
301
  | Category | Count | Examples |
278
302
  |----------|:-----:|---------|
279
- | UX / Design | 14 | `ux-completeness`, `a11y-accessibility`, `forms-ux`, `design-system` |
303
+ | UX / Design | 14 | `design-system`, `a11y-accessibility`, `forms-ux`, `empty-loading-error-states` |
280
304
  | SEO / i18n | 5 | `seo`, `i18n`, `content-marketing` |
281
305
  | Growth / Data | 7 | `analytics-tracking`, `ab-testing-experimentation` |
282
- | Frontend Arch | 8 | `state-management`, `data-fetching-caching`, `agent-architecture` |
283
- | Backend / Platform | 8 | `database-orm-migrations`, `jobs-queue-scheduler`, `feature-flags-config` |
284
- | Security | 5 | `auth-security`, `permissions-rbac-ux`, `fraud-abuse-prevention` |
306
+ | Frontend Arch | 8 | `state-management`, `data-fetching-caching`, `realtime-collaboration` |
307
+ | Backend / Platform | 8 | `database-orm-migrations`, `caching-rate-limit`, `feature-flags-config` |
308
+ | Security | 5 | `auth-security`, `security-hardening`, `fraud-abuse-prevention` |
285
309
  | Observability | 4 | `logging-tracing-metrics`, `error-monitoring` |
286
310
  | Delivery / DevEx | 6 | `testing-strategy`, `ci-cd-release`, `dependency-management` |
287
311
  | Performance | 3 | `performance-web-vitals`, `cost-optimization` |
@@ -293,7 +317,7 @@ Standalone scanner — returns detections and workspace info without recommendat
293
317
  ## Testing
294
318
 
295
319
  ```bash
296
- pnpm test # 198 tests (vitest + fast-check)
320
+ pnpm test # 210 tests (vitest + fast-check)
297
321
  pnpm typecheck # TypeScript strict mode
298
322
  pnpm build # Compile to dist/
299
323
  ```
@@ -330,6 +354,13 @@ pnpm build # Compile to dist/
330
354
  | [`update-plan.md`](./templates/update-plan.md) | Dependency update plan |
331
355
  | [`prd-template.md`](./templates/prd-template.md) | PRD for stakeholder presentation |
332
356
 
357
+ ## References
358
+
359
+ | Reference | Purpose |
360
+ |-----------|---------|
361
+ | [`design-system-sources.md`](./references/design-system-sources.md) | 25+ curated design system repos for scaffolding (Primer, Polaris, Dub, Supabase, etc.) |
362
+ | [`design-system-extraction.md`](./references/design-system-extraction.md) | Workflow for extracting a design system from existing code (6 principles, 5 phases) |
363
+
333
364
  ## Contributing
334
365
 
335
366
  See [CONTRIBUTING.md](./CONTRIBUTING.md) for development setup, architecture overview, and contribution guidelines.
@@ -340,8 +371,8 @@ Releases are automated via GitHub Actions:
340
371
 
341
372
  ```bash
342
373
  # Tag a new version
343
- git tag v2.0.0
344
- git push origin v2.0.0
374
+ git tag v1.0.5
375
+ git push origin v1.0.5
345
376
  # → CI runs tests → creates GitHub Release → publishes to npmjs + GitHub Packages
346
377
  ```
347
378
 
package/dist/index.d.ts CHANGED
@@ -18,7 +18,7 @@ import type { VulnerabilityClient } from './security/osv-client.js';
18
18
  import type { RegistryClient } from './updater/registry-client.js';
19
19
  import type { PlatformClient } from './pr-creator/platform-client.js';
20
20
  import type { GitOperations } from './pr-creator/git-operations.js';
21
- export declare const VERSION = "1.0.4";
21
+ export declare const VERSION = "1.0.5";
22
22
  /**
23
23
  * A library recommendation provided by the AI agent (or caller).
24
24
  * The scanner detects WHAT is hand-rolled; the recommender decides WHAT to use.
package/dist/index.js CHANGED
@@ -29,7 +29,7 @@ import { executePRPlans } from './pr-creator/pr-executor.js';
29
29
  // ---------------------------------------------------------------------------
30
30
  // Version
31
31
  // ---------------------------------------------------------------------------
32
- export const VERSION = '1.0.4';
32
+ export const VERSION = '1.0.5';
33
33
  export { analyzeStructure } from './analyzer/structure-analyzer.js';
34
34
  export { scanCodebase } from './analyzer/scanner.js';
35
35
  export { getPatternCatalog } from './analyzer/pattern-catalog.js';
@@ -11,11 +11,27 @@ export interface VerificationResult {
11
11
  /**
12
12
  * Client interface for Context7 MCP integration.
13
13
  * Designed for easy mocking in tests — the real implementation calls
14
- * Context7 MCP tools (`resolve-library-id` and `get-library-docs`).
14
+ * Context7 MCP tools (`resolve-library-id` and `query-docs`).
15
+ *
16
+ * Per Context7 best practices:
17
+ * - resolveLibraryId accepts both query (for ranking) and libraryName
18
+ * - getLibraryDocs accepts libraryId and query
19
+ * - Implementations should handle 202 (processing), 301 (redirect), 429 (rate limit)
15
20
  */
16
21
  export interface Context7Client {
17
- resolveLibraryId(libraryName: string): Promise<string | null>;
18
- getLibraryDocs(libraryId: string, useCase: string): Promise<{
22
+ /**
23
+ * Resolve a library name to a Context7-compatible library ID.
24
+ * @param libraryName — the library to search for
25
+ * @param query — the user's question/task (used by Context7 to rank results)
26
+ * @returns library ID string, or null if not found
27
+ */
28
+ resolveLibraryId(libraryName: string, query?: string): Promise<string | null>;
29
+ /**
30
+ * Fetch documentation for a library by its Context7 ID.
31
+ * @param libraryId — Context7-compatible library ID (e.g., "/vercel/next.js")
32
+ * @param query — the question/task to get relevant docs for
33
+ */
34
+ getLibraryDocs(libraryId: string, query: string): Promise<{
19
35
  url: string;
20
36
  version: string;
21
37
  } | null>;
@@ -25,14 +41,14 @@ export interface Context7Client {
25
41
  *
26
42
  * Flow:
27
43
  * 1. Call `resolveLibraryId` to get the canonical library ID.
28
- * - If it returns `null` → status "unverified" (library not found).
29
- * - If it throws → retry once. If still failing status "unavailable".
44
+ * - If it returns `null` → status "unverified" (library not found / 404).
45
+ * - If it throws → retry with exponential backoff (handles 429, 202, 5xx).
46
+ * - After max retries → status "unavailable".
30
47
  * 2. Call `getLibraryDocs` with the library ID and use case.
31
48
  * - If it returns docs → status "verified" with URL and version.
32
49
  * - If it returns `null` → status "unverified" (use case not confirmed).
33
- * - If it throws → retry once. If still failing → status "unavailable".
34
- *
35
- * Requirements: 2.1, 2.2, 2.3, 2.4, 2.5, 9.5
50
+ * - If it throws → retry with exponential backoff.
51
+ * - After max retries → status "unavailable".
36
52
  */
37
53
  export declare function verifyRecommendation(client: Context7Client, libraryName: string, useCase: string): Promise<VerificationResult>;
38
54
  /**
@@ -52,8 +68,6 @@ export interface VerificationItem {
52
68
  *
53
69
  * Processes each item independently — a failure for one library does
54
70
  * not affect others. Returns a Map keyed by detection index.
55
- *
56
- * Requirements: 2.1, 2.2, 2.3, 2.4, 2.5, 9.5
57
71
  */
58
72
  export declare function verifyAllRecommendations(client: Context7Client, items: Array<VerificationItem | null>): Promise<Map<number, VerificationResult>>;
59
73
  //# sourceMappingURL=context7.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"context7.d.ts","sourceRoot":"","sources":["../../src/verifier/context7.ts"],"names":[],"mappings":"AAMA;;GAEG;AACH,MAAM,WAAW,kBAAkB;IACjC,MAAM,EAAE,UAAU,GAAG,YAAY,GAAG,aAAa,CAAC;IAClD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED;;;;GAIG;AACH,MAAM,WAAW,cAAc;IAC7B,gBAAgB,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IAC9D,cAAc,CACZ,SAAS,EAAE,MAAM,EACjB,OAAO,EAAE,MAAM,GACd,OAAO,CAAC;QAAE,GAAG,EA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AAuBD;;;;;;;;;;;;;GAaG;AACH,wBAAsB,oBAAoB,CACxC,MAAM,EAAE,cAAc,EACtB,WAAW,EAAE,MAAM,EACnB,OAAO,EAAE,MAAM,GACd,OAAO,CAAC,kBAAkB,CAAC,CAoD7B;AAuCD;;;;GAIG;AACH,MAAM,WAAW,gBAAgB;IAC/B,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,MAAM,CAAC;CACjB;AAED;;;;;;;;GAQG;AACH,wBAAsB,wBAAwB,CAC5C,MAAM,EAAE,cAAc,EACtB,KAAK,EAAE,KAAK,CAAC,gBAAgB,GAAG,IAAI,CAAC,GACpC,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,kBAAkB,CAAC,CAAC,CAe1C"}
@@ -1,38 +1,47 @@
1
- // No longer depends on Detection — recommendations come from the AI agent
2
1
  // ---------------------------------------------------------------------------
3
- // Single recommendation verification (with retry-once logic)
2
+ // Public interfaces
3
+ // ---------------------------------------------------------------------------
4
+ // ---------------------------------------------------------------------------
5
+ // Retry configuration
6
+ // ---------------------------------------------------------------------------
7
+ /** Maximum retry attempts (Context7 best practice: 3) */
8
+ const MAX_RETRIES = 3;
9
+ /** Base delay for exponential backoff in ms */
10
+ const BASE_DELAY_MS = 1000;
11
+ /**
12
+ * Sleep for a given number of milliseconds.
13
+ */
14
+ function sleep(ms) {
15
+ return new Promise((resolve) => setTimeout(resolve, ms));
16
+ }
17
+ // ---------------------------------------------------------------------------
18
+ // Single recommendation verification (with exponential backoff retry)
4
19
  // ---------------------------------------------------------------------------
5
20
  /**
6
21
  * Verify a single library recommendation against Context7 MCP.
7
22
  *
8
23
  * Flow:
9
24
  * 1. Call `resolveLibraryId` to get the canonical library ID.
10
- * - If it returns `null` → status "unverified" (library not found).
11
- * - If it throws → retry once. If still failing status "unavailable".
25
+ * - If it returns `null` → status "unverified" (library not found / 404).
26
+ * - If it throws → retry with exponential backoff (handles 429, 202, 5xx).
27
+ * - After max retries → status "unavailable".
12
28
  * 2. Call `getLibraryDocs` with the library ID and use case.
13
29
  * - If it returns docs → status "verified" with URL and version.
14
30
  * - If it returns `null` → status "unverified" (use case not confirmed).
15
- * - If it throws → retry once. If still failing → status "unavailable".
16
- *
17
- * Requirements: 2.1, 2.2, 2.3, 2.4, 2.5, 9.5
31
+ * - If it throws → retry with exponential backoff.
32
+ * - After max retries → status "unavailable".
18
33
  */
19
34
  export async function verifyRecommendation(client, libraryName, useCase) {
20
- // Step 1: Resolve library ID (with retry-once on failure)
35
+ // Step 1: Resolve library ID (with exponential backoff)
21
36
  let libraryId;
22
37
  try {
23
- libraryId = await client.resolveLibraryId(libraryName);
38
+ libraryId = await retryWithBackoff(() => client.resolveLibraryId(libraryName, useCase));
24
39
  }
25
40
  catch {
26
- // Retry once
27
- try {
28
- libraryId = await client.resolveLibraryId(libraryName);
29
- }
30
- catch {
31
- return {
32
- status: 'unavailable',
33
- note: `Context7 service error resolving library "${libraryName}" after retry`,
34
- };
35
- }
41
+ return {
42
+ status: 'unavailable',
43
+ note: `Context7 service error resolving library "${libraryName}" after ${MAX_RETRIES} retries`,
44
+ };
36
45
  }
37
46
  // Library not found in Context7
38
47
  if (libraryId === null) {
@@ -41,23 +50,17 @@ export async function verifyRecommendation(client, libraryName, useCase) {
41
50
  note: `Library "${libraryName}" not found in Context7`,
42
51
  };
43
52
  }
44
- // Step 2: Get library docs (with retry-once on failure)
53
+ // Step 2: Get library docs (with exponential backoff)
45
54
  let docs;
46
55
  try {
47
- docs = await client.getLibraryDocs(libraryId, useCase);
56
+ docs = await retryWithBackoff(() => client.getLibraryDocs(libraryId, useCase));
48
57
  }
49
58
  catch {
50
- // Retry once
51
- try {
52
- docs = await client.getLibraryDocs(libraryId, useCase);
53
- }
54
- catch {
55
- return {
56
- status: 'unavailable',
57
- libraryId,
58
- note: `Context7 service error fetching docs for "${libraryName}" after retry`,
59
- };
60
- }
59
+ return {
60
+ status: 'unavailable',
61
+ libraryId,
62
+ note: `Context7 service error fetching docs for "${libraryName}" after ${MAX_RETRIES} retries`,
63
+ };
61
64
  }
62
65
  // Use case not confirmed by documentation
63
66
  if (docs === null) {
@@ -75,6 +78,34 @@ export async function verifyRecommendation(client, libraryName, useCase) {
75
78
  version: docs.version,
76
79
  };
77
80
  }
81
+ // ---------------------------------------------------------------------------
82
+ // Retry with exponential backoff
83
+ // ---------------------------------------------------------------------------
84
+ /**
85
+ * Retry a function with exponential backoff.
86
+ * Delay: BASE_DELAY_MS * 2^attempt (1s, 2s, 4s for 3 attempts).
87
+ *
88
+ * Per Context7 best practices:
89
+ * - 429 (rate limit): exponential backoff
90
+ * - 202 (processing): wait and retry
91
+ * - 5xx (server error): retry with backoff
92
+ */
93
+ async function retryWithBackoff(fn) {
94
+ let lastError;
95
+ for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
96
+ try {
97
+ return await fn();
98
+ }
99
+ catch (error) {
100
+ lastError = error;
101
+ if (attempt < MAX_RETRIES - 1) {
102
+ const delay = BASE_DELAY_MS * Math.pow(2, attempt);
103
+ await sleep(delay);
104
+ }
105
+ }
106
+ }
107
+ throw lastError;
108
+ }
78
109
  /**
79
110
  * Verify all library recommendations provided by the AI agent (or caller).
80
111
  *
@@ -83,8 +114,6 @@ export async function verifyRecommendation(client, libraryName, useCase) {
83
114
  *
84
115
  * Processes each item independently — a failure for one library does
85
116
  * not affect others. Returns a Map keyed by detection index.
86
- *
87
- * Requirements: 2.1, 2.2, 2.3, 2.4, 2.5, 9.5
88
117
  */
89
118
  export async function verifyAllRecommendations(client, items) {
90
119
  const results = new Map();
@@ -1 +1 @@
1
- {"version":3,"file":"context7.js","sourceRoot":"","sources":["../../src/verifier/context7.ts"],"names":[],"mappings":"AAAA,0EAA0E;AA8B1E,8EAA8E;AAC9E,6DAA6D;AAC7D,8EAA8E;AAE9E;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACxC,MAAsB,EACtB,WAAmB,EACnB,OAAe;IAEf,0DAA0D;IAC1D,IAAI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G,CAAC,EAAE,OAAO,GAAG,WAAW,EAAE,OAAO,EAAE,EAAE,CAAC;QACvD,IAAI,CAAC;YACH,OAAO,MAAM,EAAE,EAAE,CAAC;QACpB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,SAAS,GAAG,KAAK,CAAC;YAClB,IAAI,OAAO,GAAG,WAAW,GAAG,CAAC,EAAE,CAAC;gBAC9B,MAAM,KAAK,GAAG,aAAa,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC;gBACnD,MAAM,KAAK,CAAC,KAAK,CAAC,CAAC;YACrB,CAAC;QACH,CAAC;IACH,CAAC;IAED,MAAM,SAAS,CAAC;AAClB,CAAC;AAgBD;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAC5C,MAAsB,EACtB,KAAqC;IAErC,MAAM,OAAO,GAAG,IAAI,GAAG,EAA8B,CAAC;IAEtD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACtC,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;QACtB,IAAI,CAAC,IAAI;YAAE,SAAS;QACpB,MAAM,MAAM,GAAG,MAAM,oBAAoB,CACvC,MAAM,EACN,IAAI,CAAC,WAAW,EAChB,IAAI,CAAC,OAAO,CACb,CAAC;QACF,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;IACzB,CAAC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nebutra/next-unicorn-skill",
3
- "version": "1.0.4",
3
+ "version": "1.0.5",
4
4
  "description": "Stop Vibe Coding debt: audit your codebase, replace reinvented wheels with unicorn-grade libraries, scan vulnerabilities, auto-update deps, and auto-create PRs — all verified via Context7 MCP.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",