@deveco-test/deveco-cli-common 1.3.13-23.2 → 1.3.13-23.4

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 (50) hide show
  1. package/README.md +7 -81
  2. package/THIRD-PARTY-LICENSES +76 -0
  3. package/dist/cli.js +245 -287
  4. package/dist/design2arkts-engine/resources/skill/SKILL.md +82 -9
  5. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-arkui-scoring-workflow/INSTRUCTIONS.md +25 -0
  6. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-react-to-arkui/INSTRUCTIONS.md +2 -0
  7. package/dist/design2arkts-engine/resources/skill/references/cli-integration.md +26 -1
  8. package/dist/design2arkts-engine/resources/skill/references/figma/fast/stages/01-acquire-figma-react-source.md +1 -1
  9. package/dist/design2arkts-engine/resources/skill/references/figma/fast/stages/02-convert-react-to-arkui.md +3 -1
  10. package/dist/design2arkts-engine/resources/skill/references/figma/fast/stages/03-complete-interaction-logic.md +1 -1
  11. package/dist/design2arkts-engine/resources/skill/references/figma/fast/stages/04-quality-and-build.md +3 -1
  12. package/dist/design2arkts-engine/resources/skill/references/figma/fast/stages/05-summary.md +9 -1
  13. package/dist/design2arkts-engine/resources/skill/references/figma/full/stages/01-acquire-figma-react-source.md +1 -1
  14. package/dist/design2arkts-engine/resources/skill/references/figma/full/stages/02-convert-react-to-arkui.md +3 -1
  15. package/dist/design2arkts-engine/resources/skill/references/figma/full/stages/03-complete-interaction-logic.md +1 -1
  16. package/dist/design2arkts-engine/resources/skill/references/figma/full/stages/04-quality-and-build.md +3 -1
  17. package/dist/design2arkts-engine/resources/skill/references/figma/full/stages/05-visual-calibration.md +5 -2
  18. package/dist/design2arkts-engine/resources/skill/references/figma/full/stages/06-summary.md +14 -2
  19. package/dist/design2arkts-engine/resources/skill/references/pixso/fast/stages/01-acquire-pixso-dsl.md +2 -2
  20. package/dist/design2arkts-engine/resources/skill/references/pixso/fast/stages/02-generate-skeleton-and-assets.md +4 -2
  21. package/dist/design2arkts-engine/resources/skill/references/pixso/fast/stages/03-understand-repository.md +2 -2
  22. package/dist/design2arkts-engine/resources/skill/references/pixso/fast/stages/05-design-component-tree.md +2 -2
  23. package/dist/design2arkts-engine/resources/skill/references/pixso/fast/stages/06-implement-static-layout.md +2 -2
  24. package/dist/design2arkts-engine/resources/skill/references/pixso/fast/stages/07-complete-interaction-logic.md +2 -2
  25. package/dist/design2arkts-engine/resources/skill/references/pixso/fast/stages/08-quality-build-and-audits.md +4 -2
  26. package/dist/design2arkts-engine/resources/skill/references/pixso/fast/stages/09-summary.md +13 -3
  27. package/dist/design2arkts-engine/resources/skill/references/pixso/full/stages/01-acquire-pixso-dsl.md +2 -2
  28. package/dist/design2arkts-engine/resources/skill/references/pixso/full/stages/02-generate-skeleton-and-assets.md +4 -2
  29. package/dist/design2arkts-engine/resources/skill/references/pixso/full/stages/03-understand-repository.md +2 -2
  30. package/dist/design2arkts-engine/resources/skill/references/pixso/full/stages/05-design-and-confirm-component-tree.md +5 -5
  31. package/dist/design2arkts-engine/resources/skill/references/pixso/full/stages/06-implement-static-layout.md +2 -2
  32. package/dist/design2arkts-engine/resources/skill/references/pixso/full/stages/07-complete-interaction-logic.md +2 -2
  33. package/dist/design2arkts-engine/resources/skill/references/pixso/full/stages/08-quality-build-and-audits.md +4 -2
  34. package/dist/design2arkts-engine/resources/skill/references/pixso/full/stages/09-visual-calibration.md +5 -2
  35. package/dist/design2arkts-engine/resources/skill/references/pixso/full/stages/10-summary.md +23 -3
  36. package/dist/design2arkts-engine/resources/skill/references/runtime-contract.md +24 -15
  37. package/dist/design2arkts-engine/resources/skill/scripts/workflow.mjs +464 -7
  38. package/dist/internal/telemetry-upload-background.js +9 -9
  39. package/package.json +3 -5
  40. package/skills/deveco-cli/SKILL.md +13 -51
  41. package/skills/hmos-dfx-analyzer/SKILL.md +42 -8
  42. package/skills/hmos-dfx-analyzer/references/report-encoding-pitfalls.md +41 -0
  43. package/skills/hmos-dfx-analyzer/scripts/export_report.py +10 -4
  44. package/skills/hmos-dfx-analyzer/test-cases/functional.md +54 -6
  45. package/skills/hmos-dfx-analyzer/test-cases/smoke.md +40 -3
  46. package/skills/hmos-dfx-analyzer/test-cases/trigger.md +21 -2
  47. package/skills/index.json +2 -2
  48. package/NOTICE +0 -5022
  49. package/skills/deveco-cli/docs/arkts-rules.md +0 -33
  50. package/skills/deveco-cli/docs/design2arkts.md +0 -276
