ai-engineering-loop 2.0.0 → 2.2.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.
@@ -0,0 +1,877 @@
1
+ 'use strict';
2
+
3
+ // Read-side evidence for Studio node details (#91). Built-in gates record
4
+ // proof in state.json artifacts and run files, not on workflow nodes.
5
+ // nodes[id].artifact stays authoritative for agent and artifact-check nodes.
6
+
7
+ const crypto = require('crypto');
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+ const { runsDir } = require('./run-state.js');
11
+ const { readAllRunLifecycle } = require('./run-lifecycle.js');
12
+ const { isBlockingFinding } = require('./orchestration.js');
13
+ const { summarizeVerificationBundle } = require('./verification-summary.js');
14
+
15
+ const FILE_BY_KEY = Object.freeze({
16
+ goalContract: 'goal-contract.json',
17
+ diff: 'diff.patch',
18
+ verification: 'verification.json',
19
+ findings: 'findings.json',
20
+ verdict: 'verdict.json',
21
+ delivery: 'delivery.json',
22
+ report: 'report.json',
23
+ receipt: 'receipt.json',
24
+ impactDrift: 'impact-drift.json',
25
+ impactMap: 'impact-map.json',
26
+ verificationSummary: 'verification-summary.json'
27
+ });
28
+
29
+ const PRIMARY_KEY = Object.freeze({
30
+ 'goal-contract': 'goalContract',
31
+ maker: 'diff',
32
+ verification: 'verification',
33
+ 'devil-advocate': 'findings',
34
+ judge: 'verdict',
35
+ delivery: 'delivery',
36
+ report: 'report'
37
+ });
38
+
39
+ const FINISH_TYPES = new Set(['NODE_COMPLETED', 'NODE_FAILED', 'GATE_PASSED', 'NODE_APPROVED']);
40
+ const BOUNDARY_TYPES = new Set([
41
+ 'GATE_PASSED',
42
+ 'NODE_APPROVED',
43
+ 'NODE_COMPLETED',
44
+ 'NODE_FAILED',
45
+ 'WORKFLOW_CREATED',
46
+ 'WORKFLOW_EXECUTION_STARTED'
47
+ ]);
48
+
49
+ function sha256Bytes(bytes) {
50
+ return crypto.createHash('sha256').update(bytes).digest('hex');
51
+ }
52
+
53
+ function runDirectory(rootDir, runId) {
54
+ return path.join(runsDir(rootDir), runId);
55
+ }
56
+
57
+ function resolveInsideRun(rootDir, runId, relativePath) {
58
+ if (!relativePath || typeof relativePath !== 'string' || path.isAbsolute(relativePath)) return null;
59
+ const normalized = relativePath.replace(/\\/g, '/');
60
+ const prefix = `.ai-engineering-loop/runs/${runId}/`;
61
+ const runRelative = normalized.startsWith(prefix) ? normalized.slice(prefix.length) : normalized;
62
+ if (!runRelative || runRelative.split('/').includes('..')) return null;
63
+ const directory = runDirectory(rootDir, runId);
64
+ const requested = path.resolve(directory, runRelative);
65
+ const relative = path.relative(directory, requested);
66
+ if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) return null;
67
+ return { directory, requested, relative: relative.split(path.sep).join('/') };
68
+ }
69
+
70
+ function readConfined(rootDir, runId, relativePath) {
71
+ const located = resolveInsideRun(rootDir, runId, relativePath);
72
+ if (!located) return { state: 'rejected', code: 'UNSAFE_HISTORY_PATH' };
73
+ let stat;
74
+ try {
75
+ stat = fs.lstatSync(located.requested);
76
+ } catch {
77
+ return { state: 'missing', path: located.relative };
78
+ }
79
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.nlink !== 1) {
80
+ return { state: 'rejected', code: 'UNSAFE_HISTORY_PATH', path: located.relative };
81
+ }
82
+ let real;
83
+ try {
84
+ real = fs.realpathSync(located.requested);
85
+ } catch {
86
+ return { state: 'rejected', code: 'UNSAFE_HISTORY_PATH', path: located.relative };
87
+ }
88
+ let realDirectory;
89
+ try {
90
+ realDirectory = fs.realpathSync(located.directory);
91
+ } catch {
92
+ return { state: 'rejected', code: 'UNSAFE_HISTORY_PATH', path: located.relative };
93
+ }
94
+ const realRelative = path.relative(realDirectory, real);
95
+ if (realRelative.startsWith('..') || path.isAbsolute(realRelative)) {
96
+ return { state: 'rejected', code: 'UNSAFE_HISTORY_PATH', path: located.relative };
97
+ }
98
+ const bytes = fs.readFileSync(real);
99
+ return {
100
+ state: 'present',
101
+ path: located.relative,
102
+ bytes,
103
+ text: bytes.toString('utf8'),
104
+ sha256: sha256Bytes(bytes)
105
+ };
106
+ }
107
+
108
+ function descriptorFor(run, key, fileName) {
109
+ const artifacts = run?.artifacts || {};
110
+ const direct = artifacts[key];
111
+ if (direct?.path && direct?.sha256) return direct;
112
+ return Object.values(artifacts).find((item) =>
113
+ item && typeof item.path === 'string' && item.sha256 &&
114
+ item.path.replace(/\\/g, '/').endsWith(`/${fileName}`)
115
+ ) || null;
116
+ }
117
+
118
+ function loadChecked(rootDir, run, key) {
119
+ const fileName = FILE_BY_KEY[key];
120
+ if (!fileName) return { key, state: 'missing' };
121
+ const descriptor = descriptorFor(run, key, fileName);
122
+ const relative = descriptor?.path || `.ai-engineering-loop/runs/${run.runId}/${fileName}`;
123
+ const file = readConfined(rootDir, run.runId, relative);
124
+ const base = { key, fileName, path: file.path || fileName };
125
+ if (file.state === 'rejected') return { ...base, state: 'rejected', code: file.code || 'UNSAFE_HISTORY_PATH' };
126
+ if (file.state !== 'present') return { ...base, state: 'missing' };
127
+ if (descriptor?.sha256 && file.sha256 !== descriptor.sha256) {
128
+ return { ...base, state: 'changed', sha256: file.sha256 };
129
+ }
130
+ let json = null;
131
+ if (fileName.endsWith('.json')) {
132
+ try { json = JSON.parse(file.text); } catch { json = null; }
133
+ }
134
+ return {
135
+ ...base,
136
+ state: descriptor?.sha256 ? 'verified' : 'unlisted',
137
+ sha256: file.sha256,
138
+ text: file.text,
139
+ json
140
+ };
141
+ }
142
+
143
+ function publicFile(loaded) {
144
+ if (!loaded || loaded.state === 'missing') return null;
145
+ return {
146
+ name: loaded.fileName,
147
+ path: loaded.path,
148
+ state: loaded.state,
149
+ ...(loaded.sha256 ? { sha256: loaded.sha256 } : {}),
150
+ ...(loaded.code ? { code: loaded.code } : {})
151
+ };
152
+ }
153
+
154
+ function changedCard(loaded) {
155
+ return {
156
+ id: loaded.key,
157
+ title: loaded.fileName || loaded.key,
158
+ state: 'changed',
159
+ lines: [{ label: 'State', value: 'artifact changed' }]
160
+ };
161
+ }
162
+
163
+ function usable(loaded) {
164
+ return loaded && (loaded.state === 'verified' || loaded.state === 'unlisted') && loaded.state !== 'changed';
165
+ }
166
+
167
+ function diffStats(text) {
168
+ const files = [];
169
+ let current = null;
170
+ let plus = 0;
171
+ let minus = 0;
172
+ for (const line of String(text || '').split('\n')) {
173
+ const match = line.match(/^diff --git a\/(.+) b\/(.+)$/);
174
+ if (match) {
175
+ current = match[2];
176
+ if (!files.includes(current)) files.push(current);
177
+ continue;
178
+ }
179
+ if (!current || line.startsWith('+++') || line.startsWith('---')) continue;
180
+ if (line.startsWith('+')) plus += 1;
181
+ else if (line.startsWith('-')) minus += 1;
182
+ }
183
+ return { fileCount: files.length, plus, minus, files };
184
+ }
185
+
186
+ function commandDurationMs(command) {
187
+ if (command?.durationMs != null && Number.isFinite(Number(command.durationMs))) return Number(command.durationMs);
188
+ const start = Date.parse(command?.startTime || command?.startedAt || '');
189
+ const end = Date.parse(command?.endTime || command?.finishedAt || '');
190
+ if (Number.isFinite(start) && Number.isFinite(end) && end >= start) return end - start;
191
+ return null;
192
+ }
193
+
194
+ function outputSha256(command) {
195
+ return sha256Bytes(Buffer.from(`${command?.stdout || ''}\n${command?.stderr || ''}`));
196
+ }
197
+
198
+ function verificationDetail(loaded) {
199
+ if (!usable(loaded)) return null;
200
+ let summary = null;
201
+ try {
202
+ summary = summarizeVerificationBundle(loaded.json || {});
203
+ } catch {
204
+ summary = null;
205
+ }
206
+ const rawCommands = Array.isArray(loaded.json?.commands) ? loaded.json.commands : [];
207
+ const commands = rawCommands.map((command, index) => {
208
+ const summaryCommand = summary?.commands?.[index] || {};
209
+ return {
210
+ command: String(command.command || summaryCommand.command || ''),
211
+ exitCode: command.exitCode == null ? null : Number(command.exitCode),
212
+ durationMs: commandDurationMs(command),
213
+ passed: summaryCommand.testCounts?.passed ?? null,
214
+ failed: summaryCommand.testCounts?.failed ?? null,
215
+ outputSha256: outputSha256(command),
216
+ excerpt: String(command.stdout || summaryCommand.failureExcerpt || '').split('\n').find((line) => line.trim()) || ''
217
+ };
218
+ });
219
+ return {
220
+ passed: summary?.passed ?? null,
221
+ exitCode: summary?.exitCode ?? null,
222
+ commands
223
+ };
224
+ }
225
+
226
+ function findingDetail(loaded) {
227
+ if (!usable(loaded)) return null;
228
+ const findings = Array.isArray(loaded.json?.findings) ? loaded.json.findings : [];
229
+ const bySeverity = { BLOCKER: 0, HIGH: 0, MEDIUM: 0, LOW: 0 };
230
+ for (const finding of findings) {
231
+ if (Object.hasOwn(bySeverity, finding?.severity)) bySeverity[finding.severity] += 1;
232
+ }
233
+ return {
234
+ count: findings.length,
235
+ blocking: findings.filter(isBlockingFinding).length,
236
+ bySeverity,
237
+ top: findings.slice(0, 5).map((finding) => ({
238
+ id: finding.id || '',
239
+ severity: finding.severity || '',
240
+ location: finding.location || '',
241
+ failureScenario: finding.failureScenario || ''
242
+ }))
243
+ };
244
+ }
245
+
246
+ function goalDetail(loaded, run, workflowEvents) {
247
+ if (!usable(loaded)) return null;
248
+ const criteria = Array.isArray(loaded.json?.acceptanceCriteria) ? loaded.json.acceptanceCriteria : [];
249
+ const frozenEvent = (workflowEvents || []).find((event) => event.type === 'GATE_PASSED' && event.gate === 'goal');
250
+ return {
251
+ version: run?.goal?.version || loaded.json?.version || 1,
252
+ acceptanceCriteria: criteria.length,
253
+ frozenBy: run?.goal?.actor || null,
254
+ frozenAt: run?.goal?.frozenAt || frozenEvent?.at || null,
255
+ criteria: criteria.map((item) => ({ id: item.id, statement: item.statement || '' }))
256
+ };
257
+ }
258
+
259
+ function eventAt(event) {
260
+ const value = Date.parse(event?.at || '');
261
+ return Number.isFinite(value) ? value : null;
262
+ }
263
+
264
+ function eventsForNode(node, workflowEvents, lifecycleEvents) {
265
+ const legacy = node?.legacyGate || null;
266
+ const selected = [];
267
+ for (const event of workflowEvents || []) {
268
+ if (event?.nodeId === node.id || (legacy && event?.gate === legacy)) selected.push(event);
269
+ }
270
+ for (const event of lifecycleEvents || []) {
271
+ if (event?.nodeId === node.id) selected.push(event);
272
+ }
273
+ return selected.sort((left, right) => (eventAt(left) || 0) - (eventAt(right) || 0));
274
+ }
275
+
276
+ function latestOf(events, types) {
277
+ let found = null;
278
+ for (const event of events) {
279
+ if (!types.has(event.type)) continue;
280
+ const at = eventAt(event);
281
+ if (at == null) continue;
282
+ if (!found || at >= eventAt(found)) found = event;
283
+ }
284
+ return found;
285
+ }
286
+
287
+ function nodeTiming({ nodeId, status, workflowEvents = [], lifecycleEvents = [], now = Date.now() } = {}) {
288
+ const node = { id: nodeId, legacyGate: null };
289
+ const own = eventsForNode(node, workflowEvents, lifecycleEvents)
290
+ .filter((event) => event.nodeId === nodeId);
291
+ const normalized = String(status || '').toUpperCase();
292
+ if (normalized !== 'PASSED' && normalized !== 'FAILED') {
293
+ return { durationMs: null, finishedAt: null };
294
+ }
295
+ const workflowCompletions = (workflowEvents || []).filter((event) =>
296
+ event.nodeId === nodeId && (event.type === 'NODE_COMPLETED' || event.type === 'NODE_FAILED')
297
+ );
298
+ const workflowStarts = (workflowEvents || []).filter((event) => event.nodeId === nodeId && event.type === 'NODE_STARTED');
299
+ const lifecycleCompletions = (lifecycleEvents || []).filter((event) =>
300
+ event.nodeId === nodeId && (event.type === 'NODE_COMPLETED' || event.type === 'NODE_FAILED')
301
+ );
302
+ const lifecycleStarts = (lifecycleEvents || []).filter((event) => event.nodeId === nodeId && event.type === 'NODE_STARTED');
303
+ const paired = pairDuration(workflowStarts, workflowCompletions) || pairDuration(lifecycleStarts, lifecycleCompletions);
304
+ if (paired && paired > 0) {
305
+ const finish = latestOf(workflowCompletions, FINISH_TYPES) || latestOf(lifecycleCompletions, FINISH_TYPES);
306
+ return { durationMs: paired, finishedAt: finish?.at || null };
307
+ }
308
+ const finish = latestOf(own, FINISH_TYPES);
309
+ if (!finish) return { durationMs: null, finishedAt: null };
310
+ const finishAt = eventAt(finish);
311
+ const startAt = startBefore(nodeId, workflowEvents, lifecycleEvents, finishAt);
312
+ if (startAt == null || finishAt <= startAt) return { durationMs: null, finishedAt: finish.at };
313
+ return { durationMs: finishAt - startAt, finishedAt: finish.at };
314
+ }
315
+
316
+ function pairDuration(starts, finishes) {
317
+ if (!starts.length || !finishes.length) return null;
318
+ const finish = finishes[finishes.length - 1];
319
+ const finishAt = eventAt(finish);
320
+ const start = [...starts].reverse().find((event) => eventAt(event) != null && eventAt(event) <= finishAt);
321
+ if (!start || finishAt == null) return null;
322
+ return finishAt - eventAt(start);
323
+ }
324
+
325
+ function startBefore(nodeId, workflowEvents, lifecycleEvents, finishAt) {
326
+ const ownStarts = [...(workflowEvents || []), ...(lifecycleEvents || [])]
327
+ .filter((event) => event.nodeId === nodeId && event.type === 'NODE_STARTED')
328
+ .map(eventAt)
329
+ .filter((value) => value != null && value < finishAt);
330
+ if (ownStarts.length) return Math.max(...ownStarts);
331
+ const boundaries = (workflowEvents || [])
332
+ .filter((event) => BOUNDARY_TYPES.has(event.type) && event.nodeId !== nodeId)
333
+ .map(eventAt)
334
+ .filter((value) => value != null && value < finishAt);
335
+ if (!boundaries.length) return null;
336
+ return Math.max(...boundaries);
337
+ }
338
+
339
+ function humanEventLabel(event, context = {}) {
340
+ const gate = event?.gate;
341
+ if (event?.type === 'GATE_PASSED') {
342
+ if (gate === 'goal') return context.frozenBy ? `Goal frozen by ${context.frozenBy}` : 'Goal frozen';
343
+ if (gate === 'maker') {
344
+ return context.fileCount ? `Maker gate passed · ${context.fileCount} files` : 'Maker gate passed';
345
+ }
346
+ if (gate === 'verification') return 'Verification gate passed';
347
+ if (gate === 'review') return 'Review gate passed';
348
+ if (gate === 'judge') return context.verdict ? `Judge verdict ${context.verdict}` : 'Judge gate passed';
349
+ if (gate === 'delivery') return 'Delivery gate passed';
350
+ if (gate === 'report') return 'Report gate passed';
351
+ return 'Gate passed';
352
+ }
353
+ if (event?.type === 'NODE_APPROVED') return `Approved by ${event.approvedBy || context.approvedBy || 'human'}`;
354
+ if (event?.type === 'NODE_STARTED') return 'Started';
355
+ if (event?.type === 'NODE_COMPLETED') return event.message || 'Completed';
356
+ if (event?.type === 'NODE_FAILED') return event.message || 'Failed';
357
+ if (event?.type === 'NODE_ACTIVITY') return event.message || 'Activity';
358
+ if (event?.type === 'GOAL_FROZEN') return context.frozenBy ? `Goal frozen by ${context.frozenBy}` : 'Goal frozen';
359
+ if (event?.type === 'PHASE_COMPLETED') return `${event.phase || 'Phase'} completed`;
360
+ return String(event?.type || 'event').replaceAll('_', ' ').toLowerCase();
361
+ }
362
+
363
+ function groupNodeTimeline({ node, workflowEvents = [], lifecycleEvents = [], evidence = null, run = null } = {}) {
364
+ const context = {
365
+ frozenBy: evidence?.goal?.frozenBy || run?.goal?.actor || null,
366
+ fileCount: evidence?.diff?.fileCount || null,
367
+ verdict: evidence?.verdict?.verdict || null,
368
+ approvedBy: evidence?.approval?.approvedBy || null
369
+ };
370
+ const events = eventsForNode(node, workflowEvents, lifecycleEvents);
371
+ const groups = [];
372
+ let current = null;
373
+ let attempt = 0;
374
+ for (const event of events) {
375
+ const iteration = Number(event.iteration || event.loopIteration || current?.iteration || 1);
376
+ if (event.type === 'NODE_STARTED') attempt += 1;
377
+ if (!current || current.iteration !== iteration) {
378
+ attempt = Math.max(attempt, 1);
379
+ current = {
380
+ id: `iteration-${iteration}`,
381
+ iteration,
382
+ attempt,
383
+ label: `Iteration ${iteration}`,
384
+ events: []
385
+ };
386
+ groups.push(current);
387
+ }
388
+ current.events.push({
389
+ at: event.at || null,
390
+ type: event.type || '',
391
+ nodeId: event.nodeId || node?.id || null,
392
+ label: humanEventLabel(event, context)
393
+ });
394
+ }
395
+ for (const group of groups) {
396
+ if (group.attempt > 1) group.label = `Iteration ${group.iteration} · attempt ${group.attempt}`;
397
+ }
398
+ return groups;
399
+ }
400
+
401
+ function fileList(items) {
402
+ return items.map(publicFile).filter(Boolean);
403
+ }
404
+
405
+ function evidenceResult({ source, status, summary, cards, files, extra = {} }) {
406
+ return {
407
+ source,
408
+ status,
409
+ summary,
410
+ cards,
411
+ files,
412
+ count: cards.length,
413
+ message: status === 'changed' ? 'artifact changed' : (extra.message || null),
414
+ ...extra
415
+ };
416
+ }
417
+
418
+ function nodeArtifactEvidence(rootDir, run, node, runtime) {
419
+ const artifact = runtime.artifact;
420
+ const loaded = readConfined(rootDir, run.runId, artifact.path);
421
+ if (loaded.state === 'rejected') {
422
+ return evidenceResult({
423
+ source: 'node',
424
+ status: 'rejected',
425
+ summary: 'Node artifact path is outside the run directory.',
426
+ cards: [{ id: 'artifact', title: 'NODE ARTIFACT', state: 'rejected', lines: [{ label: 'State', value: 'path rejected' }] }],
427
+ files: [{ name: path.posix.basename(String(artifact.path)), path: artifact.path, state: 'rejected', code: 'UNSAFE_HISTORY_PATH' }],
428
+ extra: { message: 'path rejected' }
429
+ });
430
+ }
431
+ if (artifact.sha256 && loaded.state === 'present' && loaded.sha256 !== artifact.sha256) {
432
+ return evidenceResult({
433
+ source: 'node',
434
+ status: 'changed',
435
+ summary: 'artifact changed',
436
+ cards: [{ id: 'artifact', title: 'NODE ARTIFACT', state: 'changed', lines: [{ label: 'State', value: 'artifact changed' }] }],
437
+ files: [{ name: path.posix.basename(loaded.path || artifact.path), path: loaded.path || artifact.path, state: 'changed' }]
438
+ });
439
+ }
440
+ const name = path.posix.basename(loaded.path || artifact.path);
441
+ return evidenceResult({
442
+ source: 'node',
443
+ status: loaded.state === 'present' ? 'present' : 'missing',
444
+ summary: loaded.state === 'present'
445
+ ? `Recorded node artifact ${name}.`
446
+ : 'The node artifact descriptor is set, but the file is missing.',
447
+ cards: [{
448
+ id: 'artifact',
449
+ title: 'NODE ARTIFACT',
450
+ state: loaded.state === 'present' ? 'verified' : 'missing',
451
+ lines: [{ label: 'Path', value: name }]
452
+ }],
453
+ files: loaded.state === 'present'
454
+ ? [{ name, path: loaded.path, state: artifact.sha256 ? 'verified' : 'unlisted', sha256: loaded.sha256 }]
455
+ : []
456
+ });
457
+ }
458
+
459
+ function resolveNodeEvidence({ rootDir, run, node, runtime = {}, workflowEvents = [] } = {}) {
460
+ if (runtime?.artifact?.path) return nodeArtifactEvidence(rootDir, run, node, runtime);
461
+ const type = node?.type;
462
+ const primaryKey = PRIMARY_KEY[type] || null;
463
+ const primary = primaryKey ? loadChecked(rootDir, run, primaryKey) : null;
464
+ if (primary?.state === 'changed' || primary?.state === 'rejected') {
465
+ return evidenceResult({
466
+ source: 'run',
467
+ status: primary.state === 'rejected' ? 'rejected' : 'changed',
468
+ summary: primary.state === 'rejected' ? 'Artifact path is outside the run directory.' : 'artifact changed',
469
+ cards: [changedCard(primary)],
470
+ files: fileList([primary]),
471
+ extra: { message: primary.state === 'rejected' ? 'path rejected' : 'artifact changed' }
472
+ });
473
+ }
474
+
475
+ if (type === 'goal-contract') return goalEvidence(primary, run, workflowEvents);
476
+ if (type === 'maker') return makerEvidence(rootDir, run, primary);
477
+ if (type === 'verification') return verificationEvidence(rootDir, run, primary, workflowEvents);
478
+ if (type === 'devil-advocate') return reviewEvidence(primary);
479
+ if (type === 'judge') return judgeEvidence(rootDir, run, primary, workflowEvents);
480
+ if (type === 'approval') return approvalEvidence(runtime, workflowEvents, node);
481
+ if (type === 'delivery') return deliveryEvidence(rootDir, run, primary);
482
+ if (type === 'report') return reportEvidence(primary);
483
+ return evidenceResult({
484
+ source: 'run',
485
+ status: 'missing',
486
+ summary: 'No evidence recorded for this node yet.',
487
+ cards: [],
488
+ files: []
489
+ });
490
+ }
491
+
492
+ function goalEvidence(primary, run, workflowEvents) {
493
+ if (!usable(primary)) {
494
+ return evidenceResult({
495
+ source: 'run',
496
+ status: 'missing',
497
+ summary: 'No evidence recorded for this node yet.',
498
+ cards: [],
499
+ files: []
500
+ });
501
+ }
502
+ const goal = goalDetail(primary, run, workflowEvents);
503
+ const frozen = goal.frozenBy ? `frozen by ${goal.frozenBy}` : 'frozen';
504
+ return evidenceResult({
505
+ source: 'run',
506
+ status: 'present',
507
+ summary: `Goal contract version ${goal.version} with ${goal.acceptanceCriteria} acceptance criteria, ${frozen}.`,
508
+ cards: [{
509
+ id: 'goal',
510
+ title: 'GOAL CONTRACT',
511
+ state: primary.state,
512
+ lines: [
513
+ { label: 'Version', value: String(goal.version) },
514
+ { label: 'Acceptance criteria', value: String(goal.acceptanceCriteria) },
515
+ { label: 'Frozen by', value: goal.frozenBy || 'not recorded' },
516
+ { label: 'Frozen at', value: goal.frozenAt || 'not recorded' }
517
+ ]
518
+ }],
519
+ files: fileList([primary]),
520
+ extra: { goal }
521
+ });
522
+ }
523
+
524
+ function makerEvidence(rootDir, run, primary) {
525
+ if (!usable(primary)) {
526
+ return evidenceResult({
527
+ source: 'run',
528
+ status: 'missing',
529
+ summary: 'No evidence recorded for this node yet.',
530
+ cards: [],
531
+ files: []
532
+ });
533
+ }
534
+ const diff = diffStats(primary.text);
535
+ const drift = loadChecked(rootDir, run, 'impactDrift');
536
+ const map = loadChecked(rootDir, run, 'impactMap');
537
+ const outOfMap = Array.isArray(drift.json?.outOfMap) ? drift.json.outOfMap : [];
538
+ const driftValue = !usable(drift)
539
+ ? 'not recorded'
540
+ : outOfMap.length === 0 ? 'none' : `${outOfMap.length} out of map`;
541
+ const coverage = !usable(drift)
542
+ ? 'no drift file'
543
+ : outOfMap.length === 0 ? 'in map' : `${outOfMap.length} outside the impact map`;
544
+ const cards = [{
545
+ id: 'diff',
546
+ title: 'CHANGE · diff.patch',
547
+ state: primary.state,
548
+ lines: [
549
+ { label: 'Files', value: String(diff.fileCount) },
550
+ { label: 'Added', value: `+${diff.plus}` },
551
+ { label: 'Removed', value: `−${diff.minus}` },
552
+ { label: 'Files touched', value: diff.files.join(' · ') || 'none' },
553
+ { label: 'Drift', value: driftValue },
554
+ { label: 'Impact map', value: coverage }
555
+ ]
556
+ }];
557
+ if (drift.state === 'changed') cards.push(changedCard(drift));
558
+ const mapNote = usable(map) ? map.json?.status || 'recorded' : null;
559
+ if (mapNote) cards[0].lines.push({ label: 'Map status', value: String(mapNote) });
560
+ return evidenceResult({
561
+ source: 'run',
562
+ status: 'present',
563
+ summary: `Changed ${diff.fileCount} files, +${diff.plus} −${diff.minus}. Drift: ${driftValue}.`,
564
+ cards,
565
+ files: fileList([primary, drift, map]),
566
+ extra: { diff: { ...diff, drift: driftValue, coverage } }
567
+ });
568
+ }
569
+
570
+ function verificationEvidence(rootDir, run, primary, workflowEvents) {
571
+ if (!usable(primary)) {
572
+ return evidenceResult({
573
+ source: 'run',
574
+ status: 'missing',
575
+ summary: 'No evidence recorded for this node yet.',
576
+ cards: [],
577
+ files: []
578
+ });
579
+ }
580
+ const detail = verificationDetail(primary);
581
+ const lines = (detail?.commands || []).map((command) => {
582
+ const counts = command.passed == null && command.failed == null
583
+ ? `exit ${command.exitCode ?? '—'}`
584
+ : `${command.passed ?? 0} passed · ${command.failed ?? 0} failed`;
585
+ return {
586
+ label: command.command || 'command',
587
+ value: counts,
588
+ detail: `exit ${command.exitCode ?? '—'}`,
589
+ durationMs: command.durationMs,
590
+ outputSha256: command.outputSha256
591
+ };
592
+ });
593
+ const cards = [{
594
+ id: 'verification',
595
+ title: `VERIFICATION · ${lines.length} COMMANDS`,
596
+ state: primary.state,
597
+ lines,
598
+ note: 'output sha256 recorded'
599
+ }];
600
+ const diff = loadChecked(rootDir, run, 'diff');
601
+ let diffStatsValue = null;
602
+ if (usable(diff)) {
603
+ diffStatsValue = diffStats(diff.text);
604
+ cards.push({
605
+ id: 'diff',
606
+ title: 'CHANGE · diff.patch',
607
+ state: diff.state,
608
+ lines: [
609
+ { label: 'Files', value: String(diffStatsValue.fileCount) },
610
+ { label: 'Added', value: `+${diffStatsValue.plus}` },
611
+ { label: 'Removed', value: `−${diffStatsValue.minus}` },
612
+ { label: 'Files touched', value: diffStatsValue.files.join(' · ') || 'none' }
613
+ ]
614
+ });
615
+ } else if (diff.state === 'changed') cards.push(changedCard(diff));
616
+ const goal = loadChecked(rootDir, run, 'goalContract');
617
+ const goalInfo = usable(goal) ? goalDetail(goal, run, workflowEvents) : null;
618
+ if (goalInfo) {
619
+ const passed = detail?.passed === true;
620
+ cards.push({
621
+ id: 'claimed',
622
+ title: 'CLAIMED VS REALITY',
623
+ state: goal.state,
624
+ lines: goalInfo.criteria.map((item) => ({
625
+ label: item.id,
626
+ value: item.statement,
627
+ detail: passed ? 'verification passed' : 'verification not green'
628
+ }))
629
+ });
630
+ }
631
+ const summaryFile = loadChecked(rootDir, run, 'verificationSummary');
632
+ const first = detail?.commands?.[0];
633
+ const summary = first
634
+ ? `${first.command || 'Verification'} · ${first.passed ?? '—'} passed, ${first.failed ?? '—'} failed.`
635
+ : 'Verification evidence recorded.';
636
+ return evidenceResult({
637
+ source: 'run',
638
+ status: 'present',
639
+ summary,
640
+ cards,
641
+ files: fileList([primary, diff, goal, summaryFile]),
642
+ extra: { verification: detail, diff: diffStatsValue }
643
+ });
644
+ }
645
+
646
+ function reviewEvidence(primary) {
647
+ if (!usable(primary)) {
648
+ return evidenceResult({
649
+ source: 'run',
650
+ status: 'missing',
651
+ summary: 'No evidence recorded for this node yet.',
652
+ cards: [],
653
+ files: []
654
+ });
655
+ }
656
+ const findings = findingDetail(primary);
657
+ const severity = Object.entries(findings.bySeverity)
658
+ .filter(([, count]) => count > 0)
659
+ .map(([name, count]) => `${count} ${name}`)
660
+ .join(' · ');
661
+ return evidenceResult({
662
+ source: 'run',
663
+ status: 'present',
664
+ summary: `${findings.count} findings, ${findings.blocking} blocking.`,
665
+ cards: [{
666
+ id: 'findings',
667
+ title: 'FINDINGS',
668
+ state: primary.state,
669
+ lines: [
670
+ { label: 'Count', value: String(findings.count) },
671
+ { label: 'Blocking', value: String(findings.blocking) },
672
+ { label: 'Severity', value: severity || 'none' },
673
+ ...findings.top.map((finding) => ({
674
+ label: `${finding.severity || 'FINDING'} ${finding.id}`.trim(),
675
+ value: finding.failureScenario || finding.location || finding.id
676
+ }))
677
+ ]
678
+ }],
679
+ files: fileList([primary]),
680
+ extra: { findings }
681
+ });
682
+ }
683
+
684
+ function judgeEvidence(rootDir, run, primary, workflowEvents) {
685
+ if (!usable(primary)) {
686
+ return evidenceResult({
687
+ source: 'run',
688
+ status: 'missing',
689
+ summary: 'No evidence recorded for this node yet.',
690
+ cards: [],
691
+ files: []
692
+ });
693
+ }
694
+ const verdict = primary.json || {};
695
+ const goal = loadChecked(rootDir, run, 'goalContract');
696
+ const verification = loadChecked(rootDir, run, 'verification');
697
+ const goalInfo = usable(goal) ? goalDetail(goal, run, workflowEvents) : null;
698
+ const verificationInfo = usable(verification) ? verificationDetail(verification) : null;
699
+ const criteria = (goalInfo?.criteria || []).map((item) => ({
700
+ id: item.id,
701
+ statement: item.statement,
702
+ reality: verificationInfo?.passed ? 'verification passed' : 'verification not recorded as green'
703
+ }));
704
+ const cards = [{
705
+ id: 'verdict',
706
+ title: 'VERDICT',
707
+ state: primary.state,
708
+ lines: [
709
+ { label: 'Verdict', value: String(verdict.verdict || '—') },
710
+ { label: 'Reason', value: String(verdict.reason || '—') },
711
+ { label: 'Action', value: String(verdict.action || '—') }
712
+ ]
713
+ }];
714
+ if (criteria.length) {
715
+ cards.push({
716
+ id: 'claimed',
717
+ title: 'CLAIMED VS REALITY',
718
+ state: 'verified',
719
+ lines: criteria.map((item) => ({
720
+ label: item.id,
721
+ value: item.statement,
722
+ detail: item.reality
723
+ }))
724
+ });
725
+ }
726
+ return evidenceResult({
727
+ source: 'run',
728
+ status: 'present',
729
+ summary: `Judge verdict ${verdict.verdict || 'recorded'}.`,
730
+ cards,
731
+ files: fileList([primary, goal, verification]),
732
+ extra: { verdict: { verdict: verdict.verdict || null, reason: verdict.reason || '', criteria } }
733
+ });
734
+ }
735
+
736
+ function approvalEvidence(runtime, workflowEvents, node) {
737
+ const event = (workflowEvents || []).findLast?.((item) => item.type === 'NODE_APPROVED' && item.nodeId === node?.id)
738
+ || (workflowEvents || []).filter((item) => item.type === 'NODE_APPROVED' && item.nodeId === node?.id).at(-1);
739
+ const approvedBy = runtime?.approvedBy || event?.approvedBy || null;
740
+ const at = event?.at || (approvedBy ? runtime?.updatedAt : null) || null;
741
+ if (!approvedBy && String(runtime?.status || '').toUpperCase() !== 'PASSED') {
742
+ return evidenceResult({
743
+ source: 'run',
744
+ status: 'missing',
745
+ summary: 'No evidence recorded for this node yet.',
746
+ cards: [],
747
+ files: []
748
+ });
749
+ }
750
+ return evidenceResult({
751
+ source: 'run',
752
+ status: 'present',
753
+ summary: `Approved by ${approvedBy || 'human'}.`,
754
+ cards: [{
755
+ id: 'approval',
756
+ title: 'APPROVAL',
757
+ state: 'verified',
758
+ lines: [
759
+ { label: 'Approver', value: approvedBy || 'human' },
760
+ { label: 'Time', value: at || 'not recorded' }
761
+ ]
762
+ }],
763
+ files: [],
764
+ extra: { approval: { approvedBy: approvedBy || 'human', at } }
765
+ });
766
+ }
767
+
768
+ function deliveryEvidence(rootDir, run, primary) {
769
+ if (!usable(primary)) {
770
+ return evidenceResult({
771
+ source: 'run',
772
+ status: 'missing',
773
+ summary: 'No evidence recorded for this node yet.',
774
+ cards: [],
775
+ files: []
776
+ });
777
+ }
778
+ const delivery = primary.json || {};
779
+ const receipt = loadChecked(rootDir, run, 'receipt');
780
+ let receiptMessage = null;
781
+ let receiptState = receipt.state;
782
+ if (receipt.state === 'missing') {
783
+ receiptMessage = ['DELIVERED', 'REPORTED'].includes(run?.state)
784
+ ? 'no receipt: run predates receipts'
785
+ : 'receipt pending';
786
+ receiptState = 'missing';
787
+ } else if (receipt.state === 'changed' || receipt.state === 'rejected') {
788
+ receiptMessage = 'artifact changed';
789
+ } else {
790
+ const digest = delivery.receipt?.digest;
791
+ if (digest && receipt.json?.digest && digest !== receipt.json.digest) {
792
+ receiptState = 'changed';
793
+ receiptMessage = 'artifact changed';
794
+ } else {
795
+ receiptMessage = 'receipt recorded';
796
+ }
797
+ }
798
+ const cards = [{
799
+ id: 'delivery',
800
+ title: 'DELIVERY',
801
+ state: primary.state,
802
+ lines: [
803
+ { label: 'Destination', value: String(delivery.destination || '—') },
804
+ { label: 'Summary', value: String(delivery.summary || '—') },
805
+ { label: 'Approved', value: delivery.humanApproved === true ? (delivery.approvedBy || 'yes') : 'not recorded' }
806
+ ]
807
+ }, {
808
+ id: 'receipt',
809
+ title: 'RECEIPT',
810
+ state: receiptState,
811
+ lines: [{ label: 'Receipt', value: receiptMessage }]
812
+ }];
813
+ const summary = `Delivered to ${delivery.destination || 'the recorded destination'}. ${receiptMessage}.`;
814
+ return evidenceResult({
815
+ source: 'run',
816
+ status: receiptState === 'changed' ? 'present' : 'present',
817
+ summary,
818
+ cards,
819
+ files: fileList([primary, receipt]),
820
+ extra: {
821
+ message: receiptMessage,
822
+ receipt: { state: receiptState, message: receiptMessage, destination: delivery.destination || null }
823
+ }
824
+ });
825
+ }
826
+
827
+ function reportEvidence(primary) {
828
+ if (!usable(primary)) {
829
+ return evidenceResult({
830
+ source: 'run',
831
+ status: 'missing',
832
+ summary: 'No evidence recorded for this node yet.',
833
+ cards: [],
834
+ files: []
835
+ });
836
+ }
837
+ return evidenceResult({
838
+ source: 'run',
839
+ status: 'present',
840
+ summary: String(primary.json?.summary || 'Report recorded.'),
841
+ cards: [{
842
+ id: 'report',
843
+ title: 'REPORT',
844
+ state: primary.state,
845
+ lines: [{ label: 'Summary', value: String(primary.json?.summary || '—') }]
846
+ }],
847
+ files: fileList([primary])
848
+ });
849
+ }
850
+
851
+ function inspectNodeRun(rootDir, run, node, runtime, workflowEvents, now = Date.now()) {
852
+ let lifecycleEvents = [];
853
+ try {
854
+ lifecycleEvents = readAllRunLifecycle(rootDir, run.runId);
855
+ } catch {
856
+ lifecycleEvents = [];
857
+ }
858
+ const timing = nodeTiming({
859
+ nodeId: node.id,
860
+ status: runtime?.status || 'PENDING',
861
+ workflowEvents,
862
+ lifecycleEvents,
863
+ now
864
+ });
865
+ const nodeEvidence = resolveNodeEvidence({ rootDir, run, node, runtime, workflowEvents });
866
+ const timelineGroups = groupNodeTimeline({ node, workflowEvents, lifecycleEvents, evidence: nodeEvidence, run });
867
+ return { ...timing, nodeEvidence, timelineGroups };
868
+ }
869
+
870
+ module.exports = {
871
+ diffStats,
872
+ groupNodeTimeline,
873
+ humanEventLabel,
874
+ inspectNodeRun,
875
+ nodeTiming,
876
+ resolveNodeEvidence
877
+ };