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
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,6 @@ LLM_MODEL=
ANTHROPIC_API_KEY=
OPENAI_API_KEY=
GEMINI_API_KEY=

# Optional: number of repositories enriched through additional Web Data API calls (0–12; default 6)
GITHUB_METADATA_ENRICH_LIMIT=6
28 changes: 28 additions & 0 deletions .github/workflows/research-quality-ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
name: Research quality checks

on:
pull_request:
paths:
- 'apps/backend/**'
- 'apps/shared/**'
- '.github/workflows/research-quality-ci.yml'

permissions:
contents: read

jobs:
validate:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v4
- uses: oven-sh/setup-bun@v2
with:
bun-version: latest
- run: bun install --frozen-lockfile
- name: Build shared workspace
run: bun run --cwd apps/shared build
- name: Typecheck backend
run: bunx tsc --noEmit -p apps/backend/tsconfig.json
- name: Run research regression tests
run: bun run --cwd apps/backend test --runInBand --runTestsByPath src/features/research/research-insights.spec.ts src/features/github/github-parser.service.spec.ts
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,17 @@ Keyword research can use:

The LLM analyzes the normalized repository data and returns a research summary, recurring themes, notable repositories, and historical comparisons when previous matching runs exist.

### Research accuracy improvements

- **Evidence-backed themes.** Each reported theme must have exact quotes from at least two current repositories and name its supporting repositories. The tool returns up to three themes and may return none rather than inventing connections.
- **Standout Trending activity.** Deterministic checks highlight dominant rolling period-star figures and unusually large changes in the rolling metric between saved snapshots. These are not the number of new stars earned between runs.
- **Recurring name clusters.** Terms shared by at least three repository names can be reported independently of the LLM, without claiming a shared cause.
- **More complete source data.** GitHub search attempts a second page when the first is full. Missing topics, descriptions, and fork counts can be filled by scraping a bounded subset of repository pages, while failures do not prevent the main report.
- **More dependable comparisons.** Historical runs are matched by research configuration, and overlapping repository counts and measured deltas are computed outside the LLM. Short comparison windows are described as diagnostic, not durable trends.
- **Richer exports.** The UI and Markdown reports include the standalone signals, name clusters, supported themes, and historical comparisons.

Metadata enrichment can add up to six Web Data API requests per run by default. Set `GITHUB_METADATA_ENRICH_LIMIT=0` to disable it, or use a value between 1 and 12 to control the maximum number of additional repository requests. Pagination may add one more request in search-based modes.

## Track GitHub repository research over time

Any research configuration can be saved as a recurring monitor.
Expand Down Expand Up @@ -260,6 +271,7 @@ The comparison describes each product's main workflow. These tools solve overlap
| `MONGODB_URI` | MongoDB connection string |
| `DECODO_AUTH_TOKEN` | Decodo Web Data API key, without the `Bearer` prefix |
| `DECODO_SCRAPER_ENDPOINT` | Decodo scraping endpoint. The included default is normally sufficient |
| `GITHUB_METADATA_ENRICH_LIMIT` | Optional maximum repository-page metadata enrichment requests per run (default: 6; maximum: 12; 0 disables) |
| `LLM_PROVIDER` | LLM provider: `claude`, `openai`, or `gemini` |
| `LLM_MODEL` | Optional model override |
| `ANTHROPIC_API_KEY` | Anthropic API key |
Expand Down
76 changes: 76 additions & 0 deletions apps/backend/src/features/github/github-parser.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { GithubParserService } from './github-parser.service';
import type { RepositorySnapshot } from './github.types';