@@ -93,6 +93,360 @@ function hashFile(path) {
93
93
  return createHash('sha256').update(readFileSync(path)).digest('hex');
94
94
  }
95
95
 
96
+ // ─── analytics observability ────────────────────────────────────────────────
97
+ // Optional workflow-state.json analytics subobject: per-stage net timing
98
+ // (elapsed minus human confirmation waits), calibration rounds, the frozen
99
+ // final visual score and the delivery task-completion summary. States written
100
+ // before this subobject existed keep loading; their stages simply carry no
101
+ // timing. Observation failures never change the business result.
102
+
103
+ const FINAL_VISUAL_SCORE_FILE = 'final-visual-score.json';
104
+ const TASK_COMPLETION_FILE = 'task-completion.json';
105
+ const TASK_COMPLETION_STATUSES = new Set(['passed', 'failed', 'unverified']);
106
+ const EXECUTION_OBSERVATIONS_FILE = 'execution-observations.json';
107
+
108
+ // A fresh init seeds the build-observation file so the Agent records attempts
109
+ // from before its first build. Only init creates it: status, stage-start,
110
+ // recovery and replays never backfill a run whose file is missing.
111
+ function initializeObservations(runDir) {
112
+ const target = join(runDir, EXECUTION_OBSERVATIONS_FILE);
113
+ try {
114
+ if (lstatSync(target, { throwIfNoEntry: false })) {
115
+ return;
116
+ }
117
+ writeJsonAtomic(target, {
118
+ version: 1,
119
+ buildCoverage: 'recording',
120
+ builds: [],
121
+ });
122
+ } catch {
123
+ process.stderr.write(
124
+ 'workflow: cannot initialize execution-observations.json; delivery build metrics will stay unavailable\n'
125
+ );
126
+ }
127
+ }
128
+
129
+ function isEpochMs(value) {
130
+ return Number.isSafeInteger(value) && value >= 0;
131
+ }
132
+
133
+ /** Only Full runs calibrate visually: Figma 5, Pixso 9. */
134
+ function visualCalibrationStage(catalog) {
135
+ return (catalog.designSource ?? 'pixso') === 'figma' ? 5 : 9;
136
+ }
137
+
138
+ /** Prepares the analytics object for the next committed state change. */
139
+ function withAnalyticsUpdate(state, mutate) {
140
+ const analytics = state.analytics === undefined
141
+ ? { version: 1, stages: {} }
142
+ : {
143
+ ...state.analytics,
144
+ stages: { ...(state.analytics.stages ?? {}) },
145
+ };
146
+ mutate(analytics);
147
+ return { ...state, analytics };
148
+ }
149
+
150
+ function stageTimingOf(analytics, stage) {
151
+ return analytics?.stages?.[String(stage)];
152
+ }
153
+
154
+ // Only the first entry into a stage records its start; re-entering after a
155
+ // revision request or a duplicate call keeps the original time.
156
+ function recordStageStart(analytics, stage, startedAtMs) {
157
+ if (stageTimingOf(analytics, stage)?.startedAtMs !== undefined) return;
158
+ const existing = analytics.stages[String(stage)] ?? {};
159
+ analytics.stages[String(stage)] = { ...existing, startedAtMs };
160
+ }
161
+
162
+ function openConfirmationWait(analytics, stage, startedAtMs) {
163
+ const existing = analytics.stages[String(stage)] ?? {};
164
+ const waits = Array.isArray(existing.confirmationWaits) ? existing.confirmationWaits : [];
165
+ analytics.stages[String(stage)] = {
166
+ ...existing,
167
+ confirmationWaits: [...waits, { startedAtMs }],
168
+ };
169
+ }
170
+
171
+ // accepted/revision-requested close the latest open wait; a failed
172
+ // confirmation never closes anything. One stage may hold several waits.
173
+ function closeConfirmationWait(analytics, stage, endedAtMs) {
174
+ const timing = analytics.stages[String(stage)];
175
+ const waits = Array.isArray(timing?.confirmationWaits) ? timing.confirmationWaits : [];
176
+ const openIndex = waits.findLastIndex((wait) => wait.endedAtMs === undefined);
177
+ if (openIndex === -1) return;
178
+ analytics.stages[String(stage)] = {
179
+ ...timing,
180
+ confirmationWaits: waits.map((wait, index) =>
181
+ index === openIndex ? { ...wait, endedAtMs } : wait
182
+ ),
183
+ };
184
+ }
185
+
186
+ // Net active duration: elapsed time minus every closed confirmation wait.
187
+ // Missing timestamps, unclosed, overlapping, out-of-order or out-of-stage
188
+ // waits and negative results make the value untrustworthy, so the duration is
189
+ // omitted while the business state stays valid; zero is a legitimate value.
190
+ function computeActiveDurationMs(timing) {
191
+ if (!isEpochMs(timing?.startedAtMs) || !isEpochMs(timing?.completedAtMs)) return null;
192
+ const waits = Array.isArray(timing.confirmationWaits) ? timing.confirmationWaits : [];
193
+ let waited = 0;
194
+ let previousEnd = timing.startedAtMs;
195
+ for (const wait of waits) {
196
+ if (!isEpochMs(wait?.startedAtMs) || !isEpochMs(wait?.endedAtMs)) return null;
197
+ if (wait.startedAtMs < previousEnd || wait.endedAtMs < wait.startedAtMs || wait.endedAtMs > timing.completedAtMs) {
198
+ return null;
199
+ }
200
+ waited += wait.endedAtMs - wait.startedAtMs;
201
+ previousEnd = wait.endedAtMs;
202
+ }
203
+ const duration = timing.completedAtMs - timing.startedAtMs - waited;
204
+ return Number.isSafeInteger(duration) && duration >= 0 ? duration : null;
205
+ }
206
+
207
+ // The canonical gate completedAt (preserved when replaying an interrupted
208
+ // write) becomes the stage end; the net duration is derived once from the
209
+ // stored timestamps.
210
+ function recordStageCompletion(analytics, stage, completedAtMs) {
211
+ const existing = analytics.stages[String(stage)] ?? {};
212
+ const timing = { ...existing, completedAtMs };
213
+ const activeDurationMs = computeActiveDurationMs(timing);
214
+ analytics.stages[String(stage)] = activeDurationMs === null
215
+ ? { ...timing, activeDurationMs: undefined }
216
+ : { ...timing, activeDurationMs };
217
+ }
218
+
219
+ // Observation-only reader for run-root artifacts: a missing, symlinked,
220
+ // oversized or unparsable file yields null so analytics degrades to
221
+ // unavailable instead of failing the stage.
222
+ function readRunRootJson(runDir, name) {
223
+ const target = join(runDir, name);
224
+ const info = lstatSync(target, { throwIfNoEntry: false });
225
+ if (!info || !info.isFile() || info.isSymbolicLink() || info.size > 50 * 1024 * 1024) {
226
+ return null;
227
+ }
228
+ try {
229
+ return readJsonFile(target);
230
+ } catch {
231
+ return null;
232
+ }
233
+ }
234
+
235
+ // Calibration summary taken straight from the existing calibration report.
236
+ // Only an enabled, completed calibration produces rounds; a skipped report and
237
+ // Fast runs keep the field absent.
238
+ function recordCalibrationAnalytics(runDir, catalog, analytics) {
239
+ const stage = visualCalibrationStage(catalog);
240
+ const report = readRunRootJson(runDir, `stage${stage}-visual-calibration-report.json`);
241
+ if (report?.status !== 'completed' || !Number.isInteger(report.roundsCompleted) || report.roundsCompleted < 1) return;
242
+ analytics.calibration = {
243
+ calibrationRounds: report.roundsCompleted,
244
+ correctionRounds: report.roundsCompleted - 1,
245
+ completionReason: report.completionReason,
246
+ };
247
+ }
248
+
249
+ function resolveInsideRunPath(runDir, value) {
250
+ if (typeof value !== 'string' || value.length === 0 || isAbsolute(value)) return null;
251
+ const resolved = resolve(runDir, value);
252
+ const relFromRun = relative(runDir, resolved);
253
+ if (relFromRun.startsWith('..') || isAbsolute(relFromRun) || relFromRun === '') {
254
+ return null;
255
+ }
256
+ return resolved;
257
+ }
258
+
259
+ function readInsideRunJson(runDir, value) {
260
+ const resolved = resolveInsideRunPath(runDir, value);
261
+ if (!resolved || !existsSync(resolved) || !statSync(resolved).isFile()) return null;
262
+ try {
263
+ return readJsonFile(resolved);
264
+ } catch {
265
+ return null;
266
+ }
267
+ }
268
+
269
+ function isValidScore(value) {
270
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 100;
271
+ }
272
+
273
+ // Freezes the delivered-page score at workflow completion. calibration_round
274
+ // reuses one scored round of the run's own calibration report; delivery_check
275
+ // reuses the single-round scorer output the summary stage saved for the current
276
+ // page. Everything else is unavailable; Fast is not_applicable and an
277
+ // explicitly disabled calibration is skipped.
278
+ function resolveFinalScore(runDir, catalog, finalStage) {
279
+ if (catalog.variant !== 'full') return { status: 'not_applicable' };
280
+ const stage = visualCalibrationStage(catalog);
281
+ const report = readRunRootJson(runDir, `stage${stage}-visual-calibration-report.json`);
282
+ if (!report) return { status: 'unavailable' };
283
+ if (report.status === 'skipped') return { status: 'skipped' };
284
+ if (report.status !== 'completed' || !Number.isInteger(report.roundsCompleted) || report.roundsCompleted < 1) {
285
+ return { status: 'unavailable' };
286
+ }
287
+ const artifact = readRunRootJson(runDir, FINAL_VISUAL_SCORE_FILE);
288
+ if (!artifact) {
289
+ // A passed Full calibration without the delivery artifact is a
290
+ // diagnosable collection gap: the stage still completes as unavailable,
291
+ // but the operator gets one stderr hint naming the final stage.
292
+ if (!existsSync(join(runDir, FINAL_VISUAL_SCORE_FILE))) {
293
+ process.stderr.write(
294
+ `workflow: missing final-visual-score.json; record the delivered page score before completing stage ${finalStage}\n`
295
+ );
296
+ }
297
+ return { status: 'unavailable' };
298
+ }
299
+ if (artifact?.status === 'recorded' && artifact.source === 'calibration_round') {
300
+ const round = artifact.round;
301
+ const rounds = Array.isArray(report.rounds)
302
+ ? report.rounds.filter((item) => Number(item?.round) === round)
303
+ : [];
304
+ if (
305
+ !Number.isInteger(round) || round < 1 || round > report.roundsCompleted ||
306
+ rounds.length !== 1 || !isValidScore(rounds[0]?.score)
307
+ ) {
308
+ return { status: 'unavailable' };
309
+ }
310
+ return { status: 'recorded', source: 'calibration_round', scoredRound: round, score: rounds[0].score };
311
+ }
312
+ if (artifact?.status === 'recorded' && artifact.source === 'delivery_check') {
313
+ const scoreJson = readInsideRunJson(runDir, artifact.scoreJson);
314
+ if (!scoreJson || !isValidScore(scoreJson?.aggregate?.final_baseline_score)) return { status: 'unavailable' };
315
+ for (const field of ['metricsJson', 'candidate', 'buildLog', 'deploymentLog']) {
316
+ const resolved = resolveInsideRunPath(runDir, artifact[field]);
317
+ if (!resolved || !existsSync(resolved) || !statSync(resolved).isFile()) return { status: 'unavailable' };
318
+ }
319
+ return { status: 'recorded', source: 'delivery_check', score: scoreJson.aggregate.final_baseline_score };
320
+ }
321
+ return { status: 'unavailable' };
322
+ }
323
+
324
+ function validateFinalScoreShape(finalScore) {
325
+ if (!finalScore || typeof finalScore !== 'object' || Array.isArray(finalScore)) {
326
+ fail('workflow-state.analytics.finalScore must be an object');
327
+ }
328
+ if (finalScore.status === 'recorded') {
329
+ if (finalScore.source !== 'calibration_round' && finalScore.source !== 'delivery_check') {
330
+ fail(`workflow-state.analytics.finalScore.source is invalid: ${finalScore.source}`);
331
+ }
332
+ const keys = Object.keys(finalScore).sort();
333
+ const expected = finalScore.source === 'calibration_round'
334
+ ? ['score', 'scoredRound', 'source', 'status']
335
+ : ['score', 'source', 'status'];
336
+ if (JSON.stringify(keys) !== JSON.stringify(expected)) {
337
+ fail('workflow-state.analytics.finalScore has unexpected fields');
338
+ }
339
+ if (finalScore.source === 'calibration_round' &&
340
+ (!Number.isInteger(finalScore.scoredRound) || finalScore.scoredRound < 1)) {
341
+ fail('workflow-state.analytics.finalScore.scoredRound must be a positive integer');
342
+ }
343
+ if (!isValidScore(finalScore.score)) {
344
+ fail('workflow-state.analytics.finalScore.score must be a finite number between 0 and 100');
345
+ }
346
+ return;
347
+ }
348
+ if (!['unavailable', 'skipped', 'not_applicable'].includes(finalScore.status)) {
349
+ fail(`workflow-state.analytics.finalScore.status is invalid: ${finalScore.status}`);
350
+ }
351
+ if (Object.keys(finalScore).length !== 1) {
352
+ fail('workflow-state.analytics.finalScore carries unexpected fields');
353
+ }
354
+ }
355
+
356
+ // Reads the Agent-authored task acceptance report at the run root and reduces
357
+ // it to the summary stored on workflow-state.json. The report itself stays a
358
+ // local artifact; only counts survive. Any missing, unreadable (a symlinked or
359
+ // otherwise escaping file included) or invalid report degrades to unavailable
360
+ // so the final stage never breaks on analytics collection.
361
+ function resolveTaskCompletion(runDir) {
362
+ const report = readRunRootJson(runDir, TASK_COMPLETION_FILE);
363
+ if (!report || typeof report !== 'object' || Array.isArray(report) || !Array.isArray(report.tasks) || report.tasks.length === 0) {
364
+ return { status: 'unavailable' };
365
+ }
366
+ const seenIds = new Set();
367
+ const counts = { passed: 0, failed: 0, unverified: 0 };
368
+ for (const task of report.tasks) {
369
+ if (!task || typeof task !== 'object' || Array.isArray(task)) return { status: 'unavailable' };
370
+ for (const field of ['id', 'task', 'evidence']) {
371
+ if (typeof task[field] !== 'string' || task[field].length === 0) return { status: 'unavailable' };
372
+ }
373
+ if (seenIds.has(task.id)) return { status: 'unavailable' };
374
+ seenIds.add(task.id);
375
+ if (!TASK_COMPLETION_STATUSES.has(task.status)) return { status: 'unavailable' };
376
+ counts[task.status] += 1;
377
+ }
378
+ // Completion is program-computed from the per-item verdicts: an invalid
379
+ // whole report is unavailable, never a silently shrunk denominator.
380
+ const total = counts.passed + counts.failed + counts.unverified;
381
+ return {
382
+ status: 'recorded',
383
+ passed: counts.passed,
384
+ failed: counts.failed,
385
+ unverified: counts.unverified,
386
+ rate: counts.passed / total,
387
+ };
388
+ }
389
+
390
+ function validateTaskCompletionShape(taskCompletion) {
391
+ if (!taskCompletion || typeof taskCompletion !== 'object' || Array.isArray(taskCompletion)) {
392
+ fail('workflow-state.analytics.taskCompletion must be an object');
393
+ }
394
+ if (taskCompletion.status === 'recorded') {
395
+ const keys = Object.keys(taskCompletion).sort();
396
+ if (JSON.stringify(keys) !== JSON.stringify(['failed', 'passed', 'rate', 'status', 'unverified'])) {
397
+ fail('workflow-state.analytics.taskCompletion has unexpected fields');
398
+ }
399
+ for (const field of ['passed', 'failed', 'unverified']) {
400
+ if (!Number.isSafeInteger(taskCompletion[field]) || taskCompletion[field] < 0) {
401
+ fail(`workflow-state.analytics.taskCompletion.${field} must be a non-negative safe integer`);
402
+ }
403
+ }
404
+ const total = taskCompletion.passed + taskCompletion.failed + taskCompletion.unverified;
405
+ if (!Number.isSafeInteger(total) || total < 1) {
406
+ fail('workflow-state.analytics.taskCompletion counts must sum to a positive integer');
407
+ }
408
+ if (typeof taskCompletion.rate !== 'number' || !Number.isFinite(taskCompletion.rate) || taskCompletion.rate < 0 || taskCompletion.rate > 1) {
409
+ fail('workflow-state.analytics.taskCompletion.rate must be a finite ratio between 0 and 1');
410
+ }
411
+ if (taskCompletion.rate !== taskCompletion.passed / total) {
412
+ fail('workflow-state.analytics.taskCompletion.rate must equal passed / total');
413
+ }
414
+ return;
415
+ }
416
+ if (taskCompletion.status !== 'unavailable') {
417
+ fail(`workflow-state.analytics.taskCompletion.status is invalid: ${taskCompletion.status}`);
418
+ }
419
+ if (Object.keys(taskCompletion).length !== 1) {
420
+ fail('workflow-state.analytics.taskCompletion carries unexpected fields');
421
+ }
422
+ }
423
+
424
+ // Quotes one argument for the shell that runs the returned command line:
425
+ // PowerShell on Windows, a POSIX shell elsewhere. Single quotes stop splitting
426
+ // on spaces and expansion of `$` and backticks; an embedded single quote is
427
+ // doubled for PowerShell and closed/reopened for POSIX.
428
+ function quoteShellArgument(value) {
429
+ if (process.platform === 'win32') {
430
+ return `'${value.replaceAll("'", "''")}'`;
431
+ }
432
+ return `'${value.replaceAll("'", `'"'"'`)}'`;
433
+ }
434
+
435
+ // Delivered when entering the last catalog stage: acceptance first, then the
436
+ // final submission through the CLI wrapper.
437
+ function taskCompletionInstruction(runDir, catalog, finalStage) {
438
+ const instruction = {
439
+ taskCompletionPath: join(runDir, TASK_COMPLETION_FILE),
440
+ instruction: 'Read design-doc.md, judge every promised deliverable against the delivered code and existing evidence, and write task-completion.json before submitting the final stage.',
441
+ submitCommand: `devecocli d2a stage-complete --run-dir ${quoteShellArgument(runDir)} --stage ${finalStage} --result passed`,
442
+ };
443
+ if (catalog.variant === 'full') {
444
+ instruction.finalVisualScorePath = join(runDir, FINAL_VISUAL_SCORE_FILE);
445
+ instruction.instruction = 'Read design-doc.md, judge every promised deliverable against the delivered code and existing evidence, write task-completion.json, then record the delivered page score in final-visual-score.json before submitting the final stage.';
446
+ }
447
+ return instruction;
448
+ }
449
+
96
450
  function gatePath(runDir, stage) {
97
451
  return join(runDir, 'stage-gates', `stage${String(stage).padStart(2, '0')}-gate.json`);
98
452
  }
