1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
|
import {
pgTable,
uuid,
text,
jsonb,
integer,
timestamp,
date,
index,
uniqueIndex,
} from "drizzle-orm/pg-core";
import { eq, desc, sql, and } from "drizzle-orm";
import { db } from "../db";
import { config } from "./config";
import { getAnthropic, isAiAvailable, extractText, parseJsonResponse } from "./ai-client";
export const competitorReports = pgTable(
"competitor_reports",
{
id: uuid("id").primaryKey().defaultRandom(),
competitor: text("competitor").notNull(),
reportDate: date("report_date").notNull(),
rawContent: text("raw_content").notNull(),
featuresShipped: jsonb("features_shipped")
.notNull()
.$type<FeatureShipped[]>()
.default([]),
gapsIdentified: jsonb("gaps_identified")
.notNull()
.$type<GapIdentified[]>()
.default([]),
summary: text("summary").notNull().default(""),
modelUsed: text("model_used").notNull().default("claude-sonnet-4-6"),
createdAt: timestamp("created_at", { withTimezone: true })
.notNull()
.defaultNow(),
},
(table) => [
index("competitor_reports_competitor").on(table.competitor),
index("competitor_reports_date").on(table.reportDate),
uniqueIndex("competitor_reports_unique").on(
table.competitor,
table.reportDate
),
]
);
export const intelScanRuns = pgTable("intel_scan_runs", {
id: uuid("id").primaryKey().defaultRandom(),
startedAt: timestamp("started_at", { withTimezone: true })
.notNull()
.defaultNow(),
completedAt: timestamp("completed_at", { withTimezone: true }),
status: text("status").notNull().default("running"),
competitorsScanned: integer("competitors_scanned").notNull().default(0),
error: text("error"),
});
export type FeatureShipped = {
title: string;
description: string;
url?: string;
};
export type GapIdentified = {
feature: string;
priority: "high" | "medium" | "low";
notes: string;
};
export type CompetitorReport = typeof competitorReports.$inferSelect;
export type IntelScanRun = typeof intelScanRuns.$inferSelect;
const COMPETITORS = [
{
id: "github",
name: "GitHub",
changelogUrl: "https://github.blog/changelog/",
rssUrl: "https://github.blog/changelog/feed/",
},
{
id: "gitlab",
name: "GitLab",
changelogUrl: "https://about.gitlab.com/releases/",
rssUrl: "https://about.gitlab.com/atom.xml",
},
{
id: "bitbucket",
name: "Bitbucket",
changelogUrl: "https://bitbucket.org/blog/",
rssUrl: "https://bitbucket.org/blog/rss",
},
{
id: "linear",
name: "Linear",
changelogUrl: "https://linear.app/changelog",
rssUrl: "https://linear.app/changelog/rss.xml",
},
{
id: "vercel",
name: "Vercel",
changelogUrl: "https://vercel.com/changelog",
rssUrl: null,
},
{
id: "render",
name: "Render",
changelogUrl: "https://render.com/changelog",
rssUrl: null,
},
] as const;
export { COMPETITORS };
function getMondayOfCurrentWeek(): string {
const now = new Date();
const day = now.getUTCDay();
const diff = (day === 0 ? -6 : 1 - day);
const monday = new Date(now);
monday.setUTCDate(now.getUTCDate() + diff);
return monday.toISOString().slice(0, 10);
}
function stripHtml(html: string): string {
return html
.replace(/<script[\s\S]*?<\/script>/gi, " ")
.replace(/<style[\s\S]*?<\/style>/gi, " ")
.replace(/<[^>]+>/g, " ")
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, '"')
.replace(/'/g, "'")
.replace(/ /g, " ")
.replace(/\s{2,}/g, " ")
.trim();
}
function parseRssItems(xml: string, limit = 20): string {
const items: string[] = [];
const itemRe = /<(?:item|entry)[\s>]([\s\S]*?)<\/(?:item|entry)>/gi;
let match: RegExpExecArray | null;
while ((match = itemRe.exec(xml)) !== null && items.length < limit) {
const chunk = match[1];
const titleMatch =
chunk.match(/<title[^>]*><!\[CDATA\[([\s\S]*?)\]\]><\/title>/i) ||
chunk.match(/<title[^>]*>([\s\S]*?)<\/title>/i);
const title = titleMatch ? stripHtml(titleMatch[1]).trim() : "";
const descMatch =
chunk.match(
/<(?:description|summary|content(?::[a-z]+)?)[^>]*><!\[CDATA\[([\s\S]*?)\]\]><\/(?:description|summary|content(?::[a-z]+)?)>/i
) ||
chunk.match(
/<(?:description|summary|content(?::[a-z]+)?)[^>]*>([\s\S]*?)<\/(?:description|summary|content(?::[a-z]+)?)>/i
);
const desc = descMatch ? stripHtml(descMatch[1]).trim() : "";
const linkMatch =
chunk.match(/<link[^>]*href="([^"]+)"/i) ||
chunk.match(/<link[^>]*>(https?:\/\/[^\s<]+)<\/link>/i);
const link = linkMatch ? linkMatch[1].trim() : "";
if (title || desc) {
const parts = [title && `Title: ${title}`, desc && `Summary: ${desc.slice(0, 500)}`, link && `URL: ${link}`].filter(Boolean);
items.push(parts.join("\n"));
}
}
return items.join("\n\n---\n\n");
}
export async function fetchCompetitorContent(competitor: (typeof COMPETITORS)[number]): Promise<string> {
const timeout = 15_000;
if (competitor.rssUrl) {
try {
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), timeout);
const res = await fetch(competitor.rssUrl, {
signal: ctrl.signal,
headers: { "User-Agent": "Gluecron-Intel-Bot/1.0" },
});
clearTimeout(timer);
if (res.ok) {
const xml = await res.text();
const parsed = parseRssItems(xml, 20);
if (parsed.trim().length > 50) return parsed;
}
} catch {
}
}
try {
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), timeout);
const res = await fetch(competitor.changelogUrl, {
signal: ctrl.signal,
headers: { "User-Agent": "Gluecron-Intel-Bot/1.0" },
});
clearTimeout(timer);
if (res.ok) {
const html = await res.text();
const text = stripHtml(html);
return text.slice(0, 8000);
}
} catch {
}
return "";
}
export function getGluecronFeatureSummary(): string {
return `
Gluecron is an AI-native GitHub-alternative platform. It currently ships the following features:
CORE GIT HOSTING
- Bare git repository hosting with Smart HTTP (clone, push, pull)
- Branch management, tags, commits, file browser, diffs, blame
- Syntax highlighting for 40+ languages; Markdown rendering
- Raw file serving; semantic code search (Voyage AI embeddings)
AI FEATURES
- AI code review on every pull request (Claude-powered, inline annotations)
- AI merge conflict resolver (auto-repair on push)
- Spec-to-PR: describe a feature → Claude writes the code + opens a PR
- AI commit message generation
- AI PR summary / changelog generation
- AI code explain (explain any file or diff in plain English)
- AI test generation
- GateTest integration: push-time security + quality gate enforcement
- Auto-repair pipeline: lint/type/test failures auto-fixed by Claude
- AI-powered dep-updater (automated dependency PRs)
COLLABORATION
- Issue tracker with labels, comments, open/close/reopen
- Pull requests with reviews, inline comments, close/merge
- Branch comparison view
- Activity feed per repository
- Discussions (threaded, category-based)
- Wikis per repository
- Gists (standalone code snippets)
- Projects (kanban board)
PLATFORM
- Webhooks (HMAC-signed, per-event filtering, delivery log)
- Personal access tokens (SHA-256 hashed)
- OAuth 2.0 provider (developer apps can request scopes)
- Two-factor authentication (TOTP)
- Passkeys / WebAuthn
- SSH key management
- Organization accounts with team-level permissions
- Repository forking with fork count tracking
- Repository stars
- Repository topics / tags for discoverability
- Explore / discover public repos
- Contributors graph + commit activity
- Repo settings (description, visibility, delete)
- Branch protection rules (require PR, green gates, approvals)
- Repository templates
- Repository archival
- Site admin panel (user management, flags, audit log)
- Email digests + mention/assign notifications
DEPLOYMENT & PACKAGING
- GitHub Pages-style static site hosting (Pages)
- Package registry (Packages)
- Workflow / CI engine (YAML-based, similar to GitHub Actions)
- Deployment environments (staging, production)
- Deploy webhooks to external services (Render, Fly.io, etc.)
- Workflow secrets management (AES-256-GCM)
- Workflow artifact storage
`.trim();
}
type AnalysisResult = {
featuresShipped: FeatureShipped[];
gapsIdentified: GapIdentified[];
summary: string;
};
export async function analyzeWithClaude(
competitor: (typeof COMPETITORS)[number],
rawContent: string,
existingGluecronFeatures: string
): Promise<AnalysisResult> {
const empty: AnalysisResult = {
featuresShipped: [],
gapsIdentified: [],
summary: "Analysis unavailable.",
};
if (!isAiAvailable()) return empty;
if (!rawContent.trim()) return empty;
try {
const anthropic = getAnthropic();
const systemPrompt = `You are a product intelligence analyst for Gluecron, an AI-native GitHub-alternative platform.
Your job is to analyse a competitor's recent changelog and identify:
1. What features the competitor has shipped recently
2. Which of those features Gluecron does NOT already have (gaps)
When rating gap priority:
- HIGH: Core developer workflow features that many users would miss; features that give the competitor a meaningful advantage
- MEDIUM: Nice-to-have additions that improve UX or cover secondary use-cases
- LOW: Niche, very org-specific, or features that few users would care about
Always respond with ONLY valid JSON matching this exact schema (no surrounding prose):
{
"featuresShipped": [
{ "title": "string", "description": "string", "url": "string or omit" }
],
"gapsIdentified": [
{ "feature": "string", "priority": "high|medium|low", "notes": "string" }
],
"summary": "2-sentence overall summary of what this competitor is focused on and what the biggest threat to Gluecron is."
}`;
const userPrompt = `Competitor: ${competitor.name}
Changelog URL: ${competitor.changelogUrl}
--- GLUECRON EXISTING FEATURES ---
${existingGluecronFeatures}
--- ${competitor.name.toUpperCase()} RECENT CHANGELOG ---
${rawContent.slice(0, 12000)}
Analyse the changelog above. List all features shipped. Then identify gaps — features the competitor has that Gluecron does NOT already have based on the list above. Rate each gap's priority. Return only JSON.`;
const message = await anthropic.messages.create({
model: "claude-sonnet-4-6",
max_tokens: 4096,
messages: [{ role: "user", content: userPrompt }],
system: systemPrompt,
});
const text = extractText(message);
const parsed = parseJsonResponse<AnalysisResult>(text);
if (!parsed) return empty;
return {
featuresShipped: Array.isArray(parsed.featuresShipped)
? parsed.featuresShipped
: [],
gapsIdentified: Array.isArray(parsed.gapsIdentified)
? parsed.gapsIdentified
: [],
summary:
typeof parsed.summary === "string" && parsed.summary.trim()
? parsed.summary.trim()
: "Analysis unavailable.",
};
} catch (err) {
console.error(`[competitive-intel] Claude analysis failed for ${competitor.name}:`, err);
return empty;
}
}
export async function runIntelligenceScan(): Promise<{
success: boolean;
reportsCreated: number;
errors: string[];
}> {
const errors: string[] = [];
let reportsCreated = 0;
let runId: string | null = null;
try {
const [run] = await db
.insert(intelScanRuns)
.values({ status: "running" })
.returning({ id: intelScanRuns.id });
runId = run?.id ?? null;
} catch (err) {
console.error("[competitive-intel] Failed to create scan run record:", err);
}
const weekOf = getMondayOfCurrentWeek();
const gluecronFeatures = getGluecronFeatureSummary();
for (const competitor of COMPETITORS) {
try {
const [existing] = await db
.select({ id: competitorReports.id })
.from(competitorReports)
.where(
and(
eq(competitorReports.competitor, competitor.id),
eq(competitorReports.reportDate, weekOf)
)
)
.limit(1);
if (existing) {
console.log(`[competitive-intel] Skipping ${competitor.name} — report for ${weekOf} already exists`);
continue;
}
console.log(`[competitive-intel] Fetching ${competitor.name}...`);
const rawContent = await fetchCompetitorContent(competitor);
if (!rawContent.trim()) {
errors.push(`${competitor.name}: no content fetched`);
console.warn(`[competitive-intel] ${competitor.name}: empty content, skipping`);
continue;
}
console.log(`[competitive-intel] Analysing ${competitor.name} with Claude...`);
const analysis = await analyzeWithClaude(competitor, rawContent, gluecronFeatures);
await db.insert(competitorReports).values({
competitor: competitor.id,
reportDate: weekOf,
rawContent,
featuresShipped: analysis.featuresShipped,
gapsIdentified: analysis.gapsIdentified,
summary: analysis.summary,
modelUsed: "claude-sonnet-4-6",
});
reportsCreated++;
console.log(`[competitive-intel] ${competitor.name}: report created (${analysis.featuresShipped.length} features, ${analysis.gapsIdentified.length} gaps)`);
} catch (err) {
const msg = `${competitor.name}: ${err instanceof Error ? err.message : String(err)}`;
errors.push(msg);
console.error(`[competitive-intel] Error processing ${competitor.name}:`, err);
}
}
if (runId) {
try {
await db
.update(intelScanRuns)
.set({
completedAt: new Date(),
status: errors.length === COMPETITORS.length ? "failed" : "completed",
competitorsScanned: reportsCreated,
error: errors.length > 0 ? errors.slice(0, 5).join("; ") : null,
})
.where(eq(intelScanRuns.id, runId));
} catch (err) {
console.error("[competitive-intel] Failed to update scan run record:", err);
}
}
return {
success: reportsCreated > 0 || errors.length === 0,
reportsCreated,
errors,
};
}
export async function getLatestReports(): Promise<CompetitorReport[]> {
try {
const rows = await db.execute(sql`
SELECT DISTINCT ON (competitor)
id, competitor, report_date, raw_content,
features_shipped, gaps_identified, summary,
model_used, created_at
FROM competitor_reports
ORDER BY competitor, report_date DESC
`);
return (rows.rows as CompetitorReport[]).map((r) => ({
...r,
featuresShipped: (r.featuresShipped ?? []) as FeatureShipped[],
gapsIdentified: (r.gapsIdentified ?? []) as GapIdentified[],
}));
} catch (err) {
console.error("[competitive-intel] getLatestReports:", err);
return [];
}
}
export async function getReportHistory(
competitor: string,
limit = 12
): Promise<CompetitorReport[]> {
try {
const rows = await db
.select()
.from(competitorReports)
.where(eq(competitorReports.competitor, competitor))
.orderBy(desc(competitorReports.reportDate))
.limit(limit);
return rows.map((r) => ({
...r,
featuresShipped: (r.featuresShipped ?? []) as FeatureShipped[],
gapsIdentified: (r.gapsIdentified ?? []) as GapIdentified[],
}));
} catch (err) {
console.error("[competitive-intel] getReportHistory:", err);
return [];
}
}
export async function getLastScanRun(): Promise<IntelScanRun | null> {
try {
const [row] = await db
.select()
.from(intelScanRuns)
.orderBy(desc(intelScanRuns.startedAt))
.limit(1);
return row ?? null;
} catch {
return null;
}
}
|