@magnusekdahl/parallix 1.2.1 → 1.3.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.
Files changed (79) hide show
  1. package/index.js +190 -185
  2. package/lib/commands/active.js +502 -579
  3. package/lib/commands/active.ts +665 -0
  4. package/lib/commands/checkpoint.js +98 -74
  5. package/lib/commands/checkpoint.ts +79 -0
  6. package/lib/commands/config.js +61 -31
  7. package/lib/commands/config.ts +47 -0
  8. package/lib/commands/coverage-gate.js +271 -246
  9. package/lib/commands/coverage-gate.ts +362 -0
  10. package/lib/commands/diff.js +140 -119
  11. package/lib/commands/diff.ts +125 -0
  12. package/lib/commands/draft.js +770 -923
  13. package/lib/commands/draft.ts +1021 -0
  14. package/lib/commands/handoff.js +588 -608
  15. package/lib/commands/handoff.ts +694 -0
  16. package/lib/commands/integrate.js +1331 -1468
  17. package/lib/commands/integrate.ts +1688 -0
  18. package/lib/commands/mission-start.js +279 -237
  19. package/lib/commands/mission-start.ts +263 -0
  20. package/lib/commands/rebase.js +606 -582
  21. package/lib/commands/rebase.ts +635 -0
  22. package/lib/commands/repair-handoff.js +181 -179
  23. package/lib/commands/repair-handoff.ts +228 -0
  24. package/lib/commands/resolve-conflict.js +121 -102
  25. package/lib/commands/resolve-conflict.ts +112 -0
  26. package/lib/commands/review.js +3 -4
  27. package/lib/commands/review.ts +14 -0
  28. package/lib/commands/setup-review.js +4 -5
  29. package/lib/commands/setup-review.ts +14 -0
  30. package/lib/commands/setup.js +3 -3
  31. package/lib/commands/setup.ts +2 -0
  32. package/lib/commands/stats-backfill.js +394 -359
  33. package/lib/commands/stats-backfill.ts +418 -0
  34. package/lib/commands/stats.js +1424 -1665
  35. package/lib/commands/stats.ts +2186 -0
  36. package/lib/commands/status.js +219 -200
  37. package/lib/commands/status.ts +219 -0
  38. package/lib/commands/verify.js +3 -1
  39. package/lib/commands/verify.ts +2 -0
  40. package/lib/core/nels.js +112 -127
  41. package/lib/core/nels.ts +189 -0
  42. package/lib/core/subagent-limit.js +15 -16
  43. package/lib/core/subagent-limit.ts +25 -0
  44. package/lib/index.js +142 -59
  45. package/lib/index.ts +134 -0
  46. package/lib/review/rebase.js +142 -145
  47. package/lib/review/rebase.ts +188 -0
  48. package/lib/review/review-adapter.js +99 -87
  49. package/lib/review/review-adapter.ts +198 -0
  50. package/lib/review/review-artifacts.js +486 -629
  51. package/lib/review/review-artifacts.ts +622 -0
  52. package/lib/review/review-commands.js +1220 -1373
  53. package/lib/review/review-commands.ts +1579 -0
  54. package/lib/review/review-events.js +544 -886
  55. package/lib/review/review-events.ts +954 -0
  56. package/lib/review/review-loop.js +945 -1020
  57. package/lib/review/review-loop.ts +1174 -0
  58. package/lib/review/review-polling.js +86 -115
  59. package/lib/review/review-polling.ts +194 -0
  60. package/lib/review/review-prompts.js +154 -189
  61. package/lib/review/review-prompts.ts +182 -0
  62. package/lib/review/review-state.js +246 -225
  63. package/lib/review/review-state.ts +353 -0
  64. package/lib/review/review.js +63 -84
  65. package/lib/review/review.ts +138 -0
  66. package/lib/tools/backlog.js +694 -680
  67. package/lib/tools/backlog.ts +835 -0
  68. package/lib/tools/forgejo.js +1270 -1405
  69. package/lib/tools/forgejo.ts +1793 -0
  70. package/lib/tools/gatekeeper.js +106 -96
  71. package/lib/tools/gatekeeper.ts +124 -0
  72. package/lib/tools/redgreen.js +200 -181
  73. package/lib/tools/redgreen.ts +221 -0
  74. package/lib/tools/sessions.js +58 -52
  75. package/lib/tools/sessions.ts +81 -0
  76. package/lib/tools/setup-review.js +902 -975
  77. package/lib/tools/setup-review.ts +1152 -0
  78. package/package.json +4 -4
  79. package/px.js +226 -208
