@bbcsoftwarefactory/cli 0.1.1 → 1.1.2

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.
Files changed (86) hide show
  1. package/dist/audit-ledger.d.ts +2 -0
  2. package/dist/audit-ledger.js +71 -0
  3. package/dist/bbc-install.d.ts +2 -0
  4. package/dist/bbc-install.js +1250 -0
  5. package/dist/bbc.js +87 -3
  6. package/dist/change-lane/classification.js +3 -1
  7. package/dist/check-issue-claim.d.ts +2 -0
  8. package/dist/check-issue-claim.js +146 -0
  9. package/dist/check-worktree-guard.d.ts +2 -0
  10. package/dist/check-worktree-guard.js +114 -0
  11. package/dist/error-scan.d.ts +3 -0
  12. package/dist/error-scan.js +216 -0
  13. package/dist/export-public.d.ts +9 -0
  14. package/dist/export-public.js +274 -0
  15. package/dist/fetch-issue-attachments.d.ts +22 -0
  16. package/dist/fetch-issue-attachments.js +325 -0
  17. package/dist/issue-claim/evaluation.d.ts +66 -0
  18. package/dist/issue-claim/evaluation.js +259 -0
  19. package/dist/issue-claim/loaders.d.ts +5 -0
  20. package/dist/issue-claim/loaders.js +116 -0
  21. package/dist/list-zed-commands.d.ts +7 -0
  22. package/dist/list-zed-commands.js +288 -0
  23. package/dist/plan-issue-triage.d.ts +3 -0
  24. package/dist/plan-issue-triage.js +404 -0
  25. package/dist/question-gate/ledger.d.ts +5 -0
  26. package/dist/question-gate/ledger.js +115 -0
  27. package/dist/question-gate/rules.d.ts +40 -0
  28. package/dist/question-gate/rules.js +483 -0
  29. package/dist/recap/board.d.ts +5 -0
  30. package/dist/recap/board.js +384 -0
  31. package/dist/recap/git-and-github.d.ts +11 -0
  32. package/dist/recap/git-and-github.js +620 -0
  33. package/dist/recap/report-and-hud.d.ts +2 -0
  34. package/dist/recap/report-and-hud.js +294 -0
  35. package/dist/recap/time-and-refs.d.ts +27 -0
  36. package/dist/recap/time-and-refs.js +148 -0
  37. package/dist/recap.d.ts +2 -0
  38. package/dist/recap.js +217 -0
  39. package/dist/render-workflow.js +12 -14
  40. package/dist/resolve-containers.d.ts +2 -0
  41. package/dist/resolve-containers.js +96 -0
  42. package/dist/review-loop.d.ts +7 -0
  43. package/dist/review-loop.js +622 -0
  44. package/dist/save-counts.d.ts +2 -0
  45. package/dist/save-counts.js +191 -0
  46. package/dist/summarize-logs.d.ts +2 -0
  47. package/dist/summarize-logs.js +41 -0
  48. package/dist/sweep-github.d.ts +10 -0
  49. package/dist/sweep-github.js +453 -0
  50. package/dist/sweep-issues.d.ts +56 -0
  51. package/dist/sweep-issues.js +650 -0
  52. package/dist/sweep.d.ts +2 -0
  53. package/dist/sweep.js +301 -0
  54. package/dist/triage-question.d.ts +2 -0
  55. package/dist/triage-question.js +189 -0
  56. package/dist/validate-skills.d.ts +2 -0
  57. package/dist/validate-skills.js +48 -0
  58. package/dist/watch-live.d.ts +7 -0
  59. package/dist/watch-live.js +83 -0
  60. package/dist/watcher/config.d.ts +11 -0
  61. package/dist/watcher/config.js +265 -0
  62. package/dist/watcher/live-classifier.d.ts +52 -0
  63. package/dist/watcher/live-classifier.js +510 -0
  64. package/dist/watcher/safe-fs.d.ts +9 -0
  65. package/dist/watcher/safe-fs.js +159 -0
  66. package/dist/watcher/stream.d.ts +27 -0
  67. package/dist/watcher/stream.js +340 -0
  68. package/dist/watcher/summarizer.d.ts +19 -0
  69. package/dist/watcher/summarizer.js +121 -0
  70. package/dist/wave3/process.d.ts +14 -0
  71. package/dist/wave3/process.js +84 -0
  72. package/dist/wave4/process.d.ts +14 -0
  73. package/dist/wave4/process.js +128 -0
  74. package/dist/workflow/render.d.ts +1 -1
  75. package/dist/workflow/render.js +1 -1
  76. package/dist/workflow-auditor/audit.d.ts +27 -0
  77. package/dist/workflow-auditor/audit.js +583 -0
  78. package/dist/workflow-auditor/ledger-io.d.ts +5 -0
  79. package/dist/workflow-auditor/ledger-io.js +99 -0
  80. package/dist/workflow-auditor/skills-validator.d.ts +10 -0
  81. package/dist/workflow-auditor/skills-validator.js +533 -0
  82. package/dist/worktree-guard/evaluation.d.ts +19 -0
  83. package/dist/worktree-guard/evaluation.js +84 -0
  84. package/dist/worktree-guard/git.d.ts +3 -0
  85. package/dist/worktree-guard/git.js +61 -0
  86. package/package.json +32 -33
