-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlearningComment.js
More file actions
324 lines (281 loc) Β· 9.42 KB
/
learningComment.js
File metadata and controls
324 lines (281 loc) Β· 9.42 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
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
/**
* Learning status comment formatting and upsert utilities
*/
import { getGitHubHeaders } from "./github.js";
/**
* Marker that identifies a learning status comment posted by this app.
*/
const COMMENT_MARKER = "<!-- dalestudy-learning-status -->";
/**
* Hidden marker for embedding cumulative usage data in the comment.
* Format: <!-- usage-data: {"prompt":N,"completion":N,"requests":N} -->
*/
const USAGE_DATA_RE = /<!-- usage-data: ({.*?}) -->/;
/** gpt-4.1-nano pricing (USD per token) */
const INPUT_COST_PER_TOKEN = 0.10 / 1_000_000;
const OUTPUT_COST_PER_TOKEN = 0.40 / 1_000_000;
/**
* Calculates cost in USD from token counts.
*
* @param {number} promptTokens
* @param {number} completionTokens
* @returns {number}
*/
function calcCost(promptTokens, completionTokens) {
return promptTokens * INPUT_COST_PER_TOKEN + completionTokens * OUTPUT_COST_PER_TOKEN;
}
/**
* Formats a number with thousand-separating commas.
*
* @param {number} n
* @returns {string}
*/
function fmt(n) {
return n.toLocaleString("en-US");
}
/**
* Parses per-request usage history embedded in an existing comment body.
*
* @param {string|undefined} body
* @returns {Array<{ prompt: number, completion: number }>}
*/
function parseUsageFromComment(body) {
if (!body) return [];
const match = body.match(USAGE_DATA_RE);
if (!match) return [];
try {
const parsed = JSON.parse(match[1]);
return Array.isArray(parsed) ? parsed : [];
} catch {
return [];
}
}
/**
* Builds the usage footer section (per-request history table + hidden data marker).
*
* @param {Array<{ prompt: number, completion: number }>} history - all requests including current (latest last)
* @returns {string}
*/
function formatUsageSection(history) {
const lines = [];
lines.push("<details>");
lines.push("<summary>π’ API μ¬μ©λ (gpt-4.1-nano)</summary>");
lines.push("");
lines.push("| μμ² | μ
λ ₯ ν ν° | μΆλ ₯ ν ν° | ν©κ³ | λΉμ© |");
lines.push("|---:|---:|---:|---:|---:|");
let totalPrompt = 0;
let totalCompletion = 0;
for (let i = 0; i < history.length; i++) {
const { prompt, completion } = history[i];
const total = prompt + completion;
const cost = calcCost(prompt, completion);
lines.push(`| #${i + 1} | ${fmt(prompt)} | ${fmt(completion)} | ${fmt(total)} | $${cost.toFixed(6)} |`);
totalPrompt += prompt;
totalCompletion += completion;
}
if (history.length > 1) {
const totalCost = calcCost(totalPrompt, totalCompletion);
lines.push(`| **ν©κ³** | **${fmt(totalPrompt)}** | **${fmt(totalCompletion)}** | **${fmt(totalPrompt + totalCompletion)}** | **$${totalCost.toFixed(6)}** |`);
}
lines.push("");
lines.push("</details>");
// Embed history for future parsing
lines.push(`<!-- usage-data: ${JSON.stringify(history)} -->`);
return lines.join("\n");
}
/**
* Returns true when `comment` is a Bot comment containing our marker.
*
* @param {{ user?: { type?: string }, body?: string }} comment
* @returns {boolean}
*/
function isLearningStatusComment(comment) {
return comment.user?.type === "Bot" && comment.body?.includes(COMMENT_MARKER);
}
/**
* Renders a simple block-character progress bar.
*
* @param {number} completed
* @param {number} total
* @param {number} [barLength=7]
* @returns {string} e.g. "β β β β‘β‘β‘β‘"
*/
function progressBar(completed, total, barLength = 7) {
if (total === 0) {
return "β‘".repeat(barLength);
}
const filled = Math.min(Math.round((completed / total) * barLength), barLength);
return "β ".repeat(filled) + "β‘".repeat(barLength - filled);
}
/**
* Formats a learning status Markdown comment.
*
* @param {string} username
* @param {Array<{ problemName: string, difficulty: string|null, matches: boolean|null, explanation: string }>} submissions
* @param {number} totalSolved
* @param {number} totalProblems
* @param {Array<{ category: string, solved: number, total: number, difficulties: string }>} categoryProgress
* @returns {string}
*/
export function formatLearningStatusComment(
username,
submissions,
totalSolved,
totalProblems,
categoryProgress
) {
const lines = [];
lines.push(COMMENT_MARKER);
lines.push(`## π ${username} λμ νμ΅ νν©`);
lines.push("");
// --- Submission table ---
lines.push("### μ΄λ² μ£Ό μ μΆ λ¬Έμ ");
lines.push("| λ¬Έμ | λμ΄λ | μ ν λΆμ |");
lines.push("|---|---|---|");
for (const { problemName, difficulty, matches } of submissions) {
const difficultyCell = difficulty ?? "-";
let analysisCell;
if (matches === null) {
analysisCell = "βΉοΈ μΉ΄ν
κ³ λ¦¬ μ 보 μμ";
} else if (matches === true) {
analysisCell = "β
μλν μ ν";
} else {
analysisCell = "β οΈ μ ν λΆμΌμΉ";
}
lines.push(`| ${problemName} | ${difficultyCell} | ${analysisCell} |`);
}
lines.push("");
// --- Cumulative summary ---
lines.push("### λμ νμ΅ μμ½");
lines.push(`- νμ΄ν λ¬Έμ : ${totalSolved} / ${totalProblems}κ°`);
// Match rate line β only include when at least one submission has matches !== null
const gradedSubmissions = submissions.filter((s) => s.matches !== null);
if (gradedSubmissions.length > 0) {
const matched = gradedSubmissions.filter((s) => s.matches === true).length;
const total = gradedSubmissions.length;
const rate = Math.round((matched / total) * 100);
lines.push(
`- μ΄λ² μ£Ό μ ν μΌμΉμ¨: ${rate}% (${total}λ¬Έμ μ€ ${matched}λ¬Έμ μΌμΉ)`
);
}
lines.push("");
// --- Category progress ---
if (categoryProgress.length > 0) {
lines.push("### λ¬Έμ νμ΄ νν©");
lines.push("| μΉ΄ν
κ³ λ¦¬ | μ§νλ | μλ£ |");
lines.push("|---|---|---|");
for (const { category, solved, total, difficulties } of categoryProgress) {
const bar = progressBar(solved, total);
let completionCell = difficulties
? `${solved} / ${total} (${difficulties})`
: `${solved} / ${total}`;
if (solved === 0) {
completionCell += " β μμ§ μμ μ ν¨";
}
lines.push(`| ${category} | ${bar} | ${completionCell} |`);
}
lines.push("");
}
lines.push("---");
lines.push("π€ μ΄ λκΈμ GitHub Appμ ν΅ν΄ μλμΌλ‘ μμ±λμμ΅λλ€.");
return lines.join("\n") + "\n";
}
/**
* Creates or updates the learning status comment on a PR.
*
* Searches through the first 100 issue comments for an existing Bot comment
* that contains COMMENT_MARKER. If found, PATCHes it; otherwise POSTs a new one.
*
* When `currentUsage` is provided, appends a collapsible usage/cost section to
* the comment and accumulates it with any previously stored cumulative totals.
*
* @param {string} repoOwner
* @param {string} repoName
* @param {number} prNumber
* @param {string} commentBody
* @param {string} appToken
* @param {{ prompt_tokens: number, completion_tokens: number }|null} [currentUsage]
* @returns {Promise<void>}
*/
export async function upsertLearningStatusComment(
repoOwner,
repoName,
prNumber,
commentBody,
appToken,
currentUsage = null
) {
const baseUrl = `https://api.github.com/repos/${repoOwner}/${repoName}`;
// Fetch existing comments
const listResponse = await fetch(
`${baseUrl}/issues/${prNumber}/comments?per_page=100`,
{ headers: getGitHubHeaders(appToken) }
);
if (!listResponse.ok) {
throw new Error(
`[learningStatus] Failed to list comments on PR #${prNumber}: ${listResponse.status} ${listResponse.statusText}`
);
}
const comments = await listResponse.json();
const existing = comments.find(isLearningStatusComment);
// Append usage section when token data is available
if (currentUsage) {
const prevHistory = parseUsageFromComment(existing?.body);
const history = [
...prevHistory,
{ prompt: currentUsage.prompt_tokens, completion: currentUsage.completion_tokens },
];
commentBody = commentBody.trimEnd() + "\n\n" + formatUsageSection(history) + "\n";
}
if (existing) {
// Update existing comment
console.log(
`[learningStatus] Updating existing comment ${existing.id} on PR #${prNumber}`
);
const patchResponse = await fetch(
`${baseUrl}/issues/comments/${existing.id}`,
{
method: "PATCH",
headers: {
...getGitHubHeaders(appToken),
"Content-Type": "application/json",
},
body: JSON.stringify({ body: commentBody }),
}
);
if (!patchResponse.ok) {
const errorData = await patchResponse.json();
throw new Error(
`[learningStatus] Failed to update comment ${existing.id} on PR #${prNumber}: ${JSON.stringify(errorData)}`
);
}
console.log(
`[learningStatus] Updated comment ${existing.id} on PR #${prNumber}`
);
} else {
// Post new comment
console.log(
`[learningStatus] Posting new learning status comment on PR #${prNumber}`
);
const postResponse = await fetch(
`${baseUrl}/issues/${prNumber}/comments`,
{
method: "POST",
headers: {
...getGitHubHeaders(appToken),
"Content-Type": "application/json",
},
body: JSON.stringify({ body: commentBody }),
}
);
if (!postResponse.ok) {
const errorData = await postResponse.json();
throw new Error(
`[learningStatus] Failed to post comment on PR #${prNumber}: ${JSON.stringify(errorData)}`
);
}
console.log(
`[learningStatus] Created new comment on PR #${prNumber}`
);
}
}