@infaris/calendar-cli 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,335 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { listCalendars, listEvents, listHours, listTasks, upsertHours, deleteHours, } from "./api.js";
3
+ import { activityTaskKeys, gatherDayActivity } from "./activity.js";
4
+ import { defaultMinutesFor, draftHoursNotes, FALLBACK_WEEKDAY_MINUTES, formatMinutes, isIsoDate, parseHoursInput, taskTouchedOnDate, WEEKDAY_LABELS_NL_SHORT, weekdayIndex, fromIsoDate, } from "./hours.js";
5
+ import { endOfDay, localDayKey, parseDateInput, resolveRange, startOfDay } from "./dates.js";
6
+ function fail(message) {
7
+ process.stderr.write(`\x1b[31mError:\x1b[0m ${message}\n`);
8
+ process.exit(1);
9
+ }
10
+ function ok(message) {
11
+ process.stdout.write(`\x1b[32mOK\x1b[0m ${message}\n`);
12
+ }
13
+ function warn(message) {
14
+ process.stderr.write(`\x1b[33mWarning:\x1b[0m ${message}\n`);
15
+ }
16
+ function hoursDashboardUrl(baseUrl) {
17
+ return `${baseUrl.replace(/\/$/, "")}/dashboard/hours`;
18
+ }
19
+ function resolveWorkedOn(input) {
20
+ const raw = input?.trim() || "today";
21
+ if (isIsoDate(raw))
22
+ return raw;
23
+ const parsed = parseDateInput(raw);
24
+ if (!parsed)
25
+ fail(`Invalid date: ${raw}`);
26
+ return localDayKey(parsed);
27
+ }
28
+ function defaultsFor(hours, userId) {
29
+ return (hours.defaults[userId] ?? {
30
+ weekdayMinutes: [...FALLBACK_WEEKDAY_MINUTES],
31
+ defaultNotes: null,
32
+ defaultBillable: false,
33
+ });
34
+ }
35
+ function entryForDay(hours, userId, iso) {
36
+ return hours.entries.find((e) => e.userId === userId && e.workedOn === iso);
37
+ }
38
+ function printHoursList(hours, userId, baseUrl) {
39
+ const mine = hours.entries
40
+ .filter((e) => e.userId === userId)
41
+ .sort((a, b) => a.workedOn.localeCompare(b.workedOn));
42
+ if (mine.length === 0) {
43
+ process.stdout.write(`No hours logged ${hours.from} – ${hours.to}.\n`);
44
+ process.stdout.write(`${hoursDashboardUrl(baseUrl)}\n`);
45
+ return;
46
+ }
47
+ let total = 0;
48
+ for (const entry of mine) {
49
+ total += entry.minutes;
50
+ const day = WEEKDAY_LABELS_NL_SHORT[weekdayIndex(entry.workedOn)] ?? "";
51
+ const notes = (entry.notes ?? "").replace(/\s+/g, " ").trim();
52
+ process.stdout.write(`${entry.workedOn} ${day.padEnd(2)} ${formatMinutes(entry.minutes).padEnd(8)} ${notes}\n`);
53
+ }
54
+ process.stdout.write(`\n${formatMinutes(total)} over ${mine.length} dag(en) — ${hoursDashboardUrl(baseUrl)}\n`);
55
+ }
56
+ function toTaskRef(task) {
57
+ return {
58
+ taskKey: task.taskKey,
59
+ title: task.title,
60
+ product: task.product,
61
+ parentTaskId: task.parentTaskId,
62
+ updatedAt: task.updatedAt,
63
+ createdAt: task.createdAt,
64
+ completedAt: task.completedAt,
65
+ };
66
+ }
67
+ async function tasksForDay(iso, userId, extraKeys) {
68
+ const { tasks } = await listTasks({
69
+ assigneeId: userId,
70
+ includeDone: true,
71
+ });
72
+ const byKey = new Map(tasks.map((t) => [t.taskKey.replace(/^#/, ""), t]));
73
+ for (const key of extraKeys) {
74
+ if (byKey.has(key))
75
+ continue;
76
+ const { tasks: found } = await listTasks({
77
+ search: key,
78
+ includeDone: true,
79
+ });
80
+ const match = found.find((t) => t.taskKey.replace(/^#/, "") === key) ?? found[0];
81
+ if (match)
82
+ byKey.set(match.taskKey.replace(/^#/, ""), match);
83
+ }
84
+ const extra = new Set(extraKeys);
85
+ return [...byKey.values()].filter((task) => {
86
+ const key = task.taskKey.replace(/^#/, "");
87
+ return extra.has(key) || taskTouchedOnDate(toTaskRef(task), iso);
88
+ });
89
+ }
90
+ async function buildFillDraft(opts) {
91
+ const iso = opts.date;
92
+ const activity = gatherDayActivity(iso);
93
+ for (const warning of activity.warnings)
94
+ warn(warning);
95
+ const extraKeys = activityTaskKeys(activity);
96
+ const { hours, baseUrl } = await listHours({ from: iso, to: iso });
97
+ const userId = hours.currentUserId;
98
+ const existing = entryForDay(hours, userId, iso);
99
+ const dayStart = startOfDay(fromIsoDate(iso));
100
+ const dayEnd = endOfDay(fromIsoDate(iso));
101
+ const [dayTasks, { events }, { accounts }] = await Promise.all([
102
+ tasksForDay(iso, userId, extraKeys),
103
+ listEvents({
104
+ start: dayStart,
105
+ end: dayEnd,
106
+ expand: true,
107
+ }),
108
+ listCalendars(),
109
+ ]);
110
+ const calendarNameById = new Map(accounts.flatMap((account) => account.calendars.map((calendar) => [calendar.id, calendar.name])));
111
+ let notes = opts.notes;
112
+ if (opts.notesFile) {
113
+ const source = opts.notesFile === "-" ? 0 : opts.notesFile;
114
+ notes = readFileSync(source, "utf8");
115
+ }
116
+ notes = notes?.trim();
117
+ if (!notes) {
118
+ notes = draftHoursNotes({
119
+ tasks: dayTasks.map(toTaskRef),
120
+ commits: activity.commits,
121
+ pullRequests: activity.pullRequests,
122
+ events: events.map((event) => ({
123
+ title: event.title,
124
+ calendarName: calendarNameById.get(event.calendarId) ?? null,
125
+ })),
126
+ });
127
+ }
128
+ const hourDefaults = defaultsFor(hours, userId);
129
+ let minutes = defaultMinutesFor(hourDefaults, iso);
130
+ if (opts.hours) {
131
+ const parsed = parseHoursInput(opts.hours);
132
+ if (parsed === null)
133
+ fail(`Invalid --hours value: ${opts.hours}`);
134
+ minutes = parsed;
135
+ }
136
+ else if (existing) {
137
+ minutes = existing.minutes;
138
+ }
139
+ if (!notes && existing?.notes)
140
+ notes = existing.notes;
141
+ return {
142
+ date: iso,
143
+ minutes,
144
+ notes: notes ?? "",
145
+ existing,
146
+ tasks: dayTasks.map(toTaskRef),
147
+ commits: activity.commits,
148
+ pullRequests: activity.pullRequests,
149
+ warnings: activity.warnings,
150
+ dashboardUrl: hoursDashboardUrl(baseUrl),
151
+ };
152
+ }
153
+ async function writeDayLog(input) {
154
+ if (input.existing && !input.replace) {
155
+ const same = input.existing.minutes === input.minutes &&
156
+ (input.existing.notes ?? "").trim() === input.notes.trim();
157
+ if (same) {
158
+ ok(`${input.date} stond al zo op de urenstaat (${formatMinutes(input.minutes)}).`);
159
+ return;
160
+ }
161
+ fail(`${input.date} heeft al ${formatMinutes(input.existing.minutes)}` +
162
+ `${input.existing.notes ? ` — ${input.existing.notes}` : ""}. ` +
163
+ `Gebruik --replace om te overschrijven.`);
164
+ }
165
+ const { entry, baseUrl } = await upsertHours({
166
+ workedOn: input.date,
167
+ minutes: input.minutes,
168
+ notes: input.notes || null,
169
+ });
170
+ if (!entry) {
171
+ ok(`${input.date} gewist (0u zonder toelichting).`);
172
+ return;
173
+ }
174
+ ok(`${entry.workedOn} ${formatMinutes(entry.minutes)} ${entry.notes ?? ""}`.trimEnd());
175
+ process.stdout.write(`${hoursDashboardUrl(baseUrl)}\n`);
176
+ }
177
+ export function registerHoursCommands(program) {
178
+ const hours = program
179
+ .command("hours")
180
+ .description("Urenstaat: tonen, voorstellen vanuit taken/commits/PRs, of wegschrijven")
181
+ .option("--from <date>", "Range start (ISO, of today/yesterday/+3d)")
182
+ .option("--to <date>", "Range end (inclusive)")
183
+ .option("--days <n>", "Aantal dagen vanaf --from of vandaag")
184
+ .option("--today", "Alleen vandaag (standaard)")
185
+ .option("--week", "Huidige week (ma-zo)")
186
+ .option("--month", "Huidige kalendermaand")
187
+ .option("--json", "Output as JSON")
188
+ .action(async (opts) => {
189
+ try {
190
+ const range = resolveRange(opts);
191
+ const from = localDayKey(range.start);
192
+ const to = localDayKey(range.end);
193
+ const { hours: payload, baseUrl } = await listHours({ from, to });
194
+ if (opts.json) {
195
+ process.stdout.write(`${JSON.stringify({
196
+ ...payload,
197
+ dashboardUrl: hoursDashboardUrl(baseUrl),
198
+ }, null, 2)}\n`);
199
+ return;
200
+ }
201
+ printHoursList(payload, payload.currentUserId, baseUrl);
202
+ }
203
+ catch (err) {
204
+ fail(err instanceof Error ? err.message : String(err));
205
+ }
206
+ });
207
+ hours
208
+ .command("fill")
209
+ .description("Stel uren voor vanuit Calendar-taken, git-commits en PRs (en schrijf weg met --write)")
210
+ .option("--date <date>", "Dag (ISO, today, yesterday, -1d). Standaard vandaag")
211
+ .option("--hours <hours>", "Uren (8, 7,5, 7:30). Standaard je weekdefault")
212
+ .option("--notes <text>", "Eigen toelichting in plaats van de samenvatting")
213
+ .option("--notes-file <path>", "Toelichting uit bestand (`-` = stdin)")
214
+ .option("--write", "Schrijf de regel naar de urenstaat")
215
+ .option("--replace", "Overschrijf een bestaande regel")
216
+ .option("--json", "Output as JSON")
217
+ .action(async (opts) => {
218
+ try {
219
+ const draft = await buildFillDraft({
220
+ date: resolveWorkedOn(opts.date),
221
+ hours: opts.hours,
222
+ notes: opts.notes,
223
+ notesFile: opts.notesFile,
224
+ });
225
+ if (opts.json) {
226
+ process.stdout.write(`${JSON.stringify(draft, null, 2)}\n`);
227
+ }
228
+ else {
229
+ process.stdout.write(`${draft.date} ${formatMinutes(draft.minutes)}\n`);
230
+ process.stdout.write(` ${draft.notes || "(geen toelichting)"}\n`);
231
+ if (draft.tasks.length) {
232
+ process.stdout.write(` taken: ${draft.tasks.map((t) => `#${t.taskKey}`).join(", ")}\n`);
233
+ }
234
+ if (draft.commits.length) {
235
+ process.stdout.write(` commits: ${draft.commits.length}\n`);
236
+ for (const commit of draft.commits.slice(0, 8)) {
237
+ process.stdout.write(` ${commit.subject}\n`);
238
+ }
239
+ }
240
+ if (draft.pullRequests.length) {
241
+ process.stdout.write(` PRs: ${draft.pullRequests.map((pr) => `#${pr.number}`).join(", ")}\n`);
242
+ }
243
+ if (draft.existing) {
244
+ process.stdout.write(` bestaat al: ${formatMinutes(draft.existing.minutes)}` +
245
+ `${draft.existing.notes ? ` — ${draft.existing.notes}` : ""}\n`);
246
+ }
247
+ process.stdout.write(` ${draft.dashboardUrl}\n`);
248
+ if (!opts.write) {
249
+ process.stdout.write(`\nNog niet weggeschreven. Voeg --write toe om ${draft.date} op de urenstaat te zetten.\n`);
250
+ }
251
+ }
252
+ if (opts.write) {
253
+ await writeDayLog({
254
+ date: draft.date,
255
+ minutes: draft.minutes,
256
+ notes: draft.notes,
257
+ replace: Boolean(opts.replace),
258
+ existing: draft.existing,
259
+ });
260
+ }
261
+ }
262
+ catch (err) {
263
+ fail(err instanceof Error ? err.message : String(err));
264
+ }
265
+ });
266
+ hours
267
+ .command("log")
268
+ .description("Schrijf uren voor één dag (zonder git/taken-voorstel)")
269
+ .option("--date <date>", "Dag (ISO, today, yesterday). Standaard vandaag")
270
+ .requiredOption("--hours <hours>", "Uren (8, 7,5, 7:30)")
271
+ .option("--notes <text>", "Wat je gedaan hebt")
272
+ .option("--notes-file <path>", "Toelichting uit bestand (`-` = stdin)")
273
+ .option("--replace", "Overschrijf een bestaande regel")
274
+ .option("--json", "Output the saved entry as JSON")
275
+ .action(async (opts) => {
276
+ try {
277
+ const iso = resolveWorkedOn(opts.date);
278
+ const minutes = parseHoursInput(opts.hours);
279
+ if (minutes === null)
280
+ fail(`Invalid --hours value: ${opts.hours}`);
281
+ let notes = opts.notes;
282
+ if (opts.notesFile) {
283
+ const source = opts.notesFile === "-" ? 0 : opts.notesFile;
284
+ notes = readFileSync(source, "utf8");
285
+ }
286
+ notes = notes?.trim() ?? "";
287
+ const { hours, baseUrl } = await listHours({ from: iso, to: iso });
288
+ const existing = entryForDay(hours, hours.currentUserId, iso);
289
+ if (opts.json) {
290
+ if (existing && !opts.replace) {
291
+ const same = existing.minutes === minutes &&
292
+ (existing.notes ?? "").trim() === notes;
293
+ if (!same) {
294
+ fail(`${iso} heeft al een regel. Gebruik --replace om te overschrijven.`);
295
+ }
296
+ }
297
+ const { entry } = await upsertHours({
298
+ workedOn: iso,
299
+ minutes,
300
+ notes: notes || null,
301
+ });
302
+ process.stdout.write(`${JSON.stringify({ entry, dashboardUrl: hoursDashboardUrl(baseUrl) }, null, 2)}\n`);
303
+ return;
304
+ }
305
+ await writeDayLog({
306
+ date: iso,
307
+ minutes,
308
+ notes,
309
+ replace: Boolean(opts.replace),
310
+ existing,
311
+ });
312
+ }
313
+ catch (err) {
314
+ fail(err instanceof Error ? err.message : String(err));
315
+ }
316
+ });
317
+ hours
318
+ .command("delete")
319
+ .description("Verwijder de urenstaat-regel van één dag")
320
+ .option("--date <date>", "Dag (ISO, today, yesterday). Standaard vandaag")
321
+ .action(async (opts) => {
322
+ try {
323
+ const iso = resolveWorkedOn(opts.date);
324
+ const { deleted, baseUrl } = await deleteHours({ workedOn: iso });
325
+ if (deleted)
326
+ ok(`Deleted hours for ${iso}`);
327
+ else
328
+ process.stdout.write(`No hours logged on ${iso}.\n`);
329
+ process.stdout.write(`${hoursDashboardUrl(baseUrl)}\n`);
330
+ }
331
+ catch (err) {
332
+ fail(err instanceof Error ? err.message : String(err));
333
+ }
334
+ });
335
+ }
package/dist/hours.js ADDED
@@ -0,0 +1,276 @@
1
+ /**
2
+ * Pure helpers for the Calendar timesheet (urenstaat).
3
+ *
4
+ * `workedOn` is a YYYY-MM-DD calendar date, never a timestamp: parsing
5
+ * `new Date("2026-08-31")` as UTC midnight shifts the booked day in a
6
+ * negative-offset timezone.
7
+ */
8
+ export const MAX_MINUTES_PER_DAY = 24 * 60;
9
+ /** Dashboard field is one line but unbounded; keep a ceiling for sanity. */
10
+ export const NOTES_MAX_LENGTH = 600;
11
+ export const FALLBACK_WEEKDAY_MINUTES = [
12
+ 480, 480, 480, 480, 480, 0, 0,
13
+ ];
14
+ export const WEEKDAY_LABELS_NL_SHORT = [
15
+ "ma",
16
+ "di",
17
+ "wo",
18
+ "do",
19
+ "vr",
20
+ "za",
21
+ "zo",
22
+ ];
23
+ export function isIsoDate(value) {
24
+ return typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value);
25
+ }
26
+ export function toIsoDate(date) {
27
+ const y = date.getFullYear();
28
+ const m = String(date.getMonth() + 1).padStart(2, "0");
29
+ const d = String(date.getDate()).padStart(2, "0");
30
+ return `${y}-${m}-${d}`;
31
+ }
32
+ export function todayIso(now = new Date()) {
33
+ return toIsoDate(now);
34
+ }
35
+ /** YYYY-MM-DD to a Date at local midnight (no UTC shift). */
36
+ export function fromIsoDate(iso) {
37
+ const [y, m, d] = iso.split("-").map(Number);
38
+ return new Date(y, m - 1, d);
39
+ }
40
+ /** Weekday index of a YYYY-MM-DD string, 0 = Monday. */
41
+ export function weekdayIndex(iso) {
42
+ const [y, m, d] = iso.split("-").map(Number);
43
+ const jsDay = new Date(Date.UTC(y, m - 1, d)).getUTCDay();
44
+ return (jsDay + 6) % 7;
45
+ }
46
+ export function clampMinutes(value) {
47
+ if (!Number.isFinite(value))
48
+ return 0;
49
+ return Math.min(MAX_MINUTES_PER_DAY, Math.max(0, Math.round(value)));
50
+ }
51
+ export function defaultMinutesFor(defaults, iso) {
52
+ return defaults.weekdayMinutes[weekdayIndex(iso)] ?? 0;
53
+ }
54
+ export function formatMinutes(totalMinutes) {
55
+ const sign = totalMinutes < 0 ? "-" : "";
56
+ const abs = Math.abs(Math.round(totalMinutes));
57
+ const h = Math.floor(abs / 60);
58
+ const m = abs % 60;
59
+ if (h && m)
60
+ return `${sign}${h}u ${m}m`;
61
+ if (h)
62
+ return `${sign}${h}u`;
63
+ return `${sign}${m}m`;
64
+ }
65
+ export function minutesToHoursInput(minutes) {
66
+ if (!minutes)
67
+ return "";
68
+ const hours = minutes / 60;
69
+ return (Math.round(hours * 100) / 100).toString().replace(".", ",");
70
+ }
71
+ /**
72
+ * What someone types in the hours field: `7,5`, `7.5`, `7:30`, `7u30`.
73
+ * `null` = unreadable (do not coerce to 0).
74
+ */
75
+ export function parseHoursInput(raw) {
76
+ const value = raw.trim().toLowerCase().replace(",", ".");
77
+ if (!value)
78
+ return 0;
79
+ const clock = /^(\d{1,2})\s*[:u]\s*(\d{1,2})$/.exec(value);
80
+ if (clock) {
81
+ const h = Number(clock[1]);
82
+ const m = Number(clock[2]);
83
+ if (m > 59)
84
+ return null;
85
+ return clampMinutes(h * 60 + m);
86
+ }
87
+ const plain = /^(\d{1,2})(?:\.(\d{1,2}))?\s*u?$/.exec(value);
88
+ if (plain) {
89
+ return clampMinutes(Number(plain[1] + (plain[2] ? `.${plain[2]}` : "")) * 60);
90
+ }
91
+ return null;
92
+ }
93
+ /** Calendar task keys mentioned as `IF-687`, legacy `IP-687`, or `#687` (not GitHub `(#123)`). */
94
+ export function extractTaskKeys(text) {
95
+ const keys = new Set();
96
+ for (const match of text.matchAll(/\b(?:IF|IP)-(\d+)\b/gi)) {
97
+ keys.add(match[1]);
98
+ }
99
+ for (const match of text.matchAll(/(?<![\w(])#(\d+)\b(?!\))/g)) {
100
+ keys.add(match[1]);
101
+ }
102
+ return [...keys];
103
+ }
104
+ export function instantToLocalIso(value) {
105
+ if (!value)
106
+ return null;
107
+ const date = value instanceof Date ? value : new Date(value);
108
+ if (Number.isNaN(date.getTime()))
109
+ return null;
110
+ return toIsoDate(date);
111
+ }
112
+ export function taskTouchedOnDate(task, iso) {
113
+ return (instantToLocalIso(task.updatedAt) === iso ||
114
+ instantToLocalIso(task.createdAt) === iso ||
115
+ instantToLocalIso(task.completedAt) === iso);
116
+ }
117
+ const GENERIC_SUBTASK = /^(implement|pr review|testen)$/i;
118
+ export function isGenericSubtask(task) {
119
+ return Boolean(task.parentTaskId) && GENERIC_SUBTASK.test(task.title.trim());
120
+ }
121
+ function shortTitle(title, max = 48) {
122
+ const cleaned = title.replace(/\s+/g, " ").trim();
123
+ if (cleaned.length <= max)
124
+ return cleaned;
125
+ const sliced = cleaned.slice(0, max - 1);
126
+ const atSpace = sliced.lastIndexOf(" ");
127
+ return `${(atSpace > 20 ? sliced.slice(0, atSpace) : sliced).trimEnd()}…`;
128
+ }
129
+ const CONVENTIONAL = /^(feat|fix|chore|refactor|docs|test|style|perf)(?:\(([^)]+)\))?:\s*/i;
130
+ const JUNK_COMMIT = /^(index on |untracked files |t3 checkpoint )/i;
131
+ const PERSONAL_CALENDAR = /gezin|family|priv[eé]|personal|kids|thuis/i;
132
+ const SKIP_EVENT = /^(busy|out of office|ooo|focus)$/i;
133
+ export function isJunkCommitSubject(subject) {
134
+ return JUNK_COMMIT.test(subject.trim());
135
+ }
136
+ function stripConventional(title) {
137
+ return title.replace(CONVENTIONAL, "").trim();
138
+ }
139
+ const BUCKET_ORDER = [
140
+ "Guard",
141
+ "Calendar",
142
+ "Env",
143
+ "Support",
144
+ "Infaris",
145
+ "Platform",
146
+ "Reviews",
147
+ "Agenda",
148
+ ];
149
+ function bucketForProductOrScope(raw) {
150
+ const value = (raw ?? "").toLowerCase();
151
+ if (!value)
152
+ return "Platform";
153
+ if (value.includes("guard"))
154
+ return "Guard";
155
+ if (value.includes("calendar"))
156
+ return "Calendar";
157
+ if (value.includes("env"))
158
+ return "Env";
159
+ if (value.includes("support"))
160
+ return "Support";
161
+ if (value.includes("infaris") || value === "ipulse")
162
+ return "Infaris";
163
+ return "Platform";
164
+ }
165
+ function scopeFromTitle(title) {
166
+ const match = CONVENTIONAL.exec(title.trim());
167
+ return match?.[2] ?? null;
168
+ }
169
+ function pushUnique(list, value) {
170
+ const trimmed = value.replace(/\s+/g, " ").trim();
171
+ if (!trimmed)
172
+ return;
173
+ const key = trimmed.toLowerCase();
174
+ if (list.some((item) => item.toLowerCase() === key))
175
+ return;
176
+ list.push(trimmed);
177
+ }
178
+ function formatGroup(label, group) {
179
+ const phrases = group.phrases.slice(0, 4);
180
+ const keys = group.keys.slice(0, 8).map((key) => `#${key}`);
181
+ if (phrases.length === 0 && keys.length === 0)
182
+ return "";
183
+ if (phrases.length === 0)
184
+ return `${label}: ${keys.join(" ")}`;
185
+ if (keys.length === 0)
186
+ return `${label}: ${phrases.join(", ")}`;
187
+ return `${label}: ${phrases.join(", ")} (${keys.join(" ")})`;
188
+ }
189
+ /**
190
+ * One-line "wat heb je gedaan?": fetch every task/commit/PR/meeting for the
191
+ * day, then summarise by product. Do not invent work that is not in the input.
192
+ */
193
+ export function draftHoursNotes(input) {
194
+ const tasks = (input.tasks ?? []).filter((task) => !isGenericSubtask(task));
195
+ const taskKeys = new Set(tasks.map((task) => task.taskKey.replace(/^#/, "")));
196
+ const groups = new Map();
197
+ const group = (bucket) => {
198
+ const current = groups.get(bucket) ?? { phrases: [], keys: [] };
199
+ groups.set(bucket, current);
200
+ return current;
201
+ };
202
+ for (const task of tasks) {
203
+ const key = task.taskKey.replace(/^#/, "");
204
+ const bucket = bucketForProductOrScope(task.product);
205
+ const target = group(bucket);
206
+ pushUnique(target.keys, key);
207
+ pushUnique(target.phrases, shortTitle(task.title, 42));
208
+ }
209
+ for (const pr of input.pullRequests ?? []) {
210
+ const keys = extractTaskKeys(`${pr.title} ${pr.url ?? ""}`);
211
+ if (keys.some((key) => taskKeys.has(key)))
212
+ continue;
213
+ const phrase = shortTitle(stripConventional(pr.title), 40);
214
+ if (pr.reviewed) {
215
+ pushUnique(group("Reviews").phrases, phrase);
216
+ continue;
217
+ }
218
+ const bucket = bucketForProductOrScope(scopeFromTitle(pr.title));
219
+ const target = group(bucket);
220
+ pushUnique(target.phrases, phrase);
221
+ }
222
+ for (const commit of input.commits ?? []) {
223
+ if (isJunkCommitSubject(commit.subject))
224
+ continue;
225
+ const keys = extractTaskKeys(commit.subject);
226
+ if (keys.some((key) => taskKeys.has(key)))
227
+ continue;
228
+ const bucket = bucketForProductOrScope(scopeFromTitle(commit.subject));
229
+ pushUnique(group(bucket).phrases, shortTitle(stripConventional(commit.subject), 40));
230
+ }
231
+ for (const event of input.events ?? []) {
232
+ const title = event.title.replace(/\s+/g, " ").trim();
233
+ if (!title || SKIP_EVENT.test(title))
234
+ continue;
235
+ if (event.calendarName && PERSONAL_CALENDAR.test(event.calendarName)) {
236
+ continue;
237
+ }
238
+ pushUnique(group("Agenda").phrases, shortTitle(title, 36));
239
+ }
240
+ const parts = BUCKET_ORDER.flatMap((label) => {
241
+ const current = groups.get(label);
242
+ if (!current)
243
+ return [];
244
+ const formatted = formatGroup(label, current);
245
+ return formatted ? [formatted] : [];
246
+ });
247
+ const joined = parts.join(". ");
248
+ if (joined.length <= NOTES_MAX_LENGTH)
249
+ return joined;
250
+ return joined.slice(0, NOTES_MAX_LENGTH - 1).trimEnd() + "…";
251
+ }
252
+ /** Parse `hash\\tauthor\\temail\\tsubject` lines from `git log --format`. */
253
+ export function parseGitLog(text) {
254
+ const commits = [];
255
+ for (const line of text.split("\n")) {
256
+ if (!line.trim())
257
+ continue;
258
+ const [hash, authorName, authorEmail, ...rest] = line.split("\t");
259
+ if (!hash || rest.length === 0)
260
+ continue;
261
+ commits.push({
262
+ hash,
263
+ authorName: authorName ?? "",
264
+ authorEmail: (authorEmail ?? "").toLowerCase(),
265
+ subject: rest.join("\t"),
266
+ });
267
+ }
268
+ return commits;
269
+ }
270
+ export function filterCommitsByAuthor(commits, identity) {
271
+ const emails = new Set(identity.emails.map((e) => e.toLowerCase()).filter(Boolean));
272
+ const names = new Set(identity.names.map((n) => n.toLowerCase()).filter(Boolean));
273
+ if (emails.size === 0 && names.size === 0)
274
+ return commits;
275
+ return commits.filter((c) => emails.has(c.authorEmail) || names.has(c.authorName.toLowerCase()));
276
+ }