@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,135 @@
1
+ import { z } from 'zod';
2
+ import { CitationError, citationSchema, modelEvidence } from './evidence.js';
3
+ import { digest } from './prepare.js';
4
+ const planSchema = z.strictObject({
5
+ entries: z.array(z.strictObject({
6
+ assessmentId: z.string(),
7
+ applicability: z.enum(['applicable', 'not_applicable', 'unresolved']),
8
+ reason: z.string().min(1),
9
+ workUnit: z.string().regex(/^[A-Za-z0-9_-]{1,80}$/u),
10
+ checks: z
11
+ .array(z.strictObject({
12
+ passage: citationSchema.describe('ref must be an exact guidance[].evidence[].ref for this context. assessmentId, nodeId and contentHash are not evidence refs. quote must be exact unique text from that evidence.'),
13
+ interpretation: z.string().min(1),
14
+ }))
15
+ .min(1),
16
+ surfaces: z.array(z.string()),
17
+ evidenceNeeds: z.array(z.string()),
18
+ })),
19
+ });
20
+ export function exactIds(actual, expected) {
21
+ if (new Set(actual).size !== actual.length ||
22
+ actual.length !== expected.length ||
23
+ actual.some((id) => !expected.includes(id)))
24
+ throw new Error('assessment_coverage_mismatch');
25
+ }
26
+ /** Package-created correction metadata; rejected model text and quotations are never copied. */
27
+ export class PlanCitationError extends Error {
28
+ corrections;
29
+ omittedCount;
30
+ code = 'plan_citations_invalid';
31
+ constructor(corrections, omittedCount) {
32
+ super('plan_citations_invalid');
33
+ this.corrections = corrections;
34
+ this.omittedCount = omittedCount;
35
+ this.name = 'PlanCitationError';
36
+ }
37
+ }
38
+ function governingRefs(entry, ledger) {
39
+ const all = Object.values(ledger.records)
40
+ .filter((record) => record.provenance.kind === 'publication' &&
41
+ record.provenance.nodeId === entry.nodeId &&
42
+ record.provenance.version === entry.version &&
43
+ record.provenance.contentHash === entry.contentHash)
44
+ .map((record) => ({
45
+ ...modelEvidence(record),
46
+ path: String(record.provenance.path ?? ''),
47
+ nodeId: entry.nodeId,
48
+ version: entry.version,
49
+ }));
50
+ const preferred = all.filter((record) => record.path === '/content/body' ||
51
+ record.path.startsWith('/content/rules/') ||
52
+ record.path.startsWith('/content/checklist/'));
53
+ return (preferred.length ? preferred : all).sort((a, b) => a.path.localeCompare(b.path) || a.ref.localeCompare(b.ref));
54
+ }
55
+ function ownGoverningPassage(entry, passage) {
56
+ return (passage.provenance.kind === 'publication' &&
57
+ passage.provenance.nodeId === entry.nodeId &&
58
+ passage.provenance.version === entry.version &&
59
+ passage.provenance.contentHash === entry.contentHash);
60
+ }
61
+ function resolveGoverningPassage(selection, entry, ledger) {
62
+ try {
63
+ const passage = ledger.cite(selection);
64
+ if (!ownGoverningPassage(entry, passage))
65
+ return { code: 'wrong_governing_publication' };
66
+ return { passage };
67
+ }
68
+ catch (error) {
69
+ if (error instanceof CitationError)
70
+ return { code: error.code };
71
+ const message = error instanceof Error ? error.message : '';
72
+ if (message.startsWith('Unknown evidence ref'))
73
+ return { code: 'citation_unknown' };
74
+ if (message.startsWith('Quote absent'))
75
+ return { code: 'citation_absent' };
76
+ if (message.startsWith('Quote ambiguous'))
77
+ return { code: 'citation_ambiguous' };
78
+ return { code: 'citation_invalid' };
79
+ }
80
+ }
81
+ export function validatePlan(input, entries, ledger, structured = {}) {
82
+ const parsed = planSchema.parse(input);
83
+ exactIds(parsed.entries.map((e) => e.assessmentId), entries.map((e) => e.assessmentId));
84
+ const corrections = [];
85
+ let omittedCount = 0;
86
+ const plan = {
87
+ entries: parsed.entries.map((e, entryIndex) => {
88
+ const entry = entries.find((expected) => expected.assessmentId === e.assessmentId);
89
+ const allowed = governingRefs(entry, ledger), checks = [];
90
+ for (const [checkIndex, check] of e.checks.entries()) {
91
+ const { passage, code } = resolveGoverningPassage(check.passage, entry, ledger);
92
+ if (code) {
93
+ if (corrections.length < 100)
94
+ corrections.push({
95
+ assessmentId: entry.assessmentId,
96
+ entryIndex,
97
+ checkIndex,
98
+ code,
99
+ rejectedRefHash: digest(check.passage.ref),
100
+ allowedRefs: allowed.slice(0, 32),
101
+ allowedRefsOmitted: Math.max(0, allowed.length - 32),
102
+ });
103
+ else
104
+ omittedCount++;
105
+ continue;
106
+ }
107
+ checks.push({
108
+ checkId: `check:${digest([
109
+ e.assessmentId,
110
+ passage.ref,
111
+ passage.start,
112
+ passage.end,
113
+ passage.quote,
114
+ check.interpretation.trim(),
115
+ ]).slice(7)}`,
116
+ assessmentId: e.assessmentId,
117
+ passageRef: passage,
118
+ interpretation: check.interpretation,
119
+ });
120
+ }
121
+ return { ...e, checks };
122
+ }),
123
+ };
124
+ if (corrections.length || omittedCount)
125
+ throw new PlanCitationError(corrections, omittedCount);
126
+ for (const entry of plan.entries)
127
+ for (const requirement of structured[entry.assessmentId] ?? []) {
128
+ const prefix = requirement.path;
129
+ if (!entry.checks.some((c) => typeof c.passageRef.provenance.path === 'string' &&
130
+ (c.passageRef.provenance.path === prefix ||
131
+ c.passageRef.provenance.path.startsWith(prefix + '/'))))
132
+ throw new Error('structured_requirement_unaccounted');
133
+ }
134
+ return plan;
135
+ }
@@ -0,0 +1,316 @@
1
+ import { z } from 'zod';
2
+ import type { GitIdentity } from './prepare.js';
3
+ export declare const prContextSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
4
+ repository: z.ZodString;
5
+ pr: z.ZodNumber;
6
+ reviewer: z.ZodString;
7
+ capturedAt: z.ZodISODateTime;
8
+ comparison: z.ZodObject<{
9
+ base: z.ZodString;
10
+ head: z.ZodString;
11
+ }, z.core.$strict>;
12
+ history: z.ZodObject<{
13
+ status: z.ZodEnum<{
14
+ unavailable: "unavailable";
15
+ available: "available";
16
+ }>;
17
+ runs: z.ZodArray<z.ZodObject<{
18
+ provider: z.ZodEnum<{
19
+ unknown: "unknown";
20
+ openai: "openai";
21
+ openrouter: "openrouter";
22
+ }>;
23
+ model: z.ZodString;
24
+ effort: z.ZodString;
25
+ cliRunId: z.ZodNullable<z.ZodString>;
26
+ id: z.ZodString;
27
+ attempt: z.ZodNumber;
28
+ base: z.ZodNullable<z.ZodString>;
29
+ head: z.ZodNullable<z.ZodString>;
30
+ at: z.ZodISODateTime;
31
+ assessment: z.ZodEnum<{
32
+ unknown: "unknown";
33
+ complete: "complete";
34
+ incomplete: "incomplete";
35
+ not_started: "not_started";
36
+ running: "running";
37
+ }>;
38
+ execution: z.ZodEnum<{
39
+ unknown: "unknown";
40
+ failed: "failed";
41
+ finished: "finished";
42
+ }>;
43
+ exit: z.ZodNullable<z.ZodUnion<readonly [z.ZodLiteral<0>, z.ZodLiteral<1>, z.ZodLiteral<2>]>>;
44
+ findings: z.ZodNumber;
45
+ unresolved: z.ZodNumber;
46
+ durationMs: z.ZodNullable<z.ZodNumber>;
47
+ cost: z.ZodNullable<z.ZodNumber>;
48
+ costComplete: z.ZodBoolean;
49
+ packageVersion: z.ZodString;
50
+ reviewerVersion: z.ZodNullable<z.ZodNumber>;
51
+ }, z.core.$strict>>;
52
+ omitted: z.ZodNumber;
53
+ assessment: z.ZodNullable<z.ZodObject<{
54
+ base: z.ZodString;
55
+ head: z.ZodString;
56
+ cliRunId: z.ZodString;
57
+ run: z.ZodString;
58
+ attempt: z.ZodNumber;
59
+ reviewerVersion: z.ZodNullable<z.ZodNumber>;
60
+ scopeIdentity: z.ZodString;
61
+ provider: z.ZodEnum<{
62
+ unknown: "unknown";
63
+ openai: "openai";
64
+ openrouter: "openrouter";
65
+ }>;
66
+ model: z.ZodString;
67
+ effort: z.ZodString;
68
+ entries: z.ZodArray<z.ZodObject<{
69
+ nodeId: z.ZodString;
70
+ version: z.ZodNumber;
71
+ disposition: z.ZodEnum<{
72
+ not_evaluated: "not_evaluated";
73
+ evaluated: "evaluated";
74
+ not_applicable: "not_applicable";
75
+ unresolved: "unresolved";
76
+ }>;
77
+ finding: z.ZodEnum<{
78
+ none: "none";
79
+ binding_violation: "binding_violation";
80
+ behavioral_defect: "behavioral_defect";
81
+ guidance_departure: "guidance_departure";
82
+ }>;
83
+ explanation: z.ZodString;
84
+ correction: z.ZodString;
85
+ }, z.core.$strict>>;
86
+ omitted: z.ZodNumber;
87
+ }, z.core.$strict>>;
88
+ }, z.core.$strict>;
89
+ discussion: z.ZodObject<{
90
+ status: z.ZodEnum<{
91
+ unavailable: "unavailable";
92
+ available: "available";
93
+ partial: "partial";
94
+ }>;
95
+ items: z.ZodArray<z.ZodObject<{
96
+ kind: z.ZodEnum<{
97
+ comment: "comment";
98
+ review: "review";
99
+ thread: "thread";
100
+ dismissal: "dismissal";
101
+ }>;
102
+ id: z.ZodString;
103
+ author: z.ZodString;
104
+ association: z.ZodString;
105
+ body: z.ZodString;
106
+ url: z.ZodString;
107
+ at: z.ZodString;
108
+ state: z.ZodString;
109
+ resolved: z.ZodNullable<z.ZodBoolean>;
110
+ outdated: z.ZodNullable<z.ZodBoolean>;
111
+ resolvedBy: z.ZodString;
112
+ path: z.ZodString;
113
+ line: z.ZodNullable<z.ZodNumber>;
114
+ }, z.core.$strict>>;
115
+ }, z.core.$strict>;
116
+ changesSincePrevious: z.ZodObject<{
117
+ status: z.ZodEnum<{
118
+ unavailable: "unavailable";
119
+ available: "available";
120
+ partial: "partial";
121
+ same_head: "same_head";
122
+ }>;
123
+ base: z.ZodNullable<z.ZodString>;
124
+ head: z.ZodString;
125
+ relation: z.ZodString;
126
+ files: z.ZodArray<z.ZodObject<{
127
+ path: z.ZodString;
128
+ status: z.ZodString;
129
+ }, z.core.$strict>>;
130
+ }, z.core.$strict>;
131
+ limitations: z.ZodArray<z.ZodString>;
132
+ version: z.ZodLiteral<1>;
133
+ }, z.core.$strict>, z.ZodObject<{
134
+ observedChecks: z.ZodOptional<z.ZodObject<{
135
+ source: z.ZodLiteral<"github_api">;
136
+ head: z.ZodString;
137
+ capturedAt: z.ZodISODateTime;
138
+ checkRuns: z.ZodObject<{
139
+ status: z.ZodEnum<{
140
+ unavailable: "unavailable";
141
+ available: "available";
142
+ partial: "partial";
143
+ }>;
144
+ items: z.ZodArray<z.ZodObject<{
145
+ name: z.ZodString;
146
+ status: z.ZodString;
147
+ conclusion: z.ZodNullable<z.ZodString>;
148
+ }, z.core.$strict>>;
149
+ }, z.core.$strict>;
150
+ commitStatuses: z.ZodObject<{
151
+ status: z.ZodEnum<{
152
+ unavailable: "unavailable";
153
+ available: "available";
154
+ partial: "partial";
155
+ }>;
156
+ items: z.ZodArray<z.ZodObject<{
157
+ context: z.ZodString;
158
+ state: z.ZodString;
159
+ }, z.core.$strict>>;
160
+ }, z.core.$strict>;
161
+ }, z.core.$strict>>;
162
+ intent: z.ZodObject<{
163
+ title: z.ZodString;
164
+ body: z.ZodString;
165
+ source: z.ZodEnum<{
166
+ github_pull_request: "github_pull_request";
167
+ caller: "caller";
168
+ }>;
169
+ }, z.core.$strict>;
170
+ history: z.ZodObject<{
171
+ status: z.ZodEnum<{
172
+ unavailable: "unavailable";
173
+ available: "available";
174
+ }>;
175
+ omitted: z.ZodNumber;
176
+ assessment: z.ZodNullable<z.ZodObject<{
177
+ base: z.ZodString;
178
+ head: z.ZodString;
179
+ cliRunId: z.ZodString;
180
+ run: z.ZodString;
181
+ attempt: z.ZodNumber;
182
+ reviewerVersion: z.ZodNullable<z.ZodNumber>;
183
+ scopeIdentity: z.ZodString;
184
+ provider: z.ZodEnum<{
185
+ unknown: "unknown";
186
+ openai: "openai";
187
+ openrouter: "openrouter";
188
+ }>;
189
+ model: z.ZodString;
190
+ effort: z.ZodString;
191
+ entries: z.ZodArray<z.ZodObject<{
192
+ nodeId: z.ZodString;
193
+ version: z.ZodNumber;
194
+ disposition: z.ZodEnum<{
195
+ not_evaluated: "not_evaluated";
196
+ evaluated: "evaluated";
197
+ not_applicable: "not_applicable";
198
+ unresolved: "unresolved";
199
+ }>;
200
+ finding: z.ZodEnum<{
201
+ none: "none";
202
+ binding_violation: "binding_violation";
203
+ behavioral_defect: "behavioral_defect";
204
+ guidance_departure: "guidance_departure";
205
+ }>;
206
+ explanation: z.ZodString;
207
+ correction: z.ZodString;
208
+ }, z.core.$strict>>;
209
+ omitted: z.ZodNumber;
210
+ }, z.core.$strict>>;
211
+ runs: z.ZodArray<z.ZodObject<{
212
+ provider: z.ZodEnum<{
213
+ unknown: "unknown";
214
+ openai: "openai";
215
+ openrouter: "openrouter";
216
+ }>;
217
+ model: z.ZodString;
218
+ effort: z.ZodString;
219
+ cliRunId: z.ZodNullable<z.ZodString>;
220
+ id: z.ZodString;
221
+ attempt: z.ZodNumber;
222
+ base: z.ZodNullable<z.ZodString>;
223
+ head: z.ZodNullable<z.ZodString>;
224
+ at: z.ZodISODateTime;
225
+ assessment: z.ZodEnum<{
226
+ unknown: "unknown";
227
+ complete: "complete";
228
+ incomplete: "incomplete";
229
+ not_started: "not_started";
230
+ running: "running";
231
+ }>;
232
+ execution: z.ZodEnum<{
233
+ unknown: "unknown";
234
+ failed: "failed";
235
+ finished: "finished";
236
+ }>;
237
+ exit: z.ZodNullable<z.ZodUnion<readonly [z.ZodLiteral<0>, z.ZodLiteral<1>, z.ZodLiteral<2>]>>;
238
+ findings: z.ZodNumber;
239
+ unresolved: z.ZodNumber;
240
+ durationMs: z.ZodNullable<z.ZodNumber>;
241
+ cost: z.ZodNullable<z.ZodNumber>;
242
+ costComplete: z.ZodBoolean;
243
+ packageVersion: z.ZodString;
244
+ reviewerVersion: z.ZodNullable<z.ZodNumber>;
245
+ phaseModels: z.ZodOptional<z.ZodArray<z.ZodObject<{
246
+ phase: z.ZodEnum<{
247
+ assess: "assess";
248
+ plan: "plan";
249
+ verify: "verify";
250
+ }>;
251
+ provider: z.ZodEnum<{
252
+ openai: "openai";
253
+ openrouter: "openrouter";
254
+ }>;
255
+ model: z.ZodString;
256
+ effort: z.ZodOptional<z.ZodString>;
257
+ }, z.core.$strict>>>;
258
+ }, z.core.$strict>>;
259
+ }, z.core.$strict>;
260
+ repository: z.ZodString;
261
+ pr: z.ZodNumber;
262
+ reviewer: z.ZodString;
263
+ capturedAt: z.ZodISODateTime;
264
+ comparison: z.ZodObject<{
265
+ base: z.ZodString;
266
+ head: z.ZodString;
267
+ }, z.core.$strict>;
268
+ discussion: z.ZodObject<{
269
+ status: z.ZodEnum<{
270
+ unavailable: "unavailable";
271
+ available: "available";
272
+ partial: "partial";
273
+ }>;
274
+ items: z.ZodArray<z.ZodObject<{
275
+ kind: z.ZodEnum<{
276
+ comment: "comment";
277
+ review: "review";
278
+ thread: "thread";
279
+ dismissal: "dismissal";
280
+ }>;
281
+ id: z.ZodString;
282
+ author: z.ZodString;
283
+ association: z.ZodString;
284
+ body: z.ZodString;
285
+ url: z.ZodString;
286
+ at: z.ZodString;
287
+ state: z.ZodString;
288
+ resolved: z.ZodNullable<z.ZodBoolean>;
289
+ outdated: z.ZodNullable<z.ZodBoolean>;
290
+ resolvedBy: z.ZodString;
291
+ path: z.ZodString;
292
+ line: z.ZodNullable<z.ZodNumber>;
293
+ }, z.core.$strict>>;
294
+ }, z.core.$strict>;
295
+ changesSincePrevious: z.ZodObject<{
296
+ status: z.ZodEnum<{
297
+ unavailable: "unavailable";
298
+ available: "available";
299
+ partial: "partial";
300
+ same_head: "same_head";
301
+ }>;
302
+ base: z.ZodNullable<z.ZodString>;
303
+ head: z.ZodString;
304
+ relation: z.ZodString;
305
+ files: z.ZodArray<z.ZodObject<{
306
+ path: z.ZodString;
307
+ status: z.ZodString;
308
+ }, z.core.$strict>>;
309
+ }, z.core.$strict>;
310
+ limitations: z.ZodArray<z.ZodString>;
311
+ version: z.ZodLiteral<2>;
312
+ }, z.core.$strict>], "version">;
313
+ export type PrContext = z.infer<typeof prContextSchema>;
314
+ /** This binds advisory data to the current comparison; parsing does not authenticate its claims. */
315
+ export declare function parsePrContext(value: unknown, artifact: GitIdentity, reviewer: string): PrContext;
316
+ export declare function loadPrContext(file: string, artifact: GitIdentity, reviewer: string): PrContext;
@@ -0,0 +1,198 @@
1
+ import { closeSync, fstatSync, openSync, readSync } from 'node:fs';
2
+ import { z } from 'zod';
3
+ const MAX_PR_CONTEXT_BYTES = 200 * 1024;
4
+ const sha = z.string().regex(/^[a-f0-9]{40}$/);
5
+ const text = (max) => z.string().max(max);
6
+ const disposition = z.enum(['evaluated', 'unresolved', 'not_applicable', 'not_evaluated']);
7
+ const finding = z.enum(['none', 'binding_violation', 'behavioral_defect', 'guidance_departure']);
8
+ const entry = z.strictObject({
9
+ nodeId: text(500).startsWith('context://'),
10
+ version: z.number().int().positive(),
11
+ disposition,
12
+ finding,
13
+ explanation: text(300),
14
+ correction: text(200),
15
+ });
16
+ const run = z.strictObject({
17
+ provider: z.enum(['openai', 'openrouter', 'unknown']),
18
+ model: text(200),
19
+ effort: text(20),
20
+ cliRunId: z
21
+ .string()
22
+ .regex(/^[A-Za-z0-9_-]{1,200}$/)
23
+ .nullable(),
24
+ id: z.string().regex(/^[1-9][0-9]{0,19}$/),
25
+ attempt: z.number().int().positive().max(1000000),
26
+ base: sha.nullable(),
27
+ head: sha.nullable(),
28
+ at: z.iso.datetime(),
29
+ assessment: z.enum(['complete', 'incomplete', 'running', 'not_started', 'unknown']),
30
+ execution: z.enum(['finished', 'failed', 'unknown']),
31
+ exit: z.union([z.literal(0), z.literal(1), z.literal(2)]).nullable(),
32
+ findings: z.number().int().nonnegative(),
33
+ unresolved: z.number().int().nonnegative(),
34
+ durationMs: z.number().nonnegative().nullable(),
35
+ cost: z.number().nonnegative().nullable(),
36
+ costComplete: z.boolean(),
37
+ packageVersion: text(100),
38
+ reviewerVersion: z.number().nonnegative().nullable(),
39
+ });
40
+ const contextFields = {
41
+ repository: text(301).regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/),
42
+ pr: z.number().int().positive(),
43
+ reviewer: text(500).startsWith('skill://'),
44
+ capturedAt: z.iso.datetime(),
45
+ comparison: z.strictObject({ base: sha, head: sha }),
46
+ history: z.strictObject({
47
+ status: z.enum(['available', 'unavailable']),
48
+ runs: z.array(run).max(10),
49
+ omitted: z.number().int().nonnegative(),
50
+ assessment: z
51
+ .strictObject({
52
+ base: sha,
53
+ head: sha,
54
+ cliRunId: z.string().regex(/^[A-Za-z0-9_-]{1,200}$/),
55
+ run: z.string().regex(/^[1-9][0-9]{0,19}$/),
56
+ attempt: z.number().int().positive(),
57
+ reviewerVersion: z.number().nonnegative().nullable(),
58
+ scopeIdentity: text(150),
59
+ provider: z.enum(['openai', 'openrouter', 'unknown']),
60
+ model: text(200),
61
+ effort: text(20),
62
+ entries: z.array(entry).max(30),
63
+ omitted: z.number().int().nonnegative(),
64
+ })
65
+ .nullable(),
66
+ }),
67
+ discussion: z.strictObject({
68
+ status: z.enum(['available', 'partial', 'unavailable']),
69
+ items: z
70
+ .array(z.strictObject({
71
+ kind: z.enum(['comment', 'review', 'thread', 'dismissal']),
72
+ id: text(200),
73
+ author: text(100),
74
+ association: text(100),
75
+ body: text(1000),
76
+ url: text(1000).startsWith('https://github.com/'),
77
+ at: text(50),
78
+ state: text(50),
79
+ resolved: z.boolean().nullable(),
80
+ outdated: z.boolean().nullable(),
81
+ resolvedBy: text(100),
82
+ path: text(500),
83
+ line: z.number().int().positive().nullable(),
84
+ }))
85
+ .max(80),
86
+ }),
87
+ changesSincePrevious: z.strictObject({
88
+ status: z.enum(['available', 'partial', 'unavailable', 'same_head']),
89
+ base: sha.nullable(),
90
+ head: sha,
91
+ relation: text(50),
92
+ files: z.array(z.strictObject({ path: text(500), status: text(50) })).max(100),
93
+ }),
94
+ limitations: z.array(text(300)).max(12),
95
+ };
96
+ const phaseModel = z.strictObject({
97
+ phase: z.enum(['plan', 'assess', 'verify']),
98
+ provider: z.enum(['openai', 'openrouter']),
99
+ model: text(200),
100
+ effort: text(20).optional(),
101
+ });
102
+ const v1 = z.strictObject({ version: z.literal(1), ...contextFields });
103
+ const observationStatus = z.enum(['available', 'partial', 'unavailable']);
104
+ const observedChecks = z.strictObject({
105
+ source: z.literal('github_api'),
106
+ head: sha,
107
+ capturedAt: z.iso.datetime(),
108
+ checkRuns: z.strictObject({
109
+ status: observationStatus,
110
+ items: z
111
+ .array(z.strictObject({
112
+ name: text(200),
113
+ status: text(50),
114
+ conclusion: text(50).nullable(),
115
+ }))
116
+ .max(50),
117
+ }),
118
+ commitStatuses: z.strictObject({
119
+ status: observationStatus,
120
+ items: z.array(z.strictObject({ context: text(200), state: text(50) })).max(50),
121
+ }),
122
+ });
123
+ const v2 = z.strictObject({
124
+ version: z.literal(2),
125
+ ...contextFields,
126
+ observedChecks: observedChecks.optional(),
127
+ intent: z.strictObject({
128
+ title: text(1000),
129
+ body: text(20000),
130
+ source: z.enum(['github_pull_request', 'caller']),
131
+ }),
132
+ history: contextFields.history.extend({
133
+ runs: z.array(run.extend({ phaseModels: z.array(phaseModel).max(3).optional() })).max(10),
134
+ }),
135
+ });
136
+ export const prContextSchema = z.discriminatedUnion('version', [v1, v2]);
137
+ /** This binds advisory data to the current comparison; parsing does not authenticate its claims. */
138
+ export function parsePrContext(value, artifact, reviewer) {
139
+ try {
140
+ if (Buffer.byteLength(JSON.stringify(value)) > MAX_PR_CONTEXT_BYTES)
141
+ throw new Error();
142
+ const context = prContextSchema.parse(value);
143
+ if (context.comparison.base !== artifact.base.commit ||
144
+ context.comparison.head !== artifact.head.commit ||
145
+ context.reviewer !== reviewer ||
146
+ (context.version === 2 &&
147
+ context.observedChecks !== undefined &&
148
+ context.observedChecks.head !== context.comparison.head))
149
+ throw new Error();
150
+ for (const item of context.discussion.items) {
151
+ const url = new URL(item.url);
152
+ if (url.search ||
153
+ ![`/${context.repository}/pull/${context.pr}`, `/${context.repository}/issues/${context.pr}`].includes(url.pathname))
154
+ throw new Error();
155
+ }
156
+ const repository = artifact.repositoryEnvironment;
157
+ if (repository.status === 'reported' &&
158
+ (repository.provider !== 'github.com' ||
159
+ context.repository.toLowerCase() !== `${repository.owner}/${repository.name}`.toLowerCase()))
160
+ throw new Error();
161
+ if (repository.status !== 'reported' &&
162
+ !context.limitations.includes('Repository origin unavailable; PR identity is reported, not independently bound.'))
163
+ context.limitations = [
164
+ ...context.limitations.slice(0, 11),
165
+ 'Repository origin unavailable; PR identity is reported, not independently bound.',
166
+ ];
167
+ return context;
168
+ }
169
+ catch {
170
+ throw new Error('invalid_pr_context');
171
+ }
172
+ }
173
+ export function loadPrContext(file, artifact, reviewer) {
174
+ let fd;
175
+ try {
176
+ fd = openSync(file, 'r');
177
+ if (!fstatSync(fd).isFile())
178
+ throw new Error();
179
+ const buffer = Buffer.alloc(MAX_PR_CONTEXT_BYTES + 1);
180
+ let size = 0;
181
+ while (size < buffer.length) {
182
+ const count = readSync(fd, buffer, size, buffer.length - size, null);
183
+ if (!count)
184
+ break;
185
+ size += count;
186
+ }
187
+ if (size > MAX_PR_CONTEXT_BYTES)
188
+ throw new Error();
189
+ return parsePrContext(JSON.parse(buffer.subarray(0, size).toString('utf8')), artifact, reviewer);
190
+ }
191
+ catch {
192
+ throw new Error('invalid_pr_context');
193
+ }
194
+ finally {
195
+ if (fd !== undefined)
196
+ closeSync(fd);
197
+ }
198
+ }