@polymorphism-tech/morph-spec 8.2.0 → 8.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 (54) hide show
  1. package/README.md +70 -99
  2. package/bin/morph-spec.js +13 -1
  3. package/claude-plugin.json +1 -1
  4. package/docs/CHEATSHEET.md +76 -135
  5. package/docs/QUICKSTART.md +35 -51
  6. package/framework/CLAUDE.md +3 -2
  7. package/framework/MORPH.md +20 -2
  8. package/framework/agents.json +3 -1
  9. package/framework/hooks/README.md +3 -0
  10. package/framework/hooks/claude-code/core/protect-spec-files.js +7 -1
  11. package/framework/hooks/claude-code/core/telemetry-log.js +102 -0
  12. package/framework/hooks/shared/build-check.js +8 -1
  13. package/framework/hooks/shared/payload-utils.js +16 -2
  14. package/framework/hooks/shared/phase-utils.js +2 -0
  15. package/framework/hooks/shared/telemetry-logger.js +75 -0
  16. package/framework/rules/ai-agents-standards.md +1 -0
  17. package/framework/schemas/feature.schema.json +0 -5
  18. package/framework/skills/core/create-umbraco-lp/SKILL.md +1 -1
  19. package/framework/skills/core/migrate-lp-to-umbraco/SKILL.md +1 -1
  20. package/framework/skills/core/morph-apply/SKILL.md +12 -7
  21. package/framework/skills/core/morph-brainstorming/SKILL.md +1 -1
  22. package/framework/skills/core/morph-eval/SKILL.md +1 -1
  23. package/framework/skills/core/morph-hotfix/SKILL.md +1 -1
  24. package/framework/skills/core/morph-implement/SKILL.md +22 -10
  25. package/framework/skills/core/morph-plan/SKILL.md +1 -1
  26. package/framework/skills/core/morph-proposal/SKILL.md +1 -1
  27. package/framework/skills/core/morph-review/SKILL.md +19 -12
  28. package/framework/skills/core/morph-stack-scan/SKILL.md +1 -1
  29. package/framework/skills/core/morph-standards/SKILL.md +1 -1
  30. package/framework/standards/STANDARDS.json +43 -1
  31. package/framework/standards/ai-agents/observability-patterns.md +156 -0
  32. package/framework/standards/ai-agents/production.md +3 -47
  33. package/framework/templates/REGISTRY.json +0 -93
  34. package/package.json +1 -1
  35. package/src/commands/observability/telemetry.js +75 -0
  36. package/src/commands/project/worktree.js +150 -36
  37. package/src/commands/state/score.js +13 -2
  38. package/src/commands/tasks/dag.js +11 -3
  39. package/src/core/paths/output-schema.js +28 -0
  40. package/src/core/state/state-manager.js +0 -128
  41. package/src/dashboard/app/pages/LiveState.jsx +0 -43
  42. package/src/lib/detectors/design-system-detector.js +0 -43
  43. package/src/lib/generators/index.js +0 -1
  44. package/src/lib/stack/stack-profile.js +40 -9
  45. package/src/lib/tasks/tasks-json-parser.js +21 -0
  46. package/src/lib/tasks/test-runner.js +26 -4
  47. package/src/lib/telemetry/telemetry-reader.js +103 -0
  48. package/src/lib/validators/validation-runner.js +13 -74
  49. package/src/utils/hooks-installer.js +27 -3
  50. package/framework/templates/context/CONTEXT-FEATURE.md +0 -269
  51. package/framework/templates/context/CONTEXT.md +0 -181
  52. package/src/lib/agents/metrics-aggregator.js +0 -56
  53. package/src/lib/agents/metrics-calculator.js +0 -125
  54. package/src/lib/generators/metadata-extractor.js +0 -385
