@critical-path/core 0.15.2 → 0.17.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 (66) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +25 -0
  3. package/dist/domain/cpm.d.ts +10 -0
  4. package/dist/domain/cpm.d.ts.map +1 -0
  5. package/dist/domain/cpm.js +176 -0
  6. package/dist/domain/cpm.js.map +1 -0
  7. package/dist/domain/cpm.test.d.ts +2 -0
  8. package/dist/domain/cpm.test.d.ts.map +1 -0
  9. package/dist/domain/cpm.test.js +113 -0
  10. package/dist/domain/cpm.test.js.map +1 -0
  11. package/dist/domain/entities.d.ts.map +1 -1
  12. package/dist/domain/entities.js +5 -0
  13. package/dist/domain/entities.js.map +1 -1
  14. package/dist/domain/index.d.ts +3 -0
  15. package/dist/domain/index.d.ts.map +1 -1
  16. package/dist/domain/index.js +3 -0
  17. package/dist/domain/index.js.map +1 -1
  18. package/dist/domain/ladder.d.ts +16 -0
  19. package/dist/domain/ladder.d.ts.map +1 -0
  20. package/dist/domain/ladder.js +352 -0
  21. package/dist/domain/ladder.js.map +1 -0
  22. package/dist/domain/ladder.test.d.ts +2 -0
  23. package/dist/domain/ladder.test.d.ts.map +1 -0
  24. package/dist/domain/ladder.test.js +213 -0
  25. package/dist/domain/ladder.test.js.map +1 -0
  26. package/dist/domain/metrics.d.ts +29 -0
  27. package/dist/domain/metrics.d.ts.map +1 -0
  28. package/dist/domain/metrics.js +403 -0
  29. package/dist/domain/metrics.js.map +1 -0
  30. package/dist/domain/metrics.test.d.ts +2 -0
  31. package/dist/domain/metrics.test.d.ts.map +1 -0
  32. package/dist/domain/metrics.test.js +251 -0
  33. package/dist/domain/metrics.test.js.map +1 -0
  34. package/dist/engine/index.d.ts +8 -1
  35. package/dist/engine/index.d.ts.map +1 -1
  36. package/dist/engine/index.js +124 -1
  37. package/dist/engine/index.js.map +1 -1
  38. package/dist/store/firebase.d.ts +3 -1
  39. package/dist/store/firebase.d.ts.map +1 -1
  40. package/dist/store/firebase.js +1 -1
  41. package/dist/store/firebase.js.map +1 -1
  42. package/dist/store/index.d.ts +6 -2
  43. package/dist/store/index.d.ts.map +1 -1
  44. package/dist/store/index.js +1 -1
  45. package/dist/store/index.js.map +1 -1
  46. package/dist/store/sqlite.d.ts +3 -1
  47. package/dist/store/sqlite.d.ts.map +1 -1
  48. package/dist/store/sqlite.js +1 -1
  49. package/dist/store/sqlite.js.map +1 -1
  50. package/dist/types/index.d.ts +177 -0
  51. package/dist/types/index.d.ts.map +1 -1
  52. package/package.json +1 -1
  53. package/src/domain/cpm.test.ts +128 -0
  54. package/src/domain/cpm.ts +215 -0
  55. package/src/domain/entities.ts +6 -0
  56. package/src/domain/index.ts +4 -0
  57. package/src/domain/ladder.test.ts +251 -0
  58. package/src/domain/ladder.ts +453 -0
  59. package/src/domain/metrics.test.ts +286 -0
  60. package/src/domain/metrics.ts +484 -0
  61. package/src/engine/index.ts +169 -4
  62. package/src/store/firebase.ts +2 -2
  63. package/src/store/index.ts +3 -3
  64. package/src/store/sqlite.ts +2 -2
  65. package/src/types/index.ts +206 -0
  66. package/tsconfig.tsbuildinfo +1 -1
