@contextrail/assess 1.0.0-alpha.3 → 1.0.0-alpha.4

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/dist/git.d.ts CHANGED
@@ -10,6 +10,12 @@ export declare function readableDiff(artifact: ReturnType<typeof fixGitIdentity>
10
10
  files: string[];
11
11
  excludedPaths: string[];
12
12
  };
13
+ /**
14
+ * The git executable, resolved once from absolute PATH entries. Spawning the bare name repeats the PATH search
15
+ * on every call, which costs tens of milliseconds per call on some macOS setups. Falls back to the bare name so
16
+ * a missing git still fails at spawn as before.
17
+ */
18
+ export declare function gitExecutable(): string;
13
19
  export declare function passiveGitEnvironment(): NodeJS.ProcessEnv;
14
20
  export type RepositoryEnvironment = {
15
21
  status: 'reported';
package/dist/git.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { execFileSync } from 'node:child_process';
2
- import { realpathSync } from 'node:fs';
2
+ import { accessSync, constants, realpathSync, statSync } from 'node:fs';
3
+ import { delimiter, isAbsolute, join } from 'node:path';
3
4
  export const MAX_PREPARATION_BYTES = 16 * 1024 * 1024;
4
5
  export function sensitiveGitPath(path) {
5
6
  return path
@@ -30,7 +31,7 @@ export function readableDiff(artifact, options = {}) {
30
31
  const remaining = deadline - Date.now();
31
32
  if (remaining <= 0)
32
33
  throw new Error('readable_diff_deadline');
33
- return execFileSync('git', [
34
+ return execFileSync(gitExecutable(), [
34
35
  '--no-pager',
35
36
  '--no-lazy-fetch',
36
37
  '--no-replace-objects',
@@ -85,6 +86,32 @@ export function readableDiff(artifact, options = {}) {
85
86
  const stat = eligible.length ? decode(run([...common, '--stat', ...revisions, '--', ...eligible])) : '';
86
87
  return { patch, stat, files: eligible, excludedPaths: omitted };
87
88
  }
89
+ let resolvedGit;
90
+ /**
91
+ * The git executable, resolved once from absolute PATH entries. Spawning the bare name repeats the PATH search
92
+ * on every call, which costs tens of milliseconds per call on some macOS setups. Falls back to the bare name so
93
+ * a missing git still fails at spawn as before.
94
+ */
95
+ export function gitExecutable() {
96
+ if (resolvedGit)
97
+ return resolvedGit;
98
+ const name = process.platform === 'win32' ? 'git.exe' : 'git';
99
+ for (const directory of (process.env.PATH ?? '').split(delimiter)) {
100
+ const candidate = join(directory, name);
101
+ if (isAbsolute(directory) && executableFile(candidate))
102
+ return (resolvedGit = candidate);
103
+ }
104
+ return 'git';
105
+ }
106
+ function executableFile(path) {
107
+ try {
108
+ accessSync(path, constants.X_OK);
109
+ return statSync(path).isFile();
110
+ }
111
+ catch {
112
+ return false;
113
+ }
114
+ }
88
115
  export function passiveGitEnvironment() {
89
116
  const env = { ...process.env };
90
117
  for (const name of Object.keys(env))
@@ -102,7 +129,7 @@ export function passiveGitEnvironment() {
102
129
  };
103
130
  }
104
131
  function git(repository, args) {
105
- return execFileSync('git', [
132
+ return execFileSync(gitExecutable(), [
106
133
  '--no-pager',
107
134
  '--no-lazy-fetch',
108
135
  '--no-replace-objects',
package/dist/github.js CHANGED
@@ -5,6 +5,7 @@ import { join, resolve } from 'node:path';
5
5
  import { z } from 'zod';
6
6
  import { digest, preparationManifest } from './prepare.js';
7
7
  import { validatePhaseRecord } from './phases.js';
8
+ import { gitExecutable } from './git.js';
8
9
  import { phaseItems } from './change-summary.js';
9
10
  import { revalidateCandidate, validateConcern, projectCandidates } from './candidate.js';
10
11
  import { EvidenceLedger } from './evidence.js';
@@ -73,7 +74,7 @@ function git(repo, args, token) {
73
74
  }
74
75
  : {}),
75
76
  };
76
- const out = spawnSync('git', [
77
+ const out = spawnSync(gitExecutable(), [
77
78
  '--no-pager',
78
79
  '-c',
79
80
  'core.hooksPath=/dev/null',
@@ -462,18 +463,7 @@ function createComparisonCheckout(outputDir, c, token) {
462
463
  export async function prepareGitHubAssessment(options) {
463
464
  const request = githubRequester(options.repository, options.token ?? process.env.GITHUB_TOKEN ?? '', options.fetch);
464
465
  const pr = object(await request(`/pulls/${options.prNumber}`));
465
- const c = githubInputSchema.parse({
466
- version: 1,
467
- repository: options.repository,
468
- pr: options.prNumber,
469
- reviewer: options.reviewer,
470
- base: options.fixed?.base ?? string(object(pr.base).sha),
471
- head: options.fixed?.head ?? string(object(pr.head).sha),
472
- baseBranch: options.baseBranch ?? '',
473
- ...(process.env.GITHUB_RUN_ID
474
- ? { githubRun: process.env.GITHUB_RUN_ID, githubAttempt: Number(process.env.GITHUB_RUN_ATTEMPT ?? 1) }
475
- : {}),
476
- });
466
+ const c = comparisonInput(options, pr);
477
467
  if (!sameComparison(pr, c))
478
468
  fail('ineligible_pr');
479
469
  const { root, repository } = createComparisonCheckout(options.outputDir, c, options.token ?? process.env.GITHUB_TOKEN);
@@ -506,6 +496,21 @@ export async function prepareGitHubAssessment(options) {
506
496
  prContextPath: join(root, 'pr-context.json'),
507
497
  };
508
498
  }
499
+ /** The PR's current base and head unless fixed commits were supplied, plus the Actions run identity. */
500
+ function comparisonInput(options, pr) {
501
+ return githubInputSchema.parse({
502
+ version: 1,
503
+ repository: options.repository,
504
+ pr: options.prNumber,
505
+ reviewer: options.reviewer,
506
+ base: options.fixed?.base ?? string(object(pr.base).sha),
507
+ head: options.fixed?.head ?? string(object(pr.head).sha),
508
+ baseBranch: options.baseBranch ?? '',
509
+ ...(process.env.GITHUB_RUN_ID
510
+ ? { githubRun: process.env.GITHUB_RUN_ID, githubAttempt: Number(process.env.GITHUB_RUN_ATTEMPT ?? 1) }
511
+ : {}),
512
+ });
513
+ }
509
514
  export function parseDiffAnchors(diff) {
510
515
  const anchors = new Map();
511
516
  let oldPath = '', newPath = '', oldLine = 0, newLine = 0, inHunk = false;
@@ -1019,6 +1024,30 @@ function verifyPublishedReaderGuidance(state, handoffs) {
1019
1024
  function verifyCandidateJudgments(runDir, state, handoffs, files) {
1020
1025
  if (!files['evidence.json'])
1021
1026
  fail('publication_evidence_unbound');
1027
+ const ledger = verifiedLedger(runDir, state);
1028
+ if (!Array.isArray(state.observations)) {
1029
+ verifyIncompleteAssessment(state, ledger);
1030
+ return;
1031
+ }
1032
+ const entries = structuredClone(objects(state.entries));
1033
+ const proposals = [...handoffs.proposals.values()].map((proposal) => revalidateCandidate(proposal, entries, ledger));
1034
+ const observations = proposals.flatMap((proposal) => proposal.observations ?? []);
1035
+ if (digest(observations) !== digest(state.observations))
1036
+ fail('publication_observations_changed');
1037
+ const decisions = verifiedDecisions(handoffs, observations, ledger);
1038
+ if (digest(orderedDecisions(decisions)) !== digest(orderedDecisions(state.concernDecisions)))
1039
+ fail('publication_concern_decisions_changed');
1040
+ verifyProjection(state, entries, proposals, decisions);
1041
+ const expected = observations.filter((row) => row.concern).length;
1042
+ const counters = object(state.concernValidation);
1043
+ if (counters.expected !== expected ||
1044
+ counters.validated !== decisions.length ||
1045
+ counters.complete !== (expected === decisions.length))
1046
+ fail('publication_coverage_unverified');
1047
+ verifyChangeSummary(state, handoffs);
1048
+ }
1049
+ /** Every retained evidence record re-adds to the same ref, and source evidence names the artifact's commit. */
1050
+ function verifiedLedger(runDir, state) {
1022
1051
  const ledger = new EvidenceLedger();
1023
1052
  for (const [ref, raw] of Object.entries(object(json(join(runDir, 'evidence.json'))))) {
1024
1053
  const record = raw;
@@ -1030,27 +1059,26 @@ function verifyCandidateJudgments(runDir, state, handoffs, files) {
1030
1059
  record.provenance.commit !== object(object(state.artifact)[string(record.provenance.side)]).commit)
1031
1060
  fail('publication_source_identity_changed');
1032
1061
  }
1033
- if (!Array.isArray(state.observations)) {
1034
- const counts = object(state.concernValidation);
1035
- if (objects(state.entries).some((entry) => object(entry.result).disposition !== 'not_evaluated') ||
1036
- objects(state.findings).length ||
1037
- objects(state.followUps).length ||
1038
- objects(state.concernDecisions).length ||
1039
- counts.expected !== 0 ||
1040
- counts.validated !== 0 ||
1041
- counts.complete !== false)
1042
- fail('publication_incomplete_assessment_changed');
1043
- for (const phase of objects(state.phases).filter((phase) => phase.phase === 'assess')) {
1044
- for (const proposal of objects(object(phase.output).assessments))
1045
- revalidateCandidate(proposal, objects(state.entries), ledger);
1046
- }
1047
- return;
1062
+ return ledger;
1063
+ }
1064
+ /** Without observations nothing may be evaluated or found, yet every retained candidate must still revalidate. */
1065
+ function verifyIncompleteAssessment(state, ledger) {
1066
+ const counts = object(state.concernValidation);
1067
+ if (objects(state.entries).some((entry) => object(entry.result).disposition !== 'not_evaluated') ||
1068
+ objects(state.findings).length ||
1069
+ objects(state.followUps).length ||
1070
+ objects(state.concernDecisions).length ||
1071
+ counts.expected !== 0 ||
1072
+ counts.validated !== 0 ||
1073
+ counts.complete !== false)
1074
+ fail('publication_incomplete_assessment_changed');
1075
+ for (const phase of objects(state.phases).filter((phase) => phase.phase === 'assess')) {
1076
+ for (const proposal of objects(object(phase.output).assessments))
1077
+ revalidateCandidate(proposal, objects(state.entries), ledger);
1048
1078
  }
1049
- const entries = structuredClone(objects(state.entries));
1050
- const proposals = [...handoffs.proposals.values()].map((proposal) => revalidateCandidate(proposal, entries, ledger));
1051
- const observations = proposals.flatMap((proposal) => proposal.observations ?? []);
1052
- if (digest(observations) !== digest(state.observations))
1053
- fail('publication_observations_changed');
1079
+ }
1080
+ /** Re-derive each completed concern decision from its own current, correctly bound verification record. */
1081
+ function verifiedDecisions(handoffs, observations, ledger) {
1054
1082
  const clean = ({ ref, quote, start, end }) => ({ ref, quote, start, end });
1055
1083
  const decisions = [];
1056
1084
  for (const observation of observations.filter((row) => row.concern)) {
@@ -1071,14 +1099,16 @@ function verifyCandidateJudgments(runDir, state, handoffs, files) {
1071
1099
  fail('publication_concern_changed');
1072
1100
  decisions.push(decision);
1073
1101
  }
1074
- const orderedDecisions = (values) => {
1075
- const rows = objects(values);
1076
- if (!Array.isArray(values) || rows.length !== values.length)
1077
- fail('publication_concern_decisions_changed');
1078
- return rows.sort((a, b) => string(a.observationId).localeCompare(string(b.observationId)));
1079
- };
1080
- if (digest(orderedDecisions(decisions)) !== digest(orderedDecisions(state.concernDecisions)))
1102
+ return decisions;
1103
+ }
1104
+ function orderedDecisions(values) {
1105
+ const rows = objects(values);
1106
+ if (!Array.isArray(values) || rows.length !== values.length)
1081
1107
  fail('publication_concern_decisions_changed');
1108
+ return rows.sort((a, b) => string(a.observationId).localeCompare(string(b.observationId)));
1109
+ }
1110
+ /** Re-projecting the verified decisions must reproduce the retained findings, follow-ups and results. */
1111
+ function verifyProjection(state, entries, proposals, decisions) {
1082
1112
  const projected = { entries, checks: [], findings: [], followUps: [] };
1083
1113
  projectCandidates(projected, proposals, decisions);
1084
1114
  if (digest(projected.findings) !== digest(state.findings))
@@ -1092,19 +1122,15 @@ function verifyCandidateJudgments(runDir, state, handoffs, files) {
1092
1122
  digest(entry.result))
1093
1123
  fail('publication_resolution_changed');
1094
1124
  }
1095
- const expected = observations.filter((row) => row.concern).length;
1096
- const counters = object(state.concernValidation);
1097
- if (counters.expected !== expected ||
1098
- counters.validated !== decisions.length ||
1099
- counters.complete !== (expected === decisions.length))
1100
- fail('publication_coverage_unverified');
1125
+ }
1126
+ function verifyChangeSummary(state, handoffs) {
1101
1127
  const summary = object(state.changeSummary);
1102
- if (summary.status === 'verified') {
1103
- const record = handoffs.concernRecords.get('change-summary');
1104
- const output = object(object(record?.output).entries ?? record?.output);
1105
- if (record?.status !== 'complete' || !output.summary || digest(output.summary) !== digest(summary.accepted))
1106
- fail('publication_summary_unverified');
1107
- }
1128
+ if (summary.status !== 'verified')
1129
+ return;
1130
+ const record = handoffs.concernRecords.get('change-summary');
1131
+ const output = object(object(record?.output).entries ?? record?.output);
1132
+ if (record?.status !== 'complete' || !output.summary || digest(output.summary) !== digest(summary.accepted))
1133
+ fail('publication_summary_unverified');
1108
1134
  }
1109
1135
  /** Validate caller-controlled retained records before using their judgments for a privileged write.
1110
1136
  * Hashes detect changed material; they do not authenticate a caller able to replace the whole bundle. */
package/dist/index.d.ts CHANGED
@@ -6,6 +6,7 @@ export { FixedSnapshotSource, DEFAULT_SOURCE_LIMITS, SourceAccessError, type Sou
6
6
  export { runAssessment, DEFAULT_EXECUTION_LIMITS, type ExecutionLimits, type AssessmentState } from './assess.js';
7
7
  export { loadAssessmentCheckpoint, type AssessmentCheckpoint } from './resume.js';
8
8
  export { assessmentModel, type ProviderConfiguration, type AssessmentProvider } from './providers.js';
9
+ export { PROVIDER_SPEEDS, type ProviderSpeed } from './speed.js';
9
10
  export { decideExit, DEFAULT_POLICY, type AssessmentPolicy, type AcceptedResult } from './results.js';
10
11
  export { projectAssessmentReport, sendAssessmentReport, type ReportingStatus, type AssessmentFeedbackSender, } from './feedback.js';
11
12
  export { reviewReportInputSchema, type ReviewReportInput, type ReviewReportReceipt } from './report-contract.js';
package/dist/index.js CHANGED
@@ -6,6 +6,7 @@ export { FixedSnapshotSource, DEFAULT_SOURCE_LIMITS, SourceAccessError, } from '
6
6
  export { runAssessment, DEFAULT_EXECUTION_LIMITS } from './assess.js';
7
7
  export { loadAssessmentCheckpoint } from './resume.js';
8
8
  export { assessmentModel } from './providers.js';
9
+ export { PROVIDER_SPEEDS } from './speed.js';
9
10
  export { decideExit, DEFAULT_POLICY } from './results.js';
10
11
  export { projectAssessmentReport, sendAssessmentReport, } from './feedback.js';
11
12
  export { reviewReportInputSchema } from './report-contract.js';
package/dist/mcp.d.ts CHANGED
@@ -22,6 +22,8 @@ export declare class McpPublishedReader implements PublishedReader {
22
22
  read(name: Parameters<PublishedReader['read']>[0], args: Record<string, unknown>): Promise<unknown>;
23
23
  submitReport(report: ReviewReportInput): Promise<unknown>;
24
24
  private call;
25
+ /** Repository attribution only when enabled; the harness is named and the model is never exposed. */
26
+ private environment;
25
27
  close(): Promise<void>;
26
28
  }
27
29
  /** Only controlled categories, numeric HTTP/RPC codes and recognized SDK codes survive. */
package/dist/mcp.js CHANGED
@@ -68,22 +68,10 @@ export class McpPublishedReader {
68
68
  this.responseStatus = undefined;
69
69
  const result = await this.client.callTool({
70
70
  name,
71
- arguments: {
72
- ...args,
73
- environment: {
74
- repository: this.options.repositoryAttribution
75
- ? this.repository
76
- : { status: 'unavailable', reason: 'withheld' },
77
- harness: { status: 'reported', name: 'contextrail-assess' },
78
- model: { status: 'unavailable', reason: 'not_exposed' },
79
- },
80
- },
71
+ arguments: { ...args, environment: this.environment() },
81
72
  }, requestOptions());
82
73
  if (result.isError) {
83
- const error = result.structuredContent?.error;
84
- const code = typeof error?.code === 'string' && /^[a-z_]{3,80}$/u.test(error.code)
85
- ? error.code
86
- : 'mcp_read_rejected';
74
+ const code = toolErrorCode(result.structuredContent);
87
75
  throw new PreparationReadError(code, { phase, category: serviceCategory(code) });
88
76
  }
89
77
  phase = 'decode';
@@ -97,10 +85,25 @@ export class McpPublishedReader {
97
85
  throw safeReadFailure(error, phase, this.options.signal?.aborted, this.responseStatus);
98
86
  }
99
87
  }
88
+ /** Repository attribution only when enabled; the harness is named and the model is never exposed. */
89
+ environment() {
90
+ return {
91
+ repository: this.options.repositoryAttribution
92
+ ? this.repository
93
+ : { status: 'unavailable', reason: 'withheld' },
94
+ harness: { status: 'reported', name: 'contextrail-assess' },
95
+ model: { status: 'unavailable', reason: 'not_exposed' },
96
+ };
97
+ }
100
98
  async close() {
101
99
  await this.client.close().catch(() => undefined);
102
100
  }
103
101
  }
102
+ /** A service error code passes through only in the expected snake_case shape. */
103
+ function toolErrorCode(structuredContent) {
104
+ const error = structuredContent?.error;
105
+ return typeof error?.code === 'string' && /^[a-z_]{3,80}$/u.test(error.code) ? error.code : 'mcp_read_rejected';
106
+ }
104
107
  function serviceCategory(code) {
105
108
  if (['graph_node_not_found', 'graph_node_unpublished', 'graph_node_published_version_missing'].includes(code))
106
109
  return 'missing_publication';
@@ -117,32 +120,44 @@ function serviceCategory(code) {
117
120
  }
118
121
  /** Only controlled categories, numeric HTTP/RPC codes and recognized SDK codes survive. */
119
122
  export function safeReadFailure(error, phase, cancelled = false, responseStatus) {
120
- const source = error && typeof error === 'object'
121
- ? error
122
- : {};
123
+ const source = error && typeof error === 'object' ? error : {};
124
+ const status = httpStatus(source, responseStatus);
125
+ const upstreamCode = recognizedUpstreamCode(source.code);
126
+ return new PreparationReadError(failureCode(source, status, cancelled, hasInvalidResponseCause(error)), {
127
+ phase,
128
+ ...(status ? { status } : {}),
129
+ ...(upstreamCode !== undefined ? { upstreamCode } : {}),
130
+ });
131
+ }
132
+ const SDK_CODES = [
133
+ 'REQUEST_TIMEOUT',
134
+ 'CLIENT_HTTP_AUTHENTICATION',
135
+ 'CLIENT_HTTP_FORBIDDEN',
136
+ 'CLIENT_HTTP_NOT_IMPLEMENTED',
137
+ 'CLIENT_HTTP_UNEXPECTED_CONTENT',
138
+ 'INVALID_RESULT',
139
+ 'CONNECTION_CLOSED',
140
+ 'ERA_NEGOTIATION_FAILED',
141
+ ];
142
+ /** The error's own HTTP status, or the transport's when it is an error status. */
143
+ function httpStatus(source, responseStatus) {
123
144
  const statusValue = source.status ?? source.data?.status ?? (responseStatus && responseStatus >= 400 ? responseStatus : undefined);
124
- const status = typeof statusValue === 'number' && Number.isInteger(statusValue) && statusValue >= 100 && statusValue <= 599
145
+ return typeof statusValue === 'number' && Number.isInteger(statusValue) && statusValue >= 100 && statusValue <= 599
125
146
  ? statusValue
126
147
  : undefined;
127
- const sdkCodes = [
128
- 'REQUEST_TIMEOUT',
129
- 'CLIENT_HTTP_AUTHENTICATION',
130
- 'CLIENT_HTTP_FORBIDDEN',
131
- 'CLIENT_HTTP_NOT_IMPLEMENTED',
132
- 'CLIENT_HTTP_UNEXPECTED_CONTENT',
133
- 'INVALID_RESULT',
134
- 'CONNECTION_CLOSED',
135
- 'ERA_NEGOTIATION_FAILED',
136
- ];
137
- const upstreamCode = (typeof source.code === 'string' && sdkCodes.includes(source.code)) ||
138
- (typeof source.code === 'number' &&
139
- Number.isInteger(source.code) &&
140
- source.code >= -32768 &&
141
- source.code <= 32767)
142
- ? source.code
143
- : undefined;
144
- let cause = error;
148
+ }
149
+ /** A recognized SDK code or a JSON-RPC-sized integer code; anything else is dropped. */
150
+ function recognizedUpstreamCode(code) {
151
+ if (typeof code === 'string' && SDK_CODES.includes(code))
152
+ return code;
153
+ if (typeof code === 'number' && Number.isInteger(code) && code >= -32768 && code <= 32767)
154
+ return code;
155
+ return undefined;
156
+ }
157
+ /** A parse or schema failure anywhere in the first four causes means the response itself was invalid. */
158
+ function hasInvalidResponseCause(error) {
145
159
  let invalidResponse = false;
160
+ let cause = error;
146
161
  for (let depth = 0; depth < 4 && cause && typeof cause === 'object'; depth++) {
147
162
  const nested = cause;
148
163
  if (['SyntaxError', 'ZodError'].includes(String(nested.name)) ||
@@ -150,24 +165,20 @@ export function safeReadFailure(error, phase, cancelled = false, responseStatus)
150
165
  invalidResponse = true;
151
166
  cause = nested.cause;
152
167
  }
153
- const code = cancelled || source.name === 'AbortError'
154
- ? 'mcp_cancelled'
155
- : source.name === 'TimeoutError' || source.code === 'REQUEST_TIMEOUT'
156
- ? 'mcp_timeout'
157
- : status === 401 || source.code === 'CLIENT_HTTP_AUTHENTICATION'
158
- ? 'mcp_authentication_failed'
159
- : status === 403 || source.code === 'CLIENT_HTTP_FORBIDDEN'
160
- ? 'mcp_authorization_failed'
161
- : status
162
- ? 'mcp_http_failed'
163
- : invalidResponse || source.code === -32700
164
- ? 'invalid_mcp_response'
165
- : typeof source.code === 'number'
166
- ? 'mcp_provider_failed'
167
- : 'mcp_transport_failed';
168
- return new PreparationReadError(code, {
169
- phase,
170
- ...(status ? { status } : {}),
171
- ...(upstreamCode !== undefined ? { upstreamCode } : {}),
172
- });
168
+ return invalidResponse;
169
+ }
170
+ function failureCode(source, status, cancelled, invalidResponse) {
171
+ if (cancelled || source.name === 'AbortError')
172
+ return 'mcp_cancelled';
173
+ if (source.name === 'TimeoutError' || source.code === 'REQUEST_TIMEOUT')
174
+ return 'mcp_timeout';
175
+ if (status === 401 || source.code === 'CLIENT_HTTP_AUTHENTICATION')
176
+ return 'mcp_authentication_failed';
177
+ if (status === 403 || source.code === 'CLIENT_HTTP_FORBIDDEN')
178
+ return 'mcp_authorization_failed';
179
+ if (status)
180
+ return 'mcp_http_failed';
181
+ if (invalidResponse || source.code === -32700)
182
+ return 'invalid_mcp_response';
183
+ return typeof source.code === 'number' ? 'mcp_provider_failed' : 'mcp_transport_failed';
173
184
  }
package/dist/pack.js CHANGED
@@ -362,10 +362,17 @@ function splitsSurrogate(text, offset) {
362
362
  text.charCodeAt(offset - 1) >= 0xd800 &&
363
363
  text.charCodeAt(offset - 1) <= 0xdbff);
364
364
  }
365
+ function utf8ByteLength(codePoint) {
366
+ if (codePoint <= 0x7f)
367
+ return 1;
368
+ if (codePoint <= 0x7ff)
369
+ return 2;
370
+ return codePoint <= 0xffff ? 3 : 4;
371
+ }
365
372
  function boundedEnd(text, start, maxBytes, maxSegments) {
366
373
  let end = start, bytes = 0, segments = 0;
367
374
  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;
375
+ const point = text.codePointAt(end), crlf = point === 13 && text.charCodeAt(end + 1) === 10, size = crlf ? 2 : utf8ByteLength(point);
369
376
  if (bytes + size > maxBytes)
370
377
  break;
371
378
  bytes += size;
@@ -140,23 +140,10 @@ export function parsePrContext(value, artifact, reviewer) {
140
140
  if (Buffer.byteLength(JSON.stringify(value)) > MAX_PR_CONTEXT_BYTES)
141
141
  throw new Error();
142
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
143
  const repository = artifact.repositoryEnvironment;
157
- if (repository.status === 'reported' &&
158
- (repository.provider !== 'github.com' ||
159
- context.repository.toLowerCase() !== `${repository.owner}/${repository.name}`.toLowerCase()))
144
+ if (!bindsArtifact(context, artifact, reviewer) ||
145
+ !discussionStaysOnPr(context) ||
146
+ !matchesReportedRepository(context, repository))
160
147
  throw new Error();
161
148
  if (repository.status !== 'reported' &&
162
149
  !context.limitations.includes('Repository origin unavailable; PR identity is reported, not independently bound.'))
@@ -170,6 +157,29 @@ export function parsePrContext(value, artifact, reviewer) {
170
157
  throw new Error('invalid_pr_context');
171
158
  }
172
159
  }
160
+ /** The context describes this exact comparison and reviewer, and any observed checks ran on its head. */
161
+ function bindsArtifact(context, artifact, reviewer) {
162
+ return (context.comparison.base === artifact.base.commit &&
163
+ context.comparison.head === artifact.head.commit &&
164
+ context.reviewer === reviewer &&
165
+ !(context.version === 2 &&
166
+ context.observedChecks !== undefined &&
167
+ context.observedChecks.head !== context.comparison.head));
168
+ }
169
+ /** Discussion links point only at this PR's own pull or issue page, without query strings. */
170
+ function discussionStaysOnPr(context) {
171
+ const pages = [`/${context.repository}/pull/${context.pr}`, `/${context.repository}/issues/${context.pr}`];
172
+ return context.discussion.items.every((item) => {
173
+ const url = new URL(item.url);
174
+ return !url.search && pages.includes(url.pathname);
175
+ });
176
+ }
177
+ /** A reported repository origin must be this GitHub repository. */
178
+ function matchesReportedRepository(context, repository) {
179
+ return (repository.status !== 'reported' ||
180
+ (repository.provider === 'github.com' &&
181
+ context.repository.toLowerCase() === `${repository.owner}/${repository.name}`.toLowerCase()));
182
+ }
173
183
  export function loadPrContext(file, artifact, reviewer) {
174
184
  let fd;
175
185
  try {