describe('GitHub metadata extraction', () => {
const parser = new GithubParserService();

it('preserves a trending count expressed with comma separators', () => {
const repos = parser.parseTrending(`<html><body><article class="Box-row">
<h2><a href="/morluto/rea">morluto/rea</a></h2>
<p>Browser exploration tool</p>
<a href="/morluto/rea/stargazers">243,000</a>
<a href="/morluto/rea/forks">1,200</a>
<span class="d-inline-block float-sm-right">229,300 stars this week</span>
</article></body></html>`);
expect(repos[0]).toMatchObject({
owner: 'morluto', name: 'rea', stars: 243000, forks: 1200, periodStars: 229300,
});
});

it('extracts search-page results and metadata without inventing absent fields', () => {
const payload = JSON.stringify({
payload: { blackbirdSearchRoute: { results: [{
repo: { owner_login: 'example', name: 'project' },
hl_trunc_description: 'A tool for AI agents',
followers: 540,
}] } },
});
const results = parser.parseSearch(`<html><head>
<script type="application/json" data-target="react-app.embeddedData">${payload}</script>
</head></html>`);
expect(results).toHaveLength(1);
expect(results[0]).toMatchObject({
owner: 'example', name: 'project', stars: 540, description: 'A tool for AI agents',
});
expect(results[0].forks).toBeUndefined();
});

it('enriches missing topics and forks without replacing the trending period metric', () => {
const input: RepositorySnapshot = {
owner: 'example', name: 'project', url: 'https://github.com/example/project',
stars: 1000, periodStars: 120, observedAt: '2026-10-26T12:00:00Z',
};
const result = parser.enrichFromRepositoryPage(input, `<html><head>
<meta property="og:description" content="GitHub - example/project: AI agent configuration skills" />
</head><body>
<a href="/topics/ai-agent">ai-agent</a>
<a href="/topics/developer-tools">developer-tools</a>
<span id="repo-network-counter" title="2.3k">2.3k</span>
<span id="repo-stars-counter-star" title="5k">5k</span>
</body></html>`);
expect(result).toMatchObject({
description: 'AI agent configuration skills',
stars: 1000,
forks: 2300,
periodStars: 120,
topics: ['ai-agent', 'developer-tools'],
});
});
it('uses fork-link fallback, deduplicates topics, and expands truncated descriptions', () => {
const input: RepositorySnapshot = {
owner: 'example', name: 'project', url: 'https://github.com/example/project',
description: 'Read a longer truncated project descript…',
observedAt: '2026-10-26T12:00:00Z',
};
const result = parser.enrichFromRepositoryPage(input, `<html><head>
<meta property="og:description" content="GitHub - example/project: Read a longer complete project description for AI-agent tooling" />
</head><body>
<a href="/topics/security">security</a>
<a href="/topics/security">security</a>
<a href="/example/project/forks" aria-label="1,234 forks">Fork</a>
</body></html>`);
expect(result.forks).toBe(1234);
expect(result.topics).toEqual(['security']);
expect(result.description).toBe('Read a longer complete project description for AI-agent tooling');
});
});
78 changes: 63 additions & 15 deletions apps/backend/src/features/github/github-parser.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,16 @@ import * as cheerio from 'cheerio';
import type { RepositorySnapshot } from './github.types';

const number = (value: string): number | undefined => {
const n = Number(value.replace(/,/g, '').trim());
return Number.isFinite(n) ? n : undefined;
const cleaned = value.replace(/,/g, '').trim();
if (!cleaned) return undefined;
const match = cleaned.match(/([\d.]+)\s*([kmb])?\b/i);
if (!match) return undefined;
const base = Number(match[1]);
const multiplier = { k: 1_000, m: 1_000_000, b: 1_000_000_000 }[
(match[2] ?? '').toLowerCase() as 'k' | 'm' | 'b'
] ?? 1;
const result = base * multiplier;
return Number.isFinite(result) ? Math.round(result) : undefined;
};
const clean = (value: string): string => value.replace(/\s+/g, ' ').trim();