@@ -0,0 +1,453 @@
1
+ import type {
2
+ Project,
3
+ Task,
4
+ TaskDependency,
5
+ TaskContainer,
6
+ Iteration,
7
+ Deliverable,
8
+ Attachment,
9
+ TimeEntry,
10
+ Activity,
11
+ TimelineLadder,
12
+ TimelineLadderOptions,
13
+ MacroTimelineSummary,
14
+ MacroPhaseRollup,
15
+ MacroPhaseHealth,
16
+ StandardTaskTimelineItem,
17
+ ConcreteTaskEvidence,
18
+ ConcreteEvidenceSummary,
19
+ RealityDelta,
20
+ TaskLadderView
21
+ } from '../types/index.js';
22
+ import { calculateCPM, getTaskDurationHours } from './cpm.js';
23
+
24
+ export interface LadderContext {
25
+ project: Project;
26
+ tasks: Task[];
27
+ dependencies: TaskDependency[];
28
+ containers?: TaskContainer[];
29
+ iterations?: Iteration[];
30
+ deliverables?: Deliverable[];
31
+ attachments?: Attachment[];
32
+ timeEntries?: TimeEntry[];
33
+ activities?: Activity[];
34
+ }
35
+
36
+ export function aggregateConcreteEvidenceForTask(
37
+ task: Task,
38
+ attachments: Attachment[] = [],
39
+ deliverables: Deliverable[] = [],
40
+ timeEntries: TimeEntry[] = [],
41
+ activities: Activity[] = []
42
+ ): ConcreteTaskEvidence {
43
+ const taskAttachments = attachments.filter((a) => a.taskId === task.id);
44
+ const taskDeliverables = deliverables.filter(
45
+ (d) => d.id === task.deliverableId || (task.customFields?.deliverableId === d.id)
46
+ );
47
+ const taskTimeEntries = timeEntries.filter((te) => te.taskId === task.id);
48
+ const taskActivities = activities.filter((act) => act.taskId === task.id);
49
+ const todos = task.todos || [];
50
+
51
+ // Group time entries by date for daily effort distribution
52
+ const effortByDate = new Map<string, number>();
53
+ for (const entry of taskTimeEntries) {
54
+ const dateStr = entry.loggedAt.includes('T') ? entry.loggedAt.split('T')[0] : entry.loggedAt.substring(0, 10);
55
+ const existing = effortByDate.get(dateStr) || 0;
56
+ effortByDate.set(dateStr, Math.round((existing + entry.hours) * 100) / 100);
57
+ }
58
+
59
+ const dailyEffortDistribution = Array.from(effortByDate.entries())
60
+ .map(([date, hours]) => ({ date, hours }))
61
+ .sort((a, b) => a.date.localeCompare(b.date));
62
+
63
+ const loggedHoursFromEntries = taskTimeEntries.reduce((sum, e) => sum + e.hours, 0);
64
+ const effectiveLoggedHours = Math.max(loggedHoursFromEntries, task.loggedHours || 0, task.actualHours || 0);
65
+ const estimatedHours = task.estimatedHours || (task.estimatedDurationMinutes ? task.estimatedDurationMinutes / 60 : 0);
66
+ const varianceHours = Math.round((effectiveLoggedHours - estimatedHours) * 100) / 100;
67
+
68
+ const nowIso = new Date().toISOString();
69
+ const isOverdue = Boolean(task.dueDate && task.dueDate < nowIso && task.semanticStatus !== 'completed' && task.semanticStatus !== 'canceled');
70
+ const isOverEstimate = Boolean(estimatedHours > 0 && effectiveLoggedHours > estimatedHours);
71
+
72
+ let scheduleVarianceDays: number | undefined;
73
+ if (task.dueDate && task.actualEndDate) {
74
+ const dueTime = new Date(task.dueDate).getTime();
75
+ const actualTime = new Date(task.actualEndDate).getTime();
76
+ scheduleVarianceDays = Math.round((actualTime - dueTime) / (1000 * 60 * 60 * 24));
77
+ }
78
+
79
+ let durationVarianceHours: number | undefined;
80
+ if (task.actualStartDate && task.actualEndDate && task.plannedStartDate && task.dueDate) {
81
+ const actualDuration = (new Date(task.actualEndDate).getTime() - new Date(task.actualStartDate).getTime()) / (1000 * 60 * 60);
82
+ const plannedDuration = (new Date(task.dueDate).getTime() - new Date(task.plannedStartDate).getTime()) / (1000 * 60 * 60);
83
+ if (!isNaN(actualDuration) && !isNaN(plannedDuration)) {
84
+ durationVarianceHours = Math.round((actualDuration - plannedDuration) * 100) / 100;
85
+ }
86
+ }
87
+
88
+ const accuracyRatio = estimatedHours > 0
89
+ ? Math.round((effectiveLoggedHours / estimatedHours) * 100) / 100
90
+ : undefined;
91
+
92
+ const realityDelta: RealityDelta = {
93
+ plannedStartDate: task.plannedStartDate,
94
+ actualStartDate: task.actualStartDate,
95
+ dueDate: task.dueDate,
96
+ actualEndDate: task.actualEndDate,
97
+ estimatedHours: Math.round(estimatedHours * 100) / 100,
98
+ loggedHours: Math.round(effectiveLoggedHours * 100) / 100,
99
+ varianceHours,
100
+ effortVarianceHours: varianceHours,
101
+ durationVarianceHours,
102
+ scheduleVarianceDays,
103
+ accuracyRatio,
104
+ isOverdue,
105
+ isOverEstimate
106
+ };
107
+
108
+ const hasVisualAsset = taskAttachments.some(
109
+ (a) => a.mimeType?.startsWith('image/') || a.mimeType?.startsWith('video/')
110
+ ) || taskDeliverables.some((d) => (d.outputUrls && d.outputUrls.length > 0) || Boolean(d.format));
111
+
112
+ const timestamps = [
113
+ ...taskActivities.map((a) => a.createdAt),
114
+ ...taskTimeEntries.map((te) => te.loggedAt),
115
+ task.updatedAt
116
+ ].filter(Boolean);
117
+ timestamps.sort();
118
+ const lastActivityAt = timestamps.length > 0 ? timestamps[timestamps.length - 1] : undefined;
119
+
120
+ const completedTodoCount = todos.filter((t) => t.completed).length;
121
+
122
+ const evidenceSummary: ConcreteEvidenceSummary = {
123
+ attachmentCount: taskAttachments.length,
124
+ deliverableCount: taskDeliverables.length,
125
+ todoCount: todos.length,
126
+ completedTodoCount,
127
+ timeEntryCount: taskTimeEntries.length,
128
+ totalLoggedHours: Math.round(effectiveLoggedHours * 100) / 100,
129
+ hasVisualAsset,
130
+ lastActivityAt
131
+ };
132
+
133
+ return {
134
+ taskId: task.id,
135
+ attachments: taskAttachments,
136
+ deliverables: taskDeliverables,
137
+ todos,
138
+ timeEntries: taskTimeEntries,
139
+ dailyEffortDistribution,
140
+ activities: taskActivities,
141
+ realityDelta,
142
+ evidenceSummary
143
+ };
144
+ }
145
+
146
+ export function computeMacroPhases(
147
+ tasks: Task[],
148
+ containers: TaskContainer[] = [],
149
+ iterations: Iteration[] = [],
150
+ criticalTaskIds: Set<string>
151
+ ): MacroPhaseRollup[] {
152
+ const containerMap = new Map<string, TaskContainer>(containers.map((c) => [c.id, c]));
153
+ const iterationMap = new Map<string, Iteration>(iterations.map((it) => [it.id, it]));
154
+
155
+ // Group tasks by container if any exist; fallback to iteration or unassigned
156
+ const phaseBuckets = new Map<string, { type: 'container' | 'iteration' | 'phase'; name: string; description?: string; tasks: Task[] }>();
157
+
158
+ if (containers.length > 0) {
159
+ for (const c of containers) {
160
+ phaseBuckets.set(c.id, {
161
+ type: 'container',
162
+ name: c.name,
163
+ description: c.description,
164
+ tasks: []
165
+ });
166
+ }
167
+ } else if (iterations.length > 0) {
168
+ for (const it of iterations) {
169
+ phaseBuckets.set(it.id, {
170
+ type: 'iteration',
171
+ name: it.name,
172
+ description: it.goal,
173
+ tasks: []
174
+ });
175
+ }
176
+ }
177
+
178
+ // Populate tasks into buckets
179
+ for (const t of tasks) {
180
+ let bucketId: string | null = null;
181
+ if (t.containerId && phaseBuckets.has(t.containerId)) {
182
+ bucketId = t.containerId;
183
+ } else if (t.iterationId && phaseBuckets.has(t.iterationId)) {
184
+ bucketId = t.iterationId;
185
+ }
186
+
187
+ if (!bucketId) {
188
+ const fallbackId = 'unassigned';
189
+ if (!phaseBuckets.has(fallbackId)) {
190
+ phaseBuckets.set(fallbackId, {
191
+ type: 'phase',
192
+ name: containers.length > 0 || iterations.length > 0 ? 'General Tasks' : 'All Tasks',
193
+ tasks: []
194
+ });
195
+ }
196
+ bucketId = fallbackId;
197
+ }
198
+
199
+ phaseBuckets.get(bucketId)!.tasks.push(t);
200
+ }
201
+
202
+ const nowIso = new Date().toISOString();
203
+ const phases: MacroPhaseRollup[] = [];
204
+
205
+ for (const [id, bucket] of phaseBuckets.entries()) {
206
+ const bucketTasks = bucket.tasks;
207
+ if (bucketTasks.length === 0 && id === 'unassigned') continue;
208
+
209
+ const taskIds = bucketTasks.map((t) => t.id);
210
+ const totalTasks = bucketTasks.length;
211
+ const completedTasks = bucketTasks.filter((t) => t.semanticStatus === 'completed' || t.status === 'done').length;
212
+ const inProgressTasks = bucketTasks.filter((t) => t.semanticStatus === 'in_progress' || t.status === 'in_progress').length;
213
+ const blockedTasks = bucketTasks.filter((t) => t.tags?.includes('blocked') || (t as any).isBlocked).length;
214
+
215
+ let totalEstimatedHours = 0;
216
+ let totalLoggedHours = 0;
217
+ let weightedProgressSum = 0;
218
+ let totalProgressWeight = 0;
219
+
220
+ const startDates: string[] = [];
221
+ const endDates: string[] = [];
222
+
223
+ // Inherit container/iteration dates if set
224
+ if (bucket.type === 'iteration' && iterationMap.has(id)) {
225
+ const it = iterationMap.get(id)!;
226
+ if (it.startDate) startDates.push(it.startDate);
227
+ if (it.endDate) endDates.push(it.endDate);
228
+ }
229
+
230
+ let criticalCount = 0;
231
+
232
+ for (const t of bucketTasks) {
233
+ const duration = getTaskDurationHours(t);
234
+ const est = t.estimatedHours || duration;
235
+ const logged = t.loggedHours || 0;
236
+ totalEstimatedHours += est;
237
+ totalLoggedHours += logged;
238
+
239
+ const progress = typeof t.progress === 'number'
240
+ ? t.progress
241
+ : (t.semanticStatus === 'completed' || t.status === 'done' ? 100 : 0);
242
+
243
+ weightedProgressSum += progress * Math.max(est, 1);
244
+ totalProgressWeight += Math.max(est, 1);
245
+
246
+ if (t.plannedStartDate) startDates.push(t.plannedStartDate);
247
+ if (t.actualStartDate) startDates.push(t.actualStartDate);
248
+ if (t.dueDate) endDates.push(t.dueDate);
249
+ if (t.actualEndDate) endDates.push(t.actualEndDate);
250
+
251
+ if (criticalTaskIds.has(t.id)) {
252
+ criticalCount++;
253
+ }
254
+ }
255
+
256
+ startDates.sort();
257
+ endDates.sort();
258
+
259
+ const startDate = startDates.length > 0 ? startDates[0] : undefined;
260
+ const endDate = endDates.length > 0 ? endDates[endDates.length - 1] : undefined;
261
+
262
+ const progressPercentage = totalProgressWeight > 0
263
+ ? Math.round(weightedProgressSum / totalProgressWeight)
264
+ : (totalTasks > 0 ? Math.round((completedTasks / totalTasks) * 100) : 0);
265
+
266
+ // Derive health
267
+ let health: MacroPhaseHealth = 'on_track';
268
+ if (totalTasks > 0 && completedTasks === totalTasks) {
269
+ health = 'completed';
270
+ } else if (blockedTasks > 0) {
271
+ health = 'blocked';
272
+ } else if (endDate && endDate < nowIso) {
273
+ health = 'overdue';
274
+ } else if (criticalCount > 0 && progressPercentage < 50 && endDate && (new Date(endDate).getTime() - Date.now() < 3 * 24 * 3600 * 1000)) {
275
+ health = 'at_risk';
276
+ }
277
+
278
+ phases.push({
279
+ id,
280
+ type: bucket.type,
281
+ name: bucket.name,
282
+ description: bucket.description,
283
+ startDate,
284
+ endDate,
285
+ durationHours: Math.round(totalEstimatedHours * 100) / 100,
286
+ totalTasks,
287
+ completedTasks,
288
+ inProgressTasks,
289
+ blockedTasks,
290
+ progressPercentage,
291
+ totalEstimatedHours: Math.round(totalEstimatedHours * 100) / 100,
292
+ totalLoggedHours: Math.round(totalLoggedHours * 100) / 100,
293
+ isCritical: criticalCount > 0,
294
+ criticalTaskCount: criticalCount,
295
+ health,
296
+ taskIds
297
+ });
298
+ }
299
+
300
+ return phases;
301
+ }
302
+
303
+ export function buildTimelineLadder(
304
+ context: LadderContext,
305
+ options: TimelineLadderOptions = {}
306
+ ): TimelineLadder {
307
+ const { project, tasks, dependencies, containers = [], iterations = [], deliverables = [], attachments = [], timeEntries = [], activities = [] } = context;
308
+
309
+ const targetLevel = options.level || 'all';
310
+ const generatedAt = new Date().toISOString();
311
+
312
+ // Run Critical Path Method (CPM)
313
+ const cpm = calculateCPM(project.id, tasks, dependencies);
314
+ const criticalSet = new Set(cpm.criticalTaskIds);
315
+ const scheduleMap = new Map(cpm.tasks.map((s) => [s.taskId, s]));
316
+
317
+ // Adjacency for dependencies
318
+ const blockingMap = new Map<string, string[]>();
319
+ const dependentMap = new Map<string, string[]>();
320
+ for (const t of tasks) {
321
+ blockingMap.set(t.id, []);
322
+ dependentMap.set(t.id, []);
323
+ }
324
+
325
+ for (const dep of dependencies) {
326
+ if (dep.type === 'blocking') {
327
+ // dep.taskId depends on dep.dependsOnTaskId
328
+ // dep.dependsOnTaskId blocks dep.taskId
329
+ blockingMap.get(dep.taskId)?.push(dep.dependsOnTaskId);
330
+ dependentMap.get(dep.dependsOnTaskId)?.push(dep.taskId);
331
+ } else if (dep.type === 'blocked_by') {
332
+ blockingMap.get(dep.dependsOnTaskId)?.push(dep.taskId);
333
+ dependentMap.get(dep.taskId)?.push(dep.dependsOnTaskId);
334
+ }
335
+ }
336
+
337
+ // Subtask hierarchy (parentId -> children)
338
+ const childMap = new Map<string, string[]>();
339
+ for (const t of tasks) {
340
+ if (t.parentId) {
341
+ const list = childMap.get(t.parentId) || [];
342
+ list.push(t.id);
343
+ childMap.set(t.parentId, list);
344
+ }
345
+ }
346
+
347
+ // 1. Concrete View (Grounding)
348
+ const concreteRecords: Record<string, ConcreteTaskEvidence> = {};
349
+ for (const t of tasks) {
350
+ concreteRecords[t.id] = aggregateConcreteEvidenceForTask(
351
+ t,
352
+ attachments,
353
+ deliverables,
354
+ timeEntries,
355
+ activities
356
+ );
357
+ }
358
+
359
+ // 2. Standard View (Tasks & CPM)
360
+ const standardTasks: StandardTaskTimelineItem[] = tasks.map((t) => {
361
+ const evidence = concreteRecords[t.id];
362
+ return {
363
+ ...t,
364
+ cpm: scheduleMap.get(t.id),
365
+ blockingTaskIds: blockingMap.get(t.id) || [],
366
+ dependentTaskIds: dependentMap.get(t.id) || [],
367
+ childTaskIds: childMap.get(t.id) || [],
368
+ concreteEvidenceSummary: evidence.evidenceSummary
369
+ };
370
+ });
371
+
372
+ // 3. Macro View (Phases & Project Envelope)
373
+ const phases = computeMacroPhases(tasks, containers, iterations, criticalSet);
374
+
375
+ const startDates = phases.map((p) => p.startDate).filter(Boolean) as string[];
376
+ const endDates = phases.map((p) => p.endDate).filter(Boolean) as string[];
377
+ startDates.sort();
378
+ endDates.sort();
379
+
380
+ const overallStartDate = startDates.length > 0 ? startDates[0] : undefined;
381
+ const overallEndDate = endDates.length > 0 ? endDates[endDates.length - 1] : undefined;
382
+
383
+ const totalTasks = tasks.length;
384
+ const completedTasks = tasks.filter((t) => t.semanticStatus === 'completed' || t.status === 'done').length;
385
+ const inProgressTasks = tasks.filter((t) => t.semanticStatus === 'in_progress' || t.status === 'in_progress').length;
386
+ const blockedTasks = tasks.filter((t) => t.tags?.includes('blocked') || (t as any).isBlocked).length;
387
+ const totalEstimatedHours = standardTasks.reduce((sum, t) => sum + (t.estimatedHours || 0), 0);
388
+ const totalLoggedHours = standardTasks.reduce((sum, t) => sum + (t.loggedHours || 0), 0);
389
+
390
+ const weightedProgress = standardTasks.reduce(
391
+ (sum, t) => sum + ((t.progress || 0) * Math.max(t.estimatedHours || 1, 1)),
392
+ 0
393
+ );
394
+ const totalWeight = standardTasks.reduce((sum, t) => sum + Math.max(t.estimatedHours || 1, 1), 0);
395
+ const overallProgressPercentage = totalWeight > 0
396
+ ? Math.round(weightedProgress / totalWeight)
397
+ : (totalTasks > 0 ? Math.round((completedTasks / totalTasks) * 100) : 0);
398
+
399
+ let overallHealth: MacroPhaseHealth = 'on_track';
400
+ if (totalTasks > 0 && completedTasks === totalTasks) {
401
+ overallHealth = 'completed';
402
+ } else if (phases.some((p) => p.health === 'blocked')) {
403
+ overallHealth = 'blocked';
404
+ } else if (phases.some((p) => p.health === 'overdue')) {
405
+ overallHealth = 'overdue';
406
+ } else if (phases.some((p) => p.health === 'at_risk')) {
407
+ overallHealth = 'at_risk';
408
+ }
409
+
410
+ const macro: MacroTimelineSummary = {
411
+ projectId: project.id,
412
+ projectName: project.name,
413
+ overallStartDate,
414
+ overallEndDate,
415
+ projectedFinishDate: overallEndDate,
416
+ totalDurationHours: Math.round(totalEstimatedHours * 100) / 100,
417
+ criticalPathDurationHours: cpm.totalDurationHours,
418
+ overallProgressPercentage,
419
+ health: overallHealth,
420
+ totalTasks,
421
+ completedTasks,
422
+ inProgressTasks,
423
+ blockedTasks,
424
+ totalEstimatedHours: Math.round(totalEstimatedHours * 100) / 100,
425
+ totalLoggedHours: Math.round(totalLoggedHours * 100) / 100,
426
+ phases
427
+ };
428
+
429
+ const ladder: TimelineLadder = {
430
+ projectId: project.id,
431
+ generatedAt,
432
+ level: targetLevel
433
+ };
434
+
435
+ if (targetLevel === 'all' || targetLevel === 'macro') {
436
+ ladder.macro = macro;
437
+ }
438
+
439
+ if (targetLevel === 'all' || targetLevel === 'standard') {
440
+ ladder.standard = {
441
+ tasks: standardTasks,
442
+ criticalPathTaskIds: cpm.criticalTaskIds,
443
+ dependencies,
444
+ totalDurationHours: cpm.totalDurationHours
445
+ };
446
+ }
447
+
448
+ if (targetLevel === 'all' || targetLevel === 'concrete') {
449
+ ladder.concrete = concreteRecords;
450
+ }
451
+
452
+ return ladder;
453
+ }