-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbackfill-issues.ts
More file actions
221 lines (189 loc) · 8.47 KB
/
backfill-issues.ts
File metadata and controls
221 lines (189 loc) · 8.47 KB
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
/**
* CLI entry point for backfilling GitHub issues and comments into the corpus.
*
* Usage:
* bun scripts/backfill-issues.ts # Full backfill for xbmc/xbmc
* bun scripts/backfill-issues.ts --repo xbmc/xbmc # Explicit repo
* bun scripts/backfill-issues.ts --sync # Incremental sync (nightly mode)
* bun scripts/backfill-issues.ts --dry-run # Fetch and log, don't store
*
* Environment variables required:
* DATABASE_URL - PostgreSQL connection string
* GITHUB_APP_ID - GitHub App ID
* GITHUB_PRIVATE_KEY - GitHub App private key (PEM, file path, or base64)
* VOYAGE_API_KEY - VoyageAI API key (optional, embeddings disabled without it)
*/
import { parseArgs } from "node:util";
import pino from "pino";
import { createDbClient } from "../src/db/client.ts";
import { runMigrations } from "../src/db/migrate.ts";
import { createIssueStore } from "../src/knowledge/issue-store.ts";
import { createEmbeddingProvider, createNoOpEmbeddingProvider } from "../src/knowledge/embeddings.ts";
import { createGitHubApp } from "../src/auth/github-app.ts";
import { backfillIssues, backfillIssueComments } from "../src/knowledge/issue-backfill.ts";
const logger = pino({ level: process.env.LOG_LEVEL ?? "info" });
// ── Parse arguments ─────────────────────────────────────────────────────────
const { values } = parseArgs({
args: process.argv.slice(2),
options: {
repo: { type: "string", default: "xbmc/xbmc" },
sync: { type: "boolean", default: false },
"dry-run": { type: "boolean", default: false },
help: { type: "boolean", default: false },
},
});
if (values.help) {
console.log(`
Usage: bun scripts/backfill-issues.ts [options]
Options:
--repo <owner/repo> Repository to backfill (default: xbmc/xbmc)
--sync Incremental sync (only issues updated since last sync)
--dry-run Fetch and log but don't store
--help Show this help
Environment:
DATABASE_URL PostgreSQL connection string (required)
GITHUB_APP_ID GitHub App ID (required)
GITHUB_PRIVATE_KEY GitHub App private key (required)
VOYAGE_API_KEY VoyageAI API key (optional)
`);
process.exit(0);
}
const repo = values.repo!;
const syncMode = values.sync!;
const dryRun = values["dry-run"]!;
// ── Validate environment ────────────────────────────────────────────────────
if (!process.env.DATABASE_URL) {
console.error("ERROR: DATABASE_URL environment variable is required.");
process.exit(1);
}
if (!process.env.GITHUB_APP_ID) {
console.error("ERROR: GITHUB_APP_ID environment variable is required.");
process.exit(1);
}
if (!process.env.GITHUB_PRIVATE_KEY && process.env.GITHUB_PRIVATE_KEY_BASE64) {
process.env.GITHUB_PRIVATE_KEY = process.env.GITHUB_PRIVATE_KEY_BASE64;
}
if (!process.env.GITHUB_PRIVATE_KEY) {
console.error("ERROR: GITHUB_PRIVATE_KEY or GITHUB_PRIVATE_KEY_BASE64 environment variable is required.");
process.exit(1);
}
// ── Load private key ────────────────────────────────────────────────────────
async function loadPrivateKey(): Promise<string> {
const keyEnv = process.env.GITHUB_PRIVATE_KEY!;
if (keyEnv.startsWith("-----BEGIN")) return keyEnv;
if (keyEnv.startsWith("/") || keyEnv.startsWith("./")) {
return await Bun.file(keyEnv).text();
}
return atob(keyEnv);
}
// ── Main ────────────────────────────────────────────────────────────────────
async function main() {
const [owner, repoName] = repo.split("/");
if (!owner || !repoName) {
console.error(`ERROR: Invalid repo format "${repo}". Expected "owner/repo".`);
process.exit(1);
}
const mode = syncMode ? "incremental sync" : "full backfill";
console.log(`Mode: ${mode}`);
console.log(`Repository: ${repo}`);
if (dryRun) console.log("DRY RUN: No data will be written.");
console.log();
// ── Database ──────────────────────────────────────────────────────────────
const db = createDbClient({ logger });
await runMigrations(db.sql);
const store = createIssueStore({ sql: db.sql, logger });
// ── Embeddings ────────────────────────────────────────────────────────────
const voyageApiKey = process.env.VOYAGE_API_KEY;
const embeddingProvider = voyageApiKey
? createEmbeddingProvider({
apiKey: voyageApiKey,
model: "voyage-code-3",
dimensions: 1024,
logger,
})
: createNoOpEmbeddingProvider(logger);
// ── GitHub App ────────────────────────────────────────────────────────────
const privateKey = await loadPrivateKey();
const githubApp = createGitHubApp(
{
githubAppId: process.env.GITHUB_APP_ID!,
githubPrivateKey: privateKey,
webhookSecret: "unused",
slackSigningSecret: "unused",
slackBotToken: "unused",
slackBotUserId: "unused",
slackKodiaiChannelId: "unused",
slackDefaultRepo: repo,
slackAssistantModel: "unused",
port: 0,
logLevel: "info",
botAllowList: [],
slackWikiChannelId: "",
wikiStalenessThresholdDays: 30,
wikiGithubOwner: "",
wikiGithubRepo: "",
botUserPat: "",
botUserLogin: "",
addonRepos: [],
mcpInternalBaseUrl: "",
acaJobImage: "",
acaResourceGroup: "rg-kodiai",
acaJobName: "caj-kodiai-agent",
},
logger,
);
await githubApp.initialize();
const installCtx = await githubApp.getRepoInstallationContext(owner, repoName);
if (!installCtx) {
console.error(`ERROR: GitHub App is not installed on ${repo}.`);
await db.close();
process.exit(1);
}
const octokit = await githubApp.getInstallationOctokit(installCtx.installationId);
// ── Execute ───────────────────────────────────────────────────────────────
const startTime = Date.now();
try {
if (syncMode) {
logger.info({ repo }, "Starting incremental sync...");
} else {
logger.info({ repo }, "Starting full backfill...");
}
// Both modes use the same engine — sync state determines behavior
const issueResult = await backfillIssues({
octokit,
store,
sql: db.sql,
embeddingProvider,
repo,
dryRun,
logger,
});
const commentResult = await backfillIssueComments({
octokit,
store,
sql: db.sql,
embeddingProvider,
repo,
dryRun,
logger,
});
const totalDuration = Date.now() - startTime;
// Summary report
console.log();
console.log("═══════════════════════════════════════");
console.log(` ${syncMode ? "Sync" : "Backfill"} Complete`);
console.log("═══════════════════════════════════════");
console.log(` Issues processed: ${issueResult.totalIssues}`);
console.log(` Comments processed: ${commentResult.totalComments}`);
console.log(` Comment chunks: ${commentResult.totalChunks}`);
console.log(` Embeddings created: ${issueResult.totalEmbeddings}`);
console.log(` Failed embeddings: ${issueResult.failedEmbeddings + commentResult.failedEmbeddings}`);
console.log(` Pages fetched: ${issueResult.pagesProcessed}`);
console.log(` Duration: ${(totalDuration / 1000).toFixed(1)}s`);
console.log(` Resumed: ${issueResult.resumed}`);
console.log("═══════════════════════════════════════");
} finally {
await db.close();
}
}
await main();