@@ -1,269 +0,0 @@
1
- # {{FEATURE_NAME}} - Feature Context
2
-
3
- > Auto-generated by MORPH-SPEC Framework
4
- > Last updated: {{TIMESTAMP}}
5
-
6
- ## Feature Overview
7
-
8
- **Name:** {{FEATURE_NAME}}
9
- **Phase:** {{PHASE}}
10
- **Status:** {{STATUS}}
11
- **Complexity:** {{COMPLEXITY}}
12
-
13
- {{#if DESCRIPTION}}
14
- {{DESCRIPTION}}
15
- {{/if}}
16
-
17
- ---
18
-
19
- ## Progress Tracking
20
-
21
- ### Current Phase: {{PHASE}}
22
-
23
- {{PHASE_DESCRIPTION}}
24
-
25
- **Completed Phases:**
26
- {{#each COMPLETED_PHASES}}
27
- - ✅ {{name}} - {{completedAt}}
28
- {{/each}}
29
-
30
- **Next Phases:**
31
- {{#each UPCOMING_PHASES}}
32
- - ⏭️ {{name}}
33
- {{/each}}
34
-
35
- ### Task Progress
36
-
37
- **Total Tasks:** {{TASKS_TOTAL}}
38
- **Completed:** {{TASKS_COMPLETED}} ({{TASKS_PROGRESS}}%)
39
- **In Progress:** {{TASKS_IN_PROGRESS}}
40
- **Blocked:** {{TASKS_BLOCKED}}
41
-
42
- {{#if CURRENT_TASK}}
43
- **Current Task:** {{CURRENT_TASK.id}} - {{CURRENT_TASK.title}}
44
- {{/if}}
45
-
46
- ---
47
-
48
- ## Active Agents ({{ACTIVE_AGENTS_COUNT}})
49
-
50
- ### Team Structure
51
-
52
- {{#if TEAM_LEAD}}
53
- **Team Lead:** {{TEAM_LEAD.title}} (`{{TEAM_LEAD.id}}`)
54
- {{/if}}
55
-
56
- {{#each SQUADS}}
57
- ### {{leader.title}} Squad
58
- **Leader:** `{{leader.id}}`
59
- **Members ({{members.length}}):**
60
- {{#each members}}
61
- - {{title}} (`{{id}}`) {{#if status}}[{{status}}]{{/if}}
62
- {{/each}}
63
- {{/each}}
64
-
65
- ### Validators (Run in Hooks)
66
- {{#each VALIDATORS}}
67
- - {{title}} (`{{id}}`)
68
- {{/each}}
69
-
70
- ---
71
-
72
- ## Agent Teams
73
-
74
- {{#if AGENT_TEAMS_DECISION}}
75
- {{#if AGENT_TEAMS_DECISION.useAgentTeams}}
76
- ✅ **Agent Teams Recommended**
77
-
78
- **Reason:** {{AGENT_TEAMS_DECISION.reason}}
79
- **Display Mode:** {{AGENT_TEAMS_DECISION.displayMode}}
80
- **Total Teammates:** {{AGENT_TEAMS_DECISION.totalTeammates}}
81
-
82
- **Team Composition:**
83
- - Team Lead: {{AGENT_TEAMS_DECISION.teamLead}}
84
- - Domain Leaders: {{AGENT_TEAMS_DECISION.squads}}
85
- - Validators (hooks): {{AGENT_TEAMS_DECISION.validators}}
86
-
87
- {{else}}
88
- ❌ **Single Session Recommended**
89
-
90
- **Reason:** {{AGENT_TEAMS_DECISION.reason}}
91
- **Recommendation:** {{AGENT_TEAMS_DECISION.recommendation}}
92
- {{/if}}
93
- {{/if}}
94
-
95
- ---
96
-
97
- ## Outputs Generated
98
-
99
- {{#each OUTPUTS}}
100
- ### {{type}}
101
- **Status:** {{#if generated}}✅ Generated{{else}}⏳ Pending{{/if}}
102
- {{#if path}}**Path:** `{{path}}`{{/if}}
103
- {{#if generatedAt}}**Generated:** {{generatedAt}}{{/if}}
104
- {{/each}}
105
-
106
- ---
107
-
108
- ## Decisions Log
109
-
110
- {{#each DECISIONS}}
111
- ### ADR-{{id}}: {{title}}
112
-
113
- **Status:** {{status}}
114
- **Date:** {{date}}
115
- **Decided By:** {{decidedBy}}
116
-
117
- **Context:** {{context}}
118
-
119
- **Decision:** {{decision}}
120
-
121
- {{#if constraints}}
122
- **Constraints for Validators:**
123
- ```json
124
- {{constraints}}
125
- ```
126
- {{/if}}
127
-
128
- {{#if alternatives}}
129
- **Alternatives Considered:**
130
- {{#each alternatives}}
131
- - {{name}}: {{rationale}}
132
- {{/each}}
133
- {{/if}}
134
-
135
- ---
136
- {{/each}}
137
-
138
- {{#unless DECISIONS}}
139
- No decisions documented yet. Decisions will be logged in `decisions.md` during Design phase.
140
- {{/unless}}
141
-
142
- ---
143
-
144
- ## Validation Status
145
-
146
- {{#if VALIDATION_RESULTS}}
147
- ### Latest Validation ({{VALIDATION_TIMESTAMP}})
148
-
149
- **Overall:** {{#if VALIDATION_PASSED}}✅ PASSED{{else}}❌ FAILED{{/if}}
150
-
151
- {{#each VALIDATION_RESULTS}}
152
- #### {{validator}}
153
- **Status:** {{#if passed}}✅ PASSED{{else}}❌ FAILED{{/if}}
154
- {{#if issues}}
155
- **Issues ({{issues.length}}):**
156
- {{#each issues}}
157
- - [{{severity}}] {{message}} ({{file}}:{{line}})
158
- {{/each}}
159
- {{/if}}
160
- {{/each}}
161
-
162
- {{else}}
163
- No validation runs yet. Validators run automatically via checkpoints.
164
- {{/if}}
165
-
166
- ---
167
-
168
- ## Tasks Breakdown
169
-
170
- {{#each TASKS}}
171
- ### {{id}}: {{title}}
172
-
173
- **Status:** {{status}}
174
- {{#if priority}}**Priority:** {{priority}}{{/if}}
175
- {{#if estimatedFiles}}**Estimated Files:** {{estimatedFiles}}{{/if}}
176
- {{#if dependencies}}**Dependencies:** {{dependencies}}{{/if}}
177
-
178
- {{#if description}}
179
- {{description}}
180
- {{/if}}
181
-
182
- {{#if agent}}**Assigned Agent:** `{{agent}}`{{/if}}
183
-
184
- {{#if checkpointAfter}}🔖 **Checkpoint after this task**{{/if}}
185
-
186
- {{#if completedAt}}✅ Completed: {{completedAt}}{{/if}}
187
- {{#if blockedReason}}❌ Blocked: {{blockedReason}}{{/if}}
188
-
189
- ---
190
- {{/each}}
191
-
192
- ---
193
-
194
- ## Checkpoints
195
-
196
- {{#each CHECKPOINTS}}
197
- ### {{timestamp}}
198
- **Phase:** {{phase}}
199
- **Tasks Completed:** {{tasksCompleted}}/{{tasksTotal}}
200
-
201
- {{#if note}}
202
- **Note:** {{note}}
203
- {{/if}}
204
-
205
- {{#if validation}}
206
- **Validation:** {{validation.passed}}/{{validation.total}} checks passed
207
- {{#if validation.issues}}
208
- - Issues: {{validation.issues}}
209
- {{/if}}
210
- {{/if}}
211
-
212
- ---
213
- {{/each}}
214
-
215
- ---
216
-
217
- ## Related Standards
218
-
219
- {{#each RELATED_STANDARDS}}
220
- ### {{name}}
221
- **Path:** `{{path}}`
222
- {{#if relevantSections}}
223
- **Relevant Sections:** {{relevantSections}}
224
- {{/if}}
225
- {{/each}}
226
-
227
- ---
228
-
229
- ## Quick Actions
230
-
231
- ### Continue Implementation
232
- During the implement phase, track your work with the native `TaskCreate`/`TaskUpdate`
233
- tools. Persist progress by writing `tasks.json` (`2-plan/tasks.json`), touching ONLY
234
- the mutable fields `status`, `outputs`, and `notes` — via the `Write` tool or an `Edit`
235
- that touches only those fields. The plan contract (`title`, `description`,
236
- `dependencies`, `effort`, `doneCriteria`, `group`) is frozen after Gate 2. The recap is
237
- written by the implement skill; state syncs automatically via the `state-sync` hook.
238
-
239
- ### Advance Phase
240
- ```bash
241
- # Approve the current gate and scaffold the next phase folder in one step
242
- morph-spec advance {{FEATURE_NAME}}
243
-
244
- # Validate feature outputs
245
- morph-spec validate-feature {{FEATURE_NAME}}
246
- ```
247
-
248
- ### Validation
249
- ```bash
250
- # Validate this feature's outputs against active standards
251
- morph-spec validate-feature {{FEATURE_NAME}}
252
- ```
253
-
254
- ---
255
-
256
- ## File Paths
257
-
258
- - **Outputs Directory:** `.morph/features/{{FEATURE_NAME}}/`
259
- - **Proposal:** `{{PROPOSAL_PATH}}`
260
- - **Spec:** `{{SPEC_PATH}}`
261
- - **Contracts:** `{{CONTRACTS_PATH}}`
262
- - **Tasks:** `{{TASKS_PATH}}`
263
- - **Decisions:** `{{DECISIONS_PATH}}`
264
- - **Recap:** `{{RECAP_PATH}}`
265
-
266
- ---
267
-
268
- *Generated by MORPH-SPEC Framework v{{MORPH_VERSION}}*
269
- *Feature ID: {{FEATURE_ID}}*
@@ -1,181 +0,0 @@
1
- # {{PROJECT_NAME}} - Project Context
2
-
3
- > Auto-generated by MORPH-SPEC Framework
4
- > Last updated: {{TIMESTAMP}}
5
-
6
- ## Project Overview
7
-
8
- **Name:** {{PROJECT_NAME}}
9
- **Type:** {{PROJECT_TYPE}}
10
- **Repository:** {{REPOSITORY_URL}}
11
-
12
- {{PROJECT_DESCRIPTION}}
13
-
14
- ---
15
-
16
- ## Technology Stack
17
-
18
- ### Frontend
19
- {{#if NEXTJS_ENABLED}}- **Next.js** {{NEXTJS_VERSION}}{{/if}}
20
- {{#if UI_LIBRARY}}- **UI Library:** {{UI_LIBRARY}}{{/if}}
21
-
22
- ### Backend
23
- - **.NET** {{DOTNET_VERSION}}
24
- {{#if EF_VERSION}}- **Entity Framework Core** {{EF_VERSION}}{{/if}}
25
- {{#if DAPPER_ENABLED}}- **Dapper** (Micro-ORM){{/if}}
26
- {{#if HANGFIRE_ENABLED}}- **Hangfire** (Background Jobs){{/if}}
27
- {{#if AGENT_FRAMEWORK_ENABLED}}- **Microsoft Agent Framework** (AI Agents){{/if}}
28
-
29
- ### Database
30
- {{#if SQL_ENABLED}}- **Azure SQL** ({{SQL_SERVER}}/{{SQL_DATABASE}}){{/if}}
31
- {{#if NEON_ENABLED}}- **Neon** (PostgreSQL + Connection Pooling)
32
- - Project: {{NEON_PROJECT_ID}}
33
- - Region: {{NEON_REGION}}
34
- {{/if}}
35
-
36
- ### Infrastructure
37
- {{#if AZURE_ENABLED}}- **Azure** ({{AZURE_LOCATION}})
38
- {{#if CONTAINER_APPS_ENABLED}}- **Container Apps** ({{CONTAINER_ENV}}){{/if}}
39
- {{#if OPENAI_ENABLED}}- **Azure OpenAI** ({{OPENAI_MODEL}}){{/if}}
40
- {{#if MONITORING_ENABLED}}- **Application Insights** ({{APP_INSIGHTS}}){{/if}}
41
- {{/if}}
42
-
43
- {{#if COOLIFY_ENABLED}}- **Coolify** (Docker Deployment via SSH)
44
- - Server: {{COOLIFY_SERVER}}
45
- - App: {{COOLIFY_APP_URL}}
46
- {{/if}}
47
-
48
- ---
49
-
50
- ## Active Features
51
-
52
- {{#each ACTIVE_FEATURES}}
53
- ### {{name}} ({{phase}})
54
- **Status:** {{status}}
55
- **Complexity:** {{complexity}}
56
- **Active Agents:** {{activeAgents}}
57
-
58
- {{#if description}}{{description}}{{/if}}
59
-
60
- **Progress:**
61
- - Tasks: {{tasks.completed}}/{{tasks.total}}
62
- - Outputs: {{outputs}}
63
-
64
- {{/each}}
65
-
66
- ---
67
-
68
- ## Project Standards
69
-
70
- ### Coding Standards
71
- {{#each PROJECT_STANDARDS}}
72
- - [{{name}}]({{path}}){{#if description}} - {{description}}{{/if}}
73
- {{/each}}
74
-
75
- ### Inferred Patterns
76
- {{#if INFERRED_STANDARDS}}
77
- {{INFERRED_STANDARDS}}
78
- {{/if}}
79
-
80
- ---
81
-
82
- ## Active Agents ({{AGENT_COUNT}})
83
-
84
- ### Tier 1: Orchestrators
85
- {{#each TIER_1_AGENTS}}
86
- - **{{title}}** (`{{id}}`) {{#if always_active}}[Always Active]{{/if}}
87
- {{/each}}
88
-
89
- ### Tier 2: Domain Leaders
90
- {{#each TIER_2_AGENTS}}
91
- - **{{title}}** (`{{id}}`) - {{domains}}
92
- {{/each}}
93
-
94
- ### Tier 3: Specialists
95
- {{#each TIER_3_AGENTS}}
96
- - **{{title}}** (`{{id}}`) - Reports to `{{reports_to}}`
97
- {{/each}}
98
-
99
- ---
100
-
101
- ## Agent Teams Status
102
-
103
- {{#if AGENT_TEAMS_ENABLED}}
104
- ✅ **Enabled** (Display Mode: {{AGENT_TEAMS_DISPLAY_MODE}})
105
-
106
- **Spawn Thresholds:**
107
- - Complexity: {{AGENT_TEAMS_THRESHOLDS.complexity}}
108
- - Estimated Files: ≥ {{AGENT_TEAMS_THRESHOLDS.estimatedFiles}}
109
- - Active Agents: ≥ {{AGENT_TEAMS_THRESHOLDS.activeAgents}}
110
- - Multi-Domain: {{AGENT_TEAMS_THRESHOLDS.multiDomain}}
111
-
112
- {{else}}
113
- ❌ **Disabled** - Use single session with subagents
114
- {{/if}}
115
-
116
- ---
117
-
118
- ## Recent Checkpoints
119
-
120
- {{#each RECENT_CHECKPOINTS}}
121
- ### {{timestamp}}
122
- **Feature:** {{feature}}
123
- **Phase:** {{phase}}
124
- **Note:** {{note}}
125
-
126
- {{#if validation}}
127
- **Validation:** {{validation.passed}}/{{validation.total}} checks passed
128
- {{/if}}
129
-
130
- {{/each}}
131
-
132
- ---
133
-
134
- {{#if DEVOPS_ENABLED}}
135
- ## DevOps Integration
136
-
137
- **Organization:** {{DEVOPS_ORG}}
138
- **Project:** {{DEVOPS_PROJECT}}
139
-
140
- - **Boards:** {{#if DEVOPS_BOARDS_ENABLED}}Enabled ({{DEVOPS_AREA_PATH}}){{else}}Disabled{{/if}}
141
- - **Wiki:** {{#if DEVOPS_WIKI_ENABLED}}Enabled ({{DEVOPS_WIKI_NAME}}){{else}}Disabled{{/if}}
142
- - **Pipelines:** CI: {{DEVOPS_BUILD_PIPELINE}}, CD: {{DEVOPS_RELEASE_PIPELINE}}
143
-
144
- ---
145
-
146
- {{/if}}
147
-
148
- ## Quick Reference
149
-
150
- ### Workflow Commands
151
- ```bash
152
- # Check feature status and pending gates
153
- morph-spec status {feature}
154
- morph-spec approval-status {feature}
155
-
156
- # Approve the current gate and scaffold the next phase folder in one step
157
- morph-spec advance {feature}
158
-
159
- # Validate feature outputs
160
- morph-spec validate-feature {feature}
161
-
162
- # Archive a finished feature (after Gate 3)
163
- morph-spec archive {feature}
164
- ```
165
-
166
- > Feature work starts by asking Claude Code to implement something — the proposal
167
- > phase is created for you. During the implement phase, task progress is tracked
168
- > with the native `TaskCreate`/`TaskUpdate` tools and persisted by writing
169
- > `tasks.json` (only `status`, `outputs`, `notes`); the recap is written by the
170
- > implement skill. State syncs automatically via the `state-sync` hook.
171
-
172
- ### Key Paths
173
- - **Outputs:** `.morph/features/{feature}/`
174
- - **Standards:** `.morph/context/` (project overrides)
175
- - **Config:** `.morph/config/config.json`
176
- - **State:** `.morph/state.json`
177
- - **Templates:** `.morph/framework/templates/`
178
-
179
- ---
180
-
181
- *Generated by MORPH-SPEC Framework v{{MORPH_VERSION}}*
@@ -1,56 +0,0 @@
1
- /**
2
- * Project-level metrics aggregator
3
- *
4
- * Aggregates feature-level data from state.json into a project-wide
5
- * metrics summary. Pure computation — no I/O.
6
- */
7
-
8
- /**
9
- * Aggregate project-level metrics from state.json data.
10
- *
11
- * @param {Object} state - Parsed state.json content
12
- * @returns {Object} Aggregated metrics
13
- */
14
- export function aggregateProjectMetrics(state) {
15
- const features = state?.features || {};
16
- const featureNames = Object.keys(features);
17
-
18
- const featureMetrics = featureNames.map(name => {
19
- const f = features[name];
20
- const tasks = f.tasks || {};
21
- const taskIds = Object.keys(tasks);
22
- const completedTasks = taskIds.filter(id => tasks[id]?.status === 'completed').length;
23
- const dispatchLog = f.dispatchLog || [];
24
-
25
- return {
26
- name,
27
- phase: f.phase || f.currentPhase || 'unknown',
28
- taskCount: taskIds.length,
29
- completedTasks,
30
- dispatchCount: dispatchLog.length,
31
- };
32
- });
33
-
34
- const totalFeatures = featureMetrics.length;
35
- const completedFeatures = featureMetrics.filter(f => f.phase === 'review').length;
36
- const totalTasks = featureMetrics.reduce((sum, f) => sum + f.taskCount, 0);
37
- const completedTasks = featureMetrics.reduce((sum, f) => sum + f.completedTasks, 0);
38
- const totalDispatches = featureMetrics.reduce((sum, f) => sum + f.dispatchCount, 0);
39
- const completionRate = totalTasks > 0 ? Math.round((completedTasks / totalTasks) * 100) : 0;
40
- const avgTasksPerFeature = totalFeatures > 0 ? Math.round((totalTasks / totalFeatures) * 10) / 10 : 0;
41
-
42
- return {
43
- version: state?.version || 'unknown',
44
- updatedAt: new Date().toISOString(),
45
- summary: {
46
- totalFeatures,
47
- completedFeatures,
48
- avgTasksPerFeature,
49
- totalTasks,
50
- completedTasks,
51
- completionRate,
52
- totalDispatches,
53
- },
54
- features: featureMetrics,
55
- };
56
- }
@@ -1,125 +0,0 @@
1
- /**
2
- * Agent Metrics Calculator — Pure computation, no I/O.
3
- *
4
- * Calculates per-agent performance metrics from dispatch log entries.
5
- */
6
-
7
- /**
8
- * Calculate per-agent metrics from dispatch log entries.
9
- * @param {Array} dispatchLog - Array of dispatch entries
10
- * @returns {{ agents: Array, summary: Object }}
11
- */
12
- export function calculateMetrics(dispatchLog) {
13
- if (!Array.isArray(dispatchLog) || dispatchLog.length === 0) {
14
- return {
15
- agents: [],
16
- summary: { totalDispatches: 0, totalTasks: 0, completedTasks: 0, completionRate: 0, avgTaskDurationMs: null }
17
- };
18
- }
19
-
20
- const agentMap = new Map();
21
-
22
- for (const entry of dispatchLog) {
23
- for (const agent of entry.agents || []) {
24
- if (!agentMap.has(agent.id)) {
25
- agentMap.set(agent.id, { dispatches: 0, tasksAssigned: 0, tasksCompleted: 0, durations: [] });
26
- }
27
- const acc = agentMap.get(agent.id);
28
- acc.dispatches += 1;
29
- acc.tasksAssigned += (agent.tasks || []).length;
30
- acc.tasksCompleted += (agent.tasksCompleted || []).length;
31
-
32
- if (agent.startedAt && agent.completedAt) {
33
- const start = new Date(agent.startedAt).getTime();
34
- const end = new Date(agent.completedAt).getTime();
35
- if (!isNaN(start) && !isNaN(end) && end >= start) {
36
- acc.durations.push(end - start);
37
- }
38
- }
39
- }
40
- }
41
-
42
- const agents = [];
43
- let totalDurationAll = 0;
44
- let agentsWithDuration = 0;
45
-
46
- for (const [id, acc] of agentMap) {
47
- const totalDurationMs = acc.durations.length > 0
48
- ? acc.durations.reduce((s, d) => s + d, 0)
49
- : null;
50
- const avgDurationMs = acc.durations.length > 0
51
- ? Math.round(totalDurationMs / acc.durations.length)
52
- : null;
53
-
54
- if (totalDurationMs !== null) {
55
- totalDurationAll += totalDurationMs;
56
- agentsWithDuration++;
57
- }
58
-
59
- agents.push({
60
- id,
61
- dispatches: acc.dispatches,
62
- tasksAssigned: acc.tasksAssigned,
63
- tasksCompleted: acc.tasksCompleted,
64
- completionRate: acc.tasksAssigned > 0 ? acc.tasksCompleted / acc.tasksAssigned : 0,
65
- avgDurationMs,
66
- totalDurationMs
67
- });
68
- }
69
-
70
- agents.sort((a, b) => b.tasksCompleted - a.tasksCompleted);
71
-
72
- const totalTasks = agents.reduce((s, a) => s + a.tasksAssigned, 0);
73
- const completedTasks = agents.reduce((s, a) => s + a.tasksCompleted, 0);
74
-
75
- return {
76
- agents,
77
- summary: {
78
- totalDispatches: dispatchLog.length,
79
- totalTasks,
80
- completedTasks,
81
- completionRate: totalTasks > 0 ? completedTasks / totalTasks : 0,
82
- avgTaskDurationMs: completedTasks > 0 && totalDurationAll > 0
83
- ? Math.round(totalDurationAll / completedTasks)
84
- : null
85
- }
86
- };
87
- }
88
-
89
- /**
90
- * Format milliseconds as human-readable duration.
91
- * @param {number|null} ms
92
- * @returns {string}
93
- */
94
- export function formatDuration(ms) {
95
- if (ms == null || ms < 0) return '\u2014';
96
- if (ms === 0) return '0s';
97
-
98
- const totalSeconds = Math.floor(ms / 1000);
99
- const hours = Math.floor(totalSeconds / 3600);
100
- const minutes = Math.floor((totalSeconds % 3600) / 60);
101
- const seconds = totalSeconds % 60;
102
-
103
- if (hours > 0) return `${hours}h ${minutes}m`;
104
- if (minutes > 0) return `${minutes}m`;
105
- return `${seconds}s`;
106
- }
107
-
108
- /**
109
- * Calculate cross-feature aggregated metrics.
110
- * @param {Object} features - state.features object
111
- * @returns {{ agents: Array, summary: Object, featureCount: number }}
112
- */
113
- export function calculateAggregatedMetrics(features) {
114
- const allEntries = [];
115
- let featureCount = 0;
116
-
117
- for (const feature of Object.values(features || {})) {
118
- featureCount++;
119
- const log = feature.dispatchLog || [];
120
- allEntries.push(...log);
121
- }
122
-
123
- const result = calculateMetrics(allEntries);
124
- return { ...result, featureCount };
125
- }