@contextrail/assess 0.0.0-stage → 1.0.0-alpha.1

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 (73) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +82 -2
  3. package/assets/brand/icon-dark.png +0 -0
  4. package/assets/brand/icon-light.png +0 -0
  5. package/dist/assess.d.ts +109 -0
  6. package/dist/assess.js +1548 -0
  7. package/dist/assessment.d.ts +566 -0
  8. package/dist/assessment.js +404 -0
  9. package/dist/budget.d.ts +24 -0
  10. package/dist/budget.js +52 -0
  11. package/dist/candidate.d.ts +147 -0
  12. package/dist/candidate.js +321 -0
  13. package/dist/change-summary.d.ts +33 -0
  14. package/dist/change-summary.js +26 -0
  15. package/dist/cli.d.ts +2 -0
  16. package/dist/cli.js +406 -0
  17. package/dist/contracts.d.ts +99 -0
  18. package/dist/contracts.js +62 -0
  19. package/dist/diagnostics.d.ts +44 -0
  20. package/dist/diagnostics.js +412 -0
  21. package/dist/evidence.d.ts +73 -0
  22. package/dist/evidence.js +297 -0
  23. package/dist/feedback.d.ts +21 -0
  24. package/dist/feedback.js +140 -0
  25. package/dist/git.d.ts +40 -0
  26. package/dist/git.js +207 -0
  27. package/dist/github.d.ts +90 -0
  28. package/dist/github.js +1342 -0
  29. package/dist/index.d.ts +14 -0
  30. package/dist/index.js +14 -0
  31. package/dist/mcp.d.ts +28 -0
  32. package/dist/mcp.js +173 -0
  33. package/dist/pack.d.ts +160 -0
  34. package/dist/pack.js +377 -0
  35. package/dist/phases.d.ts +65 -0
  36. package/dist/phases.js +63 -0
  37. package/dist/planning.d.ts +64 -0
  38. package/dist/planning.js +135 -0
  39. package/dist/pr-context.d.ts +316 -0
  40. package/dist/pr-context.js +198 -0
  41. package/dist/prepare.d.ts +71 -0
  42. package/dist/prepare.js +335 -0
  43. package/dist/presentation.d.ts +309 -0
  44. package/dist/presentation.js +1026 -0
  45. package/dist/provider-diagnostics.d.ts +93 -0
  46. package/dist/provider-diagnostics.js +233 -0
  47. package/dist/providers.d.ts +45 -0
  48. package/dist/providers.js +291 -0
  49. package/dist/report-contract.d.ts +132 -0
  50. package/dist/report-contract.js +240 -0
  51. package/dist/results.d.ts +90 -0
  52. package/dist/results.js +128 -0
  53. package/dist/resume.d.ts +25 -0
  54. package/dist/resume.js +116 -0
  55. package/dist/source.d.ts +167 -0
  56. package/dist/source.js +675 -0
  57. package/dist/verification.d.ts +386 -0
  58. package/dist/verification.js +168 -0
  59. package/dist/version.d.ts +2 -0
  60. package/dist/version.js +9 -0
  61. package/docs/README.md +24 -0
  62. package/docs/action-reference.md +85 -0
  63. package/docs/architecture.md +156 -0
  64. package/docs/configuration.md +83 -0
  65. package/docs/contributing.md +46 -0
  66. package/docs/getting-started.md +92 -0
  67. package/docs/github-actions.md +141 -0
  68. package/docs/operations.md +203 -0
  69. package/docs/review-results.md +173 -0
  70. package/docs/security.md +64 -0
  71. package/docs/standards.md +62 -0
  72. package/examples/assess-pull-request.yml +109 -0
  73. package/package.json +56 -5
