@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
package/dist/cli.js ADDED
@@ -0,0 +1,406 @@
1
+ #!/usr/bin/env node
2
+ import { loadPrContext } from './pr-context.js';
3
+ import { packageVersion } from './version.js';
4
+ import { systemFailureDiagnostics } from './diagnostics.js';
5
+ import { parseArgs } from 'node:util';
6
+ import { fixGitIdentity } from './git.js';
7
+ import { McpPublishedReader, mcpTimeoutMs } from './mcp.js';
8
+ import { prepareAssessment } from './prepare.js';
9
+ import { loadAssessmentCheckpoint } from './resume.js';
10
+ import { runAssessment, DEFAULT_EXECUTION_LIMITS } from './assess.js';
11
+ import { DEFAULT_SOURCE_LIMITS } from './source.js';
12
+ import { providerTransportDiagnostics } from './providers.js';
13
+ import { DEFAULT_POLICY } from './results.js';
14
+ import { prepareGitHubAssessment, publishGitHubAssessment } from './github.js';
15
+ // SDK warnings are captured and redacted in the audit; avoid uncontrolled CLI logging.
16
+ globalThis.AI_SDK_LOG_WARNINGS = false;
17
+ const executionFlags = {
18
+ 'max-turns': 'maxTurns',
19
+ 'max-output-tokens': 'maxOutputTokens',
20
+ 'max-total-tokens': 'maxTotalTokens',
21
+ 'max-time-ms': 'maxTimeMs',
22
+ };
23
+ const sourceFlags = {
24
+ 'source-page-entries': 'pageEntries',
25
+ 'source-search-matches': 'searchMatches',
26
+ 'source-search-files': 'searchFiles',
27
+ 'source-read-lines': 'readLines',
28
+ 'source-read-bytes': 'readBytes',
29
+ 'source-timeout-ms': 'timeoutMs',
30
+ };
31
+ const help = `Usage: contextrail-assess prepare|run --reviewer skill://domain/reviewer --repo DIR --base REF --head REF
32
+
33
+ Assess proposed changes against your published organizational standards.
34
+ Inspect results and source evidence under .contextrail/assess/<run-id>/.
35
+ Both commands fix the Git commits and retrieve exact published guidance versions.
36
+ prepare exit 0 means prepared, with no evaluation; incomplete preparation exits 2.
37
+ run performs governed assessment and independent verification with retained phase records.
38
+ --resume RUN_DIR reuses a sealed incomplete run with the same comparison and assessment configuration.
39
+ Resume uses the saved publications without fetching newer standards; execution limits apply to this invocation.
40
+ Requires CONTEXTRAIL_MCP_URL, CONTEXTRAIL_MCP_AUTH_TOKEN, CONTEXTRAIL_MCP_ORG_ID.
41
+ --mcp-timeout-ms N overrides CONTEXTRAIL_MCP_TIMEOUT_MS (default 30000, Node timer range).
42
+
43
+ run requires --provider openai|openrouter and --model PROVIDER_NATIVE_ID
44
+ (or CONTEXTRAIL_ASSESS_PROVIDER / CONTEXTRAIL_ASSESS_MODEL). CLI overrides environment.
45
+ Credentials: OPENAI_API_KEY / OPENROUTER_API_KEY. No implicit provider/model fallback.
46
+ --effort none|minimal|low|medium|high|xhigh (provider/model must support it).
47
+ --phase-models JSON overrides assess/verify with explicit {provider,model,effort?} objects.
48
+ --log-level quiet|info|debug (default info).
49
+ --purpose TEXT supplies caller-stated objective/stage; no inferred objective is treated as approved.
50
+ --pr-context PATH supplies bounded, untrusted PR history/discussion data bound to this comparison; never approval or governing instructions.
51
+ --enforcement advisory|required|strict (default advisory).
52
+ Advisory reports judgments without blocking; required blocks supported violations/defects;
53
+ strict also blocks unresolved evidence. No mode changes the recorded judgments.
54
+ Exit 0: allowed by enforcement policy (not proof of compliance); 1: policy blocks;
55
+ 2: assessment unavailable or execution/report error. Policy outcome is recorded separately.
56
+
57
+ Execution settings: --max-turns N, --max-output-tokens N, --max-total-tokens N, --max-time-ms N.
58
+ Default: unset (no package ceiling; provider output/context constraints still apply).
59
+ Total-token cutoff is observed after calls, can overshoot by one call; missing usage prevents enforcement.
60
+ Per-call output allowance includes provider reasoning tokens where applicable.
61
+ Source response/operation settings (positive integers, read-bytes >=4):
62
+ ${Object.entries(sourceFlags)
63
+ .map(([flag, key]) => `--${flag} N (default ${DEFAULT_SOURCE_LIMITS[key]})`)
64
+ .join('\n')}
65
+ Every run option has CONTEXTRAIL_ASSESS_<UPPERCASE_FLAG_WITH_UNDERSCORES> equivalent.
66
+ Limits are operational settings, not scope requirements.
67
+ --feedback send|off (default send) submits minimal metadata after finalization.
68
+ --repository-attribution explicitly includes repository identity in reports and preparation environment.
69
+ Feedback off suppresses metadata submission; local reports are still written.
70
+ Ordinary ContextRail retrieval still emits delivery events.
71
+ Export credentials into this process; the CLI does not load .env files.
72
+ No runtime code execution or hidden reasoning capture. Cancellation preserves accepted work.
73
+
74
+ GitHub adapter (GITHUB_TOKEN only for confirmed network operations):
75
+ github prepare --repository OWNER/REPO --pr-number N --reviewer SKILL_ID --output-dir DIR
76
+ [--base-branch BRANCH] [--collect-pr-context]
77
+ github publish --run-dir RUN_DIR --github-dir DIR [--post-comment] [--inline-comments]
78
+ [--summary-file PATH] [--artifact-url URL] [--dry-run]
79
+ Dry-run/render-only publication makes no network request. Posting requires pull-requests:write.
80
+ `;
81
+ function positive(value, flag) {
82
+ if (value === undefined)
83
+ return null;
84
+ if (!/^\d+$/u.test(value) || !Number.isSafeInteger(Number(value)) || Number(value) < 1)
85
+ throw new CliInputError(`${flag} must be a positive safe integer.`);
86
+ return Number(value);
87
+ }
88
+ class CliInputError extends Error {
89
+ }
90
+ function readArguments() {
91
+ return parseArgs({
92
+ allowPositionals: true,
93
+ options: {
94
+ reviewer: { type: 'string' },
95
+ repo: { type: 'string', default: process.cwd() },
96
+ base: { type: 'string' },
97
+ head: { type: 'string' },
98
+ 'mcp-timeout-ms': { type: 'string' },
99
+ provider: { type: 'string' },
100
+ model: { type: 'string' },
101
+ effort: { type: 'string' },
102
+ 'phase-models': { type: 'string' },
103
+ 'log-level': { type: 'string' },
104
+ repository: { type: 'string' },
105
+ 'pr-number': { type: 'string' },
106
+ 'output-dir': { type: 'string' },
107
+ 'base-branch': { type: 'string' },
108
+ 'collect-pr-context': { type: 'boolean' },
109
+ 'run-dir': { type: 'string' },
110
+ resume: { type: 'string' },
111
+ 'github-dir': { type: 'string' },
112
+ 'post-comment': { type: 'boolean' },
113
+ 'inline-comments': { type: 'boolean' },
114
+ 'summary-file': { type: 'string' },
115
+ 'artifact-url': { type: 'string' },
116
+ 'dry-run': { type: 'boolean' },
117
+ purpose: { type: 'string' },
118
+ 'pr-context': { type: 'string' },
119
+ enforcement: { type: 'string' },
120
+ feedback: { type: 'string' },
121
+ 'repository-attribution': { type: 'boolean' },
122
+ ...Object.fromEntries([...Object.keys(executionFlags), ...Object.keys(sourceFlags)].map((flag) => [
123
+ flag,
124
+ { type: 'string' },
125
+ ])),
126
+ help: { type: 'boolean' },
127
+ version: { type: 'boolean' },
128
+ },
129
+ });
130
+ }
131
+ async function runGitHubCommand(values, positionals) {
132
+ if (positionals.length !== 2)
133
+ throw new CliInputError('Use github prepare or github publish.');
134
+ const token = process.env.GITHUB_TOKEN;
135
+ if (positionals[1] === 'prepare') {
136
+ if (!values.repository || !values['pr-number'] || !values.reviewer || !values['output-dir'])
137
+ throw new CliInputError('github prepare requires repository, pr-number, reviewer and output-dir.');
138
+ const result = await prepareGitHubAssessment({
139
+ repository: values.repository,
140
+ prNumber: positive(values['pr-number'], 'pr-number'),
141
+ reviewer: values.reviewer,
142
+ outputDir: values['output-dir'],
143
+ baseBranch: values['base-branch'],
144
+ collectPrContext: values['collect-pr-context'] === true,
145
+ token,
146
+ });
147
+ process.stdout.write(`${JSON.stringify(result)}\n`);
148
+ return;
149
+ }
150
+ if (positionals[1] === 'publish') {
151
+ if (!values['run-dir'] || !values['github-dir'])
152
+ throw new CliInputError('github publish requires run-dir and github-dir.');
153
+ const result = await publishGitHubAssessment({
154
+ runDir: values['run-dir'],
155
+ githubDir: values['github-dir'],
156
+ postComment: values['post-comment'] === true,
157
+ inlineComments: values['inline-comments'] === true,
158
+ summaryFile: values['summary-file'],
159
+ artifactUrl: values['artifact-url'],
160
+ dryRun: values['dry-run'] === true,
161
+ token,
162
+ });
163
+ process.stdout.write(`${JSON.stringify(result)}\n`);
164
+ process.exitCode = result.exitCode;
165
+ return;
166
+ }
167
+ throw new CliInputError('Use github prepare or github publish.');
168
+ }
169
+ function readProvider(setting) {
170
+ const p = setting('provider'), model = setting('model'), effort = setting('effort');
171
+ if (!p || !['openai', 'openrouter'].includes(p) || !model?.trim())
172
+ throw new CliInputError('run requires explicit --provider openai|openrouter and --model (or environment).');
173
+ if (effort && !['none', 'minimal', 'low', 'medium', 'high', 'xhigh'].includes(effort))
174
+ throw new CliInputError('Invalid --effort. See --help.');
175
+ return {
176
+ provider: p,
177
+ model,
178
+ ...(effort ? { effort: effort } : {}),
179
+ };
180
+ }
181
+ function readPhaseModel(config) {
182
+ const value = config;
183
+ if (Object.keys(value).some((key) => !['provider', 'model', 'effort'].includes(key)) ||
184
+ !['openai', 'openrouter'].includes(String(value.provider)) ||
185
+ typeof value.model !== 'string' ||
186
+ !value.model.trim() ||
187
+ (value.effort !== undefined &&
188
+ !['none', 'minimal', 'low', 'medium', 'high', 'xhigh'].includes(String(value.effort))))
189
+ throw new Error();
190
+ return {
191
+ provider: value.provider,
192
+ model: value.model,
193
+ ...(value.effort === undefined ? {} : { effort: value.effort }),
194
+ };
195
+ }
196
+ function readPhaseModels(input) {
197
+ const phaseModels = {};
198
+ if (!input)
199
+ return phaseModels;
200
+ try {
201
+ const parsed = JSON.parse(input);
202
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
203
+ throw new Error();
204
+ for (const [phase, config] of Object.entries(parsed)) {
205
+ if (!['assess', 'verify'].includes(phase) || !config || typeof config !== 'object')
206
+ throw new Error();
207
+ phaseModels[phase] = readPhaseModel(config);
208
+ }
209
+ }
210
+ catch {
211
+ throw new CliInputError('phase-models must contain only assess/verify provider/model/optional effort objects.');
212
+ }
213
+ return phaseModels;
214
+ }
215
+ function readLimits(setting) {
216
+ const limits = { ...DEFAULT_EXECUTION_LIMITS };
217
+ const sourceLimits = {};
218
+ for (const [flag, key] of Object.entries(executionFlags))
219
+ limits[key] = positive(setting(flag), flag);
220
+ for (const [flag, key] of Object.entries(sourceFlags)) {
221
+ const value = positive(setting(flag), flag);
222
+ if (value !== null)
223
+ sourceLimits[key] = value;
224
+ }
225
+ if ((limits.maxTimeMs !== null && limits.maxTimeMs > 2_147_483_647) ||
226
+ (sourceLimits.timeoutMs !== undefined && sourceLimits.timeoutMs > 2_147_483_647))
227
+ throw new CliInputError('Time limit exceeds the Node timer interval.');
228
+ if (sourceLimits.readBytes !== undefined && sourceLimits.readBytes < 4)
229
+ throw new CliInputError('source-read-bytes must be >=4.');
230
+ return { limits, sourceLimits };
231
+ }
232
+ function readPolicy(setting) {
233
+ for (const name of ['ADVISORY', 'MIN_ADHERENCE', 'MIN_CONFIDENCE']) {
234
+ if (process.env[`CONTEXTRAIL_ASSESS_${name}`] !== undefined)
235
+ throw new CliInputError(`CONTEXTRAIL_ASSESS_${name} was replaced by CONTEXTRAIL_ASSESS_ENFORCEMENT.`);
236
+ }
237
+ const enforcement = setting('enforcement') ?? DEFAULT_POLICY.enforcement;
238
+ if (!['advisory', 'required', 'strict'].includes(enforcement))
239
+ throw new CliInputError('enforcement must be advisory, required or strict.');
240
+ return { enforcement: enforcement };
241
+ }
242
+ function commandSettings(values, isAssessment) {
243
+ const setting = (flag) => values[flag] ??
244
+ process.env[`CONTEXTRAIL_ASSESS_${flag.toUpperCase().replaceAll('-', '_')}`];
245
+ const resumePath = setting('resume');
246
+ if (resumePath && !isAssessment)
247
+ throw new CliInputError('--resume is only valid for run.');
248
+ const feedback = setting('feedback') ?? 'send';
249
+ if (!['send', 'off'].includes(feedback))
250
+ throw new CliInputError('feedback must be send or off.');
251
+ const repositorySetting = process.env.CONTEXTRAIL_ASSESS_REPOSITORY_ATTRIBUTION;
252
+ if (repositorySetting !== undefined && !['true', 'false'].includes(repositorySetting))
253
+ throw new CliInputError('repository attribution must be true or false.');
254
+ const repositoryAttribution = values['repository-attribution'] ?? repositorySetting === 'true';
255
+ const defaults = {
256
+ provider: undefined,
257
+ phaseModels: {},
258
+ logLevel: 'info',
259
+ limits: { ...DEFAULT_EXECUTION_LIMITS },
260
+ sourceLimits: {},
261
+ policy: { ...DEFAULT_POLICY },
262
+ };
263
+ if (!isAssessment)
264
+ return { setting, resumePath, feedback, repositoryAttribution, ...defaults };
265
+ const provider = readProvider(setting);
266
+ const phaseModels = readPhaseModels(setting('phase-models'));
267
+ const level = setting('log-level') ?? 'info';
268
+ if (!['quiet', 'info', 'debug'].includes(level))
269
+ throw new CliInputError('Invalid log-level.');
270
+ const logLevel = level;
271
+ const limits = readLimits(setting);
272
+ const policy = readPolicy(setting);
273
+ return {
274
+ setting,
275
+ resumePath,
276
+ feedback,
277
+ repositoryAttribution,
278
+ provider,
279
+ phaseModels,
280
+ logLevel,
281
+ ...limits,
282
+ policy,
283
+ };
284
+ }
285
+ function commandComparison(values, isAssessment, setting) {
286
+ if (!values.reviewer.startsWith('skill://'))
287
+ throw new CliInputError('--reviewer must be a skill:// ID.');
288
+ let artifact;
289
+ try {
290
+ artifact = fixGitIdentity(values.repo, values.base, values.head);
291
+ }
292
+ catch {
293
+ throw new CliInputError('Cannot resolve repository and base/head references to Git commits.');
294
+ }
295
+ let prContext;
296
+ const prContextPath = setting('pr-context');
297
+ if (isAssessment && prContextPath) {
298
+ try {
299
+ prContext = loadPrContext(prContextPath, artifact, values.reviewer);
300
+ }
301
+ catch {
302
+ throw new CliInputError('Invalid or oversized --pr-context file, or mismatched comparison/reviewer.');
303
+ }
304
+ }
305
+ return { artifact, prContext };
306
+ }
307
+ let commandStage = 'arguments';
308
+ async function runCommand(values, isAssessment) {
309
+ commandStage = 'configuration';
310
+ const { setting, resumePath, feedback, repositoryAttribution, provider, phaseModels, logLevel, limits, sourceLimits, policy, } = commandSettings(values, isAssessment);
311
+ const timeoutMs = mcpTimeoutMs(values['mcp-timeout-ms'] ?? process.env.CONTEXTRAIL_MCP_TIMEOUT_MS);
312
+ commandStage = 'comparison';
313
+ const { artifact, prContext } = commandComparison(values, isAssessment, setting);
314
+ const controller = new AbortController();
315
+ const cancel = () => controller.abort();
316
+ process.on('SIGINT', cancel);
317
+ process.on('SIGTERM', cancel);
318
+ commandStage = 'mcp_configuration';
319
+ const reader = new McpPublishedReader(process.env.CONTEXTRAIL_MCP_URL ?? '', process.env.CONTEXTRAIL_MCP_AUTH_TOKEN ?? '', process.env.CONTEXTRAIL_MCP_ORG_ID ?? '', artifact.repositoryEnvironment, { timeoutMs, signal: controller.signal, repositoryAttribution });
320
+ try {
321
+ commandStage = resumePath ? 'resume' : 'preparation';
322
+ const resumed = resumePath
323
+ ? loadAssessmentCheckpoint(resumePath, {
324
+ artifact,
325
+ reviewerId: values.reviewer,
326
+ })
327
+ : null;
328
+ commandStage = 'preparation';
329
+ const prepared = resumed?.prepared ??
330
+ (await prepareAssessment({
331
+ repository: values.repo,
332
+ base: values.base,
333
+ head: values.head,
334
+ reviewerId: values.reviewer,
335
+ reader,
336
+ artifact,
337
+ }));
338
+ if (isAssessment) {
339
+ commandStage = 'assess';
340
+ const result = await runAssessment({
341
+ prepared,
342
+ resume: resumed?.checkpoint,
343
+ provider: provider,
344
+ phaseModels,
345
+ logLevel,
346
+ policy,
347
+ limits,
348
+ sourceLimits,
349
+ feedback: feedback,
350
+ feedbackSender: reader,
351
+ repositoryAttribution,
352
+ purpose: setting('purpose'),
353
+ prContext,
354
+ signal: controller.signal,
355
+ });
356
+ process.stdout.write(`${JSON.stringify({ runId: result.state.runId, assessmentStatus: result.state.assessmentStatus, decision: result.state.decision, reportPath: result.reportPath, directory: result.directory, execution: result.state.execution })}\n`);
357
+ process.exitCode = result.state.decision?.exitCode ?? 2;
358
+ }
359
+ else {
360
+ process.stdout.write(`${JSON.stringify({ preparationStatus: prepared.state.preparationStatus, assessmentStatus: prepared.state.assessmentStatus, statePath: prepared.statePath, materialPath: prepared.materialPath, expectedContexts: prepared.state.expectedContextCount, recordedEntries: prepared.state.entries.length, gaps: prepared.state.gaps })}\n`);
361
+ process.exitCode = prepared.state.preparationStatus === 'prepared' ? 0 : 2;
362
+ }
363
+ }
364
+ finally {
365
+ await reader.close();
366
+ process.off('SIGINT', cancel);
367
+ process.off('SIGTERM', cancel);
368
+ }
369
+ }
370
+ async function main() {
371
+ const { values, positionals } = readArguments();
372
+ if (values.help) {
373
+ process.stdout.write(help);
374
+ return;
375
+ }
376
+ if (values.version) {
377
+ process.stdout.write(`${packageVersion}\n`);
378
+ return;
379
+ }
380
+ if (positionals[0] === 'github') {
381
+ commandStage = 'github';
382
+ return runGitHubCommand(values, positionals);
383
+ }
384
+ if (positionals.length !== 1 ||
385
+ !['prepare', 'run'].includes(positionals[0]) ||
386
+ !values.reviewer ||
387
+ !values.base ||
388
+ !values.head)
389
+ throw new CliInputError('Use prepare or run with --reviewer, --base and --head. See --help.');
390
+ await runCommand(values, positionals[0] === 'run');
391
+ }
392
+ function commandFailure(error) {
393
+ const { systemCode } = systemFailureDiagnostics(error);
394
+ if (systemCode)
395
+ return { code: systemCode };
396
+ const transport = providerTransportDiagnostics(error);
397
+ if (transport.transport !== 'unknown')
398
+ return { code: 'transport_failed', ...transport };
399
+ return { code: commandStage === 'mcp_configuration' ? 'invalid_mcp_configuration' : 'command_failed' };
400
+ }
401
+ main().catch((error) => {
402
+ process.stderr.write(error instanceof CliInputError
403
+ ? `${error.message}\n`
404
+ : `${JSON.stringify({ kind: 'cli_failed', data: { stage: commandStage, ...commandFailure(error) } })}\n`);
405
+ process.exitCode = 2;
406
+ });
@@ -0,0 +1,99 @@
1
+ import { z } from 'zod';
2
+ export declare const selectionsSchema: z.ZodObject<{
3
+ contextIds: z.ZodOptional<z.ZodArray<z.ZodString>>;
4
+ domains: z.ZodOptional<z.ZodArray<z.ZodObject<{
5
+ domainId: z.ZodString;
6
+ includeDescendants: z.ZodBoolean;
7
+ }, z.core.$strict>>>;
8
+ }, z.core.$strict>;
9
+ export declare const reviewerSectionsSchema: z.ZodObject<{
10
+ examples: z.ZodOptional<z.ZodArray<z.ZodUnknown>>;
11
+ references: z.ZodOptional<z.ZodArray<z.ZodUnknown>>;
12
+ }, z.core.$strict>;
13
+ export declare const publicationSchema: z.ZodObject<{
14
+ nodeId: z.ZodString;
15
+ title: z.ZodString;
16
+ domainId: z.ZodString;
17
+ type: z.ZodEnum<{
18
+ context: "context";
19
+ skill: "skill";
20
+ }>;
21
+ subtype: z.ZodString;
22
+ status: z.ZodLiteral<"published">;
23
+ detailLevel: z.ZodLiteral<"full">;
24
+ version: z.ZodNumber;
25
+ relationships: z.ZodArray<z.ZodObject<{
26
+ type: z.ZodString;
27
+ targetId: z.ZodString;
28
+ }, z.core.$loose>>;
29
+ content: z.ZodObject<{
30
+ kind: z.ZodString;
31
+ body: z.ZodOptional<z.ZodString>;
32
+ instructions: z.ZodOptional<z.ZodString>;
33
+ reviewer: z.ZodOptional<z.ZodObject<{
34
+ selections: z.ZodOptional<z.ZodObject<{
35
+ contextIds: z.ZodOptional<z.ZodArray<z.ZodString>>;
36
+ domains: z.ZodOptional<z.ZodArray<z.ZodObject<{
37
+ domainId: z.ZodString;
38
+ includeDescendants: z.ZodBoolean;
39
+ }, z.core.$strict>>>;
40
+ }, z.core.$strict>>;
41
+ }, z.core.$strict>>;
42
+ }, z.core.$loose>;
43
+ }, z.core.$loose>;
44
+ export type Publication = z.infer<typeof publicationSchema>;
45
+ export declare const scopeEntrySchema: z.ZodObject<{
46
+ nodeId: z.ZodString;
47
+ version: z.ZodNullable<z.ZodNumber>;
48
+ subtype: z.ZodNullable<z.ZodEnum<{
49
+ standard: "standard";
50
+ guidance: "guidance";
51
+ }>>;
52
+ contentHash: z.ZodNullable<z.ZodString>;
53
+ reasons: z.ZodArray<z.ZodString>;
54
+ }, z.core.$strict>;
55
+ export type ScopeEntry = z.infer<typeof scopeEntrySchema>;
56
+ export declare const scopePageSchema: z.ZodObject<{
57
+ reviewerId: z.ZodString;
58
+ publicationVersion: z.ZodNumber;
59
+ selectionsHash: z.ZodString;
60
+ scopeIdentity: z.ZodString;
61
+ complete: z.ZodBoolean;
62
+ totalMatched: z.ZodNumber;
63
+ offset: z.ZodNumber;
64
+ nextOffset: z.ZodNullable<z.ZodNumber>;
65
+ entries: z.ZodArray<z.ZodObject<{
66
+ nodeId: z.ZodString;
67
+ version: z.ZodNullable<z.ZodNumber>;
68
+ subtype: z.ZodNullable<z.ZodEnum<{
69
+ standard: "standard";
70
+ guidance: "guidance";
71
+ }>>;
72
+ contentHash: z.ZodNullable<z.ZodString>;
73
+ reasons: z.ZodArray<z.ZodString>;
74
+ }, z.core.$strict>>;
75
+ gaps: z.ZodArray<z.ZodObject<{
76
+ code: z.ZodString;
77
+ reason: z.ZodString;
78
+ }, z.core.$strict>>;
79
+ }, z.core.$strict>;
80
+ export type ScopePage = z.infer<typeof scopePageSchema>;
81
+ /** Only authorized published reads; deterministic tests implement the same small boundary. */
82
+ export interface PublishedReader {
83
+ read(name: 'get_skill' | 'get_context', args: Record<string, unknown>): Promise<unknown>;
84
+ }
85
+ export declare class PreparationReadError extends Error {
86
+ readonly code: string;
87
+ readonly diagnostic?: {
88
+ phase?: string;
89
+ status?: number;
90
+ upstreamCode?: string | number;
91
+ category?: string;
92
+ } | undefined;
93
+ constructor(code: string, diagnostic?: {
94
+ phase?: string;
95
+ status?: number;
96
+ upstreamCode?: string | number;
97
+ category?: string;
98
+ } | undefined);
99
+ }
@@ -0,0 +1,62 @@
1
+ import { z } from 'zod';
2
+ export const selectionsSchema = z.strictObject({
3
+ contextIds: z.array(z.string().startsWith('context://').max(500)).optional(),
4
+ domains: z.array(z.strictObject({ domainId: z.string().min(1), includeDescendants: z.boolean() })).optional(),
5
+ });
6
+ export const reviewerSectionsSchema = z.strictObject({
7
+ examples: z.array(z.unknown()).optional(),
8
+ references: z.array(z.unknown()).optional(),
9
+ });
10
+ const relationshipSchema = z.object({ type: z.string(), targetId: z.string() }).passthrough();
11
+ export const publicationSchema = z
12
+ .object({
13
+ nodeId: z.string(),
14
+ title: z.string().min(1),
15
+ domainId: z.string().min(1),
16
+ type: z.enum(['context', 'skill']),
17
+ subtype: z.string(),
18
+ status: z.literal('published'),
19
+ detailLevel: z.literal('full'),
20
+ version: z.number().int().positive(),
21
+ relationships: z.array(relationshipSchema),
22
+ content: z
23
+ .object({
24
+ kind: z.string(),
25
+ body: z.string().optional(),
26
+ instructions: z.string().optional(),
27
+ reviewer: z.strictObject({ selections: selectionsSchema.optional() }).optional(),
28
+ })
29
+ .passthrough(),
30
+ })
31
+ .passthrough();
32
+ export const scopeEntrySchema = z.strictObject({
33
+ nodeId: z.string().startsWith('context://'),
34
+ version: z.number().int().positive().nullable(),
35
+ subtype: z.enum(['standard', 'guidance']).nullable(),
36
+ contentHash: z
37
+ .string()
38
+ .regex(/^sha256:[a-f0-9]{64}$/u)
39
+ .nullable(),
40
+ reasons: z.array(z.string().min(1)).min(1),
41
+ });
42
+ export const scopePageSchema = z.strictObject({
43
+ reviewerId: z.string().startsWith('skill://'),
44
+ publicationVersion: z.number().int().positive(),
45
+ selectionsHash: z.string().regex(/^sha256:[a-f0-9]{64}$/u),
46
+ scopeIdentity: z.string().regex(/^sha256:[a-f0-9]{64}$/u),
47
+ complete: z.boolean(),
48
+ totalMatched: z.number().int().nonnegative(),
49
+ offset: z.number().int().nonnegative(),
50
+ nextOffset: z.number().int().nonnegative().nullable(),
51
+ entries: z.array(scopeEntrySchema),
52
+ gaps: z.array(z.strictObject({ code: z.string(), reason: z.string() })),
53
+ });
54
+ export class PreparationReadError extends Error {
55
+ code;
56
+ diagnostic;
57
+ constructor(code, diagnostic) {
58
+ super(code);
59
+ this.code = code;
60
+ this.diagnostic = diagnostic;
61
+ }
62
+ }
@@ -0,0 +1,44 @@
1
+ export type LogLevel = 'quiet' | 'info' | 'debug';
2
+ /** Operational records may retain assessment text; diagnostics never receive those bodies. */
3
+ export declare function sanitizeRecord<T>(value: T): T;
4
+ /** Fixed operating-system categories; no paths or exception messages leave the process. */
5
+ export declare function systemFailureDiagnostics(error: unknown): {
6
+ systemCode: string | null;
7
+ };
8
+ export declare class Diagnostics {
9
+ readonly directory: string;
10
+ readonly runId: string;
11
+ readonly level: LogLevel;
12
+ private readonly log;
13
+ private writes;
14
+ private writeFailed;
15
+ constructor(directory: string, runId: string, level: LogLevel, log?: (line: string) => void);
16
+ event(kind: string, data?: Record<string, unknown>): Promise<void>;
17
+ flush(): Promise<void>;
18
+ }
19
+ declare function safeCitationDetails(value: unknown): {
20
+ path: (string | number)[];
21
+ ref: string | null;
22
+ refHash: string | null;
23
+ };
24
+ type SubmissionDiagnostic = {
25
+ code: string;
26
+ details: {
27
+ validation: Array<{
28
+ code: string;
29
+ path: Array<string | number>;
30
+ }>;
31
+ citation?: ReturnType<typeof safeCitationDetails>;
32
+ causes?: string[];
33
+ };
34
+ };
35
+ /** Emit only finite package-owned categories and known schema field names, never rejected content. */
36
+ export declare function submissionDiagnostics(error: unknown): SubmissionDiagnostic;
37
+ /** AI SDK 7 stringifies invalid tool-call errors in step.content; original calls retain structured causes. */
38
+ export declare function submissionToolDiagnostics(toolError: {
39
+ toolCallId: string;
40
+ error: unknown;
41
+ }, toolCalls: ReadonlyArray<{
42
+ toolCallId: string;
43
+ }>): SubmissionDiagnostic;
44
+ export {};