@@ -0,0 +1,418 @@
1
+ import * as fs from 'node:fs';
2
+ import * as path from 'node:path';
3
+
4
+ import * as fmt from '../core/fmt.js';
5
+ import stats = require('./stats.js');
6
+ import { git } from '../core/git.js';
7
+ import {
8
+ getTaskFrontmatterValue,
9
+ getTaskStatus,
10
+ resolveTaskFile,
11
+ } from '../tools/backlog.js';
12
+ import { findMissionDir } from '../core/mission-utils.js';
13
+
14
+ interface StatsAugmented {
15
+ resolveMissionClassification: (slug: string, rootDir?: string) => { classification?: string; source?: string };
16
+ _internals: Record<string, (...args: unknown[]) => unknown>;
17
+ resolveStatsPath: (options?: { ensureDir?: boolean }) => string;
18
+ resolveStatsRepoName: (rootDir: string) => string;
19
+ loadStatsCsv: (filePath: string, options?: { rootDir?: string }) => { rows: Record<string, string>[] };
20
+ deriveImplementerAndFixRounds: (slug: string, rootDir?: string) => { implementer: string; prFixRounds: number; source: string };
21
+ upsertStatsRow: (row: Record<string, string>, options: { filePath: string; rootDir?: string }) => { changed: boolean };
22
+ }
23
+
24
+ function getStats(): StatsAugmented {
25
+ return stats as unknown as StatsAugmented;
26
+ }
27
+
28
+ function hasCheckpointFiles(missionDir: string) {
29
+ if (!missionDir || !fs.existsSync(missionDir)) {return false;}
30
+ return fs.readdirSync(missionDir).some(file => /^CP-\d+\.md$/i.test(file) || /^CHECKPOINT_FINAL\.md$/i.test(file));
31
+ }
32
+
33
+ function listHistoricalMissionSlugs(rootDir = process.cwd()) {
34
+ const missionsRoot = path.join(rootDir, 'docs', 'missions');
35
+ if (!fs.existsSync(missionsRoot)) {return [];}
36
+
37
+ const slugs = [];
38
+ for (const year of fs.readdirSync(missionsRoot).sort()) {
39
+ const yearDir = path.join(missionsRoot, year);
40
+ if (!/^\d{4}$/.test(year) || !fs.statSync(yearDir).isDirectory()) {continue;}
41
+ for (const slug of fs.readdirSync(yearDir).sort()) {
42
+ if (!/^task-\d+/i.test(slug)) {continue;}
43
+ const missionDir = path.join(yearDir, slug);
44
+ if (!fs.statSync(missionDir).isDirectory()) {continue;}
45
+ if (!hasCheckpointFiles(missionDir)) {continue;}
46
+ slugs.push(slug);
47
+ }
48
+ }
49
+ return slugs;
50
+ }
51
+
52
+ function extractDateOnly(value: unknown) {
53
+ const match = String(value || '').match(/^(\d{4}-\d{2}-\d{2})/);
54
+ return match ? match[1] : null;
55
+ }
56
+
57
+ function normalizeHistoricalImplementer(value: unknown) {
58
+ const normalized = String(value || '').trim().toLowerCase();
59
+ if (!normalized) {return null;}
60
+ if (/(^|[^a-z])codex([^a-z]|$)/.test(normalized)) {return 'codex';}
61
+ if (/(^|[^a-z])claude([^a-z]|$)/.test(normalized)) {return 'claude';}
62
+ if (/(^|[^a-z])gemini([^a-z]|$)/.test(normalized)) {return 'gemini';}
63
+ if (/(^|[^a-z])custom([^a-z]|$)/.test(normalized)) {return 'custom';}
64
+ if (/(^|[^a-z])mistral([^a-z]|$)/.test(normalized)) {return 'mistral';}
65
+ if (/(^|[^a-z])magnus([^a-z]|$)/.test(normalized)) {return 'magnus';}
66
+ if (/(^|[^a-z])human([^a-z]|$)/.test(normalized)) {return 'human';}
67
+ return null;
68
+ }
69
+
70
+ function deriveImplementerFromGitHistory(slug: string, taskFile: string, rootDir = process.cwd()) {
71
+ const missionDir = findMissionDir(slug, rootDir);
72
+ const targets: string[] = [missionDir, taskFile].filter((x): x is string => Boolean(x));
73
+ if (targets.length === 0) {return null;}
74
+
75
+ const result = git(['-C', rootDir, 'log', '--all', '--format=%an|%ae', '--', ...targets]);
76
+ if (result.status !== 0) {return null;}
77
+
78
+ const authors: string[] = result.stdout
79
+ .split('\n')
80
+ .map(line => line.trim())
81
+ .filter(Boolean)
82
+ .map(line => {
83
+ const [name = '', email = ''] = line.split('|');
84
+ return normalizeHistoricalImplementer(email) || normalizeHistoricalImplementer(name);
85
+ })
86
+ .filter(Boolean) as string[];
87
+
88
+ if (authors.length === 0) {return null;}
89
+ const uniqueAuthors = [...new Set(authors)];
90
+ return uniqueAuthors.length === 1 ? uniqueAuthors[0] : uniqueAuthors[0];
91
+ }
92
+
93
+ function deriveDateFromGitHistory(slug: string, taskFile: string, rootDir = process.cwd()) {
94
+ const missionDir = findMissionDir(slug, rootDir);
95
+ const targets: string[] = [missionDir, taskFile].filter((x): x is string => Boolean(x));
96
+ if (targets.length === 0) {return null;}
97
+
98
+ const result = git(['-C', rootDir, 'log', '--all', '-1', '--format=%cs', '--', ...targets]);
99
+ if (result.status !== 0) {return null;}
100
+ return extractDateOnly(result.stdout.trim());
101
+ }
102
+
103
+ function inferHistoricalClassificationFromMissionDoc(slug: string, rootDir = process.cwd()) {
104
+ const missionDir = findMissionDir(slug, rootDir);
105
+ if (!missionDir) {return null;}
106
+
107
+ const missionFile = path.join(missionDir, 'MISSION.md');
108
+ if (!fs.existsSync(missionFile)) {return null;}
109
+ const text = fs.readFileSync(missionFile, 'utf8').toLowerCase();
110
+
111
+ const productSurfacePatterns = [
112
+ /web-client\//g,
113
+ /\bios\b/g,
114
+ /\bandroid\b/g,
115
+ /\bwearos\b/g,
116
+ /\bauth-server\b/g,
117
+ /\bserver\/src\b/g,
118
+ /\bgrocer(?:y|ies)\b/g,
119
+ /\bboard\b/g,
120
+ /\bdelta\b/g,
121
+ /\bsync\b/g,
122
+ /\bprice\b/g,
123
+ /\bstore\b/g,
124
+ /\bshopping\b/g,
125
+ /\bui\b/g,
126
+ /\bclient\b/g,
127
+ /\bcheapest\b/g,
128
+ ];
129
+ const workflowPatterns = [
130
+ /workflow\//g,
131
+ /node parallix\/index\.js/g,
132
+ /\bworkflow\b/g,
133
+ /\bagent\b/g,
134
+ /\bbacklog\b/g,
135
+ /\bforgejo\b/g,
136
+ /\breview loop\b/g,
137
+ /\breview\b/g,
138
+ /\bdraft\b/g,
139
+ /\bintegrate\b/g,
140
+ /\brebase\b/g,
141
+ /\bcheckpoint\b/g,
142
+ /\bprompt\b/g,
143
+ /\bstats\b/g,
144
+ /\bworktree\b/g,
145
+ /\bcli\b/g,
146
+ /\bgit\b/g,
147
+ /\bcoverage\b/g,
148
+ /\bverification\b/g,
149
+ ];
150
+
151
+ const score = (patterns: RegExp[]) => patterns.reduce((sum: number, pattern: RegExp) => sum + ((text.match(pattern) || []).length), 0);
152
+ const productScore = score(productSurfacePatterns);
153
+ const workflowScore = score(workflowPatterns);
154
+
155
+ if (productScore === 0 && workflowScore === 0) {return null;}
156
+ if (workflowScore >= productScore + 2) {return 'ai_sdlc';}
157
+ if (productScore >= workflowScore + 2) {return 'user_value';}
158
+
159
+ const titleLine = text.split('\n')[0] || '';
160
+ if (/\bworkflow|agent|forgejo|backlog|review|rebase|checkpoint|stats|cli\b/.test(titleLine)) {
161
+ return 'ai_sdlc';
162
+ }
163
+ if (/\bweb client|web-client|ios|android|grocer|board|delta|sync|store|price\b/.test(titleLine)) {
164
+ return 'user_value';
165
+ }
166
+
167
+ return null;
168
+ }
169
+
170
+ function resolveHistoricalClassification(slug: string, taskFile: string, rootDir = process.cwd()) {
171
+ const s = getStats();
172
+ const resolution = s.resolveMissionClassification(slug, rootDir);
173
+ if (resolution.classification) {
174
+ return { value: resolution.classification, source: 'backlog-label' };
175
+ }
176
+ // Classification missing or invalid — fall through to fallbacks.
177
+ const classificationValue = getTaskFrontmatterValue(taskFile, 'classification');
178
+ const legacy = (s._internals as Record<string, (v: string) => string | null>).normalizeClassification(classificationValue ?? '');
179
+ if (legacy) {
180
+ return { value: legacy, source: 'backlog-classification' };
181
+ }
182
+ const inferred = inferHistoricalClassificationFromMissionDoc(slug, rootDir);
183
+ if (inferred) {
184
+ return { value: inferred, source: 'mission-doc-heuristic' };
185
+ }
186
+ return { value: null, source: null };
187
+ }
188
+
189
+ function collectHistoricalStatsBackfill(rootDir = process.cwd(), filePath: string | null = null) {
190
+ const s = getStats();
191
+ filePath = filePath || s.resolveStatsPath();
192
+ const repoName = s.resolveStatsRepoName(rootDir);
193
+ const existingMissions = new Set(
194
+ s.loadStatsCsv(filePath, { rootDir }).rows
195
+ .filter((row: Record<string, string>) => String(row.repo || '').trim() === repoName)
196
+ .map((row: Record<string, string>) => row.mission)
197
+ );
198
+ const rows = [];
199
+ const unresolved = [];
200
+ const skipped = [];
201
+
202
+ for (const slug of listHistoricalMissionSlugs(rootDir)) {
203
+ if (existingMissions.has(slug)) {continue;}
204
+
205
+ const taskResolution = resolveTaskFile(slug, rootDir);
206
+ if (!taskResolution.ok) {
207
+ unresolved.push({
208
+ slug,
209
+ reason: 'task-resolution',
210
+ detail: taskResolution.reason,
211
+ });
212
+ continue;
213
+ }
214
+
215
+ const taskFile = taskResolution.taskFile!;
216
+ const status = getTaskStatus(taskFile);
217
+ if (status !== 'done') {
218
+ skipped.push({ slug, reason: `status=${status || 'unknown'}` });
219
+ continue;
220
+ }
221
+
222
+ const date = extractDateOnly(getTaskFrontmatterValue(taskFile, 'updated_date') ?? '') || deriveDateFromGitHistory(slug, taskFile, rootDir);
223
+ const classification = resolveHistoricalClassification(slug, taskFile, rootDir);
224
+
225
+ let implementerInfo: { implementer: string; prFixRounds: number; source: string } | null = null;
226
+ let implementerError: string | null = null;
227
+ try {
228
+ implementerInfo = s.deriveImplementerAndFixRounds(slug, rootDir);
229
+ } catch (error) {
230
+ implementerError = error instanceof Error ? error.message : String(error);
231
+ }
232
+
233
+ if (!implementerInfo?.implementer || implementerInfo.implementer === 'unknown') {
234
+ const gitHistoryImplementer = deriveImplementerFromGitHistory(slug, taskFile, rootDir);
235
+ if (gitHistoryImplementer) {
236
+ implementerInfo = {
237
+ implementer: gitHistoryImplementer,
238
+ prFixRounds: 0,
239
+ source: 'git-history-author',
240
+ };
241
+ }
242
+ }
243
+
244
+ if (!date || !classification.value || !implementerInfo?.implementer) {
245
+ unresolved.push({
246
+ slug,
247
+ reason: 'missing-fields',
248
+ date: date || null,
249
+ classification: classification.value || null,
250
+ implementer: implementerInfo?.implementer || null,
251
+ prFixRounds: implementerInfo?.prFixRounds ?? null,
252
+ sources: {
253
+ classification: classification.source,
254
+ implementer: implementerInfo?.source || null,
255
+ },
256
+ missing: [
257
+ ...(!date ? ['date'] : []),
258
+ ...(!classification.value ? ['classification'] : []),
259
+ ...(!implementerInfo?.implementer ? ['implementer'] : []),
260
+ ],
261
+ detail: implementerError,
262
+ });
263
+ continue;
264
+ }
265
+
266
+ rows.push({
267
+ date,
268
+ repo: repoName,
269
+ mission: slug,
270
+ classification: classification.value,
271
+ implementer: implementerInfo.implementer,
272
+ pr_fix_rounds: String(implementerInfo.prFixRounds),
273
+ sources: {
274
+ date: 'backlog-updated_date',
275
+ classification: classification.source,
276
+ implementer: implementerInfo.source,
277
+ },
278
+ });
279
+ }
280
+
281
+ rows.sort((a, b) => a.date.localeCompare(b.date) || a.mission.localeCompare(b.mission));
282
+ unresolved.sort((a, b) => a.slug.localeCompare(b.slug));
283
+ skipped.sort((a, b) => a.slug.localeCompare(b.slug));
284
+
285
+ return { rows, unresolved, skipped };
286
+ }
287
+
288
+ function renderBackfillSummary(report: { rows: any[]; unresolved: any[]; skipped: any[] }) {
289
+ const lines = [];
290
+ lines.push(`Resolved rows: ${report.rows.length}`);
291
+ lines.push(`Unresolved missions: ${report.unresolved.length}`);
292
+ lines.push(`Skipped missions: ${report.skipped.length}`);
293
+ lines.push('');
294
+
295
+ if (report.rows.length > 0) {
296
+ lines.push('Resolved:');
297
+ for (const row of report.rows) {
298
+ lines.push(`- ${row.date} ${row.mission} ${row.classification} ${row.implementer} ${row.pr_fix_rounds} [${row.sources.classification}/${row.sources.implementer}]`);
299
+ }
300
+ lines.push('');
301
+ }
302
+
303
+ if (report.unresolved.length > 0) {
304
+ lines.push('Unresolved:');
305
+ for (const item of report.unresolved) {
306
+ const missing = Array.isArray(item.missing) && item.missing.length > 0 ? ` missing=${item.missing.join(',')}` : '';
307
+ const detail = item.detail ? ` detail=${item.detail}` : '';
308
+ lines.push(`- ${item.slug} reason=${item.reason}${missing}${detail}`);
309
+ }
310
+ lines.push('');
311
+ }
312
+
313
+ if (report.skipped.length > 0) {
314
+ lines.push('Skipped:');
315
+ for (const item of report.skipped) {
316
+ lines.push(`- ${item.slug} ${item.reason}`);
317
+ }
318
+ }
319
+
320
+ return lines.join('\n');
321
+ }
322
+
323
+ function applyBackfillRows(rows: any[], filePath: string | null = null, rootDir = process.cwd()) {
324
+ const s = getStats();
325
+ filePath = filePath || s.resolveStatsPath({ ensureDir: true });
326
+ let changed = 0;
327
+ for (const row of rows) {
328
+ const result = s.upsertStatsRow(row, { filePath, rootDir });
329
+ if (result.changed) {changed += 1;}
330
+ }
331
+ return changed;
332
+ }
333
+
334
+ function printUsage(log = fmt.log.plain) {
335
+ log(`Usage: px stats-backfill [--apply] [--json] [--csv-file <path>]
336
+
337
+ Examples:
338
+ px stats-backfill
339
+ px stats-backfill --json
340
+ px stats-backfill --apply
341
+
342
+ Notes:
343
+ - This command is for historical stats recovery only.
344
+ - With no --csv-file, reads and writes <PARALLIX_HOME>/stats.csv.
345
+ - It uses strict workflow stats derivation for implementer/fix rounds and historical fallbacks for classification.
346
+ - Non-done missions are skipped and unresolved missions are reported without being written.`);
347
+ }
348
+
349
+ interface BackfillOptions {
350
+ log?: (msg: string) => string | null;
351
+ error?: (msg: string) => string | null;
352
+ rootDir?: string;
353
+ }
354
+
355
+ function statsBackfill(args: string[], options: BackfillOptions = {}) {
356
+ const opts = options;
357
+ const log = opts.log || fmt.log.plain;
358
+ const error = opts.error || fmt.log.plainError;
359
+ const rootDir = opts.rootDir || process.cwd();
360
+
361
+ if (args.includes('--help') || args.includes('-h')) {
362
+ printUsage(log);
363
+ return;
364
+ }
365
+
366
+ let apply = false;
367
+ let json = false;
368
+ let filePath = null;
369
+
370
+ for (let i = 0; i < args.length; i += 1) {
371
+ const arg = args[i];
372
+ if (arg === '--apply') {
373
+ apply = true;
374
+ continue;
375
+ }
376
+ if (arg === '--json') {
377
+ json = true;
378
+ continue;
379
+ }
380
+ if (arg === '--csv-file' && i + 1 < args.length) {
381
+ filePath = args[i + 1];
382
+ i += 1;
383
+ }
384
+ }
385
+ const s = getStats();
386
+ filePath = filePath || s.resolveStatsPath({ ensureDir: apply });
387
+
388
+ const report = collectHistoricalStatsBackfill(rootDir, filePath);
389
+ const changed = apply ? applyBackfillRows(report.rows, filePath, rootDir) : 0;
390
+ const payload = {
391
+ resolved: report.rows.length,
392
+ unresolved: report.unresolved.length,
393
+ skipped: report.skipped.length,
394
+ changed,
395
+ rows: report.rows,
396
+ unresolvedItems: report.unresolved,
397
+ skippedItems: report.skipped,
398
+ };
399
+
400
+ if (json) {
401
+ log(JSON.stringify(payload, null, 2));
402
+ } else {
403
+ log(renderBackfillSummary(report));
404
+ if (apply) {
405
+ log('');
406
+ log(fmt.status('PASS', `Applied ${changed} stats rows to ${filePath}`));
407
+ }
408
+ }
409
+
410
+ if (apply && report.unresolved.length > 0) {
411
+ error(fmt.status('INFO', `${report.unresolved.length} missions remain unresolved and were not written.`));
412
+ }
413
+ }
414
+
415
+ (statsBackfill as any).collectHistoricalStatsBackfill = collectHistoricalStatsBackfill;
416
+ (statsBackfill as any).inferHistoricalClassificationFromMissionDoc = inferHistoricalClassificationFromMissionDoc;
417
+ (statsBackfill as any).extractDateOnly = extractDateOnly;
418
+ export = statsBackfill;