@@ -0,0 +1,1026 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { z } from 'zod';
3
+ import { digest } from './prepare.js';
4
+ import { validatePhaseRecord } from './phases.js';
5
+ import { PROVIDER_FAILURE_CODES } from './providers.js';
6
+ import { phaseItems } from './change-summary.js';
7
+ import { assessLogoBaseUrl } from './version.js';
8
+ export const object = (value) => value && typeof value === 'object' && !Array.isArray(value) ? value : {};
9
+ export const objects = (value) => (Array.isArray(value) ? value.map(object) : []);
10
+ export const string = (value, fallback = '') => (typeof value === 'string' ? value : fallback);
11
+ const number = (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0;
12
+ function developerRanges(finding) {
13
+ return objects(finding.locationRefs).flatMap((citation) => {
14
+ const provenance = object(citation.provenance), location = object(citation.location), quote = citation.quote;
15
+ const line = location.line, column = location.column;
16
+ if (provenance.kind !== 'source' ||
17
+ !['head', 'base'].includes(string(provenance.side)) ||
18
+ ![provenance.commit, provenance.path, provenance.object].every((value) => typeof value === 'string' && value.length > 0) ||
19
+ !Number.isSafeInteger(line) ||
20
+ Number(line) < 1 ||
21
+ !Number.isSafeInteger(column) ||
22
+ Number(column) < 0 ||
23
+ typeof quote !== 'string' ||
24
+ !quote.length)
25
+ return [];
26
+ const lines = quote.split('\n');
27
+ return [
28
+ {
29
+ identity: digest([provenance.side, provenance.commit, provenance.path, provenance.object]),
30
+ path: string(provenance.path),
31
+ start: [Number(line), Number(column)],
32
+ end: [
33
+ Number(line) + lines.length - 1,
34
+ lines.length === 1 ? Number(column) + quote.length : lines.at(-1).length,
35
+ ],
36
+ },
37
+ ];
38
+ });
39
+ }
40
+ const beforePosition = (a, b) => a[0] < b[0] || (a[0] === b[0] && a[1] < b[1]);
41
+ export function developerFindingLocations(finding) {
42
+ return developerRanges(finding)
43
+ .map((range) => `${range.path}:${range.start[0]}:${range.start[1]}–${range.end[0]}:${range.end[1]}`)
44
+ .join(', ');
45
+ }
46
+ export function developerFindingGroupLabel(accounts) {
47
+ const keys = accounts.map((account) => digest(developerRanges(account)
48
+ .map((range) => [range.identity, range.start, range.end])
49
+ .sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)))));
50
+ return keys.every((key) => key === keys[0]) ? 'the same source range' : 'overlapping source ranges';
51
+ }
52
+ /** Display connected overlapping pinned ranges; preserve every account without asserting semantic equivalence. */
53
+ export function groupDeveloperFindings(input) {
54
+ const findings = objects(input).filter((finding) => finding.verified === true);
55
+ const groups = [];
56
+ for (const [index, finding] of findings.entries()) {
57
+ const ranges = developerRanges(finding);
58
+ const overlaps = groups.filter((group) => group.ranges.some((other) => ranges.some((range) => range.identity === other.identity &&
59
+ beforePosition(range.start, other.end) &&
60
+ beforePosition(other.start, range.end))));
61
+ if (!overlaps.length) {
62
+ groups.push({ indices: [index], ranges });
63
+ continue;
64
+ }
65
+ const target = overlaps[0];
66
+ target.indices.push(index);
67
+ target.ranges.push(...ranges);
68
+ for (const group of overlaps.slice(1)) {
69
+ target.indices.push(...group.indices);
70
+ target.ranges.push(...group.ranges);
71
+ groups.splice(groups.indexOf(group), 1);
72
+ }
73
+ target.indices.sort((a, b) => a - b);
74
+ }
75
+ return groups.map((group) => group.indices.map((index) => findings[index]));
76
+ }
77
+ export function markdownText(value, limit = 500) {
78
+ const flat = String(value ?? 'unavailable').replace(/\p{Cc}/gu, ' ');
79
+ return (flat.length > limit ? flat.slice(0, limit) + '…' : flat)
80
+ .replace(/[\\`*_{}[\]()#+.!|:]/g, '\\$&')
81
+ .replace(/&/g, '&amp;')
82
+ .replace(/</g, '&lt;')
83
+ .replace(/>/g, '&gt;')
84
+ .replace(/@/g, '&#64;');
85
+ }
86
+ const clip = (v, n) => String(v ?? '')
87
+ .replace(/\p{Cc}/gu, ' ')
88
+ .slice(0, n);
89
+ const small = (n) => z
90
+ .string()
91
+ .max(n)
92
+ .refine((v) => !/\p{Cc}/u.test(v));
93
+ const sha = z.string().regex(/^[a-f0-9]{40}$/);
94
+ const nullableNumber = z.number().nonnegative().max(Number.MAX_SAFE_INTEGER).nullable();
95
+ const model = small(200).regex(/^[A-Za-z0-9._:/-]*$/);
96
+ const provider = z.enum(['openai', 'openrouter', 'unknown']);
97
+ const effort = z.enum(['', 'none', 'minimal', 'low', 'medium', 'high', 'xhigh']);
98
+ const disposition = z.enum(['evaluated', 'observed', 'unresolved', 'not_applicable', 'not_evaluated']);
99
+ const classification = z.enum(['none', 'binding_violation', 'behavioral_defect', 'guidance_departure']);
100
+ const phaseIdentity = z.object({ phase: small(40), provider, model, effort }).strict();
101
+ const runSchema = z
102
+ .object({
103
+ id: z.string().regex(/^[1-9][0-9]{0,19}$/),
104
+ attempt: z.number().int().positive().max(1000000),
105
+ cliRunId: z
106
+ .string()
107
+ .regex(/^[A-Za-z0-9_-]{1,200}$/)
108
+ .nullable(),
109
+ base: sha.nullable(),
110
+ head: sha.nullable(),
111
+ at: z.iso.datetime(),
112
+ assessment: z.enum(['complete', 'incomplete', 'running', 'not_started', 'unknown']),
113
+ execution: z.enum(['finished', 'failed', 'unknown']),
114
+ exit: z.union([z.literal(0), z.literal(1), z.literal(2)]).nullable(),
115
+ findings: z.number().int().nonnegative(),
116
+ unresolved: z.number().int().nonnegative(),
117
+ durationMs: nullableNumber,
118
+ cost: nullableNumber,
119
+ costComplete: z.boolean(),
120
+ packageVersion: small(100),
121
+ reviewerVersion: nullableNumber,
122
+ provider,
123
+ model,
124
+ effort,
125
+ phaseModels: z.array(phaseIdentity).max(10).optional(),
126
+ })
127
+ .strict();
128
+ const assessmentSchema = z
129
+ .object({
130
+ base: sha,
131
+ head: sha,
132
+ run: z.string().regex(/^[1-9][0-9]{0,19}$/),
133
+ cliRunId: z.string().regex(/^[A-Za-z0-9_-]{1,200}$/),
134
+ attempt: z.number().int().positive(),
135
+ reviewerVersion: nullableNumber,
136
+ scopeIdentity: small(150),
137
+ provider,
138
+ model,
139
+ effort,
140
+ entries: z
141
+ .array(z
142
+ .object({
143
+ nodeId: small(500).regex(/^context:\/\/[A-Za-z0-9._/-]+$/),
144
+ version: z.number().int().positive(),
145
+ disposition,
146
+ finding: classification,
147
+ explanation: small(300),
148
+ correction: small(200),
149
+ })
150
+ .strict())
151
+ .max(30),
152
+ omitted: z.number().int().nonnegative(),
153
+ })
154
+ .strict();
155
+ const historySchema = z
156
+ .object({
157
+ version: z.union([z.literal(1), z.literal(2)]),
158
+ repository: small(301).regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/),
159
+ pr: z.number().int().positive(),
160
+ reviewer: small(500).startsWith('skill://'),
161
+ runs: z.array(runSchema).max(10),
162
+ omitted: z.number().int().nonnegative(),
163
+ assessment: assessmentSchema.nullable(),
164
+ })
165
+ .strict();
166
+ export const assessmentMarker = (config) => `<!-- contextrail-assess:${createHash('sha256')
167
+ .update(typeof config === 'string' ? config : config.reviewer)
168
+ .digest('hex')
169
+ .slice(0, 24)} -->`;
170
+ export function readHistory(body, c) {
171
+ if (typeof body !== 'string' || body.length > 65536)
172
+ return null;
173
+ const match = body.match(/\n<!-- contextrail-state:v([12]):([A-Za-z0-9+/=]{1,40000}) -->\n/);
174
+ if (!match)
175
+ return null;
176
+ try {
177
+ const bytes = Buffer.from(match[2], 'base64');
178
+ if (bytes.length > 30000 || bytes.toString('base64') !== match[2])
179
+ return null;
180
+ const parsed = historySchema.parse(JSON.parse(bytes.toString('utf8')));
181
+ return parsed.version === Number(match[1]) &&
182
+ parsed.repository === c.repository &&
183
+ parsed.pr === c.pr &&
184
+ parsed.reviewer === c.reviewer
185
+ ? parsed
186
+ : null;
187
+ }
188
+ catch {
189
+ return null;
190
+ }
191
+ }
192
+ export function summarizeUsage(state) {
193
+ const execution = object(object(state).execution), calls = number(execution.calls) ? execution.calls : null;
194
+ const wire = objects(execution.providerUsage);
195
+ const records = wire.length ? wire : objects(execution.usage);
196
+ const unique = new Map();
197
+ records.forEach((r, i) => {
198
+ const call = wire.length ? r.call : i + 1;
199
+ if (number(call) &&
200
+ Number.isSafeInteger(call) &&
201
+ call > 0 &&
202
+ calls !== null &&
203
+ call <= calls &&
204
+ !unique.has(call))
205
+ unique.set(call, wire.length ? object(r.usage) : r);
206
+ });
207
+ const metric = (keys) => {
208
+ const values = [...unique.values()]
209
+ .map((u) => keys.map((k) => k.split('.').reduce((v, part) => object(v)[part], u)).find(number))
210
+ .filter(number);
211
+ return {
212
+ value: values.length ? values.reduce((a, b) => a + b, 0) : null,
213
+ reported: values.length,
214
+ complete: calls !== null && calls > 0 && values.length === calls,
215
+ };
216
+ };
217
+ return {
218
+ calls,
219
+ cost: metric(['cost']),
220
+ input: metric(['input_tokens', 'prompt_tokens', 'inputTokens']),
221
+ output: metric(['output_tokens', 'completion_tokens', 'outputTokens']),
222
+ total: metric(['total_tokens', 'totalTokens']),
223
+ cached: metric([
224
+ 'input_tokens_details.cached_tokens',
225
+ 'prompt_tokens_details.cached_tokens',
226
+ 'cachedInputTokens',
227
+ ]),
228
+ reasoning: metric([
229
+ 'output_tokens_details.reasoning_tokens',
230
+ 'completion_tokens_details.reasoning_tokens',
231
+ 'reasoningTokens',
232
+ ]),
233
+ };
234
+ }
235
+ const duration = (v) => number(v) ? `${Math.floor(v / 60000)}m ${((v % 60000) / 1000).toFixed(1)}s` : 'unavailable';
236
+ const isArtifactUrl = (url) => typeof url === 'string' &&
237
+ /^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/actions\/runs\/[0-9]+\/artifacts\/[0-9]+$/.test(url);
238
+ const runUrl = (url) => typeof url === 'string' &&
239
+ /^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/actions\/runs\/[0-9]+(?:\/attempts\/[0-9]+)?$/.test(url);
240
+ function metricText(m, calls, money = false) {
241
+ return `${m.value === null ? 'unavailable' : money ? `$${m.value.toFixed(6)} USD` : m.value.toLocaleString('en-US')} (${m.reported}/${calls ?? '?'} calls reported${m.value !== null && !m.complete ? '; partial' : ''})`;
242
+ }
243
+ function coveragePhase(raw, state, scope) {
244
+ if (!['assess', 'verify'].includes(string(raw.phase)))
245
+ return null;
246
+ const assigned = Array.isArray(raw.assessmentIds) ? raw.assessmentIds : [];
247
+ if (!assigned.length || !assigned.every((id) => typeof id === 'string' && scope.has(id)))
248
+ return null;
249
+ try {
250
+ return validatePhaseRecord(raw, {
251
+ runId: string(state.runId),
252
+ artifact: object(state.artifact),
253
+ scopeIdentity: typeof state.scopeIdentity === 'string' ? state.scopeIdentity : null,
254
+ assessmentIds: assigned,
255
+ requireComplete: false,
256
+ });
257
+ }
258
+ catch {
259
+ // Invalid or cross-run handoffs cannot establish progress.
260
+ return null;
261
+ }
262
+ }
263
+ function completeOutput(phase, ids) {
264
+ return (phase.status === 'complete' &&
265
+ (Array.isArray(phase.output) ||
266
+ Array.isArray(object(phase.output)[phase.phase === 'assess' ? 'assessments' : 'entries'])) &&
267
+ ids.length === phase.assessmentIds.length &&
268
+ new Set(ids).size === ids.length &&
269
+ ids.every((id) => phase.assessmentIds.includes(id)));
270
+ }
271
+ function recordPartialAssessment(phase, handoffs) {
272
+ if (phase.status === 'complete' || phase.configuration.kind !== 'partial_assessment_progress')
273
+ return;
274
+ const output = object(phase.output);
275
+ if (!Array.isArray(output.assessments) || !Array.isArray(output.remaining))
276
+ return;
277
+ const proposals = objects(output.assessments);
278
+ const ids = proposals.map((p) => string(object(p.result).assessmentId));
279
+ const partition = [...ids, ...output.remaining];
280
+ if (proposals.length !== output.assessments.length ||
281
+ partition.length !== phase.assessmentIds.length ||
282
+ new Set(partition).size !== partition.length ||
283
+ !partition.every((id) => phase.assessmentIds.includes(id)) ||
284
+ proposals.some((p) => !['evaluated', 'observed', 'not_applicable', 'unresolved'].includes(string(object(p.result).disposition))))
285
+ return;
286
+ for (const id of ids)
287
+ handoffs.partial.add(id);
288
+ }
289
+ function recordAssessment(phase, handoffs) {
290
+ for (const id of phase.assessmentIds) {
291
+ handoffs.partial.delete(id);
292
+ handoffs.current.delete(id);
293
+ handoffs.verification.delete(id);
294
+ }
295
+ recordPartialAssessment(phase, handoffs);
296
+ const proposals = objects(phaseItems(phase.output, 'assessments'));
297
+ const ids = proposals.map((p) => string(object(p.result).assessmentId));
298
+ if (!completeOutput(phase, ids) ||
299
+ proposals.some((p) => !['evaluated', 'observed', 'not_applicable', 'unresolved'].includes(string(object(p.result).disposition))))
300
+ return;
301
+ const origin = { ref: `phase:assess:${phase.workUnitId}:${phase.attempt}`, hash: digest(phase) };
302
+ for (const id of ids) {
303
+ handoffs.historical.add(id);
304
+ handoffs.current.set(id, origin);
305
+ }
306
+ }
307
+ function recordVerification(phase, handoffs) {
308
+ for (const id of phase.assessmentIds)
309
+ handoffs.verification.delete(id);
310
+ const outcomes = objects(phaseItems(phase.output, 'entries'));
311
+ if (!completeOutput(phase, outcomes.map((o) => string(o.assessmentId))))
312
+ return;
313
+ for (const outcome of outcomes) {
314
+ const id = string(outcome.assessmentId), origin = handoffs.current.get(id);
315
+ if (origin && phase.inputRefs.some((r) => r.ref === origin.ref && r.hash === origin.hash))
316
+ handoffs.verification.set(id, object(outcome.resolution).assessmentId === id ? 'accept' : string(outcome.disposition));
317
+ }
318
+ }
319
+ function coverageStatus(entry, verified, handoffs) {
320
+ const id = string(entry.assessmentId), disposition = string(object(entry.result).disposition);
321
+ if (handoffs.partial.has(id))
322
+ return 'saved_proposal';
323
+ if (!handoffs.historical.has(id))
324
+ return 'unexamined';
325
+ const verdict = handoffs.verification.get(id) ?? '';
326
+ if (!handoffs.current.has(id) || ['reject', 'revise', 'unresolved'].includes(verdict))
327
+ return 'needs_reassessment';
328
+ if (disposition === 'observed')
329
+ return 'observed_unverified';
330
+ if (verified > 0 &&
331
+ ['evaluated', 'observed', 'not_applicable', 'unresolved'].includes(disposition) &&
332
+ verdict === 'accept')
333
+ return disposition === 'unresolved' ? 'verified_unresolved' : 'verified';
334
+ return 'awaiting_verification';
335
+ }
336
+ /** Candidate coverage counts processed context observations separately from checked concerns. */
337
+ function candidateCoverage(state, entries) {
338
+ const observations = objects(state.observations);
339
+ const decisions = objects(state.concernDecisions);
340
+ const progress = entries.map((entry) => {
341
+ const rows = observations.filter((row) => row.assessmentId === entry.assessmentId);
342
+ const concerns = rows.filter((row) => object(row.concern).claim);
343
+ const checked = concerns.filter((row) => decisions.some((decision) => decision.observationId === row.id));
344
+ let status = 'unexamined';
345
+ if (rows.length) {
346
+ if (!concerns.length)
347
+ status = 'observed_unverified';
348
+ else if (checked.length < concerns.length)
349
+ status = 'awaiting_verification';
350
+ else
351
+ status = object(entry.result).disposition === 'unresolved' ? 'verified_unresolved' : 'verified';
352
+ }
353
+ return { assessmentId: string(entry.assessmentId), status };
354
+ });
355
+ const assessed = progress.filter((entry) => entry.status !== 'unexamined').length;
356
+ return {
357
+ total: entries.length,
358
+ assessed,
359
+ currentAssessments: assessed,
360
+ savedProposals: 0,
361
+ verified: progress.filter((entry) => ['verified', 'verified_unresolved'].includes(entry.status)).length,
362
+ awaitingVerification: progress.filter((entry) => entry.status === 'awaiting_verification').length,
363
+ needsReassessment: 0,
364
+ unexamined: progress.filter((entry) => entry.status === 'unexamined').length,
365
+ entries: progress,
366
+ };
367
+ }
368
+ /** Human progress from complete canonical assessment handoffs; never promotes proposals to verdicts. */
369
+ export function assessmentCoverage(input) {
370
+ const state = object(input), entries = objects(state.entries);
371
+ if (object(state.concernValidation).scope === 'nominated_concerns' && Array.isArray(state.observations))
372
+ return candidateCoverage(state, entries);
373
+ const ids = entries.map((e) => string(e.assessmentId)), scope = new Set(ids);
374
+ const handoffs = {
375
+ historical: new Set(),
376
+ partial: new Set(),
377
+ current: new Map(),
378
+ verification: new Map(),
379
+ };
380
+ if (ids.every(Boolean) && scope.size === ids.length) {
381
+ for (const raw of objects(state.phases)) {
382
+ const phase = coveragePhase(raw, state, scope);
383
+ if (!phase)
384
+ continue;
385
+ if (phase.phase === 'assess')
386
+ recordAssessment(phase, handoffs);
387
+ else
388
+ recordVerification(phase, handoffs);
389
+ }
390
+ }
391
+ const canonical = object(state.verification);
392
+ const verified = number(canonical.verified)
393
+ ? canonical.verified
394
+ : entries.filter((e) => object(e.verification).status === 'accepted' || e.verified === true).length;
395
+ const progress = entries.map((e) => ({
396
+ assessmentId: string(e.assessmentId),
397
+ status: coverageStatus(e, verified, handoffs),
398
+ }));
399
+ return {
400
+ total: entries.length,
401
+ assessed: handoffs.historical.size,
402
+ currentAssessments: handoffs.current.size,
403
+ savedProposals: handoffs.partial.size,
404
+ verified,
405
+ awaitingVerification: progress.filter((p) => p.status === 'awaiting_verification').length,
406
+ needsReassessment: progress.filter((p) => p.status === 'needs_reassessment').length,
407
+ unexamined: progress.filter((p) => p.status === 'unexamined').length,
408
+ entries: progress,
409
+ };
410
+ }
411
+ function countChanges(changes) {
412
+ const counts = { added: 0, modified: 0, deleted: 0, renamed: 0, typeChanged: 0, unknown: 0 };
413
+ const countKeys = new Map([
414
+ ['addition', 'added'],
415
+ ['modification', 'modified'],
416
+ ['type_change', 'modified'],
417
+ ['deletion', 'deleted'],
418
+ ['rename', 'renamed'],
419
+ ]);
420
+ for (const change of changes) {
421
+ counts[countKeys.get(string(change.kind)) ?? 'unknown']++;
422
+ if (change.kind === 'type_change')
423
+ counts.typeChanged++;
424
+ }
425
+ return counts;
426
+ }
427
+ function renderChangeCounts(counts) {
428
+ const totals = `Added ${counts.added}; modified ${counts.modified}; deleted ${counts.deleted}; renamed ${counts.renamed}.`;
429
+ const typeChanges = counts.typeChanged
430
+ ? ` Modified includes ${counts.typeChanged} ${counts.typeChanged === 1 ? 'type change' : 'type changes'}.`
431
+ : '';
432
+ const unknown = counts.unknown ? ` ${counts.unknown} unclassified entries.` : '';
433
+ return totals + typeChanges + unknown;
434
+ }
435
+ /** Human orientation is separate from the governed result and never controls enforcement. */
436
+ export function renderReaderGuidance(input) {
437
+ const state = object(input), summary = object(state.changeSummary), accepted = object(summary.accepted);
438
+ const lines = ['#### Changes and reviewer focus'];
439
+ if (summary.status === 'verified' && typeof accepted.overview === 'string') {
440
+ lines.push(markdownText(accepted.overview, 2000));
441
+ const focus = Array.isArray(accepted.reviewFocus)
442
+ ? accepted.reviewFocus.filter((item) => typeof item === 'string')
443
+ : [];
444
+ if (focus.length)
445
+ lines.push('Suggested review focus:\n\n' +
446
+ focus
447
+ .slice(0, 5)
448
+ .map((item) => `- ${markdownText(item, 1000)}`)
449
+ .join('\n'));
450
+ const locations = objects(accepted.sourceRefs)
451
+ .map((citation) => `${string(object(citation.provenance).path)}:${object(citation.location).line ?? '?'}`)
452
+ .filter((location) => !location.startsWith(':'))
453
+ .join(', ');
454
+ lines.push('Source-grounded summary, independently checked; separate from adherence.' +
455
+ (locations ? ` Sources: ${markdownText(locations, 1000)}.` : ''));
456
+ }
457
+ else {
458
+ lines.push('No independently checked narrative summary is available. The prepared file inventory below still describes the comparison.');
459
+ }
460
+ const followUps = objects(state.followUps);
461
+ if (followUps.length) {
462
+ lines.push('#### Human and operational follow-ups', 'These remain separate from artifact adherence. Pending mandatory operational gates still prevent a claim of overall completion.');
463
+ for (const item of followUps) {
464
+ const kind = item.kind === 'operational_check' ? 'Operational check' : 'Human check';
465
+ const status = item.verified === true
466
+ ? item.required === true
467
+ ? 'mandatory — pending'
468
+ : 'suggested'
469
+ : 'unverified proposal';
470
+ const criterion = findingCriteria([{ assessmentIds: [item.assessmentId] }], objects(state.entries));
471
+ const locations = objects(item.sourceRefs)
472
+ .map((citation) => `${string(object(citation.provenance).path)}:${object(citation.location).line ?? '?'}`)
473
+ .join(', ');
474
+ lines.push(`- **${kind}: ${status}.** ${markdownText(item.explanation, 1200)} **Next:** ${markdownText(item.action, 1200)} Criterion: ${criterion}. Source: ${markdownText(locations, 500)}.`);
475
+ }
476
+ }
477
+ return lines.join('\n\n');
478
+ }
479
+ function renderChangeSummary(input) {
480
+ const state = object(input), artifact = object(state.artifact), inventory = object(state.changes);
481
+ const matches = (side) => {
482
+ const snapshot = object(inventory[side]), fixed = object(artifact[side]);
483
+ return (typeof fixed.commit === 'string' &&
484
+ typeof fixed.tree === 'string' &&
485
+ snapshot.commit === fixed.commit &&
486
+ snapshot.tree === fixed.tree);
487
+ };
488
+ if (!Array.isArray(inventory.items) ||
489
+ !['complete', 'truncated'].includes(string(inventory.status)) ||
490
+ !matches('base') ||
491
+ !matches('head'))
492
+ return '#### Change summary\n\nPrepared change inventory is unavailable for this fixed comparison; no change counts are inferred from a diff prefix or working tree.';
493
+ const changes = objects(inventory.items), counts = countChanges(changes);
494
+ const complete = inventory.status === 'complete' && inventory.next === null && counts.unknown === 0;
495
+ const paths = changes.map((c) => {
496
+ const before = string(object(c.base).path), after = string(object(c.head).path);
497
+ return c.kind === 'rename' && before && after
498
+ ? `${before} → ${after}`
499
+ : after || before || '(path unavailable)';
500
+ });
501
+ const excluded = Array.isArray(inventory.excludedPaths)
502
+ ? new Set(inventory.excludedPaths.filter((p) => typeof p === 'string')).size
503
+ : 0;
504
+ return [
505
+ '#### Change summary',
506
+ `${complete ? 'Complete permitted' : 'Incomplete'} prepared inventory: ${changes.length} file changes recorded. ${renderChangeCounts(counts)}`,
507
+ paths.length
508
+ ? `Affected paths: ${paths
509
+ .slice(0, 8)
510
+ .map((p) => markdownText(p, 240))
511
+ .join(' · ')}.`
512
+ : 'No permitted changed paths are recorded.',
513
+ paths.length > 8
514
+ ? `${paths.length - 8} additional file entries are omitted from this short path list; they remain in the prepared inventory.`
515
+ : '',
516
+ excluded ? `${excluded} credential-path entries were excluded from the permitted inventory.` : '',
517
+ !complete ? 'Remaining changes may be omitted; captured counts are not full-comparison totals.' : '',
518
+ 'This is a factual file-change overview, not a semantic summary or evidence that every changed file was examined.',
519
+ ]
520
+ .filter(Boolean)
521
+ .join('\n\n');
522
+ }
523
+ const verificationLabels = {
524
+ observed_unverified: 'Observation only; not independently validated',
525
+ verified: 'Checked',
526
+ verified_unresolved: 'Checked; evidence needed',
527
+ saved_proposal: 'Saved proposal',
528
+ awaiting_verification: 'Awaiting verification',
529
+ needs_reassessment: 'Needs reassessment',
530
+ unexamined: 'Not checked',
531
+ };
532
+ export function assessmentProgressLabel(status, focused = false) {
533
+ if (focused && ['verified', 'verified_unresolved'].includes(status))
534
+ return status === 'verified_unresolved'
535
+ ? 'Nominated concerns checked; evidence needed'
536
+ : 'Nominated concerns checked';
537
+ return verificationLabels[status] ?? 'Not checked';
538
+ }
539
+ function criterionOutcome(result, accepted) {
540
+ const disposition = string(result.disposition);
541
+ if (disposition === 'observed')
542
+ return 'Observed / no concern identified';
543
+ if (disposition === 'not_applicable')
544
+ return accepted ? 'Not applicable' : 'Proposed not applicable';
545
+ if (disposition === 'unresolved')
546
+ return 'Unresolved';
547
+ if (disposition === 'not_evaluated')
548
+ return 'Not evaluated';
549
+ if (disposition !== 'evaluated')
550
+ return 'Outcome unavailable';
551
+ const labels = new Map([
552
+ ['binding_violation', ['Binding violation', 'Unverified violation judgment']],
553
+ ['behavioral_defect', ['Behavioral defect', 'Unverified defect judgment']],
554
+ ['guidance_departure', ['Guidance departure', 'Unverified guidance judgment']],
555
+ ]);
556
+ const classification = labels.get(string(result.finding));
557
+ if (classification)
558
+ return classification[accepted ? 0 : 1];
559
+ if (result.adherence === 2)
560
+ return accepted ? 'Adherent within reviewed scope' : 'Unverified adherence judgment';
561
+ return 'Evaluated judgment';
562
+ }
563
+ function criterionNote(result, status, accepted) {
564
+ const explanation = string(result.explanation), correction = string(result.correction);
565
+ if (!accepted && ['binding_violation', 'behavioral_defect', 'guidance_departure'].includes(string(result.finding)))
566
+ return `Unverified judgment: ${explanation}${correction ? ` Proposed correction: ${correction}` : ''}`;
567
+ if (explanation)
568
+ return explanation;
569
+ if (status === 'saved_proposal')
570
+ return 'Proposal saved; assessment handoff incomplete and independently unverified.';
571
+ if (status === 'awaiting_verification')
572
+ return 'Assessment recorded; independent verification pending.';
573
+ if (status === 'needs_reassessment')
574
+ return 'Previous assessment requires a new assessment.';
575
+ return 'No assessment explanation recorded.';
576
+ }
577
+ function criterionRow(entry, progress, verified, focused = false) {
578
+ const result = object(entry.result);
579
+ const status = progress.entries.find((p) => p.assessmentId === entry.assessmentId)?.status ?? 'unexamined';
580
+ const accepted = status === 'verified' || status === 'verified_unresolved';
581
+ const linked = verified.filter((f) => Array.isArray(f.assessmentIds) && f.assessmentIds.includes(entry.assessmentId));
582
+ const count = linked.length ? `[${linked.length}](#governed-findings)` : '0';
583
+ const label = assessmentProgressLabel(status, focused);
584
+ return `| ${markdownText(entry.nodeId, 500)} @ ${markdownText(entry.version, 20)} | ${criterionOutcome(result, accepted)} | ${label} | ${count} | ${markdownText(criterionNote(result, status, accepted), 200)} |`;
585
+ }
586
+ function findingCriteria(accounts, entries) {
587
+ const ids = [...new Set(accounts.flatMap((a) => (Array.isArray(a.assessmentIds) ? a.assessmentIds : [])))];
588
+ return ids
589
+ .map((id) => {
590
+ const entry = entries.find((e) => e.assessmentId === id);
591
+ return markdownText(entry ? `${entry.nodeId} @ ${entry.version}` : String(id), 600);
592
+ })
593
+ .join(', ');
594
+ }
595
+ function findingGroup(accounts, entries) {
596
+ const finding = accounts[0];
597
+ const criteria = findingCriteria(accounts, entries);
598
+ const locations = objects(finding.locationRefs)
599
+ .map((c) => `${string(object(c.provenance).path)}:${object(c.location).line ?? '?'}`)
600
+ .filter(Boolean)
601
+ .join(', ');
602
+ if (accounts.length === 1)
603
+ return `- **${markdownText(finding.classification)}:** ${markdownText(finding.explanation, 800)}\n Criterion: ${criteria}. Location: ${markdownText(locations, 500)}. Consequence: ${markdownText(finding.consequence, 500)} Correction: ${markdownText(finding.correction, 600)}`;
604
+ const details = accounts.map((account, index) => ` ${index + 1}. **${markdownText(account.classification)}:** ${markdownText(account.explanation, 800)} Consequence: ${markdownText(account.consequence, 500)} Correction: ${markdownText(account.correction, 600)} Criterion: ${findingCriteria([account], entries)}. Location: ${markdownText(developerFindingLocations(account), 1500)}. Account: ${markdownText(account.findingId, 150)}.`);
605
+ return `- **${accounts.length} verified accounts at ${developerFindingGroupLabel(accounts)}.** Location: ${markdownText(locations, 500)}. Criteria: ${criteria}.\n${details.join('\n')}`;
606
+ }
607
+ function renderGovernedFindings(entries, verified, progress) {
608
+ if (!verified.length)
609
+ return [
610
+ progress.savedProposals || progress.awaitingVerification || progress.needsReassessment
611
+ ? 'Independent verification is incomplete. Recorded assessment proposals are not accepted review findings; candidate findings remain unverified.'
612
+ : 'No independently verified finding is recorded. Inspect each criterion and its verification before relying on this result.',
613
+ ];
614
+ const groups = groupDeveloperFindings(verified);
615
+ const lines = ['#### Governed findings', ...groups.slice(0, 15).map((group) => findingGroup(group, entries))];
616
+ if (groups.length > 15)
617
+ lines.push(`${groups.length - 15} additional source-range accounts are in the full report.`);
618
+ return lines;
619
+ }
620
+ function assessmentHeadline(execution, options, completion, reviewExit, enforcement) {
621
+ if (options.failedStage ||
622
+ (reviewExit === 2 && enforcement !== 'legacy / unavailable') ||
623
+ (execution.stopReason && execution.stopReason !== 'finished'))
624
+ return 'Execution did not finish';
625
+ if (reviewExit === 1)
626
+ return 'Policy requires attention' + (completion !== 'complete' ? '; assessment incomplete' : '');
627
+ return completion !== 'complete' ? 'Assessment incomplete' : 'Bounded assessment complete';
628
+ }
629
+ export function renderAssessmentReport(input, options = {}) {
630
+ const state = object(input), execution = object(state.execution), reviewer = object(state.reviewer), artifact = object(state.artifact), entries = objects(state.entries), decision = object(state.decision), usage = summarizeUsage(state);
631
+ const progress = assessmentCoverage(state);
632
+ const findings = objects(state.findings);
633
+ const verified = findings.filter((f) => f.verified === true);
634
+ const completion = string(state.assessmentStatus, 'unknown');
635
+ const reviewExit = options.reviewExit ?? decision.exitCode ?? decision.reviewExit;
636
+ const enforcement = string(object(execution.policy).enforcement, 'legacy / unavailable');
637
+ const health = assessmentHeadline(execution, options, completion, reviewExit, enforcement);
638
+ const lines = [
639
+ '### ContextRail Assess',
640
+ `**${health}.**`,
641
+ `Enforcement: **${markdownText(enforcement)}** · Exit: ${markdownText(reviewExit ?? 'unavailable')}. Exit 0 means policy permits continuation; inspect findings and evidence gaps below.`,
642
+ `${markdownText(reviewer.title ?? reviewer.nodeId)} @ ${markdownText(reviewer.version)} · Head ${markdownText(object(artifact.head).commit)}.`,
643
+ `Run ID: ${markdownText(state.runId)}.`,
644
+ ];
645
+ if (options.failedStage)
646
+ lines.push(`Action ${markdownText(options.failedStage)} failed; no successful review is implied.`);
647
+ lines.push(renderReaderGuidance(state));
648
+ lines.push(...renderGovernedFindings(entries, verified, progress));
649
+ const count = (d) => entries.filter((e) => object(e.result).disposition === d).length;
650
+ const focusedCoverage = object(state.concernValidation).scope === 'nominated_concerns';
651
+ const criterionRows = entries.map((entry) => criterionRow(entry, progress, verified, object(state.concernValidation).scope === 'nominated_concerns'));
652
+ lines.push('#### Assessment coverage', `Assessed ${progress.assessed}/${progress.total}; awaiting verification ${progress.awaitingVerification}; needs reassessment ${progress.needsReassessment}; ${focusedCoverage ? 'contexts with nominated concerns checked' : 'verified'} ${progress.verified}; unexamined ${progress.unexamined}. Final outcomes: evaluated ${count('evaluated')}, observed ${count('observed')}, not applicable ${count('not_applicable')}, unresolved ${count('unresolved')}, not evaluated ${count('not_evaluated')}.`, '| Criterion / version | Outcome | Verification | Verified findings | Note |\n| --- | --- | --- | --- | --- |\n' +
653
+ (criterionRows.join('\n') ||
654
+ '| No governed criteria recorded | Unavailable | Not checked | 0 | No assessment scope is available. |'), 'Each original criterion is listed in its recorded order. Observed means no concern was identified by the assessor; it is not independently verified compliance. Checked means independently reviewed, including confirmed evidence gaps; it does not mean the requirement is satisfied. Awaiting verification is not acceptance. Assessed counts use complete canonical assessment handoffs for this fixed comparison. Saved proposals are separate unfinished work, not unexamined criteria or verified outcomes; final outcome labels retain the canonical disposition.');
655
+ const concerns = object(state.concernValidation);
656
+ if (concerns.scope === 'nominated_concerns' && number(concerns.expected) && number(concerns.validated))
657
+ lines.push(`Concern validation: ${concerns.validated}/${concerns.expected} nominated concerns checked. This count does not certify every observation or every obligation in a standard.`);
658
+ if (progress.savedProposals)
659
+ lines.push(`Saved proposals: ${progress.savedProposals}. Assessment handoff incomplete; these are not verified outcomes.`);
660
+ lines.push(renderChangeSummary(state));
661
+ lines.push(renderRunDetails(execution, usage, options));
662
+ return lines.join('\n\n') + '\n';
663
+ }
664
+ /** Compact developer view; the Action summary retains the complete audit explanation. */
665
+ export function renderAssessmentComment(input, options = {}) {
666
+ const state = object(input), entries = objects(state.entries), execution = object(state.execution);
667
+ const progress = assessmentCoverage(state);
668
+ const verified = objects(state.findings).filter((finding) => finding.verified === true);
669
+ const questions = entries.filter((entry) => object(entry.result).disposition === 'unresolved');
670
+ const count = (value) => entries.filter((entry) => object(entry.result).disposition === value).length;
671
+ const exit = options.reviewExit ?? object(state.decision).exitCode ?? object(state.decision).reviewExit;
672
+ const failed = Boolean(options.failedStage || exit === 2 || (execution.stopReason && execution.stopReason !== 'finished'));
673
+ const violations = verified.filter((finding) => finding.classification === 'binding_violation').length;
674
+ const outcome = violations
675
+ ? `${violations} confirmed violation${violations === 1 ? '' : 's'}`
676
+ : 'No confirmed violations';
677
+ const pending = progress.awaitingVerification + progress.needsReassessment + progress.unexamined;
678
+ const headline = failed
679
+ ? 'Review could not finish'
680
+ : pending || (state.assessmentStatus !== 'complete' && !questions.length)
681
+ ? 'Assessment incomplete'
682
+ : outcome;
683
+ const policy = string(object(execution.policy).enforcement);
684
+ const lines = [
685
+ assessLogoBaseUrl
686
+ ? `### <picture><source media="(prefers-color-scheme: dark)" srcset="${assessLogoBaseUrl}/icon-dark.png"><img src="${assessLogoBaseUrl}/icon-light.png" height="22" alt="ContextRail"></picture>&nbsp; ContextRail Assess`
687
+ : '### ContextRail Assess',
688
+ `**${headline}${questions.length ? ` · ${questions.length} question${questions.length === 1 ? '' : 's'} remain${questions.length === 1 ? 's' : ''}` : ''}**${policy ? ` · ${markdownText(policy)}` : ''}`,
689
+ ];
690
+ if (failed)
691
+ lines.push(options.failedStage
692
+ ? `Action ${markdownText(options.failedStage)} failed. Results below are partial; see run details.`
693
+ : 'Results below are partial. See the workflow run for the failure and retry details.');
694
+ const summary = object(state.changeSummary), accepted = object(summary.accepted);
695
+ if (summary.status === 'verified' && typeof accepted.overview === 'string')
696
+ lines.push(markdownText([...new Intl.Segmenter('en', { granularity: 'sentence' }).segment(accepted.overview)]
697
+ .slice(0, 2)
698
+ .map((part) => part.segment)
699
+ .join(''), 600));
700
+ if (verified.length) {
701
+ lines.push('#### Governed findings');
702
+ for (const finding of verified)
703
+ lines.push(compactFinding(finding, entries, options));
704
+ }
705
+ if (questions.length) {
706
+ lines.push('#### Needs your attention');
707
+ for (const entry of questions) {
708
+ const result = object(entry.result), action = questionAction(state, entry);
709
+ lines.push(`- **${criterionTitle(entry)}:** ${briefText(result.explanation, 2)}${action ? ` **Next:** ${briefText(action, 1)}` : ''}${sourceLinks(result.citations, options)}`);
710
+ }
711
+ }
712
+ lines.push(`${progress.assessed}/${progress.total} standards assessed · ${count('observed')} with no concern identified · ${questions.length} unresolved${pending ? ` · ${pending} awaiting assessment or verification` : ''}${count('not_applicable') ? ` · ${count('not_applicable')} not applicable` : ''}`);
713
+ const rows = entries.map((entry) => criterionRow(entry, progress, verified, object(state.concernValidation).scope === 'nominated_concerns'));
714
+ lines.push('<details>\n<summary>Standards and evidence</summary>\n\n' +
715
+ 'No concern identified is an observation, not independently verified compliance.\n\n' +
716
+ '| Criterion / version | Outcome | Verification | Verified findings | Note |\n| --- | --- | --- | --- | --- |\n' +
717
+ rows.join('\n') +
718
+ '\n\n' +
719
+ compactEvidence(state) +
720
+ '\n\n</details>');
721
+ const details = renderRunDetails(execution, summarizeUsage(state), options);
722
+ const identity = `Run ID: ${markdownText(state.runId)}. Reviewer: ${markdownText(object(state.reviewer).title ?? object(state.reviewer).nodeId)} @ ${markdownText(object(state.reviewer).version)}. Exit: ${markdownText(exit ?? 'unavailable')}.`;
723
+ lines.push(details.replace('\n\n</details>', `\n\n${identity}\n\n</details>`));
724
+ const links = [
725
+ isArtifactUrl(options.artifactUrl) ? `[Full audit](${options.artifactUrl})` : '',
726
+ runUrl(options.runUrl) ? `[Workflow run](${options.runUrl})` : '',
727
+ object(object(state.artifact).head).commit
728
+ ? `Reviewed ${markdownText(string(object(object(state.artifact).head).commit).slice(0, 7))}`
729
+ : '',
730
+ ].filter(Boolean);
731
+ if (links.length)
732
+ lines.push(links.join(' · '));
733
+ return lines.join('\n\n') + '\n';
734
+ }
735
+ function briefText(value, sentences) {
736
+ const text = string(value);
737
+ const parts = [...new Intl.Segmenter('en', { granularity: 'sentence' }).segment(text)];
738
+ const excerpt = parts
739
+ .slice(0, sentences)
740
+ .map((part) => part.segment)
741
+ .join('')
742
+ .trim();
743
+ return markdownText(excerpt, 650) + (parts.length > sentences ? ' …' : '');
744
+ }
745
+ function questionAction(state, entry) {
746
+ const ids = new Set(objects(state.observations)
747
+ .filter((item) => item.assessmentId === entry.assessmentId)
748
+ .map((item) => item.id));
749
+ const actions = objects(state.concernDecisions)
750
+ .filter((decision) => ids.has(decision.observationId) &&
751
+ ['missing_evidence', 'ambiguous_rule'].includes(string(decision.decision)))
752
+ .map((decision) => string(decision.correction))
753
+ .filter(Boolean);
754
+ return [...new Set(actions)].join(' ') || string(object(entry.result).correction);
755
+ }
756
+ function compactEvidence(state) {
757
+ const changeSummary = object(state.changeSummary);
758
+ const summary = changeSummary.status === 'verified' ? object(changeSummary.accepted) : {};
759
+ const focus = Array.isArray(summary.reviewFocus)
760
+ ? summary.reviewFocus.filter((value) => typeof value === 'string')
761
+ : [];
762
+ const lines = focus.length
763
+ ? ['Suggested review focus:', ...focus.map((value) => `- ${markdownText(value, 1000)}`)]
764
+ : [];
765
+ for (const entry of objects(state.entries).filter((entry) => object(entry.result).disposition === 'unresolved')) {
766
+ const result = object(entry.result), action = questionAction(state, entry);
767
+ lines.push(`**${criterionTitle(entry)}:** ${markdownText(result.explanation, 5000)}${action ? ` Next: ${markdownText(action, 5000)}` : ''}`);
768
+ }
769
+ return lines.join('\n\n');
770
+ }
771
+ function sourceLinks(citations, options) {
772
+ const repository = runUrl(options.runUrl) ? options.runUrl.split('/').slice(3, 5).join('/') : null;
773
+ const sources = objects(citations).filter((citation) => object(citation.provenance).kind === 'source');
774
+ const links = sources.slice(0, 2).map((citation) => {
775
+ const provenance = object(citation.provenance), line = object(citation.location).line;
776
+ const path = string(provenance.path), commit = string(provenance.commit);
777
+ const label = markdownText(`${path}:${line ?? '?'}`, 200);
778
+ if (!repository || !/^[a-f0-9]{40}$/.test(commit) || !Number.isSafeInteger(line) || Number(line) < 1)
779
+ return label;
780
+ const encoded = path
781
+ .split('/')
782
+ .map((part) => encodeURIComponent(part).replace(/[!'()*]/g, (char) => `%${char.charCodeAt(0).toString(16)}`))
783
+ .join('/');
784
+ return `[${label}](https://github.com/${repository}/blob/${commit}/${encoded}#L${line})`;
785
+ });
786
+ return links.length ? ` · ${links.join(' · ')}` : '';
787
+ }
788
+ function criterionTitle(entry) {
789
+ return markdownText(entry.title ?? string(entry.nodeId).split('/').at(-1)?.replace(/-/g, ' ') ?? entry.assessmentId, 160);
790
+ }
791
+ function compactFinding(finding, entries, options) {
792
+ const labels = {
793
+ binding_violation: 'Violation',
794
+ behavioral_defect: 'Defect',
795
+ guidance_departure: 'Suggestion',
796
+ };
797
+ const ids = Array.isArray(finding.assessmentIds) ? finding.assessmentIds : [];
798
+ const titles = entries
799
+ .filter((entry) => ids.includes(entry.assessmentId))
800
+ .map(criterionTitle)
801
+ .join(', ');
802
+ const location = sourceLinks(finding.locationRefs, options);
803
+ return `- **${labels[string(finding.classification)] ?? 'Finding'} — ${titles}:** ${markdownText(finding.explanation, 650)} ${markdownText(finding.consequence, 350)} **Next:** ${markdownText(finding.correction, 450)}${location}`;
804
+ }
805
+ function providerFailures(execution) {
806
+ const failureGroups = new Map(), failureCalls = new Set();
807
+ for (const call of objects(execution.providerUsage)) {
808
+ if (!number(call.call) ||
809
+ !Number.isInteger(call.call) ||
810
+ call.call < 1 ||
811
+ !number(execution.calls) ||
812
+ call.call > execution.calls ||
813
+ failureCalls.has(call.call))
814
+ continue;
815
+ if (!number(call.httpStatus) ||
816
+ !Number.isInteger(call.httpStatus) ||
817
+ call.httpStatus < 400 ||
818
+ call.httpStatus > 599 ||
819
+ !PROVIDER_FAILURE_CODES.some((code) => code === call.failureCode))
820
+ continue;
821
+ failureCalls.add(call.call);
822
+ const key = `${call.httpStatus} ${call.failureCode}`;
823
+ failureGroups.set(key, (failureGroups.get(key) ?? 0) + 1);
824
+ }
825
+ return [...failureGroups.entries()].sort(([a], [b]) => a.localeCompare(b));
826
+ }
827
+ function renderRunDetails(execution, usage, options) {
828
+ const failures = providerFailures(execution);
829
+ const details = [
830
+ `Duration: ${duration(execution.elapsedMs)}. Reported model cost: ${metricText(usage.cost, usage.calls, true)}.`,
831
+ options.diagnostic ? `Diagnostic: ${markdownText(options.diagnostic, 1000)}` : '',
832
+ `Execution stop: ${markdownText(execution.stopReason)}.${options.packageVersion ? ` Package: ${markdownText(options.packageVersion)}.` : ''}`,
833
+ failures.length
834
+ ? `Provider failures: ${failures
835
+ .slice(0, 8)
836
+ .map(([key, count]) => `${key} (${count} ${count === 1 ? 'call' : 'calls'})`)
837
+ .join('; ')}.${failures.length > 8 ? ` ${failures.length - 8} additional groups in the report.` : ''}`
838
+ : '',
839
+ runUrl(options.runUrl) ? `[Workflow run](${options.runUrl})` : '',
840
+ isArtifactUrl(options.artifactUrl) ? `[Artifact bundle](${options.artifactUrl})` : '',
841
+ 'Cost is provider-reported, not a verified invoice; missing cost is not zero.',
842
+ ].filter(Boolean);
843
+ return `<details>\n<summary>Run details</summary>\n\n${details.join('\n\n')}\n\n</details>`;
844
+ }
845
+ export function renderActionSummary(input, options = {}) {
846
+ const state = object(input), e = object(state.execution), usage = summarizeUsage(state);
847
+ const coverage = assessmentCoverage(state);
848
+ const rows = [
849
+ ['Execution stop', markdownText(e.stopReason)],
850
+ [
851
+ 'Assessed / awaiting verification / needs reassessment / unexamined',
852
+ `${coverage.assessed} / ${coverage.awaitingVerification} / ${coverage.needsReassessment} / ${coverage.unexamined}`,
853
+ ],
854
+ ['Saved proposals / incomplete assessment handoff', String(coverage.savedProposals)],
855
+ ['Review duration', duration(e.elapsedMs)],
856
+ ['Calls / completed SDK steps', `${usage.calls ?? 'unavailable'} / ${e.steps ?? 'unavailable'}`],
857
+ ['Reported model cost', metricText(usage.cost, usage.calls, true)],
858
+ ['Input tokens (cumulative across calls)', metricText(usage.input, usage.calls)],
859
+ ['Output tokens (includes reasoning)', metricText(usage.output, usage.calls)],
860
+ ['Total tokens', metricText(usage.total, usage.calls)],
861
+ ['Cached input tokens', metricText(usage.cached, usage.calls)],
862
+ ['Reasoning tokens (part of output)', metricText(usage.reasoning, usage.calls)],
863
+ [
864
+ 'ContextRail reporting',
865
+ markdownText(object(e.reporting).status) +
866
+ (object(e.reporting).status === 'received' ? ' (ingestion receipt only)' : ''),
867
+ ],
868
+ ['Comparison', markdownText(options.comparisonStatus ?? 'Currency unknown; verify SHAs before use')],
869
+ ];
870
+ const phases = objects(state.phases ?? e.phases);
871
+ const configurations = object(e.phaseModels);
872
+ const phaseNames = [...new Set([...Object.keys(configurations), ...phases.map((p) => string(p.phase))])];
873
+ const phaseRows = phaseNames.map((name) => {
874
+ const matching = phases.filter((p) => p.phase === name), configuration = object(configurations[name] ?? matching[0]?.configuration ?? matching[0]?.effectiveConfiguration);
875
+ const records = objects(e.providerUsage).filter((r) => r.phase === name);
876
+ const costs = records.map((r) => object(r.usage).cost).filter(number);
877
+ const starts = matching.map((p) => Date.parse(string(p.startedAt))).filter(Number.isFinite), ends = matching.map((p) => Date.parse(string(p.finishedAt))).filter(Number.isFinite);
878
+ return `| ${markdownText(name)} | ${markdownText(configuration.provider)}/${markdownText(configuration.model)} | ${matching.length ? matching.map((p) => markdownText(p.status)).join(', ') : 'not started'} | ${starts.length && ends.length ? duration(Math.max(...ends) - Math.min(...starts)) : 'unavailable'} | ${records.length} | ${costs.length ? '$' + costs.reduce((a, b) => a + b, 0).toFixed(6) + (costs.length === records.length ? '' : ' partial') : 'unavailable'} |`;
879
+ });
880
+ const phaseTable = phaseRows.length
881
+ ? `\n#### Phase health\n\n| Phase | Effective model | Outcome | Elapsed window | Calls | Reported USD |\n| --- | --- | --- | --- | --- | --- |\n${phaseRows.join('\n')}\n`
882
+ : '';
883
+ const alerts = [
884
+ options.feedback === 'send' && object(e.reporting).status !== 'received'
885
+ ? 'ContextRail reporting receipt not confirmed'
886
+ : '',
887
+ options.artifactOutcome && options.artifactOutcome !== 'success' ? 'Evidence upload not confirmed' : '',
888
+ ].filter(Boolean);
889
+ return (renderAssessmentReport(state, options) +
890
+ (alerts.length ? `\n**Operational alerts:** ${alerts.join('; ')}.\n` : '') +
891
+ `\n#### Health / performance\n\n| Health / performance | Observed |\n| --- | --- |\n${rows.map(([k, v]) => `| ${k} | ${v} |`).join('\n')}\n` +
892
+ phaseTable);
893
+ }
894
+ function recordModelIdentity(execution, config) {
895
+ const phases = Object.entries(object(execution.phaseModels)).map(([phase, configuration]) => {
896
+ const c = object(configuration);
897
+ return {
898
+ phase: clip(phase, 40),
899
+ provider: ['openai', 'openrouter'].includes(string(c.provider)) ? c.provider : 'unknown',
900
+ model: clip(c.model, 200),
901
+ effort: clip(c.effort, 20),
902
+ };
903
+ });
904
+ if (!phases.length)
905
+ return {
906
+ provider: ['openai', 'openrouter'].includes(string(config.provider)) ? config.provider : 'unknown',
907
+ model: clip(config.model, 200),
908
+ effort: clip(config.effort, 20),
909
+ phaseModels: phases,
910
+ };
911
+ const shared = (key, mixed) => new Set(phases.map((p) => p[key])).size === 1 ? phases[0][key] : mixed;
912
+ return {
913
+ provider: shared('provider', 'unknown'),
914
+ model: shared('model', 'mixed'),
915
+ effort: shared('effort', ''),
916
+ phaseModels: phases,
917
+ };
918
+ }
919
+ export function runRecord(config, fixed, input, exit, cost, costComplete) {
920
+ const state = object(input), execution = object(state.execution), f = object(fixed), entries = objects(state.entries), r = object(state.reviewer);
921
+ const row = runSchema.parse({
922
+ ...recordModelIdentity(execution, config),
923
+ cliRunId: /^[A-Za-z0-9_-]{1,200}$/.test(string(state.runId)) ? state.runId : null,
924
+ id: string(config.githubRun),
925
+ attempt: config.githubAttempt,
926
+ at: new Date().toISOString(),
927
+ base: f.base ?? null,
928
+ head: f.head ?? null,
929
+ assessment: ['complete', 'incomplete', 'running', 'not_started'].includes(string(state.assessmentStatus))
930
+ ? state.assessmentStatus
931
+ : 'unknown',
932
+ execution: execution.stopReason === 'finished'
933
+ ? 'finished'
934
+ : Object.keys(execution).length || exit === 2
935
+ ? 'failed'
936
+ : 'unknown',
937
+ exit: [0, 1, 2].includes(exit) ? exit : null,
938
+ findings: entries.filter((e) => ['binding_violation', 'behavioral_defect', 'guidance_departure'].includes(string(object(e.result).finding))).length,
939
+ unresolved: entries.filter((e) => object(e.result).disposition === 'unresolved').length,
940
+ durationMs: number(execution.elapsedMs) ? execution.elapsedMs : null,
941
+ cost: number(cost) ? cost : null,
942
+ costComplete,
943
+ packageVersion: clip(config.packageVersion, 100),
944
+ reviewerVersion: number(r.version) ? r.version : null,
945
+ });
946
+ const assessment = execution.stopReason === 'finished' &&
947
+ entries.length &&
948
+ entries.every((e) => ['evaluated', 'observed', 'unresolved', 'not_applicable'].includes(string(object(e.result).disposition)) &&
949
+ number(e.version) &&
950
+ e.version > 0)
951
+ ? assessmentSchema.parse({
952
+ base: f.base,
953
+ head: f.head,
954
+ run: row.id,
955
+ cliRunId: row.cliRunId,
956
+ attempt: row.attempt,
957
+ reviewerVersion: row.reviewerVersion,
958
+ provider: row.provider,
959
+ model: row.model,
960
+ effort: row.effort,
961
+ scopeIdentity: clip(state.scopeIdentity, 150),
962
+ omitted: Math.max(0, entries.length - 30),
963
+ entries: entries.slice(0, 30).map((e) => ({
964
+ nodeId: e.nodeId,
965
+ version: e.version,
966
+ disposition: object(e.result).disposition,
967
+ finding: object(e.result).finding ?? 'none',
968
+ explanation: clip(object(e.result).explanation, 300),
969
+ correction: clip(object(e.result).correction, 200),
970
+ })),
971
+ })
972
+ : null;
973
+ return { row, assessment };
974
+ }
975
+ function historyRow(r, repository) {
976
+ const cost = r.cost === null ? 'unavailable' : '$' + r.cost.toFixed(6) + (r.costComplete ? '' : ' partial');
977
+ return `| [${r.id}/${r.attempt}](https://github.com/${repository}/actions/runs/${r.id}/attempts/${r.attempt}) | ${r.head?.slice(0, 7) ?? 'unknown'} | ${r.execution} / ${r.assessment} | ${r.findings} | ${r.unresolved} | ${cost} |`;
978
+ }
979
+ function appendRunHistory(summary, table) {
980
+ const start = summary.indexOf('<summary>Run details</summary>');
981
+ const end = start < 0 ? -1 : summary.indexOf('</details>', start);
982
+ return end < 0
983
+ ? `${summary}\n<details>\n<summary>Run details</summary>\n\n${table}\n</details>`
984
+ : summary.slice(0, end) + table + '\n' + summary.slice(end);
985
+ }
986
+ function historyExceedsLimit(body, history) {
987
+ return body.length > 60000 || Buffer.byteLength(JSON.stringify(history)) > 30000;
988
+ }
989
+ export function withHistory(summary, previous, current, c) {
990
+ const old = readHistory(previous?.body, c);
991
+ const runs = (old?.runs ?? []).filter((r) => r.id !== current.row.id || r.attempt !== current.row.attempt || r.cliRunId !== current.row.cliRunId);
992
+ runs.push(current.row);
993
+ runs.sort((a, b) => (BigInt(a.id) < BigInt(b.id) ? -1 : BigInt(a.id) > BigInt(b.id) ? 1 : a.attempt - b.attempt));
994
+ const history = {
995
+ version: 2,
996
+ repository: c.repository,
997
+ pr: c.pr,
998
+ reviewer: c.reviewer,
999
+ runs,
1000
+ omitted: old?.omitted ?? 0,
1001
+ assessment: current.assessment ?? old?.assessment ?? null,
1002
+ };
1003
+ while (history.runs.length > 10) {
1004
+ history.runs.shift();
1005
+ history.omitted++;
1006
+ }
1007
+ const render = () => {
1008
+ const rows = history.runs.slice(-3).map((r) => historyRow(r, c.repository));
1009
+ const table = `#### Review history\n\n| Run / attempt | Head | Execution / assessment | Findings | Unresolved | Reported USD |\n| --- | --- | --- | --- | --- | --- |\n${rows.join('\n')}\n\n${history.omitted + Math.max(0, history.runs.length - 3)} older rows not shown. Full retained history remains in the comment state.\n`;
1010
+ return `${assessmentMarker(c)}\n<!-- contextrail-run:${current.row.id}:${current.row.attempt} -->\n<!-- contextrail-state:v2:${Buffer.from(JSON.stringify(history)).toString('base64')} -->\n${appendRunHistory(summary, table)}`;
1011
+ };
1012
+ let body = render();
1013
+ while (historyExceedsLimit(body, history) && history.runs.length > 1) {
1014
+ history.runs.shift();
1015
+ history.omitted++;
1016
+ body = render();
1017
+ }
1018
+ if (historyExceedsLimit(body, history)) {
1019
+ history.assessment = null;
1020
+ body = render();
1021
+ }
1022
+ historySchema.parse(history);
1023
+ if (body.length > 60000)
1024
+ throw new Error('history_invalid');
1025
+ return body;
1026
+ }