diff --git a/.env.example b/.env.example index 3918540..42ea972 100644 --- a/.env.example +++ b/.env.example @@ -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 diff --git a/.github/workflows/research-quality-ci.yml b/.github/workflows/research-quality-ci.yml new file mode 100644 index 0000000..c27bf15 --- /dev/null +++ b/.github/workflows/research-quality-ci.yml @@ -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 diff --git a/README.md b/README.md index c0aae59..edd5630 100644 --- a/README.md +++ b/README.md @@ -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. @@ -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 | diff --git a/apps/backend/src/features/github/github-parser.service.spec.ts b/apps/backend/src/features/github/github-parser.service.spec.ts new file mode 100644 index 0000000..36ff472 --- /dev/null +++ b/apps/backend/src/features/github/github-parser.service.spec.ts @@ -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(`
+

morluto/rea

+

Browser exploration tool

+ 243,000 + 1,200 + 229,300 stars this week +
`); + 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(` + + `); + 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, ` + + + ai-agent + developer-tools + 2.3k + 5k + `); + 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, ` + + + security + security + Fork + `); + expect(result.forks).toBe(1234); + expect(result.topics).toEqual(['security']); + expect(result.description).toBe('Read a longer complete project description for AI-agent tooling'); + }); +}); diff --git a/apps/backend/src/features/github/github-parser.service.ts b/apps/backend/src/features/github/github-parser.service.ts index 0340fab..1cd5a8d 100644 --- a/apps/backend/src/features/github/github-parser.service.ts +++ b/apps/backend/src/features/github/github-parser.service.ts @@ -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(); @@ -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, @@ -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); @@ -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; + 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; 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(`
${String(item.hl_name ?? '')}
`)('div').text(); + const owner = repo.owner_login ?? item.owner_login ?? htmlName.split('/')[0]; + const name = repo.name ?? htmlName.split('/').pop(); + const description = cheerio.load(`
${String(item.hl_trunc_description ?? '')}
`)('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, + }; + } } diff --git a/apps/backend/src/features/github/github-url.service.ts b/apps/backend/src/features/github/github-url.service.ts index ce73cb7..7ac383d 100644 --- a/apps/backend/src/features/github/github-url.service.ts +++ b/apps/backend/src/features/github/github-url.service.ts @@ -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())}` : ''; diff --git a/apps/backend/src/features/github/github.types.ts b/apps/backend/src/features/github/github.types.ts index 6b1022c..fa331bb 100644 --- a/apps/backend/src/features/github/github.types.ts +++ b/apps/backend/src/features/github/github.types.ts @@ -11,6 +11,7 @@ export interface RepositorySnapshot { stars?: number; forks?: number; periodStars?: number; + createdAt?: string; updatedAt?: string; observedAt: string; } diff --git a/apps/backend/src/features/queries/queries.schema.ts b/apps/backend/src/features/queries/queries.schema.ts index 1ea1115..63e2a15 100644 --- a/apps/backend/src/features/queries/queries.schema.ts +++ b/apps/backend/src/features/queries/queries.schema.ts @@ -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); diff --git a/apps/backend/src/features/queries/queries.service.ts b/apps/backend/src/features/queries/queries.service.ts index 2f201d2..2bab3e6 100644 --- a/apps/backend/src/features/queries/queries.service.ts +++ b/apps/backend/src/features/queries/queries.service.ts @@ -17,10 +17,22 @@ export class QueriesService { constructor(@InjectModel(Query.name) private readonly queryModel: Model) {} 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`); } diff --git a/apps/backend/src/features/research/research-insights.spec.ts b/apps/backend/src/features/research/research-insights.spec.ts new file mode 100644 index 0000000..09e846b --- /dev/null +++ b/apps/backend/src/features/research/research-insights.spec.ts @@ -0,0 +1,116 @@ +import type { RepositorySnapshot } from '../github/github.types'; +import { findAttentionSignals, findRepositoryClusters, validateThemes } from './research-insights'; + +const repo = (repository: string, description: string, periodStars?: number): RepositorySnapshot => { + const [owner, name] = repository.split('/'); + return { + owner, name, url: `https://github.com/${repository}`, + description, periodStars, observedAt: '2026-10-19T12:00:00Z', + }; +}; + +describe('grounded GitHub themes', () => { + const threeD = repo('wesbos/3d-model-anything', 'Capture and reconstruct 3D models with iPhone LiDAR'); + const tv = repo('pengchujin/aerial-tv', 'An ad-free Android TV launcher for a clean home screen'); + const agent1 = repo('cloudflare/security-audit-skill', 'An AI agent skill for security audits'); + const agent2 = repo('another/agent-cli', 'Tools for AI agent coding workflows'); + + it('rejects the unrelated 3D model and Android TV launcher pairing', () => { + expect(validateThemes([{ + title: '3D Model Creation and Exploration', + description: 'wesbos/3d-model-anything and pengchujin/aerial-tv expand 3D modeling.', + evidence: [ + { repository: 'wesbos/3d-model-anything', quote: 'reconstruct 3D models' }, + { repository: 'pengchujin/aerial-tv', quote: 'Android TV launcher' }, + ], + }], [threeD, tv])).toEqual([]); + }); + + it('requires quotes from the supplied repository metadata', () => { + expect(validateThemes([{ + title: 'AI Agent Tools', + description: 'cloudflare/security-audit-skill and another/agent-cli work with AI agents.', + evidence: [ + { repository: 'cloudflare/security-audit-skill', quote: 'AI agent skill' }, + { repository: 'another/agent-cli', quote: 'invented marketing claims about agents' }, + ], + }], [agent1, agent2])).toEqual([]); + }); + + it('accepts concrete two-repository agent tooling evidence', () => { + expect(validateThemes([{ + title: 'AI Agent Tooling', + description: 'cloudflare/security-audit-skill and another/agent-cli support AI agent workflows.', + evidence: [ + { repository: 'cloudflare/security-audit-skill', quote: 'AI agent skill' }, + { repository: 'another/agent-cli', quote: 'AI agent coding workflows' }, + ], + }], [agent1, agent2])).toHaveLength(1); + }); +}); + +describe('exceptional trending growth signals', () => { + const latest = [ + repo('morluto/rea', 'Analyze browser behavior', 229_300), + repo('storytold/artcraft', 'Creative authoring tool', 16_400), + repo('boykopovar/AnyPS5', 'Device tooling', 14_200), + ]; + const earlier = [{ + date: '2026-10-12T12:00:00Z', + repositories: [ + repo('morluto/rea', 'Analyze browser behavior', 127_000), + repo('storytold/artcraft', 'Creative authoring tool', 10_000), + ], + }]; + + it('flags the October 12 to October 19 REA jump explicitly', () => { + const signals = findAttentionSignals({ mode: 'trending', timeframe: 'weekly' }, latest, earlier); + expect(signals).toHaveLength(1); + expect(signals[0].repository).toBe('morluto/rea'); + expect(signals[0].message).toContain('127,000'); + expect(signals[0].message).toContain('229,300'); + expect(signals[0].message).toContain('+102,300'); + expect(signals[0].message).toContain('14.0×'); + expect(signals[0].message).toContain('do not measure new stars'); + }); + + it('flags an outlier even when no historical snapshot exists', () => { + const signals = findAttentionSignals({ mode: 'trending', timeframe: 'weekly' }, latest, []); + expect(signals[0].repository).toBe('morluto/rea'); + expect(signals[0].message).toContain('14.0×'); + }); + + it('does not infer period movement from emerging total stars', () => { + expect(findAttentionSignals({ mode: 'emerging', timeframe: '7d' }, latest, earlier)).toEqual([]); + }); + + it('does not alert on modest fluctuations', () => { + expect(findAttentionSignals({ mode: 'trending', timeframe: 'weekly' }, [ + repo('example/one', 'Example one', 900), + repo('example/two', 'Example two', 800), + ], [])).toEqual([]); + }); +}); + +describe('recurring named repository clusters', () => { + const entries = [ + repo('ikow/php2shell-poc', 'PHP security PoC'), + repo('9bie/php2shell-bypass-aslr-exp', 'PHP security exploit'), + repo('openai/php2shell-checker', 'Check security issues'), + repo('eness/php2shell-CVE-2026-109618-CVE-2026-109619-PoC', 'Security exploit PoC'), + repo('assetnote/php2shell-scanner', 'PHP scanner'), + repo('pengchujin/aerial-tv', 'Android TV launcher'), + repo('wesbos/3d-model-anything', 'LiDAR 3D model application'), + ]; + it('detects five related php2shell repository names without an LLM', () => { + const clusters = findRepositoryClusters(entries); + expect(clusters).toHaveLength(1); + expect(clusters[0].term).toBe('php2shell'); + expect(clusters[0].count).toBe(5); + expect(clusters[0].repositories).toContain('assetnote/php2shell-scanner'); + }); + + it('does not fabricate clusters from unrelated names', () => { + expect(findRepositoryClusters(entries.slice(-2))).toEqual([]); + }); +}); diff --git a/apps/backend/src/features/research/research-insights.ts b/apps/backend/src/features/research/research-insights.ts new file mode 100644 index 0000000..5292d96 --- /dev/null +++ b/apps/backend/src/features/research/research-insights.ts @@ -0,0 +1,195 @@ +import type { RepositorySnapshot, ResearchConfig } from '../github/github.types'; + +export type HistorySnapshot = { + date?: Date | string; + repositories?: RepositorySnapshot[]; + report?: unknown; +}; + +export type AttentionSignal = { + repository: string; + url: string; + message: string; +}; + +export type RepositoryCluster = { + term: string; + repositories: string[]; + count: number; +}; + +/** + * Detect repeated, distinctive terms from repository names. Name-based + * clusters can be described accurately even when the LLM misses them. + * This intentionally does not infer a shared cause, popularity, or adoption. + */ +export function findRepositoryClusters(repositories: RepositorySnapshot[]): RepositoryCluster[] { + const ignored = new Set([ + 'awesome', 'plugin', 'plugins', 'library', 'framework', 'template', + 'starter', 'example', 'examples', 'coding', 'claude', 'agents', 'agent', + 'skills', 'skill', 'project', 'research', 'security', 'python', 'javascript', + 'typescript', 'github', 'android', 'desktop', 'server', 'client', 'release', + ]); + const found = new Map(); + + for (const repository of repositories) { + const name = `${repository.owner}/${repository.name}`; + const terms = new Set(repository.name.toLowerCase().split(/[^a-z0-9]+/g) + .filter((term) => term.length >= 6 && + !ignored.has(term) && + (/\d/.test(term) || term.length >= 8))); + for (const term of terms) { + found.set(term, [...(found.get(term) ?? []), name]); + } + } + + return [...found.entries()] + .filter(([, names]) => names.length >= 3) + .map(([term, names]) => ({ term, repositories: names, count: names.length })) + .sort((a, b) => b.count - a.count || a.term.localeCompare(b.term)) + .slice(0, 2); +} + +export type ThemeEvidence = { + repository: string; + quote: string; +}; + +export type SupportedTheme = { + title: string; + description: string; + evidence: ThemeEvidence[]; +}; + +const format = (value: number): string => value.toLocaleString('en-US'); + +const stopWords = new Set([ + 'and', 'the', 'for', 'with', 'from', 'into', 'using', 'based', + 'repository', 'repositories', 'project', 'projects', 'tool', 'tools', + 'tooling', 'application', 'applications', 'software', 'system', 'systems', + 'development', 'solution', 'solutions', 'technology', 'technologies', + 'capability', 'capabilities', 'platform', 'platforms', 'new', 'open', +]); + +function words(value: string): string[] { + return (value.toLowerCase().match(/[a-z0-9]+/g) ?? []) + .map((token) => token.length > 4 && token.endsWith('s') ? token.slice(0, -1) : token) + .filter((token) => token.length >= 3 && !stopWords.has(token)); +} + +function normalized(value: string): string { + return value.toLowerCase().replace(/\s+/g, ' ').trim(); +} + +/** + * Require two real, distinct repositories, exact quotes from their supplied + * descriptions/topics, and title-relevant terminology in each quote. + * Reject unsupported clusters instead of keeping an attractive invented theme. + */ +export function validateThemes(input: unknown, repositories: RepositorySnapshot[]): SupportedTheme[] { + if (!Array.isArray(input)) return []; + const known = new Map(repositories.map((repo) => [ + `${repo.owner}/${repo.name}`.toLowerCase(), repo, + ])); + const accepted: SupportedTheme[] = []; + + for (const candidate of input) { + if (!candidate || typeof candidate !== 'object') continue; + const theme = candidate as Record; + if (typeof theme.title !== 'string' || typeof theme.description !== 'string' || + !Array.isArray(theme.evidence)) continue; + + const description = theme.description; + const anchors = new Set(words(theme.title)); + if (!anchors.size) continue; + const unique = new Map(); + + for (const raw of theme.evidence) { + if (!raw || typeof raw !== 'object') continue; + const evidence = raw as Record; + if (typeof evidence.repository !== 'string' || typeof evidence.quote !== 'string') continue; + const name = evidence.repository.toLowerCase(); + const repo = known.get(name); + const quote = evidence.quote.trim(); + if (!repo || quote.length < 8 || unique.has(name)) continue; + + const sources = [repo.description ?? '', ...(repo.topics ?? [])]; + if (!sources.some((source) => normalized(source).includes(normalized(quote)))) continue; + if (!words(quote).some((token) => anchors.has(token))) continue; + unique.set(name, { repository: `${repo.owner}/${repo.name}`, quote }); + } + + if (unique.size < 2) continue; + const supports = [...unique.values()]; + // The description must name its actual supporting repositories explicitly. + if (supports.filter(({ repository }) => + description.toLowerCase().includes(repository.toLowerCase())).length < 2) continue; + + accepted.push({ + title: theme.title, + description, + evidence: supports.slice(0, 5), + }); + if (accepted.length === 3) break; + } + return accepted; +} + +function snapshotDate(snapshot: HistorySnapshot): number { + const parsed = snapshot.date instanceof Date ? snapshot.date : new Date(snapshot.date ?? ''); + return Number.isFinite(parsed.getTime()) ? parsed.getTime() : 0; +} + +/** + * Surface exceptional GitHub Trending figures independently of the LLM. + * Period-star counts are rolling-window observations, not incremental gains + * since the previous report. + */ +export function findAttentionSignals( + config: ResearchConfig, + current: RepositorySnapshot[], + history: HistorySnapshot[], +): AttentionSignal[] { + if (config.mode !== 'trending') return []; + const ranked = current + .filter((repo) => typeof repo.periodStars === 'number' && repo.periodStars >= 0) + .sort((a, b) => (b.periodStars ?? 0) - (a.periodStars ?? 0)); + if (!ranked.length) return []; + + const previous = [...history] + .filter((snapshot) => snapshot.repositories?.length && snapshotDate(snapshot) > 0) + .sort((a, b) => snapshotDate(b) - snapshotDate(a))[0]; + const previousByUrl = new Map( + (previous?.repositories ?? []).map((repo) => [repo.url.toLowerCase(), repo]), + ); + const signals: AttentionSignal[] = []; + + for (const [index, repo] of ranked.entries()) { + const currentStars = repo.periodStars!; + const priorStars = previousByUrl.get(repo.url.toLowerCase())?.periodStars; + const increase = typeof priorStars === 'number' && priorStars > 0 + ? currentStars - priorStars : 0; + const largeIncrease = typeof priorStars === 'number' && priorStars >= 100 && + currentStars >= priorStars * 1.5 && + (increase >= 10_000 || (increase >= 2_000 && currentStars >= priorStars * 3)); + const runnerUp = index === 0 ? ranked[1]?.periodStars : undefined; + const standout = index === 0 && typeof runnerUp === 'number' && + runnerUp > 0 && currentStars >= 5000 && currentStars >= runnerUp * 3; + + if (!largeIncrease && !standout) continue; + const name = `${repo.owner}/${repo.name}`; + const parts: string[] = []; + + if (largeIncrease && typeof priorStars === 'number') { + const date = new Date(snapshotDate(previous!)).toISOString().slice(0, 10); + parts.push(`GitHub's rolling ${config.timeframe ?? 'period'} star figure for ${name} rose from ${format(priorStars)} in the ${date} snapshot to ${format(currentStars)} now (+${format(increase)} in the reported ${config.timeframe ?? 'period'} metric)`); + } + if (standout && typeof runnerUp === 'number') { + parts.push(`${name} leads the current ${config.timeframe ?? 'period'} trending snapshot with ${format(currentStars)} period stars, ${(currentStars / runnerUp).toFixed(1)}× the runner-up (${format(runnerUp)})`); + } + parts.push('These rolling-window figures do not measure new stars earned between snapshots.'); + signals.push({ repository: name, url: repo.url, message: parts.join('. ') }); + if (signals.length === 2) break; + } + return signals; +} diff --git a/apps/backend/src/features/research/research.service.ts b/apps/backend/src/features/research/research.service.ts index c7e9885..0acc6ec 100644 --- a/apps/backend/src/features/research/research.service.ts +++ b/apps/backend/src/features/research/research.service.ts @@ -1,4 +1,4 @@ -import { Injectable, NotFoundException } from '@nestjs/common'; +import { Injectable, Logger, NotFoundException } from '@nestjs/common'; import { DecodoService } from '../decodo/decodo.service'; import { GithubParserService } from '../github/github-parser.service'; import { GithubUrlService } from '../github/github-url.service'; @@ -6,9 +6,40 @@ import type { RepositorySnapshot, ResearchConfig } from '../github/github.types' import { LlmService } from '../llm/llm.service'; import { QueriesService } from '../queries/queries.service'; import type { RunResearchDto } from './dto/run-research.dto'; +import { findAttentionSignals, findRepositoryClusters, validateThemes, type HistorySnapshot } from './research-insights'; + +type HistoricalComparison = { + facts: { + previousSnapshotDate: string | null; + comparisonWindow: string | null; + isDiagnosticWindow: boolean; + currentRepositoryCount: number; + previousRepositoryCount: number; + overlappingRepositoryCount: number; + currentOnlyCount: number; + previousOnlyCount: number; + overlappingRepositories: Array<{ + repository: string; + previousStars?: number; + currentStars?: number; + starDelta?: number; + previousPeriodStars?: number; + currentPeriodStars?: number; + periodStarsDelta?: number; + }>; + currentOnlyRepositories: string[]; + previousOnlyRepositories: string[]; + } | null; + report: { + summary: string; + signals: Array<{ signal: string; detail: string }>; + }; +}; @Injectable() export class ResearchService { + private readonly logger = new Logger(ResearchService.name); + constructor(private readonly decodo: DecodoService, private readonly urls: GithubUrlService, private readonly parser: GithubParserService, private readonly llm: LlmService, private readonly queries: QueriesService) {} async run(dto: RunResearchDto, context: { runType?: 'manual'|'scheduled'|'manual-monitor'; monitorId?: string; onProgress?: (stage: 'researching'|'structuring'|'analyzing'|'saving') => void } = {}) { @@ -21,6 +52,7 @@ export class ResearchService { const html = await this.decodo.scrapeUrl(url); context.onProgress?.('structuring'); let repositories = dto.mode === 'trending' ? this.parser.parseTrending(html) : this.parser.parseSearch(html); + const primarySearchCount = repositories.length; const sourceUrls = [url]; const recentRepositoryUrls = new Set(); @@ -37,14 +69,54 @@ export class ResearchService { const seen = new Set(repositories.map((repo) => repo.url)); repositories = [...repositories, ...recent.filter((repo) => !seen.has(repo.url))]; } + + // GitHub repository search embeds a limited first page. Fetch one additional + // page when it is full, without turning each research run into a broad crawl. + if (config.mode !== 'trending' && primarySearchCount >= 10) { + const pageUrl = this.urls.withSearchPage(url, 2); + try { + context.onProgress?.('researching'); + const pageHtml = await this.decodo.scrapeUrl(pageUrl); + context.onProgress?.('structuring'); + const additional = this.parser.parseSearch(pageHtml); + const seen = new Set(repositories.map((repo) => repo.url.toLowerCase())); + repositories.push(...additional.filter((repo) => !seen.has(repo.url.toLowerCase()))); + sourceUrls.push(pageUrl); + } catch (error) { + this.logger.warn(`GitHub search page 2 unavailable; using page 1: ${String(error)}`); + } + } + if (!repositories.length) throw new NotFoundException('GitHub returned no repositories for this research configuration.'); + + // Enrich a bounded set of highly ranked repositories with missing topics and + // fork counts. Three concurrent Decodo calls at a time; failures are harmless. + const enrichmentLimit = Math.max(0, Math.min(12, Number(process.env.GITHUB_METADATA_ENRICH_LIMIT ?? 6) || 0)); + const candidates = [...repositories] + .filter((repo) => !repo.topics?.length || repo.forks === undefined || !repo.description) + .sort((a, b) => (b.periodStars ?? b.stars ?? 0) - (a.periodStars ?? a.stars ?? 0)) + .slice(0, enrichmentLimit); + const enriched = new Map(); + + for (let i = 0; i < candidates.length; i += 3) { + await Promise.all(candidates.slice(i, i + 3).map(async (repo) => { + try { + const html = await this.decodo.scrapeUrl(repo.url); + enriched.set(repo.url, this.parser.enrichFromRepositoryPage(repo, html)); + } catch (error) { + this.logger.warn(`Could not enrich ${repo.owner}/${repo.name}: ${String(error)}`); + } + })); + } + repositories = repositories.map((repo) => enriched.get(repo.url) ?? repo); const prompt = this.label(config); - const history = await this.queries.findRecentHistory(prompt, context.monitorId ?? dto.monitorId, 8); + const history = await this.queries.findRecentHistory(prompt, context.monitorId ?? dto.monitorId, 8, config); context.onProgress?.('analyzing'); const report = await this.analyze(config, repositories, history.map((h: any) => ({ date: h.createdAt, repositories: h.repositories, report: h.report })), recentRepositoryUrls); + const generatedAt = new Date().toISOString(); context.onProgress?.('saving'); const saved = await this.queries.create({ prompt, plan: config, repositories, report, monitorId: context.monitorId ?? dto.monitorId, runType: context.runType ?? 'manual' }); - return { id: String(saved._id), generatedAt: new Date().toISOString(), sourceUrl: url, sourceUrls, plan: config, repositories, report }; + return { id: String(saved._id), generatedAt, sourceUrl: url, sourceUrls, plan: config, repositories, report }; } private label(config: ResearchConfig): string { @@ -53,7 +125,7 @@ export class ResearchService { return 'Trending repositories'; } - private async analyze(config: ResearchConfig, current: RepositorySnapshot[], history: unknown[], recentRepositoryUrls = new Set()) { + private async analyze(config: ResearchConfig, current: RepositorySnapshot[], history: HistorySnapshot[], recentRepositoryUrls = new Set()) { const withPeriodStars = current.filter((repo) => typeof repo.periodStars === 'number'); const topPeriodMover = [...withPeriodStars].sort((a, b) => (b.periodStars ?? 0) - (a.periodStars ?? 0))[0]; const languageCounts = current.reduce>((counts, repo) => { @@ -61,10 +133,14 @@ export class ResearchService { return counts; }, {}); const topLanguage = Object.entries(languageCounts).sort((a, b) => b[1] - a[1])[0]; + const historicalComparison = this.buildHistoricalComparison(current, history); const deterministicFacts = { repositoryCount: current.length, topPeriodMover: topPeriodMover ? { repository: `${topPeriodMover.owner}/${topPeriodMover.name}`, periodStars: topPeriodMover.periodStars } : null, mostRepresentedLanguage: topLanguage ? { language: topLanguage[0], repositories: topLanguage[1] } : null, + longitudinalComparison: historicalComparison.facts, + attentionSignals: findAttentionSignals(config, current, history), + repositoryClusters: findRepositoryClusters(current), keywordRecentSupplement: config.mode === 'keyword' && config.timeframe !== 'any' ? { window: config.timeframe, repositoryCount: recentRepositoryUrls.size, @@ -80,17 +156,21 @@ Rules: - You may interpret observed patterns, but phrase interpretations proportionately (for example, "suggests" or "is consistent with") and keep them directly tied to supplied evidence. - When repositories repeatedly mention an unfamiliar named concept, product, model, acronym, or entity, you may identify the observable cluster, but do not infer what that name refers to unless the supplied repository metadata establishes it. If its identity or meaning is unclear, say that the available metadata does not establish it. - Do not describe a repository as "highest momentum", "accelerating", "breakout", or similar unless the supplied metrics or historical deltas directly support that wording. -- Compare historical snapshots only when they contain the same repository and metric. Calculate deltas carefully. -- Very short comparison windows (under 6 hours) are diagnostic snapshots, not evidence of a durable trend. Report concrete changes but explicitly avoid strong trend conclusions. -- Keep executiveSummary focused on current findings; do not mention missing history there. -- Return 3 to 5 genuinely distinct themes only when supported. A theme must normally be evidenced by at least two current repositories; do not turn a single repository into a trend or theme. Put an exceptional single repository under notableRepositories instead. Do not create filler themes to reach three. Keep each theme description concise (roughly 2 to 4 sentences). -- notableRepositories should contain at most 4 genuinely noteworthy repositories with evidence-based reasons. Fewer is fine. Do not speculate about why external attention occurred. +- Historical overlap counts, set membership, metric deltas, comparisonWindow, and isDiagnosticWindow in deterministicFacts.longitudinalComparison are authoritative. Do not recalculate them from Previous runs. If you mention the comparison timing, use comparisonWindow exactly rather than converting it to decimal hours. If you cite a historical count or delta in executiveSummary, themes, or notableRepositories, use the deterministic value exactly. +- If deterministicFacts.longitudinalComparison.isDiagnosticWindow is true, the comparison is a diagnostic snapshot, not evidence of a durable trend. Report concrete changes but explicitly avoid strong trend conclusions. +- Write the executiveSummary as a short, specific briefing. Name the most important repositories and their actual metrics instead of generic statements about interest or demand. Lead with the measured attentionSignals if any are supplied. Explicitly mention a prominent repositoryClusters term when present and supported, without inventing reasons for the cluster. Do not mention missing history there. +- Return 0 to 3 genuinely distinct themes, only if supported by at least two current repositories each. Zero themes is acceptable. Never group unrelated repositories merely to meet a quota. +- For each theme, provide an evidence array of objects {repository, quote}. Every quote must be an EXACT verbatim substring (8+ characters) of that repository's supplied description or topic. The quote must contain a meaningful term from the theme title and justify its grouping. Two independent sources must genuinely describe the same topic. Do not use a generic interface feature to justify a specialized category like 3D reconstruction or mobile debloating. +- Each theme description must name its real supporting repositories and explain their common concrete functionality in 1 to 3 concise sentences. +- Themes must describe the current snapshot only. Repositories that appear only in Previous runs must not be used as evidence to establish a current theme. Each theme description must explicitly name at least two supporting repositories from Current repositories using their exact owner/name form. +- Use Previous runs only for longitudinal comparison and historical context about repositories that are also present in Current repositories. Do not use previous-only repositories to create current themes or notableRepositories. +- notableRepositories should contain at most 4 current repositories with evidence-based reasons, especially a statistical outlier. Fewer is fine. Do not speculate about why external attention occurred. - In Emerging mode, focus on newly created repositories, current star counts, languages, topics, and clusters. Do not discuss a missing top period mover or other Trending-only metrics. - In Keyword mode, the main search is a current relevance landscape. deterministicFacts.keywordRecentSupplement is authoritative for the optional recent-created-repository supplement. Never call a repository recent/new based only on observedAt. Only repositories listed in keywordRecentSupplement.repositories are known from this run to match the selected creation window. Do not describe the whole dataset as being from that timeframe. - If there are no previous matching snapshots, make longitudinal.summary brief and return an empty longitudinal.signals array. - Each longitudinal signal must be an object with string fields "signal" and "detail" and must state an observed comparison, not an invented explanation. -Return JSON with keys executiveSummary (string), themes (array of {title, description}), notableRepositories (array of {repository, reason}), and longitudinal (object with summary and signals array). +Return JSON with keys executiveSummary (string), themes (array of {title, description, evidence: array of {repository, quote}}), notableRepositories (array of {repository, reason}), and longitudinal (object with summary and signals array). Research configuration: ${JSON.stringify(config)} @@ -103,6 +183,173 @@ ${JSON.stringify(current)} Previous runs: ${JSON.stringify(history)}` }] }); - return this.llm.parseJsonResponse>(response.content); + const parsed = this.llm.parseJsonResponse>(response.content); + + parsed.themes = validateThemes(parsed.themes, current); + if (Array.isArray(parsed.notableRepositories)) { + const known = new Set(current.map((repo) => `${repo.owner}/${repo.name}`.toLowerCase())); + parsed.notableRepositories = parsed.notableRepositories.filter((raw) => { + if (!raw || typeof raw !== 'object') return false; + const item = raw as Record; + return typeof item.repository === 'string' && typeof item.reason === 'string' && + known.has(item.repository.toLowerCase()); + }).slice(0, 4); + } + parsed.attentionSignals = deterministicFacts.attentionSignals; + parsed.repositoryClusters = deterministicFacts.repositoryClusters; + parsed.longitudinal = historicalComparison.report; + return parsed; + } + + private buildHistoricalComparison(current: RepositorySnapshot[], history: HistorySnapshot[]): HistoricalComparison { + const snapshotTime = (snapshot: HistorySnapshot) => { + if (!snapshot.date) return 0; + const date = snapshot.date instanceof Date ? snapshot.date : new Date(snapshot.date); + return Number.isNaN(date.getTime()) ? 0 : date.getTime(); + }; + const previous = [...history] + .filter((snapshot) => Array.isArray(snapshot.repositories) && snapshot.repositories.length > 0) + .sort((a, b) => snapshotTime(b) - snapshotTime(a))[0]; + if (!previous?.repositories?.length) { + return { + facts: null, + report: { + summary: 'No previous matching snapshot is available.', + signals: [], + }, + }; + } + + const previousRepositories = previous.repositories; + const previousByUrl = new Map( + previousRepositories.map((repo) => [repo.url.toLowerCase(), repo] as const), + ); + const currentByUrl = new Map( + current.map((repo) => [repo.url.toLowerCase(), repo] as const), + ); + const label = (repo: RepositorySnapshot) => `${repo.owner}/${repo.name}`; + + const overlappingRepositories = current + .filter((repo) => previousByUrl.has(repo.url.toLowerCase())) + .map((repo) => { + const prior = previousByUrl.get(repo.url.toLowerCase())!; + const previousStars = typeof prior.stars === 'number' ? prior.stars : undefined; + const currentStars = typeof repo.stars === 'number' ? repo.stars : undefined; + const previousPeriodStars = typeof prior.periodStars === 'number' ? prior.periodStars : undefined; + const currentPeriodStars = typeof repo.periodStars === 'number' ? repo.periodStars : undefined; + + return { + repository: label(repo), + previousStars, + currentStars, + starDelta: + previousStars !== undefined && currentStars !== undefined + ? currentStars - previousStars + : undefined, + previousPeriodStars, + currentPeriodStars, + periodStarsDelta: + previousPeriodStars !== undefined && currentPeriodStars !== undefined + ? currentPeriodStars - previousPeriodStars + : undefined, + }; + }); + + const currentOnlyRepositories = current + .filter((repo) => !previousByUrl.has(repo.url.toLowerCase())) + .map(label); + + const previousOnlyRepositories = previousRepositories + .filter((repo) => !currentByUrl.has(repo.url.toLowerCase())) + .map(label); + + const previousDate = + previous.date instanceof Date + ? previous.date + : previous.date + ? new Date(previous.date) + : null; + const validPreviousDate = + previousDate && !Number.isNaN(previousDate.getTime()) ? previousDate : null; + const now = new Date(); + const hoursBetweenSnapshots = validPreviousDate + ? (now.getTime() - validPreviousDate.getTime()) / 3_600_000 + : null; + + const previousDateLabel = validPreviousDate + ? validPreviousDate.toISOString().slice(0, 10) + : 'the previous run'; + const snapshotDistance = + hoursBetweenSnapshots === null + ? null + : hoursBetweenSnapshots < 1 + ? `${Math.max(1, Math.round(hoursBetweenSnapshots * 60))} minutes` + : hoursBetweenSnapshots < 48 + ? `${Math.round(hoursBetweenSnapshots)} hours` + : `${(hoursBetweenSnapshots / 24).toFixed(1).replace(/\.0$/, '')} days`; + + const facts = { + previousSnapshotDate: validPreviousDate ? validPreviousDate.toISOString() : null, + comparisonWindow: snapshotDistance, + isDiagnosticWindow: hoursBetweenSnapshots !== null && hoursBetweenSnapshots < 6, + currentRepositoryCount: current.length, + previousRepositoryCount: previousRepositories.length, + overlappingRepositoryCount: overlappingRepositories.length, + currentOnlyCount: currentOnlyRepositories.length, + previousOnlyCount: previousOnlyRepositories.length, + overlappingRepositories, + currentOnlyRepositories, + previousOnlyRepositories, + }; + + const timing = + snapshotDistance === null + ? '' + : hoursBetweenSnapshots! < 6 + ? ` The snapshots are approximately ${snapshotDistance} apart, so this is a diagnostic comparison rather than evidence of a durable trend.` + : ` The snapshots are approximately ${snapshotDistance} apart.`; + + const summary = + `A previous snapshot from ${previousDateLabel} contains ${previousRepositories.length} repositories. ` + + `${overlappingRepositories.length} of the ${current.length} current repositories also appeared there; ` + + `${currentOnlyRepositories.length} are newly present in the current set and ` + + `${previousOnlyRepositories.length} from the previous set are absent.` + + timing; + + const formatDelta = (value: number) => `${value >= 0 ? '+' : ''}${value.toLocaleString('en-US')}`; + const signals = overlappingRepositories + .filter((item) => item.starDelta !== undefined) + .sort((a, b) => Math.abs(b.starDelta ?? 0) - Math.abs(a.starDelta ?? 0)) + .slice(0, 8) + .map((item) => { + const signal = `${item.repository} star count changed from ${item.previousStars!.toLocaleString('en-US')} to ${item.currentStars!.toLocaleString('en-US')}`; + let detail = `Observed change of ${formatDelta(item.starDelta!)} stars between the previous and current snapshots.`; + + if ( + item.previousPeriodStars !== undefined && + item.currentPeriodStars !== undefined && + item.periodStarsDelta !== undefined + ) { + detail += ` Weekly period stars changed from ${item.previousPeriodStars.toLocaleString('en-US')} to ${item.currentPeriodStars.toLocaleString('en-US')} (${formatDelta(item.periodStarsDelta)}).`; + } + + return { signal, detail }; + }); + + if (currentOnlyRepositories.length) { + signals.push({ + signal: `${currentOnlyRepositories.length} repositories are newly present in the current snapshot`, + detail: `Current-only repositories: ${currentOnlyRepositories.join(', ')}.`, + }); + } + + if (previousOnlyRepositories.length) { + signals.push({ + signal: `${previousOnlyRepositories.length} repositories from the previous snapshot are absent from the current set`, + detail: `Previous-only repositories: ${previousOnlyRepositories.join(', ')}.`, + }); + } + + return { facts, report: { summary, signals } }; } } diff --git a/apps/frontend/src/features/tracker/components/ReportView.tsx b/apps/frontend/src/features/tracker/components/ReportView.tsx index 4494095..3a02f27 100644 --- a/apps/frontend/src/features/tracker/components/ReportView.tsx +++ b/apps/frontend/src/features/tracker/components/ReportView.tsx @@ -45,6 +45,23 @@ export function ReportView({ result }: { result: ResearchResult }) {
Research summary

{report.executiveSummary}

+ {!!report.attentionSignals?.length &&
+

Standout GitHub signals

+ {report.attentionSignals.map((signal) => + {signal.repository} +

{signal.message}

+
)} +
} + + {!!report.repositoryClusters?.length &&
+

Recurring repository name clusters

+

Repeated terms in names, not evidence of a shared cause or wider adoption.

+
{report.repositoryClusters.map((cluster) => +

{cluster.term} · {cluster.count} repositories

+

{cluster.repositories.join(', ')}

+
)}
+
} +
{plan?.mode === 'trending' ? <>
{periodLabels.mover}

{topMover ? `${topMover.owner}/${topMover.name}` : 'Not available'}

{topMover?.periodStars !== undefined &&

+{topMover.periodStars.toLocaleString()}

} : <>
{plan?.mode === 'emerging' ? 'Highest-starred new repo' : 'Highest-starred repository'}

{highestStarred ? `${highestStarred.owner}/${highestStarred.name}` : 'Not available'}

{highestStarred?.stars !== undefined &&

{highestStarred.stars.toLocaleString()} stars

}}
Repositories analyzed

{repositories.length}

diff --git a/apps/frontend/src/features/tracker/tracker.types.ts b/apps/frontend/src/features/tracker/tracker.types.ts index 6b4e089..41bc374 100644 --- a/apps/frontend/src/features/tracker/tracker.types.ts +++ b/apps/frontend/src/features/tracker/tracker.types.ts @@ -24,15 +24,18 @@ export interface RepositorySnapshot { stars?: number; forks?: number; periodStars?: number; + createdAt?: string; updatedAt?: string; observedAt: string; } export interface GithubReport { executiveSummary: string; - themes: Array<{ title: string; description: string }>; + themes: Array<{ title: string; description: string; evidence?: Array<{ repository: string; quote: string }> }>; notableRepositories: Array<{ repository: string; reason: string }>; longitudinal?: { summary: string; signals: Array<{ signal: string; detail: string }> }; + attentionSignals?: Array<{ repository: string; url: string; message: string }>; + repositoryClusters?: Array<{ term: string; repositories: string[]; count: number }>; } export interface ResearchResult { diff --git a/apps/frontend/src/features/tracker/utils/export.ts b/apps/frontend/src/features/tracker/utils/export.ts index 57af378..6eec077 100644 --- a/apps/frontend/src/features/tracker/utils/export.ts +++ b/apps/frontend/src/features/tracker/utils/export.ts @@ -25,21 +25,50 @@ export function exportAsMarkdown(result: ResearchResult) { ...githubSources.map((url, index) => `- **GitHub source${githubSources.length > 1 ? ` ${index + 1}` : ''}:** ${url}`), '', '## Summary', '', report.executiveSummary, '', ]; + if (report.attentionSignals?.length) { + lines.push('## Standout GitHub signals', ''); + for (const signal of report.attentionSignals) lines.push(`- **[${signal.repository}](${signal.url})**. ${signal.message}`); + lines.push(''); + } + if (report.repositoryClusters?.length) { + lines.push('## Recurring repository name clusters', ''); + for (const cluster of report.repositoryClusters) lines.push(`- **${cluster.term}**. Found in ${cluster.count} repository names: ${cluster.repositories.join(', ')}. This does not establish a shared cause or wider adoption.`); + lines.push(''); + } if (report.themes?.length) { lines.push('## Themes', ''); - for (const theme of report.themes) lines.push(`### ${theme.title}`, '', theme.description, ''); + for (const theme of report.themes) { + lines.push(`### ${theme.title}`, '', theme.description, ''); + for (const evidence of theme.evidence ?? []) lines.push(`- **${evidence.repository}**. “${evidence.quote}”`); + if (theme.evidence?.length) lines.push(''); + } + } + if (report.notableRepositories?.length) { + lines.push('## Notable repositories', ''); + for (const item of report.notableRepositories) lines.push(`- **${item.repository}**. ${item.reason}`); + lines.push(''); + } + if (report.longitudinal?.signals?.length) { + lines.push('## Historical comparison', '', report.longitudinal.summary, ''); + for (const item of report.longitudinal.signals) lines.push(`- **${item.signal}**. ${item.detail}`); + lines.push(''); } - if (report.longitudinal?.signals?.length) lines.push('## Historical comparison', '', report.longitudinal.summary, ''); const repositoryColumns = [ { label: 'Repository', align: '---', value: (repo: (typeof repositories)[number]) => `[${repo.owner}/${repo.name}](${repo.url})` }, + { label: 'Description', align: '---', value: (repo: (typeof repositories)[number]) => repo.description ?? '' }, { label: 'Language', align: '---', value: (repo: (typeof repositories)[number]) => repo.language ?? '' }, - { label: 'Stars', align: '---:', value: (repo: (typeof repositories)[number]) => repo.stars ?? '' }, - ...(plan.mode === 'trending' - ? [ - { label: 'Period stars', align: '---:', value: (repo: (typeof repositories)[number]) => repo.periodStars ?? '' }, - { label: 'Forks', align: '---:', value: (repo: (typeof repositories)[number]) => repo.forks ?? '' }, - ] - : []), + ...(repositories.some((repo) => repo.topics?.length) ? [ + { label: 'Topics', align: '---', value: (repo: (typeof repositories)[number]) => repo.topics?.join(', ') ?? '' }, + ] : []), + ...(repositories.some((repo) => typeof repo.stars === 'number') ? [ + { label: 'Stars', align: '---:', value: (repo: (typeof repositories)[number]) => repo.stars ?? '' }, + ] : []), + ...(plan.mode === 'trending' && repositories.some((repo) => typeof repo.periodStars === 'number') ? [ + { label: 'Period stars', align: '---:', value: (repo: (typeof repositories)[number]) => repo.periodStars ?? '' }, + ] : []), + ...(repositories.some((repo) => typeof repo.forks === 'number') ? [ + { label: 'Forks', align: '---:', value: (repo: (typeof repositories)[number]) => repo.forks ?? '' }, + ] : []), ]; lines.push( @@ -49,7 +78,7 @@ export function exportAsMarkdown(result: ResearchResult) { `| ${repositoryColumns.map((column) => column.align).join(' | ')} |`, ); for (const repo of repositories) { - lines.push(`| ${repositoryColumns.map((column) => column.value(repo)).join(' | ')} |`); + lines.push(`| ${repositoryColumns.map((column) => String(column.value(repo)).replace(/\|/g, '\\|').replace(/\r?\n/g, ' ')).join(' | ')} |`); } download(lines.join('\n'), 'text/markdown', 'github-research-report.md'); }