@contextrail/assess 0.0.0-stage → 1.0.0-alpha.2
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.
- package/LICENSE +202 -0
- package/README.md +82 -2
- package/assets/brand/icon-dark.png +0 -0
- package/assets/brand/icon-light.png +0 -0
- package/dist/assess.d.ts +109 -0
- package/dist/assess.js +1563 -0
- package/dist/assessment.d.ts +571 -0
- package/dist/assessment.js +404 -0
- package/dist/budget.d.ts +24 -0
- package/dist/budget.js +52 -0
- package/dist/candidate.d.ts +156 -0
- package/dist/candidate.js +361 -0
- package/dist/change-summary.d.ts +33 -0
- package/dist/change-summary.js +26 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +406 -0
- package/dist/contracts.d.ts +99 -0
- package/dist/contracts.js +62 -0
- package/dist/diagnostics.d.ts +44 -0
- package/dist/diagnostics.js +412 -0
- package/dist/evidence.d.ts +73 -0
- package/dist/evidence.js +297 -0
- package/dist/feedback.d.ts +21 -0
- package/dist/feedback.js +154 -0
- package/dist/git.d.ts +40 -0
- package/dist/git.js +207 -0
- package/dist/github.d.ts +90 -0
- package/dist/github.js +1342 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +14 -0
- package/dist/mcp.d.ts +28 -0
- package/dist/mcp.js +173 -0
- package/dist/pack.d.ts +160 -0
- package/dist/pack.js +377 -0
- package/dist/phases.d.ts +65 -0
- package/dist/phases.js +63 -0
- package/dist/planning.d.ts +64 -0
- package/dist/planning.js +135 -0
- package/dist/pr-context.d.ts +316 -0
- package/dist/pr-context.js +198 -0
- package/dist/prepare.d.ts +71 -0
- package/dist/prepare.js +335 -0
- package/dist/presentation.d.ts +310 -0
- package/dist/presentation.js +1076 -0
- package/dist/provider-diagnostics.d.ts +93 -0
- package/dist/provider-diagnostics.js +233 -0
- package/dist/providers.d.ts +45 -0
- package/dist/providers.js +291 -0
- package/dist/report-contract.d.ts +137 -0
- package/dist/report-contract.js +248 -0
- package/dist/results.d.ts +90 -0
- package/dist/results.js +128 -0
- package/dist/resume.d.ts +25 -0
- package/dist/resume.js +116 -0
- package/dist/source.d.ts +167 -0
- package/dist/source.js +675 -0
- package/dist/verification.d.ts +386 -0
- package/dist/verification.js +168 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +9 -0
- package/docs/README.md +24 -0
- package/docs/action-reference.md +85 -0
- package/docs/architecture.md +158 -0
- package/docs/configuration.md +83 -0
- package/docs/contributing.md +46 -0
- package/docs/getting-started.md +92 -0
- package/docs/github-actions.md +141 -0
- package/docs/operations.md +211 -0
- package/docs/review-results.md +189 -0
- package/docs/security.md +68 -0
- package/docs/standards.md +62 -0
- package/examples/assess-pull-request.yml +109 -0
- package/package.json +56 -5
package/dist/pack.js
ADDED
|
@@ -0,0 +1,377 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { open, rename, rm, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { constants } from 'node:fs';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
import { publicationSchema } from './contracts.js';
|
|
7
|
+
import { modelEvidence } from './evidence.js';
|
|
8
|
+
import { digest } from './prepare.js';
|
|
9
|
+
import { SourceAccessError } from './source.js';
|
|
10
|
+
import { MAX_PREPARATION_BYTES } from './git.js';
|
|
11
|
+
const MAX_READ_BYTES = 64 * 1024;
|
|
12
|
+
const MAX_READ_SEGMENTS = 200;
|
|
13
|
+
const MAX_ARTIFACT_BYTES = 8 * 1024 * 1024;
|
|
14
|
+
const MAX_MODEL_EVIDENCE_BYTES = 512 * 1024;
|
|
15
|
+
const packReadSchema = z.strictObject({
|
|
16
|
+
assessmentId: z.string().min(1),
|
|
17
|
+
section: z.number().int().nonnegative().optional(),
|
|
18
|
+
offset: z.number().int().nonnegative().optional(),
|
|
19
|
+
});
|
|
20
|
+
// Model reads address registered publications, never caller-provided filesystem paths.
|
|
21
|
+
const contents = new WeakMap();
|
|
22
|
+
/** Reuse the sealed plain patch; source reads still supply citation evidence. */
|
|
23
|
+
export async function modelDiffEvidence(directory, expectedHash, fallback) {
|
|
24
|
+
const omitted = (reason, bytes = null) => ({
|
|
25
|
+
...fallback,
|
|
26
|
+
fullPatch: { status: 'omitted', reason, bytes, maxBytes: 128 * 1024 },
|
|
27
|
+
});
|
|
28
|
+
if (expectedHash === undefined)
|
|
29
|
+
return omitted('artifact_unavailable');
|
|
30
|
+
if (typeof expectedHash !== 'string' || !/^sha256:[a-f0-9]{64}$/.test(expectedHash))
|
|
31
|
+
throw new Error('upstream_artifact_changed');
|
|
32
|
+
const file = await open(join(directory, 'diff.patch'), constants.O_RDONLY | constants.O_NOFOLLOW).catch(() => {
|
|
33
|
+
throw new Error('upstream_artifact_changed');
|
|
34
|
+
});
|
|
35
|
+
let bytes;
|
|
36
|
+
try {
|
|
37
|
+
const info = await file.stat();
|
|
38
|
+
if (!info.isFile() || info.size > MAX_PREPARATION_BYTES)
|
|
39
|
+
throw new Error('upstream_artifact_changed');
|
|
40
|
+
bytes = Buffer.alloc(info.size + 1);
|
|
41
|
+
const read = await file.read(bytes, 0, bytes.length, 0);
|
|
42
|
+
if (read.bytesRead !== info.size)
|
|
43
|
+
throw new Error('upstream_artifact_changed');
|
|
44
|
+
bytes = bytes.subarray(0, info.size);
|
|
45
|
+
}
|
|
46
|
+
finally {
|
|
47
|
+
await file.close();
|
|
48
|
+
}
|
|
49
|
+
if (`sha256:${createHash('sha256').update(bytes).digest('hex')}` !== expectedHash)
|
|
50
|
+
throw new Error('upstream_artifact_changed');
|
|
51
|
+
const patch = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
|
52
|
+
const complete = { status: 'complete', format: 'unified', patch, hash: expectedHash };
|
|
53
|
+
return Buffer.byteLength(JSON.stringify(complete)) <= 128 * 1024
|
|
54
|
+
? complete
|
|
55
|
+
: omitted('model_diff_budget', bytes.length);
|
|
56
|
+
}
|
|
57
|
+
/** Root authority text is source evidence, not permission to execute repository instructions. */
|
|
58
|
+
export async function repositoryInstructionsEvidence(source, ledger, signal) {
|
|
59
|
+
const request = { side: 'head', path: 'AGENTS.md' };
|
|
60
|
+
try {
|
|
61
|
+
signal?.throwIfAborted();
|
|
62
|
+
const read = await source.read(request, { signal });
|
|
63
|
+
const record = ledger.source(read);
|
|
64
|
+
return {
|
|
65
|
+
status: read.status,
|
|
66
|
+
next: read.next,
|
|
67
|
+
reason: read.reason ?? null,
|
|
68
|
+
evidence: record ? modelEvidence(record) : null,
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
if (signal?.aborted || (error instanceof SourceAccessError && error.code === 'cancelled'))
|
|
73
|
+
throw error;
|
|
74
|
+
return {
|
|
75
|
+
status: 'unavailable',
|
|
76
|
+
next: request,
|
|
77
|
+
reason: 'repository_instructions_unavailable',
|
|
78
|
+
evidence: null,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
/** Shared original input, never assessor conclusions. Oversize sections remain explicitly readable. */
|
|
83
|
+
export function modelPackEvidence(pack, ledger) {
|
|
84
|
+
const records = contents.get(pack);
|
|
85
|
+
if (!records)
|
|
86
|
+
throw new Error('pack_invalid');
|
|
87
|
+
const result = { status: 'incomplete', evidence: [], omitted: [], unavailable: [] };
|
|
88
|
+
const candidates = [];
|
|
89
|
+
for (const criterion of pack.index.criteria) {
|
|
90
|
+
if (!criterion.available) {
|
|
91
|
+
result.unavailable.push({ assessmentId: criterion.assessmentId, reason: 'pinned_publication_unavailable' });
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
for (const [section, record] of (records.get(criterion.assessmentId) ?? []).entries()) {
|
|
95
|
+
const continuation = {
|
|
96
|
+
ref: record.ref,
|
|
97
|
+
reason: 'model_evidence_budget',
|
|
98
|
+
next: { assessmentId: criterion.assessmentId, section, offset: 0 },
|
|
99
|
+
};
|
|
100
|
+
candidates.push({ record, continuation });
|
|
101
|
+
result.omitted.push(continuation);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
// Reserve every continuation first so a large body cannot crowd out omission metadata.
|
|
105
|
+
let bytes = Buffer.byteLength(JSON.stringify(result));
|
|
106
|
+
if (bytes > MAX_MODEL_EVIDENCE_BYTES)
|
|
107
|
+
throw new Error('pack_model_metadata_too_large');
|
|
108
|
+
const included = new Set();
|
|
109
|
+
for (const { record, continuation } of candidates) {
|
|
110
|
+
const view = modelEvidence(record);
|
|
111
|
+
// Conservatively retain array comma overhead; the actual serialized result stays bounded.
|
|
112
|
+
const additional = Buffer.byteLength(JSON.stringify(view)) + 1 - Buffer.byteLength(JSON.stringify(continuation));
|
|
113
|
+
if (bytes + additional > MAX_MODEL_EVIDENCE_BYTES)
|
|
114
|
+
continue;
|
|
115
|
+
bytes += additional;
|
|
116
|
+
ledger.add(record.text, structuredClone(record.provenance));
|
|
117
|
+
result.evidence.push(structuredClone(view));
|
|
118
|
+
included.add(continuation);
|
|
119
|
+
}
|
|
120
|
+
result.omitted = result.omitted.filter((continuation) => !included.has(continuation));
|
|
121
|
+
result.status = result.omitted.length || result.unavailable.length ? 'incomplete' : 'complete';
|
|
122
|
+
return result;
|
|
123
|
+
}
|
|
124
|
+
/** Original source already read during this run, with cited records first and no inferred conclusions. */
|
|
125
|
+
export function modelSourceEvidence(ledger, selectedRefs) {
|
|
126
|
+
const refs = [...new Set(selectedRefs ?? Object.keys(ledger.records))];
|
|
127
|
+
const candidates = refs
|
|
128
|
+
.map((ref) => ledger.records[ref])
|
|
129
|
+
.filter((record) => record?.provenance.kind === 'source');
|
|
130
|
+
const result = {
|
|
131
|
+
scope: 'read_fragments',
|
|
132
|
+
status: 'incomplete',
|
|
133
|
+
evidence: [],
|
|
134
|
+
omitted: candidates.map((record) => ({
|
|
135
|
+
ref: record.ref,
|
|
136
|
+
reason: 'model_evidence_budget',
|
|
137
|
+
next: {
|
|
138
|
+
side: record.provenance.side,
|
|
139
|
+
path: record.provenance.path,
|
|
140
|
+
start: record.provenance.start,
|
|
141
|
+
},
|
|
142
|
+
})),
|
|
143
|
+
};
|
|
144
|
+
let bytes = Buffer.byteLength(JSON.stringify(result));
|
|
145
|
+
if (bytes > MAX_MODEL_EVIDENCE_BYTES)
|
|
146
|
+
throw new Error('pack_model_metadata_too_large');
|
|
147
|
+
const included = new Set();
|
|
148
|
+
for (const [index, record] of candidates.entries()) {
|
|
149
|
+
const view = modelEvidence(record);
|
|
150
|
+
const additional = Buffer.byteLength(JSON.stringify(view)) + 1 - Buffer.byteLength(JSON.stringify(result.omitted[index]));
|
|
151
|
+
if (bytes + additional > MAX_MODEL_EVIDENCE_BYTES)
|
|
152
|
+
continue;
|
|
153
|
+
bytes += additional;
|
|
154
|
+
included.add(record.ref);
|
|
155
|
+
result.evidence.push(structuredClone(view));
|
|
156
|
+
}
|
|
157
|
+
result.omitted = result.omitted.filter((record) => !included.has(record.ref));
|
|
158
|
+
result.status =
|
|
159
|
+
result.omitted.length || candidates.some((record) => record.provenance.readStatus !== 'complete')
|
|
160
|
+
? 'incomplete'
|
|
161
|
+
: 'complete';
|
|
162
|
+
return result;
|
|
163
|
+
}
|
|
164
|
+
/** One inspectable pack of the original governed material and prepared comparison metadata. */
|
|
165
|
+
export function prepareEvidencePack(options) {
|
|
166
|
+
const { state, publications, ledger } = options;
|
|
167
|
+
const records = new Map();
|
|
168
|
+
const ids = state.entries.map((entry) => entry.assessmentId);
|
|
169
|
+
if (new Set(ids).size !== ids.length)
|
|
170
|
+
throw new Error('pack_scope_invalid');
|
|
171
|
+
const criteria = state.entries.map((entry) => {
|
|
172
|
+
const material = Object.hasOwn(publications, entry.assessmentId) ? publications[entry.assessmentId] : null;
|
|
173
|
+
const publication = material ? publicationSchema.parse(material) : null;
|
|
174
|
+
if (publication &&
|
|
175
|
+
(publication.nodeId !== entry.nodeId ||
|
|
176
|
+
publication.version !== entry.version ||
|
|
177
|
+
publication.subtype !== entry.subtype ||
|
|
178
|
+
digest(publication.content) !== entry.contentHash))
|
|
179
|
+
throw new Error('pack_publication_mismatch');
|
|
180
|
+
const evidence = publication ? ledger.publication(publication) : [];
|
|
181
|
+
records.set(entry.assessmentId, structuredClone(evidence));
|
|
182
|
+
return {
|
|
183
|
+
assessmentId: entry.assessmentId,
|
|
184
|
+
nodeId: entry.nodeId,
|
|
185
|
+
title: publication?.title ?? null,
|
|
186
|
+
version: entry.version,
|
|
187
|
+
subtype: entry.subtype,
|
|
188
|
+
contentHash: entry.contentHash,
|
|
189
|
+
reasons: [...entry.reasons],
|
|
190
|
+
relationships: structuredClone(publication?.relationships ?? []),
|
|
191
|
+
available: !!publication,
|
|
192
|
+
sections: evidence.map((record, index) => ({
|
|
193
|
+
index,
|
|
194
|
+
path: String(record.provenance.path),
|
|
195
|
+
ref: record.ref,
|
|
196
|
+
characters: record.text.length,
|
|
197
|
+
bytes: Buffer.byteLength(record.text),
|
|
198
|
+
})),
|
|
199
|
+
};
|
|
200
|
+
});
|
|
201
|
+
const pack = {
|
|
202
|
+
index: {
|
|
203
|
+
contractVersion: 1,
|
|
204
|
+
runId: state.runId,
|
|
205
|
+
scopeIdentity: state.scopeIdentity,
|
|
206
|
+
preparationStatus: state.preparationStatus,
|
|
207
|
+
expectedContextCount: state.expectedContextCount,
|
|
208
|
+
comparison: { base: state.artifact.base.commit, head: state.artifact.head.commit },
|
|
209
|
+
criteria,
|
|
210
|
+
changedFiles: structuredClone(state.changes ?? null),
|
|
211
|
+
assets: { diff: 'diff.patch', preparation: 'preparation.md', publications: 'publications.json' },
|
|
212
|
+
gaps: structuredClone(state.gaps),
|
|
213
|
+
limitations: [...state.limitations],
|
|
214
|
+
},
|
|
215
|
+
markdown: '',
|
|
216
|
+
};
|
|
217
|
+
const lines = [
|
|
218
|
+
'# Governed assessment evidence',
|
|
219
|
+
'',
|
|
220
|
+
`Fixed comparison: ${state.artifact.base.commit} → ${state.artifact.head.commit}.`,
|
|
221
|
+
`Run: ${state.runId}. Scope: ${state.scopeIdentity ?? 'unavailable'}.`,
|
|
222
|
+
'',
|
|
223
|
+
'This is pinned assessment input, not an assessment result or proof of complete coverage.',
|
|
224
|
+
'Original context bodies are below. Required relationships and selection reasons are retained in the index.',
|
|
225
|
+
'Numbered segments belong to their displayed evidence reference, not repository line numbers.',
|
|
226
|
+
'',
|
|
227
|
+
'- [Complete permitted changed-file inventory and governed index](evidence-index.json)',
|
|
228
|
+
'- [Prepared unified diff](diff.patch)',
|
|
229
|
+
'- [Preparation details and exclusions](preparation.md)',
|
|
230
|
+
'- [Original pinned publication objects](publications.json)',
|
|
231
|
+
'',
|
|
232
|
+
];
|
|
233
|
+
for (const criterion of criteria) {
|
|
234
|
+
lines.push(`## ${criterion.nodeId} @ ${criterion.version ?? 'unavailable'}`, '');
|
|
235
|
+
lines.push(`Assessment: ${criterion.assessmentId}. Subtype: ${criterion.subtype ?? 'unavailable'}.`, '');
|
|
236
|
+
if (!criterion.available)
|
|
237
|
+
lines.push('Pinned publication unavailable; this criterion remains in scope.', '');
|
|
238
|
+
for (const record of records.get(criterion.assessmentId) ?? []) {
|
|
239
|
+
lines.push(`### ${String(record.provenance.path)}`, '', `Evidence: ${record.ref}`, '');
|
|
240
|
+
for (const segment of modelEvidence(record).segments)
|
|
241
|
+
lines.push(`[${segment.index}] ${segment.text}`);
|
|
242
|
+
lines.push('');
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
pack.markdown = lines.join('\n');
|
|
246
|
+
contents.set(pack, records);
|
|
247
|
+
return pack;
|
|
248
|
+
}
|
|
249
|
+
/** Artifact filenames are package-owned. The caller owns the trusted run directory and manifest. */
|
|
250
|
+
export async function writeEvidencePack(directory, pack) {
|
|
251
|
+
if (!contents.has(pack))
|
|
252
|
+
throw new Error('pack_invalid');
|
|
253
|
+
const bodies = {
|
|
254
|
+
'evidence.md': pack.markdown,
|
|
255
|
+
'evidence-index.json': JSON.stringify(pack.index, null, 2) + '\n',
|
|
256
|
+
};
|
|
257
|
+
if (Object.values(bodies).some((body) => Buffer.byteLength(body) > MAX_ARTIFACT_BYTES))
|
|
258
|
+
throw new Error('pack_artifact_too_large');
|
|
259
|
+
const files = {};
|
|
260
|
+
for (const [name, body] of Object.entries(bodies)) {
|
|
261
|
+
const path = join(directory, name), temporary = `${path}.${randomUUID()}.tmp`;
|
|
262
|
+
try {
|
|
263
|
+
await writeFile(temporary, body, { mode: 0o600, flag: 'wx' });
|
|
264
|
+
await rename(temporary, path);
|
|
265
|
+
}
|
|
266
|
+
finally {
|
|
267
|
+
await rm(temporary, { force: true });
|
|
268
|
+
}
|
|
269
|
+
files[name] = `sha256:${createHash('sha256').update(body).digest('hex')}`;
|
|
270
|
+
}
|
|
271
|
+
return { files, indexHash: digest(pack.index) };
|
|
272
|
+
}
|
|
273
|
+
function publicationReadLimits(limits) {
|
|
274
|
+
const maxBytes = limits.maxBytes ?? MAX_READ_BYTES, maxSegments = limits.maxSegments ?? MAX_READ_SEGMENTS;
|
|
275
|
+
if (!Number.isSafeInteger(maxBytes) ||
|
|
276
|
+
maxBytes < 4 ||
|
|
277
|
+
maxBytes > MAX_READ_BYTES ||
|
|
278
|
+
!Number.isSafeInteger(maxSegments) ||
|
|
279
|
+
maxSegments < 1 ||
|
|
280
|
+
maxSegments > MAX_READ_SEGMENTS)
|
|
281
|
+
throw new Error('pack_read_limits_invalid');
|
|
282
|
+
return { maxBytes, maxSegments };
|
|
283
|
+
}
|
|
284
|
+
function readPublicationSections(publication, fields, request, ledger, maxBytes, maxSegments) {
|
|
285
|
+
let section = request.section ?? 0, offset = request.offset ?? 0;
|
|
286
|
+
const evidence = [], sections = [];
|
|
287
|
+
let remainingBytes = maxBytes, remainingSegments = maxSegments;
|
|
288
|
+
while (section < fields.length && remainingBytes >= 4 && remainingSegments > 0) {
|
|
289
|
+
const record = fields[section], start = offset;
|
|
290
|
+
const end = boundedEnd(record.text, start, remainingBytes, remainingSegments);
|
|
291
|
+
if (end === start) {
|
|
292
|
+
section++;
|
|
293
|
+
offset = 0;
|
|
294
|
+
continue;
|
|
295
|
+
}
|
|
296
|
+
const text = record.text.slice(start, end), page = start === 0 && end === record.text.length
|
|
297
|
+
? ledger.add(record.text, record.provenance)
|
|
298
|
+
: ledger.add(text, {
|
|
299
|
+
...record.provenance,
|
|
300
|
+
contentStart: start,
|
|
301
|
+
contentEnd: end,
|
|
302
|
+
contentLength: record.text.length,
|
|
303
|
+
});
|
|
304
|
+
const view = modelEvidence(page);
|
|
305
|
+
evidence.push(view);
|
|
306
|
+
sections.push({
|
|
307
|
+
index: section,
|
|
308
|
+
path: String(record.provenance.path),
|
|
309
|
+
offset: start,
|
|
310
|
+
end,
|
|
311
|
+
totalCharacters: record.text.length,
|
|
312
|
+
});
|
|
313
|
+
remainingBytes -= Buffer.byteLength(text);
|
|
314
|
+
remainingSegments -= view.segments.length;
|
|
315
|
+
if (end < record.text.length) {
|
|
316
|
+
offset = end;
|
|
317
|
+
break;
|
|
318
|
+
}
|
|
319
|
+
section++;
|
|
320
|
+
offset = 0;
|
|
321
|
+
}
|
|
322
|
+
const next = section < fields.length ? { assessmentId: request.assessmentId, section, offset } : null;
|
|
323
|
+
return { status: next ? 'truncated' : 'complete', publication, sections, evidence, next };
|
|
324
|
+
}
|
|
325
|
+
/** Bounded original-material reads. Continuations preserve Unicode and explicit publication offsets. */
|
|
326
|
+
export function readPackPublication(pack, ledger, input, limits = {}) {
|
|
327
|
+
const records = contents.get(pack);
|
|
328
|
+
if (!records)
|
|
329
|
+
throw new Error('pack_invalid');
|
|
330
|
+
const unavailable = (reason) => ({
|
|
331
|
+
status: 'unavailable',
|
|
332
|
+
publication: null,
|
|
333
|
+
sections: [],
|
|
334
|
+
evidence: [],
|
|
335
|
+
next: null,
|
|
336
|
+
reason,
|
|
337
|
+
});
|
|
338
|
+
const parsed = packReadSchema.safeParse(input);
|
|
339
|
+
if (!parsed.success)
|
|
340
|
+
return unavailable('pack_read_invalid');
|
|
341
|
+
const request = parsed.data, criterion = pack.index.criteria.find((entry) => entry.assessmentId === request.assessmentId);
|
|
342
|
+
if (!criterion)
|
|
343
|
+
return unavailable('pack_publication_unknown');
|
|
344
|
+
const { sections: _sections, ...publication } = criterion;
|
|
345
|
+
if (!criterion.available)
|
|
346
|
+
return { ...unavailable('pinned_publication_unavailable'), publication };
|
|
347
|
+
const fields = records.get(request.assessmentId);
|
|
348
|
+
const section = request.section ?? 0, offset = request.offset ?? 0;
|
|
349
|
+
const { maxBytes, maxSegments } = publicationReadLimits(limits);
|
|
350
|
+
if (!fields.length && section === 0 && offset === 0)
|
|
351
|
+
return { status: 'complete', publication, sections: [], evidence: [], next: null };
|
|
352
|
+
if (section >= fields.length ||
|
|
353
|
+
offset > fields[section].text.length ||
|
|
354
|
+
splitsSurrogate(fields[section].text, offset))
|
|
355
|
+
return { ...unavailable('pack_range_invalid'), publication };
|
|
356
|
+
return readPublicationSections(publication, fields, request, ledger, maxBytes, maxSegments);
|
|
357
|
+
}
|
|
358
|
+
function splitsSurrogate(text, offset) {
|
|
359
|
+
return (offset > 0 &&
|
|
360
|
+
text.charCodeAt(offset) >= 0xdc00 &&
|
|
361
|
+
text.charCodeAt(offset) <= 0xdfff &&
|
|
362
|
+
text.charCodeAt(offset - 1) >= 0xd800 &&
|
|
363
|
+
text.charCodeAt(offset - 1) <= 0xdbff);
|
|
364
|
+
}
|
|
365
|
+
function boundedEnd(text, start, maxBytes, maxSegments) {
|
|
366
|
+
let end = start, bytes = 0, segments = 0;
|
|
367
|
+
while (end < text.length && segments < maxSegments) {
|
|
368
|
+
const point = text.codePointAt(end), crlf = point === 13 && text.charCodeAt(end + 1) === 10, size = crlf ? 2 : point <= 0x7f ? 1 : point <= 0x7ff ? 2 : point <= 0xffff ? 3 : 4;
|
|
369
|
+
if (bytes + size > maxBytes)
|
|
370
|
+
break;
|
|
371
|
+
bytes += size;
|
|
372
|
+
end += crlf || point > 0xffff ? 2 : 1;
|
|
373
|
+
if (point === 10 || point === 13)
|
|
374
|
+
segments++;
|
|
375
|
+
}
|
|
376
|
+
return end;
|
|
377
|
+
}
|
package/dist/phases.d.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { type GitIdentity } from './prepare.js';
|
|
3
|
+
/** Phase records are operational review artifacts, never generic event payloads. */
|
|
4
|
+
export declare const phaseRecordSchema: z.ZodObject<{
|
|
5
|
+
contractVersion: z.ZodLiteral<1>;
|
|
6
|
+
runId: z.ZodString;
|
|
7
|
+
phase: z.ZodEnum<{
|
|
8
|
+
assess: "assess";
|
|
9
|
+
prepare: "prepare";
|
|
10
|
+
plan: "plan";
|
|
11
|
+
verify: "verify";
|
|
12
|
+
finalize: "finalize";
|
|
13
|
+
}>;
|
|
14
|
+
workUnitId: z.ZodString;
|
|
15
|
+
attempt: z.ZodNumber;
|
|
16
|
+
startedAt: z.ZodISODateTime;
|
|
17
|
+
finishedAt: z.ZodISODateTime;
|
|
18
|
+
status: z.ZodEnum<{
|
|
19
|
+
complete: "complete";
|
|
20
|
+
cancelled: "cancelled";
|
|
21
|
+
incomplete: "incomplete";
|
|
22
|
+
failed: "failed";
|
|
23
|
+
}>;
|
|
24
|
+
inputRefs: z.ZodArray<z.ZodObject<{
|
|
25
|
+
ref: z.ZodString;
|
|
26
|
+
hash: z.ZodString;
|
|
27
|
+
}, z.core.$strict>>;
|
|
28
|
+
outputHash: z.ZodString;
|
|
29
|
+
artifact: z.ZodObject<{
|
|
30
|
+
base: z.ZodObject<{
|
|
31
|
+
commit: z.ZodString;
|
|
32
|
+
tree: z.ZodString;
|
|
33
|
+
}, z.core.$strict>;
|
|
34
|
+
head: z.ZodObject<{
|
|
35
|
+
commit: z.ZodString;
|
|
36
|
+
tree: z.ZodString;
|
|
37
|
+
}, z.core.$strict>;
|
|
38
|
+
}, z.core.$strict>;
|
|
39
|
+
scopeIdentity: z.ZodNullable<z.ZodString>;
|
|
40
|
+
assessmentIds: z.ZodArray<z.ZodString>;
|
|
41
|
+
evidenceRefs: z.ZodArray<z.ZodString>;
|
|
42
|
+
limitations: z.ZodArray<z.ZodString>;
|
|
43
|
+
stopReason: z.ZodNullable<z.ZodString>;
|
|
44
|
+
configuration: z.ZodRecord<z.ZodString, z.ZodUnknown>;
|
|
45
|
+
usageRefs: z.ZodArray<z.ZodString>;
|
|
46
|
+
output: z.ZodUnknown;
|
|
47
|
+
}, z.core.$strict>;
|
|
48
|
+
export type PhaseRecord = z.infer<typeof phaseRecordSchema>;
|
|
49
|
+
export type PhaseIdentity = {
|
|
50
|
+
runId: string;
|
|
51
|
+
artifact: GitIdentity;
|
|
52
|
+
scopeIdentity: string | null;
|
|
53
|
+
assessmentIds: string[];
|
|
54
|
+
inputRefs?: PhaseRecord['inputRefs'];
|
|
55
|
+
phase?: PhaseRecord['phase'];
|
|
56
|
+
workUnitId?: string;
|
|
57
|
+
attempt?: number;
|
|
58
|
+
requireComplete?: boolean;
|
|
59
|
+
};
|
|
60
|
+
/** Build an immutable handoff; callers then validate their phase-specific output schema. */
|
|
61
|
+
export declare function createPhaseRecord(input: Omit<PhaseRecord, 'contractVersion' | 'outputHash' | 'artifact'> & {
|
|
62
|
+
artifact: GitIdentity;
|
|
63
|
+
}): PhaseRecord;
|
|
64
|
+
/** Hashes establish integrity/identity, not authority or semantic correctness. */
|
|
65
|
+
export declare function validatePhaseRecord(value: unknown, expected: PhaseIdentity): PhaseRecord;
|
package/dist/phases.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { digest } from './prepare.js';
|
|
3
|
+
const hash = z.string().regex(/^sha256:[a-f0-9]{64}$/u);
|
|
4
|
+
const objectId = z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u);
|
|
5
|
+
const snapshot = z.strictObject({ commit: objectId, tree: objectId });
|
|
6
|
+
const identity = z.strictObject({ base: snapshot, head: snapshot });
|
|
7
|
+
const reference = z.strictObject({ ref: z.string().min(1), hash });
|
|
8
|
+
/** Phase records are operational review artifacts, never generic event payloads. */
|
|
9
|
+
export const phaseRecordSchema = z.strictObject({
|
|
10
|
+
contractVersion: z.literal(1),
|
|
11
|
+
runId: z.string().uuid(),
|
|
12
|
+
phase: z.enum(['prepare', 'plan', 'assess', 'verify', 'finalize']),
|
|
13
|
+
workUnitId: z.string().regex(/^[A-Za-z0-9_-]{1,100}$/u),
|
|
14
|
+
attempt: z.number().int().positive(),
|
|
15
|
+
startedAt: z.iso.datetime(),
|
|
16
|
+
finishedAt: z.iso.datetime(),
|
|
17
|
+
status: z.enum(['complete', 'incomplete', 'failed', 'cancelled']),
|
|
18
|
+
inputRefs: z.array(reference),
|
|
19
|
+
outputHash: hash,
|
|
20
|
+
artifact: identity,
|
|
21
|
+
scopeIdentity: hash.nullable(),
|
|
22
|
+
assessmentIds: z.array(z.string().min(1)),
|
|
23
|
+
evidenceRefs: z.array(z.string().min(1)),
|
|
24
|
+
limitations: z.array(z.string()),
|
|
25
|
+
stopReason: z.string().nullable(),
|
|
26
|
+
configuration: z.record(z.string(), z.unknown()),
|
|
27
|
+
usageRefs: z.array(z.string()),
|
|
28
|
+
output: z.unknown(),
|
|
29
|
+
});
|
|
30
|
+
const fixedIdentity = (artifact) => ({
|
|
31
|
+
base: { commit: artifact.base.commit, tree: artifact.base.tree },
|
|
32
|
+
head: { commit: artifact.head.commit, tree: artifact.head.tree },
|
|
33
|
+
});
|
|
34
|
+
/** Build an immutable handoff; callers then validate their phase-specific output schema. */
|
|
35
|
+
export function createPhaseRecord(input) {
|
|
36
|
+
return phaseRecordSchema.parse({
|
|
37
|
+
...input,
|
|
38
|
+
contractVersion: 1,
|
|
39
|
+
artifact: fixedIdentity(input.artifact),
|
|
40
|
+
outputHash: digest(input.output),
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
/** Hashes establish integrity/identity, not authority or semantic correctness. */
|
|
44
|
+
export function validatePhaseRecord(value, expected) {
|
|
45
|
+
const record = phaseRecordSchema.parse(value);
|
|
46
|
+
const sameSet = (left, right) => new Set(left).size === left.length &&
|
|
47
|
+
new Set(right).size === right.length &&
|
|
48
|
+
left.length === right.length &&
|
|
49
|
+
left.every((id) => right.includes(id));
|
|
50
|
+
const matchesSelection = ['phase', 'workUnitId', 'attempt'].every((key) => expected[key] === undefined || record[key] === expected[key]);
|
|
51
|
+
if (record.runId !== expected.runId ||
|
|
52
|
+
!matchesSelection ||
|
|
53
|
+
(expected.requireComplete !== false && record.status !== 'complete') ||
|
|
54
|
+
record.scopeIdentity !== expected.scopeIdentity ||
|
|
55
|
+
digest(record.artifact) !== digest(fixedIdentity(expected.artifact)) ||
|
|
56
|
+
record.outputHash !== digest(record.output) ||
|
|
57
|
+
!sameSet(record.assessmentIds, expected.assessmentIds) ||
|
|
58
|
+
(expected.inputRefs !== undefined && digest(record.inputRefs) !== digest(expected.inputRefs)) ||
|
|
59
|
+
new Set(record.inputRefs.map((item) => item.ref)).size !== record.inputRefs.length ||
|
|
60
|
+
Date.parse(record.finishedAt) < Date.parse(record.startedAt))
|
|
61
|
+
throw new Error('invalid_phase_handoff');
|
|
62
|
+
return record;
|
|
63
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { modelEvidence, type Citation, type EvidenceLedger } from './evidence.js';
|
|
3
|
+
import type { AssessmentEntry } from './results.js';
|
|
4
|
+
declare const planSchema: z.ZodObject<{
|
|
5
|
+
entries: z.ZodArray<z.ZodObject<{
|
|
6
|
+
assessmentId: z.ZodString;
|
|
7
|
+
applicability: z.ZodEnum<{
|
|
8
|
+
not_applicable: "not_applicable";
|
|
9
|
+
unresolved: "unresolved";
|
|
10
|
+
applicable: "applicable";
|
|
11
|
+
}>;
|
|
12
|
+
reason: z.ZodString;
|
|
13
|
+
workUnit: z.ZodString;
|
|
14
|
+
checks: z.ZodArray<z.ZodObject<{
|
|
15
|
+
passage: z.ZodObject<{
|
|
16
|
+
ref: z.ZodString;
|
|
17
|
+
quote: z.ZodString;
|
|
18
|
+
start: z.ZodOptional<z.ZodNumber>;
|
|
19
|
+
end: z.ZodOptional<z.ZodNumber>;
|
|
20
|
+
}, z.core.$strict>;
|
|
21
|
+
interpretation: z.ZodString;
|
|
22
|
+
}, z.core.$strict>>;
|
|
23
|
+
surfaces: z.ZodArray<z.ZodString>;
|
|
24
|
+
evidenceNeeds: z.ZodArray<z.ZodString>;
|
|
25
|
+
}, z.core.$strict>>;
|
|
26
|
+
}, z.core.$strict>;
|
|
27
|
+
type PlannedCheck = {
|
|
28
|
+
checkId: string;
|
|
29
|
+
assessmentId: string;
|
|
30
|
+
passageRef: Citation;
|
|
31
|
+
interpretation: string;
|
|
32
|
+
};
|
|
33
|
+
export type PlanEntry = Omit<z.infer<typeof planSchema>['entries'][number], 'checks'> & {
|
|
34
|
+
checks: PlannedCheck[];
|
|
35
|
+
};
|
|
36
|
+
export type AssessmentPlan = {
|
|
37
|
+
entries: PlanEntry[];
|
|
38
|
+
};
|
|
39
|
+
export declare function exactIds(actual: string[], expected: string[]): void;
|
|
40
|
+
export type PlanCitationCorrection = {
|
|
41
|
+
assessmentId: string;
|
|
42
|
+
entryIndex: number;
|
|
43
|
+
checkIndex: number;
|
|
44
|
+
code: 'citation_unknown' | 'citation_absent' | 'citation_ambiguous' | 'citation_range_invalid' | 'wrong_governing_publication' | 'citation_invalid';
|
|
45
|
+
rejectedRefHash: string;
|
|
46
|
+
allowedRefs: Array<ReturnType<typeof modelEvidence> & {
|
|
47
|
+
path: string;
|
|
48
|
+
nodeId: string;
|
|
49
|
+
version: number;
|
|
50
|
+
}>;
|
|
51
|
+
allowedRefsOmitted: number;
|
|
52
|
+
};
|
|
53
|
+
/** Package-created correction metadata; rejected model text and quotations are never copied. */
|
|
54
|
+
export declare class PlanCitationError extends Error {
|
|
55
|
+
readonly corrections: PlanCitationCorrection[];
|
|
56
|
+
readonly omittedCount: number;
|
|
57
|
+
readonly code = "plan_citations_invalid";
|
|
58
|
+
constructor(corrections: PlanCitationCorrection[], omittedCount: number);
|
|
59
|
+
}
|
|
60
|
+
export declare function validatePlan(input: unknown, entries: AssessmentEntry[], ledger: EvidenceLedger, structured?: Record<string, Array<{
|
|
61
|
+
path: string;
|
|
62
|
+
value: unknown;
|
|
63
|
+
}>>): AssessmentPlan;
|
|
64
|
+
export {};
|