@@ -2708,6 +3062,75 @@ function validateState(state, catalog) {
2708
3062
  }
2709
3063
  }
2710
3064
  }
3065
+ if (state.analytics !== undefined) {
3066
+ if (!state.analytics || typeof state.analytics !== 'object' || Array.isArray(state.analytics)) {
3067
+ fail('workflow-state.analytics must be an object');
3068
+ }
3069
+ const analytics = state.analytics;
3070
+ if (analytics.version !== 1) {
3071
+ fail(`workflow-state.analytics.version must be 1, got ${analytics.version}`);
3072
+ }
3073
+ if (!analytics.stages || typeof analytics.stages !== 'object' || Array.isArray(analytics.stages)) {
3074
+ fail('workflow-state.analytics.stages must be an object');
3075
+ }
3076
+ for (const [stageKey, timing] of Object.entries(analytics.stages)) {
3077
+ const stageId = Number(stageKey);
3078
+ // Pixso catalogs skip stage 4, so validate membership instead of position.
3079
+ if (!Number.isInteger(stageId) || !catalog.stages.some((entry) => entry.id === stageId)) {
3080
+ fail(`workflow-state.analytics.stages contains invalid stage id: ${stageKey}`);
3081
+ }
3082
+ if (!timing || typeof timing !== 'object' || Array.isArray(timing)) {
3083
+ fail(`workflow-state.analytics.stages.${stageKey} must be an object`);
3084
+ }
3085
+ for (const key of Object.keys(timing)) {
3086
+ if (!['startedAtMs', 'completedAtMs', 'confirmationWaits', 'activeDurationMs'].includes(key)) {
3087
+ fail(`workflow-state.analytics.stages.${stageKey} contains unsupported key: ${key}`);
3088
+ }
3089
+ }
3090
+ for (const field of ['startedAtMs', 'completedAtMs', 'activeDurationMs']) {
3091
+ if (timing[field] !== undefined && !isEpochMs(timing[field])) {
3092
+ fail(`workflow-state.analytics.stages.${stageKey}.${field} must be a non-negative integer timestamp`);
3093
+ }
3094
+ }
3095
+ if (timing.confirmationWaits !== undefined) {
3096
+ if (!Array.isArray(timing.confirmationWaits)) {
3097
+ fail(`workflow-state.analytics.stages.${stageKey}.confirmationWaits must be an array`);
3098
+ }
3099
+ for (const wait of timing.confirmationWaits) {
3100
+ if (!wait || typeof wait !== 'object' || Array.isArray(wait)) {
3101
+ fail(`workflow-state.analytics.stages.${stageKey}.confirmationWaits entries must be objects`);
3102
+ }
3103
+ for (const key of Object.keys(wait)) {
3104
+ if (key !== 'startedAtMs' && key !== 'endedAtMs') {
3105
+ fail(`workflow-state.analytics.stages.${stageKey}.confirmationWaits contains unsupported key: ${key}`);
3106
+ }
3107
+ }
3108
+ if (!isEpochMs(wait.startedAtMs) || (wait.endedAtMs !== undefined && !isEpochMs(wait.endedAtMs))) {
3109
+ fail(`workflow-state.analytics.stages.${stageKey}.confirmationWaits entry timestamps are invalid`);
3110
+ }
3111
+ }
3112
+ }
3113
+ }
3114
+ if (analytics.calibration !== undefined) {
3115
+ const calibration = analytics.calibration;
3116
+ if (
3117
+ !calibration || typeof calibration !== 'object' || Array.isArray(calibration) ||
3118
+ Object.keys(calibration).length !== 3 ||
3119
+ !Number.isInteger(calibration.calibrationRounds) || calibration.calibrationRounds < 1 ||
3120
+ !Number.isInteger(calibration.correctionRounds) ||
3121
+ calibration.correctionRounds !== calibration.calibrationRounds - 1 ||
3122
+ !['score-threshold-reached', 'max-rounds-reached'].includes(calibration.completionReason)
3123
+ ) {
3124
+ fail('workflow-state.analytics.calibration is invalid');
3125
+ }
3126
+ }
3127
+ if (analytics.finalScore !== undefined) {
3128
+ validateFinalScoreShape(analytics.finalScore);
3129
+ }
3130
+ if (analytics.taskCompletion !== undefined) {
3131
+ validateTaskCompletionShape(analytics.taskCompletion);
3132
+ }
3133
+ }
2711
3134
  }