@@ -0,0 +1,294 @@
1
+ /**
2
+ * LAYER: Application
3
+ * Contains: Daily recap metric aggregator and bilingual HUD formatter.
4
+ * Rules: Never invent missing metrics; zero denominators and offline sources render as GAP/N/A.
5
+ * BigO: O(n) score:4
6
+ * keywords: [RecapReport, RatioEntry, HudFormatter, Effectiveness]
7
+ * GOAL: Compute structured daily progress metrics and render the ES/EN HUD summary.
8
+ */
9
+ import { summarizeProjectBoard } from "./board.js";
10
+ import { inWindow, parseSince } from "./time-and-refs.js";
11
+ function ratioEntry(numerator, denominator, zeroDenomLabel) {
12
+ if (numerator === null || denominator === null) {
13
+ return { numerator, denominator, pct: null, status: 'gap', display: 'N/A' };
14
+ }
15
+ if (denominator === 0) {
16
+ if (numerator > 0 && zeroDenomLabel) {
17
+ return { numerator, denominator: 0, pct: null, status: 'green', display: zeroDenomLabel };
18
+ }
19
+ return { numerator, denominator: 0, pct: null, status: 'na', display: 'N/A' };
20
+ }
21
+ const pct = Math.round((numerator / denominator) * 100);
22
+ const status = pct >= 70 ? 'green' : pct >= 40 ? 'yellow' : 'red';
23
+ return { numerator, denominator, pct, status, display: `${numerator}/${denominator} (${pct}%)` };
24
+ }
25
+ export function computeRecap(payload) {
26
+ const sinceDt = payload.since ? parseSince(String(payload.since)) : parseSince();
27
+ const ghOk = Boolean(payload.github_available);
28
+ const local = payload.local_git !== null && typeof payload.local_git === 'object' && !Array.isArray(payload.local_git)
29
+ ? payload.local_git
30
+ : { available: false };
31
+ const gaps = Array.isArray(payload.gaps) ? [...payload.gaps] : [];
32
+ if (!ghOk && payload.github_gap) {
33
+ gaps.push(String(payload.github_gap));
34
+ }
35
+ let issuesCreated = null;
36
+ let issuesClosed = null;
37
+ let prsOpened = null;
38
+ let prsMerged = null;
39
+ let prsInProgress = null;
40
+ let reviewsCount = null;
41
+ if (ghOk) {
42
+ issuesCreated = (payload.issues_created ?? []).filter((it) => it !== null && typeof it === 'object' && inWindow(it.created_at, sinceDt.ms));
43
+ issuesClosed = (payload.issues_closed ?? []).filter((it) => it !== null && typeof it === 'object' && inWindow(it.closed_at, sinceDt.ms));
44
+ prsOpened = (payload.prs_opened ?? []).filter((it) => it !== null && typeof it === 'object' && inWindow(it.created_at, sinceDt.ms));
45
+ prsMerged = (payload.prs_merged ?? []).filter((it) => it !== null && typeof it === 'object' && inWindow(it.merged_at, sinceDt.ms));
46
+ prsInProgress = (payload.prs_in_progress ?? []).filter((it) => it !== null && typeof it === 'object' && inWindow(it.updated_at, sinceDt.ms));
47
+ reviewsCount = Number(payload.reviews_and_comments ?? 0);
48
+ }
49
+ const localAvailable = Boolean(local.available);
50
+ const commits = localAvailable ? local.commits : null;
51
+ const filesChanged = localAvailable ? local.files_changed : null;
52
+ const insertions = localAvailable ? local.insertions : null;
53
+ const deletions = localAvailable ? local.deletions : null;
54
+ const aheadCommits = localAvailable ? local.ahead_commits : null;
55
+ const workingChanges = localAvailable ? local.working_changes : null;
56
+ if (!localAvailable && local.reason) {
57
+ gaps.push(`Local Git unavailable: ${String(local.reason)}`);
58
+ }
59
+ const createdCount = issuesCreated ? issuesCreated.length : null;
60
+ const closedCount = issuesClosed ? issuesClosed.length : null;
61
+ const openedCount = prsOpened ? prsOpened.length : null;
62
+ const mergedCount = prsMerged ? prsMerged.length : null;
63
+ const solvedTotal = closedCount !== null && mergedCount !== null ? closedCount + mergedCount : null;
64
+ const prsOpenUpdated = prsInProgress ? prsInProgress.length : null;
65
+ const prsDraft = prsInProgress ? prsInProgress.filter((pr) => Boolean(pr.draft)).length : null;
66
+ const prsReady = prsOpenUpdated !== null && prsDraft !== null ? prsOpenUpdated - prsDraft : null;
67
+ let ciPass;
68
+ if (prsOpened !== null) {
69
+ const checkedPrs = prsOpened.filter((pr) => pr.ci_status === 'success' || pr.ci_status === 'failing');
70
+ const greenPrs = checkedPrs.filter((pr) => pr.ci_status === 'success');
71
+ ciPass = ratioEntry(greenPrs.length, checkedPrs.length);
72
+ }
73
+ else {
74
+ ciPass = ratioEntry(null, null);
75
+ }
76
+ const mergeRatio = ratioEntry(mergedCount, openedCount, mergedCount ? `${mergedCount} merged (0 opened)` : null);
77
+ const closeRatio = ratioEntry(closedCount, createdCount, closedCount ? `${closedCount} closed (0 created)` : null);
78
+ const report = {
79
+ user: payload.user ?? null,
80
+ repo: payload.repo ?? 'all-repos',
81
+ since: sinceDt.iso,
82
+ github_available: ghOk,
83
+ local_available: localAvailable,
84
+ branch: localAvailable ? (local.branch ?? null) : null,
85
+ issues_created: { count: createdCount, items: issuesCreated ?? [] },
86
+ issues_closed: { count: closedCount, items: issuesClosed ?? [] },
87
+ prs_opened: { count: openedCount, items: prsOpened ?? [] },
88
+ contribution: {
89
+ commits,
90
+ files_changed: filesChanged,
91
+ insertions,
92
+ deletions,
93
+ reviews_and_comments: reviewsCount,
94
+ },
95
+ solved: {
96
+ issues_closed: closedCount,
97
+ prs_merged: mergedCount,
98
+ total: solvedTotal,
99
+ merged_items: prsMerged ?? [],
100
+ },
101
+ progress: {
102
+ prs_open_updated: prsOpenUpdated,
103
+ prs_ready: prsReady,
104
+ prs_draft: prsDraft,
105
+ ahead_commits: aheadCommits,
106
+ working_changes: workingChanges,
107
+ },
108
+ effectiveness: {
109
+ pr_merge_ratio: mergeRatio,
110
+ ci_pass_rate: ciPass,
111
+ issue_close_ratio: closeRatio,
112
+ },
113
+ gaps,
114
+ };
115
+ if (payload.team !== undefined && payload.team !== null) {
116
+ report.team = payload.team;
117
+ }
118
+ const rawProject = payload.project;
119
+ if (rawProject !== undefined && rawProject !== null) {
120
+ let activityItems = Array.isArray(payload.project_activity_items)
121
+ ? ([...payload.project_activity_items])
122
+ : [];
123
+ if (activityItems.length === 0 && ghOk) {
124
+ activityItems = [
125
+ ...(issuesCreated ?? []),
126
+ ...(issuesClosed ?? []).map((it) => ({ ...it, state: it.state ?? 'closed' })),
127
+ ...(prsInProgress ?? []).map((pr) => ({ ...pr, is_pr: true })),
128
+ ...(prsOpened ?? []).filter((pr) => pr.state === 'open').map((pr) => ({ ...pr, is_pr: true })),
129
+ ];
130
+ }
131
+ const projSummary = summarizeProjectBoard(rawProject, activityItems, typeof payload.repo === 'string' ? payload.repo : null);
132
+ if (!projSummary.available && projSummary.gap) {
133
+ gaps.push(String(projSummary.gap));
134
+ }
135
+ report.project = projSummary;
136
+ }
137
+ if (payload.board_sync !== undefined && payload.board_sync !== null) {
138
+ report.board_sync = payload.board_sync;
139
+ }
140
+ return report;
141
+ }
142
+ function light(status) {
143
+ return ({ green: '🟢', yellow: '🟡', red: '🔴', na: '⚪', gap: '🟡' }[String(status)] ?? '⚪');
144
+ }
145
+ function fmtNum(val, gapText = '🟡 GAP') {
146
+ return val !== null && val !== undefined ? String(val) : gapText;
147
+ }
148
+ function formatTeamLines(team, isEs) {
149
+ if (!Array.isArray(team) || team.length === 0)
150
+ return [];
151
+ const header = isEs ? '├── 👥 Equipo' : '├── 👥 Team';
152
+ const lines = [header];
153
+ for (let idx = 0; idx < team.length; idx++) {
154
+ const member = team[idx];
155
+ const branchChar = idx === team.length - 1 ? '└──' : '├──';
156
+ const login = String(member.user ?? '?');
157
+ if (!member.available) {
158
+ lines.push(`│ ${branchChar} @${login} · 🟡 GAP (${String(member.gap ?? 'unavailable')})`);
159
+ continue;
160
+ }
161
+ if (isEs) {
162
+ lines.push(`│ ${branchChar} @${login} · ${String(member.issues_created)} creados · ` +
163
+ `${String(member.issues_closed)} cerrados · ${String(member.prs_merged)}/${String(member.prs_opened)} PRs mergeados`);
164
+ }
165
+ else {
166
+ lines.push(`│ ${branchChar} @${login} · ${String(member.issues_created)} created · ` +
167
+ `${String(member.issues_closed)} closed · ${String(member.prs_merged)}/${String(member.prs_opened)} PRs merged`);
168
+ }
169
+ }
170
+ return lines;
171
+ }
172
+ function formatProjectLines(proj, isEs) {
173
+ if (proj === null || typeof proj !== 'object')
174
+ return [];
175
+ const rec = proj;
176
+ if (!rec.available) {
177
+ const label = isEs ? '├── 📋 Tablero' : '├── 📋 Board';
178
+ return [`${label} · 🟡 GAP (${String(rec.gap ?? 'unavailable')})`];
179
+ }
180
+ const title = String(rec.title ?? 'Project');
181
+ const viewName = rec.view_name ? String(rec.view_name) : null;
182
+ const viewTag = viewName ? ` · ${viewName}` : '';
183
+ const counts = rec.status_counts ?? {};
184
+ const cols = Object.entries(counts)
185
+ .map(([k, v]) => `${k}: ${String(v)}`)
186
+ .join(' · ') || (isEs ? 'sin items' : 'empty');
187
+ const missing = Array.isArray(rec.missing_from_board) ? rec.missing_from_board.length : 0;
188
+ const mismatches = Array.isArray(rec.status_mismatches) ? rec.status_mismatches.length : 0;
189
+ const totalItems = String(rec.total_items ?? 0);
190
+ if (isEs) {
191
+ return [
192
+ `├── 📋 Tablero ─ ${title}${viewTag} (${totalItems} tarjetas)`,
193
+ `│ ├── Columnas ················ ${cols}`,
194
+ `│ └── Desfase ················· ${missing} sin tarjeta · ${mismatches} estado desfasado`,
195
+ ];
196
+ }
197
+ return [
198
+ `├── 📋 Board ─ ${title}${viewTag} (${totalItems} items)`,
199
+ `│ ├── Columns ················· ${cols}`,
200
+ `│ └── Sync diff ··············· ${missing} missing · ${mismatches} status mismatch`,
201
+ ];
202
+ }
203
+ function formatSyncLines(syncRes, isEs) {
204
+ if (syncRes === null || typeof syncRes !== 'object')
205
+ return [];
206
+ const rec = syncRes;
207
+ if (rec.dry_run) {
208
+ if (isEs) {
209
+ return [
210
+ `├── 🔄 Plan tablero (dry-run) · +${String(rec.planned_adds ?? 0)} añadir · ${String(rec.planned_moves ?? 0)} mover · ${String(rec.planned_color_updates ?? 0)} colores`,
211
+ ];
212
+ }
213
+ return [
214
+ `├── 🔄 Board plan (dry-run) ··· +${String(rec.planned_adds ?? 0)} add · ${String(rec.planned_moves ?? 0)} move · ${String(rec.planned_color_updates ?? 0)} colors`,
215
+ ];
216
+ }
217
+ const addedN = Array.isArray(rec.added) ? rec.added.length : 0;
218
+ const movedN = Array.isArray(rec.moved) ? rec.moved.length : 0;
219
+ const colorsN = Array.isArray(rec.colors_updated) ? rec.colors_updated.length : 0;
220
+ const labelsN = Array.isArray(rec.labels_added) ? rec.labels_added.length : 0;
221
+ if (isEs) {
222
+ return [
223
+ `├── 🔄 Tablero organizado ····· +${addedN} añadidas · ${movedN} movidas · ${colorsN} colores · ${labelsN} etiquetas`,
224
+ ];
225
+ }
226
+ return [
227
+ `├── 🔄 Board synced ··········· +${addedN} added · ${movedN} moved · ${colorsN} colors · ${labelsN} labels`,
228
+ ];
229
+ }
230
+ export function formatHud(report, lang = 'es') {
231
+ const isEs = lang === 'es';
232
+ const user = String(report.user ?? 'local');
233
+ const repo = String(report.repo ?? 'local');
234
+ const since = String(report.since ?? '');
235
+ const branch = String(report.branch ?? '-');
236
+ const ic = report.issues_created.count;
237
+ const icl = report.issues_closed.count;
238
+ const po = report.prs_opened.count;
239
+ const contrib = report.contribution;
240
+ const solved = report.solved;
241
+ const prog = report.progress;
242
+ const eff = report.effectiveness;
243
+ const gaps = report.gaps ?? [];
244
+ const teamLines = formatTeamLines(report.team, isEs);
245
+ const projectLines = formatProjectLines(report.project, isEs);
246
+ const syncLines = formatSyncLines(report.board_sync, isEs);
247
+ const prMerge = eff.pr_merge_ratio;
248
+ const ciPass = eff.ci_pass_rate;
249
+ const issueClose = eff.issue_close_ratio;
250
+ if (isEs) {
251
+ const lines = [
252
+ `📊 RECAP ─ ${repo} (@${user} · desde ${since})`,
253
+ `│ 🌿 Rama actual: ${branch}`,
254
+ '│',
255
+ `├── 📝 Issues creados ··········· ${fmtNum(ic)}`,
256
+ `├── ✅ Issues cerrados ·········· ${fmtNum(icl)}`,
257
+ `├── 🚀 PRs enviados ············· ${fmtNum(po)}`,
258
+ `├── 🧱 Aporte ··················· ${fmtNum(contrib.commits)} commits · ${fmtNum(contrib.files_changed)} archivos (+${fmtNum(contrib.insertions)}/-${fmtNum(contrib.deletions)}) · ${fmtNum(contrib.reviews_and_comments)} PRs revisados/comentados`,
259
+ `├── 🎯 Solucionado ·············· ${fmtNum(solved.total)} total (${fmtNum(solved.prs_merged)} PRs mergeados · ${fmtNum(solved.issues_closed)} issues cerrados)`,
260
+ `├── 🏃 Avance en curso ·········· ${fmtNum(prog.prs_open_updated)} PRs activos (${fmtNum(prog.prs_ready)} ready · ${fmtNum(prog.prs_draft)} draft) · ${fmtNum(prog.ahead_commits)} commits sin push · ${fmtNum(prog.working_changes)} cambios locales`,
261
+ ...teamLines,
262
+ ...projectLines,
263
+ ...syncLines,
264
+ '└── ⚡ Efectividad',
265
+ ` ├── PRs mergeados/enviados ·· ${light(prMerge.status)} ${String(prMerge.display)}`,
266
+ ` ├── CI en verde ············· ${light(ciPass.status)} ${String(ciPass.display)}`,
267
+ ` └── Issues cerrados/creados · ${light(issueClose.status)} ${String(issueClose.display)}`,
268
+ ];
269
+ lines.push('');
270
+ lines.push(gaps.length > 0 ? `🟡 Gaps: ${gaps.join(' | ')}` : '🏁 STAGE CLEAR ─ Resumen de solo lectura completado.');
271
+ return lines.join('\n');
272
+ }
273
+ const lines = [
274
+ `📊 RECAP ─ ${repo} (@${user} · since ${since})`,
275
+ `│ 🌿 Current branch: ${branch}`,
276
+ '│',
277
+ `├── 📝 Issues created ··········· ${fmtNum(ic)}`,
278
+ `├── ✅ Issues closed ············ ${fmtNum(icl)}`,
279
+ `├── 🚀 PRs opened ··············· ${fmtNum(po)}`,
280
+ `├── 🧱 Contribution ············· ${fmtNum(contrib.commits)} commits · ${fmtNum(contrib.files_changed)} files (+${fmtNum(contrib.insertions)}/-${fmtNum(contrib.deletions)}) · ${fmtNum(contrib.reviews_and_comments)} peer PRs reviewed/commented`,
281
+ `├── 🎯 Solved ··················· ${fmtNum(solved.total)} total (${fmtNum(solved.prs_merged)} PRs merged · ${fmtNum(solved.issues_closed)} issues closed)`,
282
+ `├── 🏃 Work in progress ········· ${fmtNum(prog.prs_open_updated)} active PRs (${fmtNum(prog.prs_ready)} ready · ${fmtNum(prog.prs_draft)} draft) · ${fmtNum(prog.ahead_commits)} unpushed commits · ${fmtNum(prog.working_changes)} local changes`,
283
+ ...teamLines,
284
+ ...projectLines,
285
+ ...syncLines,
286
+ '└── ⚡ Effectiveness',
287
+ ` ├── PR merge ratio ·········· ${light(prMerge.status)} ${String(prMerge.display)}`,
288
+ ` ├── CI pass rate ············ ${light(ciPass.status)} ${String(ciPass.display)}`,
289
+ ` └── Issue close ratio ······· ${light(issueClose.status)} ${String(issueClose.display)}`,
290
+ ];
291
+ lines.push('');
292
+ lines.push(gaps.length > 0 ? `🟡 Gaps: ${gaps.join(' | ')}` : '🏁 STAGE CLEAR ─ Read-only summary complete.');
293
+ return lines.join('\n');
294
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * LAYER: Domain
3
+ * Contains: Date/time window parsing and GitHub repository / Project v2 reference parsers.
4
+ * Rules: Pure functions; validate --since and --project strictly before running collectors.
5
+ * BigO: O(1) score:5
6
+ * keywords: [SinceWindow, ProjectRef, RepoRemote, IsoTimestamp]
7
+ * GOAL: Parse --since windows, timestamps, Git remote URLs, and Project v2 references.
8
+ */
9
+ export interface ProjectRef {
10
+ readonly owner_type: 'organization' | 'user';
11
+ readonly owner: string;
12
+ readonly number: number;
13
+ readonly view: number | null;
14
+ }
15
+ export interface SinceDate {
16
+ readonly ms: number;
17
+ readonly iso: string;
18
+ readonly utcDate: string;
19
+ readonly utcIso: string;
20
+ }
21
+ export declare const REPO_RE: RegExp;
22
+ export declare function formatLocalIso(date: Date): string;
23
+ export declare function parseTs(raw: unknown): number | null;
24
+ export declare function parseSince(value?: string | null, now?: Date): SinceDate;
25
+ export declare function inWindow(tsRaw: unknown, sinceMs: number): boolean;
26
+ export declare function parseRepoFromRemote(url: string | null | undefined): string | null;
27
+ export declare function parseProjectRef(value: string | null | undefined): ProjectRef | null;
@@ -0,0 +1,148 @@
1
+ /**
2
+ * LAYER: Domain
3
+ * Contains: Date/time window parsing and GitHub repository / Project v2 reference parsers.
4
+ * Rules: Pure functions; validate --since and --project strictly before running collectors.
5
+ * BigO: O(1) score:5
6
+ * keywords: [SinceWindow, ProjectRef, RepoRemote, IsoTimestamp]
7
+ * GOAL: Parse --since windows, timestamps, Git remote URLs, and Project v2 references.
8
+ */
9
+ export const REPO_RE = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
10
+ const REL_SINCE_RE = /^(\d+)([hd])$/i;
11
+ const DATE_ONLY_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
12
+ const ORIGIN_SSH_RE = /^git@[^:]+:([^/]+\/[^/]+?)(?:\.git)?$/;
13
+ const ORIGIN_HTTPS_RE = /^https?:\/\/[^/]+\/([^/]+\/[^/]+?)(?:\.git)?\/?$/;
14
+ const PROJECT_URL_RE = /^https?:\/\/github\.com\/(orgs|users)\/([A-Za-z0-9_.-]+)\/projects\/(\d+)(?:\/views\/(\d+))?\/?$/;
15
+ const PROJECT_SHORT_RE = /^([A-Za-z0-9_.-]+)\/(\d+)$/;
16
+ export function formatLocalIso(date) {
17
+ const pad2 = (n) => String(n).padStart(2, '0');
18
+ const year = date.getFullYear();
19
+ const month = pad2(date.getMonth() + 1);
20
+ const day = pad2(date.getDate());
21
+ const hour = pad2(date.getHours());
22
+ const min = pad2(date.getMinutes());
23
+ const sec = pad2(date.getSeconds());
24
+ const offsetMin = -date.getTimezoneOffset();
25
+ const sign = offsetMin >= 0 ? '+' : '-';
26
+ const absOffset = Math.abs(offsetMin);
27
+ const offH = pad2(Math.floor(absOffset / 60));
28
+ const offM = pad2(absOffset % 60);
29
+ return `${year}-${month}-${day}T${hour}:${min}:${sec}${sign}${offH}:${offM}`;
30
+ }
31
+ export function parseTs(raw) {
32
+ if (typeof raw !== 'string' || !raw.trim())
33
+ return null;
34
+ let cleaned = raw.trim();
35
+ if (cleaned.endsWith('Z')) {
36
+ cleaned = `${cleaned.slice(0, -1)}+00:00`;
37
+ }
38
+ const hasOffset = /(?:[+-]\d{2}:?\d{2}|Z)$/i.test(cleaned);
39
+ if (!hasOffset && /^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?)?$/.test(cleaned)) {
40
+ const localDate = new Date(cleaned.replace(' ', 'T'));
41
+ const ms = localDate.getTime();
42
+ return Number.isFinite(ms) ? ms : null;
43
+ }
44
+ const ms = Date.parse(cleaned);
45
+ return Number.isFinite(ms) ? ms : null;
46
+ }
47
+ function buildSinceDate(date) {
48
+ const ms = date.getTime();
49
+ return {
50
+ ms,
51
+ iso: formatLocalIso(date),
52
+ utcDate: new Date(ms - 86_400_000).toISOString().slice(0, 10),
53
+ utcIso: new Date(ms).toISOString().replace(/\.\d{3}Z$/, 'Z'),
54
+ };
55
+ }
56
+ export function parseSince(value, now) {
57
+ const ref = now ?? new Date();
58
+ if (value === undefined || value === null || !String(value).trim()) {
59
+ const midnight = new Date(ref.getFullYear(), ref.getMonth(), ref.getDate(), 0, 0, 0, 0);
60
+ return buildSinceDate(midnight);
61
+ }
62
+ const raw = String(value).trim();
63
+ const rel = REL_SINCE_RE.exec(raw);
64
+ if (rel) {
65
+ const amount = Number.parseInt(rel[1] ?? '0', 10);
66
+ const unit = (rel[2] ?? '').toLowerCase();
67
+ if (unit === 'h') {
68
+ if (amount < 1 || amount > 24 * 30) {
69
+ throw new Error('--since hours must be between 1h and 720h.');
70
+ }
71
+ return buildSinceDate(new Date(ref.getTime() - amount * 3_600_000));
72
+ }
73
+ if (amount < 1 || amount > 90) {
74
+ throw new Error('--since days must be between 1d and 90d.');
75
+ }
76
+ return buildSinceDate(new Date(ref.getTime() - amount * 86_400_000));
77
+ }
78
+ const dateMatch = DATE_ONLY_RE.exec(raw);
79
+ if (dateMatch) {
80
+ const year = Number.parseInt(dateMatch[1] ?? '0', 10);
81
+ const month = Number.parseInt(dateMatch[2] ?? '0', 10);
82
+ const day = Number.parseInt(dateMatch[3] ?? '0', 10);
83
+ const d = new Date(year, month - 1, day, 0, 0, 0, 0);
84
+ if (d.getFullYear() !== year || d.getMonth() !== month - 1 || d.getDate() !== day) {
85
+ throw new Error(`Invalid --since value: ${JSON.stringify(value)}. Use YYYY-MM-DD, <N>h, <N>d, or ISO-8601.`);
86
+ }
87
+ return buildSinceDate(d);
88
+ }
89
+ const parsedMs = parseTs(raw);
90
+ if (parsedMs === null) {
91
+ throw new Error(`Invalid --since value: ${JSON.stringify(value)}. Use YYYY-MM-DD, <N>h, <N>d, or ISO-8601.`);
92
+ }
93
+ const normalizedRaw = raw.replace(' ', 'T');
94
+ const iso = normalizedRaw.endsWith('Z') || normalizedRaw.endsWith('z')
95
+ ? `${normalizedRaw.slice(0, -1)}+00:00`
96
+ : /[+-]\d{2}:\d{2}$/.test(normalizedRaw)
97
+ ? normalizedRaw
98
+ : /[+-]\d{4}$/.test(normalizedRaw)
99
+ ? `${normalizedRaw.slice(0, -2)}:${normalizedRaw.slice(-2)}`
100
+ : formatLocalIso(new Date(parsedMs));
101
+ return {
102
+ ms: parsedMs,
103
+ iso,
104
+ utcDate: new Date(parsedMs - 86_400_000).toISOString().slice(0, 10),
105
+ utcIso: new Date(parsedMs).toISOString().replace(/\.\d{3}Z$/, 'Z'),
106
+ };
107
+ }
108
+ export function inWindow(tsRaw, sinceMs) {
109
+ const ms = parseTs(tsRaw);
110
+ return ms !== null && ms >= sinceMs;
111
+ }
112
+ export function parseRepoFromRemote(url) {
113
+ const text = (url ?? '').trim();
114
+ for (const pattern of [ORIGIN_SSH_RE, ORIGIN_HTTPS_RE]) {
115
+ const match = pattern.exec(text);
116
+ const slug = match?.[1] ?? null;
117
+ if (slug && REPO_RE.test(slug)) {
118
+ return slug;
119
+ }
120
+ }
121
+ return null;
122
+ }
123
+ export function parseProjectRef(value) {
124
+ const text = (value ?? '').trim();
125
+ if (!text)
126
+ return null;
127
+ const urlMatch = PROJECT_URL_RE.exec(text);
128
+ if (urlMatch) {
129
+ const [, scope = '', owner = '', numS = '0', viewS] = urlMatch;
130
+ return {
131
+ owner_type: scope === 'orgs' ? 'organization' : 'user',
132
+ owner,
133
+ number: Number.parseInt(numS, 10),
134
+ view: viewS ? Number.parseInt(viewS, 10) : null,
135
+ };
136
+ }
137
+ const shortMatch = PROJECT_SHORT_RE.exec(text);
138
+ if (shortMatch) {
139
+ const [, owner = '', numS = '0'] = shortMatch;
140
+ return {
141
+ owner_type: 'organization',
142
+ owner,
143
+ number: Number.parseInt(numS, 10),
144
+ view: null,
145
+ };
146
+ }
147
+ throw new Error(`Invalid --project ${JSON.stringify(value)}; use a GitHub Project URL or <owner>/<number>.`);
148
+ }
@@ -0,0 +1,2 @@
1
+ export declare const recapUsage = "bbc recap [--repo <owner/repo>|--all-repos] [--since <YYYY-MM-DD|Nh|Nd>] [--user <login>] [--team|--users <a,b>] [--project <url|owner/n>] [--sync-board [--fix-colors] [--apply-labels] [--dry-run]] [--cwd <dir>] [--lang es|en] [--no-github] [--json] [--stdin]";
2
+ export declare function recap(argv: readonly string[]): number;