Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions apps/web/src/app/api/raw-skill/[owner]/[repo]/[skill]/route.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { NextRequest, NextResponse } from "next/server";
import { getDb } from "@/lib/db";
import { skills, repos } from "@skillshub/db/schema";
import { skills, repos, skillEvents } from "@skillshub/db/schema";
import { eq, and, sql } from "drizzle-orm";

export async function GET(
Expand All @@ -11,7 +11,7 @@ export async function GET(
const db = getDb();

const [row] = await db
.select({ readme: skills.readme })
.select({ id: skills.id, readme: skills.readme })
.from(skills)
.innerJoin(repos, eq(skills.repoId, repos.id))
.where(
Expand All @@ -37,7 +37,19 @@ export async function GET(
)
)
.execute()
.catch(() => {});
.catch((err: unknown) => console.error("fetch tracking failed:", err));

// Increment fetch count on the skill and log event (fire and forget)
db.update(skills)
.set({ fetchCount: sql`${skills.fetchCount} + 1` })
.where(eq(skills.id, row.id))
.execute()
.catch((err: unknown) => console.error("fetch tracking failed:", err));

db.insert(skillEvents)
.values({ eventType: "fetch", skillId: row.id })
.execute()
.catch((err: unknown) => console.error("fetch tracking failed:", err));

return new NextResponse(row.readme, {
headers: { "content-type": "text/markdown; charset=utf-8" },
Expand Down
20 changes: 20 additions & 0 deletions apps/web/src/app/api/v1/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,16 @@ export async function GET() {
endpoint: `${BASE_URL}/api/v1/skills/{id}`,
description: "Full skill detail by UUID",
},
skill_stats: {
endpoint: `${BASE_URL}/api/v1/skills/{id}/stats`,
method: "GET",
description: "Public trust stats: fetchCount, feedbackCount, helpfulRate, trustScore. No auth required.",
},
skill_feedback: {
endpoint: `${BASE_URL}/api/v1/skills/{id}/feedback`,
method: "GET",
description: "Public feedback summary with recent entries. No auth required.",
},
agent_profile: {
endpoint: `${BASE_URL}/api/v1/agents/{id}`,
method: "GET",
Expand Down Expand Up @@ -162,6 +172,16 @@ export async function GET() {
method: "POST",
endpoint: `${BASE_URL}/api/v1/skills/{id}/star`,
},
submit_feedback: {
method: "POST",
endpoint: `${BASE_URL}/api/v1/skills/{id}/feedback`,
body: {
task: "string (required) — what you were trying to do, max 500 chars",
helpful: "boolean (required) — was this skill helpful?",
context: "'resolve' | 'search' | 'direct' (optional) — how you found the skill",
},
note: "One feedback per agent per skill per day. Submitting again updates the existing entry.",
},
my_profile: {
method: "GET",
endpoint: `${BASE_URL}/api/v1/agents/me`,
Expand Down
156 changes: 156 additions & 0 deletions apps/web/src/app/api/v1/skills/[id]/feedback/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import { getDb } from "@/lib/db";
import { corsJson, OPTIONS as corsOptions, formatZodError } from "@/lib/api-cors";
import { authenticateApiKey, isAuthError } from "@/lib/api-key-auth";
import { skills, skillFeedback } from "@skillshub/db/schema";
import { eq, sql, desc } from "drizzle-orm";
import { z } from "zod";

const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

const feedbackSchema = z.object({
task: z.string().min(1).max(500),
helpful: z.boolean(),
context: z.enum(["resolve", "search", "direct"]).optional(),
});

export async function POST(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = await authenticateApiKey(request);
if (isAuthError(auth)) return auth;

const { id } = await params;

if (!UUID_RE.test(id)) {
return corsJson(
{ error: { code: "VALIDATION_ERROR", message: "Invalid skill ID format" } },
{ status: 400 }
);
}

let body: unknown;
try {
body = await request.json();
} catch {
return corsJson(
{ error: { code: "VALIDATION_ERROR", message: "Invalid JSON body" } },
{ status: 400 }
);
}

const parsed = feedbackSchema.safeParse(body);
if (!parsed.success) {
return corsJson(
{ error: { code: "VALIDATION_ERROR", message: formatZodError(parsed.error) } },
{ status: 400 }
);
}

const db = getDb();

// Check skill exists
const [skill] = await db
.select({ id: skills.id })
.from(skills)
.where(eq(skills.id, id))
.limit(1);

if (!skill) {
return corsJson(
{ error: { code: "NOT_FOUND", message: "Skill not found" } },
{ status: 404 }
);
}

const { task, helpful, context } = parsed.data;

// Upsert: insert or update if same agent already left feedback today
await db.execute(sql`
INSERT INTO skill_feedback (id, skill_id, agent_id, task, helpful, context)
VALUES (gen_random_uuid(), ${id}, ${auth.userId}, ${task}, ${helpful}, ${context ?? null})
ON CONFLICT (skill_id, agent_id, (created_at::date))
DO UPDATE SET task = EXCLUDED.task, helpful = EXCLUDED.helpful, context = EXCLUDED.context, created_at = NOW()
`);

// Recompute feedback stats for this skill
const [stats] = await db
.select({
totalFeedback: sql<number>`count(*)::int`,
helpfulCount: sql<number>`count(*) filter (where ${skillFeedback.helpful} = true)::int`,
})
.from(skillFeedback)
.where(eq(skillFeedback.skillId, id));

const totalFeedback = stats?.totalFeedback ?? 0;
const helpfulRate =
totalFeedback > 0
? Math.round((stats.helpfulCount / totalFeedback) * 100) / 100
: null;

// Update skill stats
await db
.update(skills)
.set({
feedbackCount: totalFeedback,
helpfulRate: helpfulRate !== null ? String(helpfulRate) : null,
})
.where(eq(skills.id, id));

return corsJson({
recorded: true,
stats: { helpfulRate, totalFeedback },
});
}

export async function GET(
_request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params;

if (!UUID_RE.test(id)) {
return corsJson(
{ error: { code: "NOT_FOUND", message: "Skill not found" } },
{ status: 404 }
);
}

const db = getDb();

const [skill] = await db
.select({
helpfulRate: skills.helpfulRate,
feedbackCount: skills.feedbackCount,
})
.from(skills)
.where(eq(skills.id, id))
.limit(1);

if (!skill) {
return corsJson(
{ error: { code: "NOT_FOUND", message: "Skill not found" } },
{ status: 404 }
);
}

const recentFeedback = await db
.select({
task: skillFeedback.task,
helpful: skillFeedback.helpful,
context: skillFeedback.context,
createdAt: skillFeedback.createdAt,
})
.from(skillFeedback)
.where(eq(skillFeedback.skillId, id))
.orderBy(desc(skillFeedback.createdAt))
.limit(5);

return corsJson({
helpfulRate: skill.helpfulRate !== null ? Number(skill.helpfulRate) : null,
totalFeedback: skill.feedbackCount,
recentFeedback,
});
}

export { corsOptions as OPTIONS };
3 changes: 3 additions & 0 deletions apps/web/src/app/api/v1/skills/[id]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ export async function GET(
manifest: skills.manifest,
tags: skills.tags,
isPublished: skills.isPublished,
fetchCount: skills.fetchCount,
feedbackCount: skills.feedbackCount,
helpfulRate: skills.helpfulRate,
createdAt: skills.createdAt,
updatedAt: skills.updatedAt,
repo: {
Expand Down
49 changes: 49 additions & 0 deletions apps/web/src/app/api/v1/skills/[id]/stats/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { getDb } from "@/lib/db";
import { corsJson, OPTIONS as corsOptions } from "@/lib/api-cors";
import { skills } from "@skillshub/db/schema";
import { eq } from "drizzle-orm";

const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

export async function GET(
_request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params;

if (!UUID_RE.test(id)) {
return corsJson(
{ error: { code: "NOT_FOUND", message: "Skill not found" } },
{ status: 404 }
);
}

const db = getDb();

const [skill] = await db
.select({
fetchCount: skills.fetchCount,
feedbackCount: skills.feedbackCount,
helpfulRate: skills.helpfulRate,
trustScore: skills.trustScore,
})
.from(skills)
.where(eq(skills.id, id))
.limit(1);

if (!skill) {
return corsJson(
{ error: { code: "NOT_FOUND", message: "Skill not found" } },
{ status: 404 }
);
}

return corsJson({
fetchCount: skill.fetchCount,
feedbackCount: skill.feedbackCount,
helpfulRate: skill.helpfulRate !== null ? Number(skill.helpfulRate) : null,
trustScore: Number(skill.trustScore),
});
}

export { corsOptions as OPTIONS };
17 changes: 16 additions & 1 deletion apps/web/src/app/api/v1/skills/resolve/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ interface SkillRow {
description: string | null;
tags: string[];
readmeLength: number;
fetchCount: number;
helpfulRate: string | null;
feedbackCount: number;
repo: {
githubOwner: string | null;
githubRepoName: string | null;
Expand All @@ -44,6 +47,8 @@ interface SkillRow {
};
}

const MIN_FEEDBACK_FOR_BONUS = 5;

function scoreSkill(skill: SkillRow, tokens: string[], tokenWeights: Map<string, number>): number {
const nameLower = skill.name.toLowerCase();
const nameParts = nameLower.split(/[-_\s]+/);
Expand Down Expand Up @@ -99,7 +104,13 @@ function scoreSkill(skill: SkillRow, tokens: string[], tokenWeights: Map<string,
const stars = Math.max(skill.repo.starCount, 1);
const popularityScore = Math.min(15, Math.log10(stars) * 4);

return Math.round(textScore + qualityScore + popularityScore);
// FEEDBACK BONUS (0-10)
let feedbackBonus = 0;
if (skill.helpfulRate !== null && skill.feedbackCount >= MIN_FEEDBACK_FOR_BONUS) {
feedbackBonus = Number(skill.helpfulRate) * 10;
}

return Math.round(textScore + qualityScore + popularityScore + feedbackBonus);
}

export async function GET(request: Request) {
Expand Down Expand Up @@ -150,6 +161,9 @@ export async function GET(request: Request) {
description: skills.description,
tags: skills.tags,
readmeLength: sql<number>`coalesce(length(${skills.readme}), 0)::int`,
fetchCount: skills.fetchCount,
helpfulRate: skills.helpfulRate,
feedbackCount: skills.feedbackCount,
repo: {
githubOwner: repos.githubOwner,
githubRepoName: repos.githubRepoName,
Expand Down Expand Up @@ -211,6 +225,7 @@ export async function GET(request: Request) {
name: r.skill.name,
description: r.skill.description,
tags: r.skill.tags,
helpfulRate: r.skill.helpfulRate !== null ? Number(r.skill.helpfulRate) : null,
repo: r.skill.repo,
owner: r.skill.owner,
},
Expand Down
Loading
Loading