Expand All @@ -17,8 +25,8 @@ export class GithubParserService {
const root = $(element);
const href = root.find('h2 a').attr('href') ?? '';
const [owner, name] = href.replace(/^\//, '').split('/');
const starLink = root.find(`a[href$="/stargazers"]`).first();
const forkLink = root.find(`a[href$="/forks"]`).first();
const starLink = root.find('a[href$="/stargazers"]').first();
const forkLink = root.find('a[href$="/forks"]').first();
const periodText = clean(root.find('span.d-inline-block.float-sm-right').text());
return {
owner,
Expand All @@ -28,7 +36,7 @@ export class GithubParserService {
language: clean(root.find('[itemprop="programmingLanguage"]').text()) || undefined,
stars: number(starLink.text()),
forks: number(forkLink.text()),
periodStars: number(periodText.match(/[\d,]+/)?.[0] ?? ''),
periodStars: number(periodText),
observedAt,
} satisfies RepositorySnapshot;
}).get().filter((repo) => repo.owner && repo.name);
Expand All @@ -38,27 +46,67 @@ export class GithubParserService {
const $ = cheerio.load(html);
const script = $('script[type="application/json"][data-target="react-app.embeddedData"]').first().text();
if (!script) throw new ServiceUnavailableException('GitHub search response did not contain embedded repository data.');
let payload: any;
let payload: unknown;
try { payload = JSON.parse(script); } catch { throw new ServiceUnavailableException('Could not parse GitHub embedded search data.'); }
const route = payload?.payload?.blackbirdSearchRoute ?? payload?.blackbirdSearchRoute ?? payload?.payload;
const results: any[] = route?.results ?? [];
const root = payload as Record<string, any>;
const route = root?.payload?.blackbirdSearchRoute ?? root?.blackbirdSearchRoute ?? root?.payload;
const results: unknown[] = Array.isArray(route?.results) ? route.results : [];
const observedAt = new Date().toISOString();
return results.map((item) => {

return results.map((raw) => {
const item = raw as Record<string, any>;
const repo = item.repo ?? item.repository ?? {};
const owner = repo.owner_login ?? item.owner_login ?? String(item.hl_name ?? '').split('/')[0];
const name = repo.name ?? String(item.hl_name ?? '').replace(/<[^>]+>/g, '').split('/').pop();
const htmlName = cheerio.load(`<div>${String(item.hl_name ?? '')}</div>`)('div').text();
const owner = repo.owner_login ?? item.owner_login ?? htmlName.split('/')[0];
const name = repo.name ?? htmlName.split('/').pop();
const description = cheerio.load(`<div>${String(item.hl_trunc_description ?? '')}</div>`)('div').text();
return {
owner,
name,
url: `https://github.com/${owner}/${name}`,
description: clean(String(item.hl_trunc_description ?? '').replace(/<[^>]+>/g, '')) || undefined,
language: item.language || undefined,
topics: Array.isArray(item.topics) ? item.topics : [],
// GitHub's Blackbird repository payload currently calls the stargazer count "followers".
description: clean(description) || undefined,
language: typeof item.language === 'string' ? item.language : undefined,
topics: Array.isArray(item.topics) ? item.topics.filter((v: unknown): v is string => typeof v === 'string') : [],
stars: typeof item.followers === 'number' ? item.followers : undefined,
forks: typeof item.fork_count === 'number' ? item.fork_count : undefined,
createdAt: repo.created_at || undefined,
updatedAt: repo.updated_at || undefined,
observedAt,
} satisfies RepositorySnapshot;
}).filter((repo) => repo.owner && repo.name);
}

/** Only fill metadata missing from search/trending; preserve authoritative trending period stars. */
enrichFromRepositoryPage(snapshot: RepositorySnapshot, html: string): RepositorySnapshot {
const $ = cheerio.load(html);
const topics = [...new Set($('a[href^="/topics/"]').map((_, el) => {
const href = $(el).attr('href') ?? '';
return href.match(/^\/topics\/([a-zA-Z0-9_.-]+)\/?$/)?.[1] ?? '';
}).get().filter(Boolean))].slice(0, 15);
const descriptionMeta = $('meta[property="og:description"]').attr('content') ??
$('meta[name="description"]').attr('content') ?? '';
const description = descriptionMeta.includes(': ')
? descriptionMeta.slice(descriptionMeta.indexOf(': ') + 2)
: descriptionMeta;
const starCounter = $('#repo-stars-counter-star');
const forkCounter = $('#repo-network-counter, [data-testid="repo-forks-counter"]').first();
const forkCount = number(forkCounter.attr('title') ?? forkCounter.text()) ??
$('a[href$="/forks"]').toArray()
.map((el) => {
const link = $(el);
return number(link.attr('aria-label') ?? '') ?? number(link.text());
})
.find((value) => value !== undefined);
const improvedDescription = clean(description);
const currentDescription = snapshot.description ?? '';
const needsFullDescription = /(?:…|\.\.\.)$/.test(currentDescription.trim());

return {
...snapshot,
description: (needsFullDescription && improvedDescription.length > currentDescription.length ? improvedDescription : currentDescription) || improvedDescription || undefined,
topics: snapshot.topics?.length ? snapshot.topics : topics,
stars: snapshot.stars ?? number(starCounter.attr('title') ?? starCounter.text()),
forks: snapshot.forks ?? forkCount,
};
}
}
9 changes: 9 additions & 0 deletions apps/backend/src/features/github/github-url.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,15 @@ export class GithubUrlService {
return `https://github.com/search?${new URLSearchParams({ q: terms.join(' '), type: 'repositories' }).toString()}`;
}

withSearchPage(url: string, page: number): string {
const parsed = new URL(url);
if (parsed.hostname !== 'github.com' || parsed.pathname !== '/search') {
throw new Error('Pagination is supported only for GitHub repository searches.');
}
parsed.searchParams.set('p', String(page));
return parsed.toString();
}

build(config: ResearchConfig): string {
if (config.mode === 'trending') {
const language = config.language ? `/${encodeURIComponent(config.language.toLowerCase())}` : '';
Expand Down
1 change: 1 addition & 0 deletions apps/backend/src/features/github/github.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export interface RepositorySnapshot {
stars?: number;
forks?: number;
periodStars?: number;
createdAt?: string;
updatedAt?: string;
observedAt: string;
}
Expand Down
4 changes: 4 additions & 0 deletions apps/backend/src/features/queries/queries.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,9 @@ export class Query {
@Prop({ type: String, index: true }) monitorId?: string;
@Prop({ type: String, enum: ['manual', 'scheduled', 'manual-monitor'], default: 'manual' })
runType: 'manual' | 'scheduled' | 'manual-monitor';

// Mongoose generates these automatically because timestamps is enabled.
declare createdAt: Date;
declare updatedAt: Date;
}
export const QuerySchema = SchemaFactory.createForClass(Query);
16 changes: 14 additions & 2 deletions apps/backend/src/features/queries/queries.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,22 @@ export class QueriesService {
constructor(@InjectModel(Query.name) private readonly queryModel: Model<QueryDocument>) {}
async create(dto: CreateQueryDto) { return new this.queryModel(dto).save(); }
async findAll() { return this.queryModel.find().select('-repositories').sort({ createdAt: -1 }).exec(); }
async findRecentHistory(prompt: string, monitorId?: string, limit = 8) {
async findRecentHistory(prompt: string, monitorId?: string, limit = 8, config?: ResearchConfig) {
const escaped = prompt.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const filter = monitorId ? { monitorId } : { prompt: { $regex: `^${escaped}$`, $options: 'i' } };
return this.queryModel.find(filter).sort({ createdAt: -1 }).limit(limit).exec();
// A label alone is insufficient: daily/weekly or language-filtered
// research would otherwise be compared as though they were the same series.
const configKeys = [
'mode', 'keyword', 'timeframe', 'language', 'spokenLanguage',
'minStars', 'minForks', 'excludeForks',
] as const;
const planFilter = config
? Object.fromEntries(configKeys.map((key) => [
`plan.${key}`,
config[key] === undefined ? { $exists: false } : config[key],
]))
: {};
return this.queryModel.find({ ...filter, ...planFilter }).sort({ createdAt: -1 }).limit(limit).exec();
}
async findOne(id: string) { const q = await this.queryModel.findById(id).exec(); if (!q) throw new NotFoundException(`Query ${id} not found`); return q; }
async remove(id: string) { const q = await this.queryModel.findByIdAndDelete(id).exec(); if (!q) throw new NotFoundException(`Query ${id} not found`); }
Expand Down
Loading
Loading