2712
3135
 
2713
3136
  function checkDigest(state, catalog, skillRoot, catalogRelPath) {
@@ -2989,10 +3412,12 @@ if (mode === 'init') {
2989
3412
  status: 'running',
2990
3413
  awaitingConfirmationFor: null,
2991
3414
  blockedReasonCode: null,
3415
+ analytics: { version: 1, stages: {} },
2992
3416
  createdAt: now,
2993
3417
  updatedAt: now
2994
3418
  };
2995
3419
  writeJsonAtomic(statePath, state);
3420
+ initializeObservations(runDir);
2996
3421
  writeTodoPayload(runDir, catalog, state);
2997
3422
  process.stdout.write(`${JSON.stringify({
2998
3423
  workflow: catalog.workflow,
@@ -3257,8 +3682,27 @@ if (mode === 'stage-start') {
3257
3682
  }
3258
3683
  if (ready) {
3259
3684
  result.instructionPath = catalog.stages.find((entry) => entry.id === requestedStage).instructionPath;
3260
- writeTodoPayload(runDir, catalog, state);
3685
+ let todoState = state;
3686
+ if (stageTimingOf(state.analytics ?? {}, requestedStage)?.startedAtMs === undefined) {
3687
+ // First entry commits its start time alongside the same state file (one
3688
+ // atomic write). Re-entry keeps the original timestamp, so a duplicate
3689
+ // call leaves the stored start time untouched; a recording failure must
3690
+ // not change the business result.
3691
+ try {
3692
+ const startedAtMs = Date.now();
3693
+ const startedState = withAnalyticsUpdate(state, (analytics) =>
3694
+ recordStageStart(analytics, requestedStage, startedAtMs));
3695
+ writeJsonAtomic(statePath, { ...startedState, updatedAt: new Date(startedAtMs).toISOString() });
3696
+ todoState = startedState;
3697
+ } catch {
3698
+ // observation must not fail the business result
3699
+ }
3700
+ }
3701
+ writeTodoPayload(runDir, catalog, todoState);
3261
3702
  result.todoPayloadPath = join(runDir, 'todo-payload.json');
3703
+ if (catalog.stages[catalog.stages.length - 1].id === requestedStage) {
3704
+ result.taskCompletionInstruction = taskCompletionInstruction(runDir, catalog, requestedStage);
3705
+ }
3262
3706
  }
3263
3707
  if (pendingGateResult && !ready) {
3264
3708
  result.completionResult = pendingGateResult.completionResult;
@@ -3334,7 +3778,8 @@ if (mode === 'confirm') {
3334
3778
  let newState;
3335
3779
  if (decision === 'request') {
3336
3780
  newState = {
3337
- ...state,
3781
+ ...withAnalyticsUpdate(state, (analytics) =>
3782
+ openConfirmationWait(analytics, requestedStage, Date.parse(now))),
3338
3783
  status: 'awaiting_confirmation',
3339
3784
  awaitingConfirmationFor: requestedStage,
3340
3785
  ...(requestedConfirmationSnapshot && {
@@ -3376,7 +3821,8 @@ if (mode === 'confirm') {
3376
3821
  confirmedStages.push(requestedStage);
3377
3822
  }
3378
3823
  newState = {
3379
- ...state,
3824
+ ...withAnalyticsUpdate(state, (analytics) =>
3825
+ closeConfirmationWait(analytics, requestedStage, Date.parse(now))),
3380
3826
  status: 'running',
3381
3827
  awaitingConfirmationFor: null,
3382
3828
  confirmedStages,
@@ -3395,7 +3841,8 @@ if (mode === 'confirm') {
3395
3841
  delete confirmationSnapshots[2];
3396
3842
  }
3397
3843
  newState = {
3398
- ...state,
3844
+ ...withAnalyticsUpdate(state, (analytics) =>
3845
+ closeConfirmationWait(analytics, requestedStage, Date.parse(now))),
3399
3846
  status: 'running',
3400
3847
  awaitingConfirmationFor: null,
3401
3848
  confirmedStages,
@@ -3622,7 +4069,7 @@ if (mode === 'stage-complete') {
3622
4069
 
3623
4070
  if (result === 'blocked') {
3624
4071
  const newState = {
3625
- ...state,
4072
+ ...withAnalyticsUpdate(state, () => {}),
3626
4073
  status: 'blocked',
3627
4074
  blockedReasonCode: reasonCode,
3628
4075
  awaitingConfirmationFor: null,
@@ -3644,7 +4091,16 @@ if (mode === 'stage-complete') {
3644
4091
  const nextStage = catalog.stages[catalog.stages.findIndex((entry) => entry.id === requestedStage) + 1];
3645
4092
  const isLastStage = nextStage === undefined;
3646
4093
  const newState = {
3647
- ...state,
4094
+ ...withAnalyticsUpdate(state, (analytics) => {
4095
+ recordStageCompletion(analytics, requestedStage, Date.parse(canonicalGate.completedAt));
4096
+ if (catalog.variant === 'full' && requestedStage === visualCalibrationStage(catalog)) {
4097
+ recordCalibrationAnalytics(runDir, catalog, analytics);
4098
+ }
4099
+ if (isLastStage) {
4100
+ analytics.finalScore = resolveFinalScore(runDir, catalog, requestedStage);
4101
+ analytics.taskCompletion = resolveTaskCompletion(runDir);
4102
+ }
4103
+ }),
3648
4104
  completedStages,
3649
4105
  currentStage: isLastStage ? requestedStage : nextStage.id,
3650
4106
  status: isLastStage ? 'completed' : 'running',
@@ -3658,7 +4114,8 @@ if (mode === 'stage-complete') {
3658
4114
  currentStage: newState.currentStage,
3659
4115
  completedStages: newState.completedStages,
3660
4116
  nextRequiredAction: 'sync_final_todo_then_finish',
3661
- todoPayloadPath: join(runDir, 'todo-payload.json')
4117
+ todoPayloadPath: join(runDir, 'todo-payload.json'),
4118
+ taskCompletion: newState.analytics.taskCompletion
3662
4119
  }, null, 2)}\n`);
3663
4120
  } else {
3664
4121
  process.stdout.write(`${JSON.stringify({