@bendyline/gezel-sdk 1.1.18 → 1.1.19

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/checks.d.ts CHANGED
@@ -941,6 +941,131 @@ declare function mergeCorpusCoverageShards(batchesContent: string, shards: reado
941
941
  batchesFile?: string;
942
942
  }): CorpusCoverageMergeResult;
943
943
 
944
+ /**
945
+ * The pull-request review's shared rules: how a patch record numbers its
946
+ * lines, what a numbered finding may say, how a reviewer's cross-file
947
+ * questions are validated, and which changed files are generated.
948
+ *
949
+ * One owner because three readers must agree: the connector that writes the
950
+ * records, the gate that judges a reviewer's observations, and the stdlib
951
+ * script that indexes them for the final report. They did not (2026-11-17,
952
+ * a 57-file pull request on a 27B local model): the gate rejected one correct
953
+ * finding three times for the phrase "If `vsce` fails" while its message
954
+ * blamed the line number, the reviewer spent its turns counting diff lines by
955
+ * hand to produce that number, and a second copy of the same pattern in the
956
+ * summary script would have dropped the finding from the report had it ever
957
+ * passed. One batch of fifteen finished in 96 minutes.
958
+ */
959
+ /**
960
+ * Shown above a numbered patch, and what marks a record as numbered: a reader
961
+ * that finds this sentence strips the number column before reading the diff.
962
+ * It describes and never instructs, because a record is content from outside;
963
+ * how to cite a line is the step prompt's to say.
964
+ */
965
+ declare const PATCH_LINE_LEGEND = "Each patch line starts with its line number in the new file, then the diff marker (`+` added, `-` removed, space unchanged). A removed line has no number.";
966
+ interface PatchLine {
967
+ kind: 'add' | 'remove' | 'context';
968
+ /** Line number in the new file. A removed line has none. */
969
+ newLine?: number;
970
+ /** The line's own text, without its diff marker. */
971
+ text: string;
972
+ }
973
+ interface ParsedPatchRecord {
974
+ lines: PatchLine[];
975
+ /** Every new-file line number the patch shows, added or unchanged. */
976
+ newLines: Set<number>;
977
+ }
978
+ /**
979
+ * Put each line's new-file number in front of it. A reviewer cites
980
+ * `path:line`, and a raw unified diff states that number only once per hunk:
981
+ * left to derive the rest, a model lists the hunk line by line and counts.
982
+ */
983
+ declare function numberUnifiedPatch(patch: string): string;
984
+ /**
985
+ * Read the patch out of a changed-file record, numbered or not. A record
986
+ * written before patches were numbered still yields its line numbers, worked
987
+ * out from the hunk headers. Null when the record carries no patch.
988
+ */
989
+ declare function parsePatchRecord(record: string): ParsedPatchRecord | null;
990
+ /** `6-12, 19-36, 83` — the lines a patch shows, short enough to put in a message. */
991
+ declare function formatLineRanges(lines: ReadonlySet<number>, limit?: number): string;
992
+ interface PrFindingBlock {
993
+ batch: number;
994
+ id: string;
995
+ text: string;
996
+ }
997
+ /**
998
+ * Models write a numbered finding plain, bold, as a heading, a bullet, or a
999
+ * table row. Matching only `B1-1:` let `**B1-1** ...` and `B1-1 | ...` pass
1000
+ * every check unread.
1001
+ */
1002
+ declare const PR_FINDING_START_RE: RegExp;
1003
+ declare function prFindingBlocks(text: string): PrFindingBlock[];
1004
+ interface PrFindingWordingProblem {
1005
+ /** `not-a-defect`: the finding says so itself. `hedge`: it is unsure of its own mechanism. */
1006
+ kind: 'not-a-defect' | 'hedge';
1007
+ /** The exact words matched, so a rejection can quote them. */
1008
+ phrase: string;
1009
+ }
1010
+ /**
1011
+ * What a numbered finding says that a proved defect would not. Read from the
1012
+ * prose only: a quoted comment or a shell snippet holds words like "may" and
1013
+ * "if this fails" that are the code's, not the reviewer's.
1014
+ *
1015
+ * Deliberately absent: a conditional ("if the publish fails, the step still
1016
+ * exits 0" is how an error-handling defect is stated), and the topic words
1017
+ * `comment`, `documentation` and `verify`, which a finding about a doc file or
1018
+ * a missing signature check cannot avoid.
1019
+ */
1020
+ declare function prFindingWordingProblem(text: string): PrFindingWordingProblem | null;
1021
+ interface PrVerificationCandidate {
1022
+ id: string;
1023
+ path: string;
1024
+ line: number;
1025
+ severity: 'critical' | 'major' | 'minor' | 'nit';
1026
+ claim: string;
1027
+ verify: string;
1028
+ }
1029
+ /** The length a reviewer is asked to keep a claim or a verification target under. */
1030
+ declare const PR_CANDIDATE_TEXT_LIMIT = 400;
1031
+ /**
1032
+ * Pull a batch's cross-file questions out of their Markdown wrapper. A
1033
+ * B-number is a defect the batch can already prove; a V-number is a bounded
1034
+ * question the checkout-aware final reviewer still has to resolve. Every
1035
+ * problem names the entry and the field, with the value that was wrong.
1036
+ */
1037
+ declare function parsePrVerificationCandidates(text: string, batch: number, assignedPaths: readonly string[]): {
1038
+ candidates: PrVerificationCandidate[];
1039
+ problems: string[];
1040
+ };
1041
+ type GeneratedFileKind = 'lockfile' | 'third-party-notices';
1042
+ /**
1043
+ * A changed file a tool wrote and a person does not read line by line. Kept
1044
+ * narrow on purpose: these get a summary instead of a reviewer, so a file
1045
+ * wrongly named here goes unread. On the pull request that prompted this, one
1046
+ * lockfile and seven notices files were 49% of the patch text.
1047
+ */
1048
+ declare function generatedFileKind(path: string): GeneratedFileKind | null;
1049
+ interface GeneratedBatchFile {
1050
+ path: string;
1051
+ kind: GeneratedFileKind;
1052
+ /** The file's record text; null when it could not be read. */
1053
+ record: string | null;
1054
+ }
1055
+ /**
1056
+ * The observations file for a batch of generated files, written by the
1057
+ * runtime in the shape a reviewer's batch has, so coverage and synthesis
1058
+ * treat it like any other. A lockfile that resolves a package from somewhere
1059
+ * other than the public registry becomes a question for the final reviewer:
1060
+ * that is the one thing in these files a read by a model was looking for.
1061
+ */
1062
+ declare function generatedBatchObservations(batch: {
1063
+ batchNumber: number;
1064
+ start: number;
1065
+ end: number;
1066
+ files: readonly GeneratedBatchFile[];
1067
+ }): string;
1068
+
944
1069
  /**
945
1070
  * `@bendyline/gezel-sdk/checks` — the shared deliverable-check predicates,
946
1071
  * re-exported for use INSIDE sandboxed scripts.
@@ -979,4 +1104,4 @@ declare function workspaceFromGezel(g: {
979
1104
  };
980
1105
  }): WorkspaceLike;
981
1106
 
982
- export { type CellType, type CheckResult, type CitationsResult, type ClaimsGroundedOptions, type ClaimsGroundedResult, type CodebaseReviewReportOptions, type CodebaseReviewReportResult, type CorpusCoverageLedger, type CorpusCoverageMergeResult, type CorpusCoverageShardInput, type CsvShapeResult, type CsvShapeSpec, type EntitiesResult, type EntitySpec, type ExplainableSniff, type FigureCheckOptions, type FigureCheckResult, type FigureFinding, type FigureFindingKind, GateScriptResult, type GroundingFact, type GroundingResult, IMG_EXT, type ImageRefsReport, type InlineScript, type JsonPathEqualsResult, type JsonScalar, type JudgeVerdict, MIN_INLINE_JS_BYTES, MIN_JUDGE_EVIDENCE_SUBSTRING, type MarkdownHeadingsMatchResult, type ParsedTable, type PlanRow, type PlanStructureResult, type PlanStructureSpec, type ReadingLevelResult, type RecordFieldSpec, type RecordSchemaResult, type RecordSchemaSpec, type ScriptValidation, type SecurityReportOptions, type SecurityReportResult, type StepSniffName, type TableShapeResult, type TableShapeSpec, type UnsupportedClaimPattern, type UnsupportedClaimViolation, type UnsupportedClaimsResult, type ValuesSubsetResult, type ValuesSubsetSpec, type WordBandResult, type WorkspaceLike, buildJudgePrompt, checkFigures, citationsResolve, citedPathKey, claimsGrounded, cleanCitedPath, codebaseReviewReport, containsPattern, countDistinctMatches, createCitedPathChecker, cssMinBytes, csvShape, dataTableSniff, detectTypeScriptOnlySyntax, detectUnclosedScript, esmImports, explainSniff, extractInlineScripts, extractMoneyAmounts, fileCountByExt, fileMinBytes, fileMinLines, findImageRefs, frontmatterList, gateResult, grepMatches, htmlCompleteSniff, htmlGameSniff, imageRefsResolve, inlineJsBytes, isRealIsoDate, jsonPathEquals, jsonValid, listedFiles, markdownHeadingsMatch, mergeCorpusCoverageShards, namedEntitiesConsistent, normalizeDigitGroups, normalizeInlineEmphasis, normalizeTypography, notContainsPattern, parseCsv, parseJudgeVerdict, parseMarkdownTable, planStructure, readingLevel, recordSchema, requireOrderedSections, resolveRelative, runSniff, securityReport, sourceListReferences, standaloneJsParses, tableShape, totalMinBytes, unsupportedClaims, validateJudgeEvidence, validateScriptSyntax, valueGrounding, valuesSubsetOf, wordBand, workspaceFromGezel, wrapperReturnHint };
1107
+ export { type CellType, type CheckResult, type CitationsResult, type ClaimsGroundedOptions, type ClaimsGroundedResult, type CodebaseReviewReportOptions, type CodebaseReviewReportResult, type CorpusCoverageLedger, type CorpusCoverageMergeResult, type CorpusCoverageShardInput, type CsvShapeResult, type CsvShapeSpec, type EntitiesResult, type EntitySpec, type ExplainableSniff, type FigureCheckOptions, type FigureCheckResult, type FigureFinding, type FigureFindingKind, GateScriptResult, type GeneratedBatchFile, type GeneratedFileKind, type GroundingFact, type GroundingResult, IMG_EXT, type ImageRefsReport, type InlineScript, type JsonPathEqualsResult, type JsonScalar, type JudgeVerdict, MIN_INLINE_JS_BYTES, MIN_JUDGE_EVIDENCE_SUBSTRING, type MarkdownHeadingsMatchResult, PATCH_LINE_LEGEND, PR_CANDIDATE_TEXT_LIMIT, PR_FINDING_START_RE, type ParsedPatchRecord, type ParsedTable, type PatchLine, type PlanRow, type PlanStructureResult, type PlanStructureSpec, type PrFindingBlock, type PrFindingWordingProblem, type PrVerificationCandidate, type ReadingLevelResult, type RecordFieldSpec, type RecordSchemaResult, type RecordSchemaSpec, type ScriptValidation, type SecurityReportOptions, type SecurityReportResult, type StepSniffName, type TableShapeResult, type TableShapeSpec, type UnsupportedClaimPattern, type UnsupportedClaimViolation, type UnsupportedClaimsResult, type ValuesSubsetResult, type ValuesSubsetSpec, type WordBandResult, type WorkspaceLike, buildJudgePrompt, checkFigures, citationsResolve, citedPathKey, claimsGrounded, cleanCitedPath, codebaseReviewReport, containsPattern, countDistinctMatches, createCitedPathChecker, cssMinBytes, csvShape, dataTableSniff, detectTypeScriptOnlySyntax, detectUnclosedScript, esmImports, explainSniff, extractInlineScripts, extractMoneyAmounts, fileCountByExt, fileMinBytes, fileMinLines, findImageRefs, formatLineRanges, frontmatterList, gateResult, generatedBatchObservations, generatedFileKind, grepMatches, htmlCompleteSniff, htmlGameSniff, imageRefsResolve, inlineJsBytes, isRealIsoDate, jsonPathEquals, jsonValid, listedFiles, markdownHeadingsMatch, mergeCorpusCoverageShards, namedEntitiesConsistent, normalizeDigitGroups, normalizeInlineEmphasis, normalizeTypography, notContainsPattern, numberUnifiedPatch, parseCsv, parseJudgeVerdict, parseMarkdownTable, parsePatchRecord, parsePrVerificationCandidates, planStructure, prFindingBlocks, prFindingWordingProblem, readingLevel, recordSchema, requireOrderedSections, resolveRelative, runSniff, securityReport, sourceListReferences, standaloneJsParses, tableShape, totalMinBytes, unsupportedClaims, validateJudgeEvidence, validateScriptSyntax, valueGrounding, valuesSubsetOf, wordBand, workspaceFromGezel, wrapperReturnHint };
package/dist/checks.js CHANGED
@@ -770,8 +770,22 @@ function isEnumerator(before, after, value) {
770
770
  if (ENUMERATOR_LABEL.test(before)) return true;
771
771
  return value < 100 && /^[\s*_#>-]*$/.test(before) && /^[.)](?:\s|\*|$)/.test(after);
772
772
  }
773
- function extractClaims(text) {
774
- const sentence = text.replace(/`[^`]*`/g, " ").replace(/\]\([^)]*\)/g, "]").replace(/\bhttps?:\/\/\S+/g, " ").replace(ATTRIBUTION_PARENTHETICAL, " ").replace(FILE_REFERENCE, " ");
773
+ var LINE_SPAN = String.raw`[~≈]?\d+(?:\s*(?:[-–—]|to|through)\s*[~≈]?\d+)?`;
774
+ var LINE_LOCATORS = [
775
+ /@@\s*-\d+(?:,\d+)?\s+\+\d+(?:,\d+)?(?:\s*@@)?/g,
776
+ /(?<![\w./-])(?:[\w.@+-]+\/)*[\w@+-][\w.@+-]*\.[A-Za-z]\w*:\d+(?:[-–]\d+|:\d+)*/g,
777
+ /(?<![\w./-])(?:[\w.@+-]+\/)+[A-Za-z_][\w.@+-]*:\d+(?:[-–]\d+|:\d+)*/g,
778
+ new RegExp(
779
+ String.raw`\blines\s+${LINE_SPAN}(?:\s*(?:,\s*(?:and\s+)?|and\s+|&\s*)${LINE_SPAN})*`,
780
+ "gi"
781
+ ),
782
+ /\bline\s+[~≈]?\d+(?:\s*[-–—]\s*\d+)?/gi,
783
+ /(?<!\w)L\d+(?:[-–]L?\d+)?\b/g
784
+ ];
785
+ function extractClaims(text, options = {}) {
786
+ const referenced = text.replace(/`[^`]*`/g, " ").replace(/\]\([^)]*\)/g, "]").replace(/\bhttps?:\/\/\S+/g, " ").replace(ATTRIBUTION_PARENTHETICAL, " ").replace(FILE_REFERENCE, " ");
787
+ const sentence = options.lineLocators === false ? LINE_LOCATORS.reduce((rest, locator) => rest.replace(locator, " "), referenced) : referenced;
788
+ const checkQuotes = options.quotes !== false;
775
789
  const claims = [];
776
790
  const seen = /* @__PURE__ */ new Set();
777
791
  const add = (kind, value, flags = {}) => {
@@ -788,8 +802,10 @@ function extractClaims(text) {
788
802
  });
789
803
  }
790
804
  };
791
- for (const m of sentence.matchAll(/["“]([^"”]{8,}?)["”]/g)) {
792
- if ((m[1] ?? "").trim().split(/\s+/).length >= 3) add("quote", (m[1] ?? "").trim());
805
+ if (checkQuotes) {
806
+ for (const m of sentence.matchAll(/["“]([^"”]{8,}?)["”]/g)) {
807
+ if ((m[1] ?? "").trim().split(/\s+/).length >= 3) add("quote", (m[1] ?? "").trim());
808
+ }
793
809
  }
794
810
  const unquoted = sentence.replace(/["“][^"”]*["”]/g, " ");
795
811
  for (const m of unquoted.matchAll(CLOCK_TIME)) add("number", m[1] ?? "", { clock: true });
@@ -994,6 +1010,7 @@ function groundContext(evidence, options) {
994
1010
  sources: [...normalized.values(), ...given ? [given] : []],
995
1011
  given,
996
1012
  names: options.names ?? true,
1013
+ claims: { quotes: options.quotes ?? true, lineLocators: options.lineLocators ?? true },
997
1014
  ...options.opaque ? { opaque: options.opaque } : {}
998
1015
  };
999
1016
  }
@@ -1037,7 +1054,9 @@ function groundWith(ctx, sentence) {
1037
1054
  if (sentence.cites.length === 0 && DISCLAIMS.test(sentence.text)) {
1038
1055
  return { ...sentence, status: "non-factual", checks: [], missing: [] };
1039
1056
  }
1040
- const claims = extractClaims(sentence.text).filter((c) => ctx.names || c.kind !== "name");
1057
+ const claims = extractClaims(sentence.text, ctx.claims).filter(
1058
+ (c) => ctx.names || c.kind !== "name"
1059
+ );
1041
1060
  const opaque = sentence.cites.filter((n) => !ctx.evidence.has(n) && ctx.opaque?.(n));
1042
1061
  const badCites = sentence.cites.filter((n) => !ctx.evidence.has(n) && !opaque.includes(n));
1043
1062
  if (badCites.length > 0) {
@@ -1757,7 +1776,8 @@ async function notContainsPattern(ws, file, pattern, flags, label) {
1757
1776
  }
1758
1777
  const match = re.exec(content);
1759
1778
  const target = label ? `: ${label}` : ` /${pattern}/`;
1760
- const matchedText = match?.[0]?.replace(/\s+/g, " ").slice(0, 180);
1779
+ const whole = match?.[0]?.replace(/\s+/g, " ");
1780
+ const matchedText = whole && whole.length > 180 ? `${whole.slice(0, 60)} \u2026 ${whole.slice(-110)}` : whole;
1761
1781
  const matchedSuffix = label && matchedText ? ` (matched "${matchedText}")` : "";
1762
1782
  return match ? { ok: false, detail: `${file} contains forbidden content${target}${matchedSuffix}` } : { ok: true, detail: `${file} excludes forbidden content${target}` };
1763
1783
  }
@@ -3710,6 +3730,376 @@ function mergeCorpusCoverageShards(batchesContent, shards, opts = {}) {
3710
3730
  };
3711
3731
  }
3712
3732
 
3733
+ // ../core/src/checks/pr-review.ts
3734
+ var HUNK_HEADER_RE = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
3735
+ var PATCH_LINE_LEGEND = "Each patch line starts with its line number in the new file, then the diff marker (`+` added, `-` removed, space unchanged). A removed line has no number.";
3736
+ function numberColumnWidth(lines) {
3737
+ let last = 0;
3738
+ for (const line of lines) {
3739
+ const header = HUNK_HEADER_RE.exec(line);
3740
+ if (!header) continue;
3741
+ const count = header[4] === void 0 ? 1 : Number(header[4]);
3742
+ if (count > 0) last = Math.max(last, Number(header[3]) + count - 1);
3743
+ }
3744
+ return last > 0 ? String(last).length : 0;
3745
+ }
3746
+ function walkPatch(lines, numberedWidth) {
3747
+ const slots = [];
3748
+ let oldLeft = 0;
3749
+ let newLeft = 0;
3750
+ let next = 0;
3751
+ let inHunk = false;
3752
+ for (let index = 0; index < lines.length; index++) {
3753
+ const line = lines[index];
3754
+ const header = HUNK_HEADER_RE.exec(line);
3755
+ if (header) {
3756
+ oldLeft = header[2] === void 0 ? 1 : Number(header[2]);
3757
+ newLeft = header[4] === void 0 ? 1 : Number(header[4]);
3758
+ next = Number(header[3]);
3759
+ inHunk = true;
3760
+ slots.push(null);
3761
+ continue;
3762
+ }
3763
+ if (!inHunk || index === lines.length - 1 && line === "") {
3764
+ slots.push(null);
3765
+ continue;
3766
+ }
3767
+ const raw = numberedWidth > 0 ? line.slice(numberedWidth + 1) : line;
3768
+ if (raw.startsWith("\\")) {
3769
+ slots.push({ kind: "meta", raw });
3770
+ continue;
3771
+ }
3772
+ if (oldLeft <= 0 && newLeft <= 0) {
3773
+ inHunk = false;
3774
+ slots.push(null);
3775
+ continue;
3776
+ }
3777
+ if (raw.startsWith("+")) {
3778
+ slots.push({ kind: "add", newLine: next, raw });
3779
+ next += 1;
3780
+ newLeft -= 1;
3781
+ } else if (raw.startsWith("-")) {
3782
+ slots.push({ kind: "remove", raw });
3783
+ oldLeft -= 1;
3784
+ } else {
3785
+ slots.push({ kind: "context", newLine: next, raw });
3786
+ next += 1;
3787
+ newLeft -= 1;
3788
+ oldLeft -= 1;
3789
+ }
3790
+ }
3791
+ return slots;
3792
+ }
3793
+ function numberUnifiedPatch(patch) {
3794
+ const lines = patch.split("\n");
3795
+ const width = numberColumnWidth(lines);
3796
+ if (width === 0) return patch;
3797
+ const blank = " ".repeat(width);
3798
+ const slots = walkPatch(lines, 0);
3799
+ return lines.map((line, index) => {
3800
+ const slot = slots[index];
3801
+ if (!slot) return line;
3802
+ const column = slot.newLine === void 0 ? blank : String(slot.newLine).padStart(width);
3803
+ return `${column} ${line}`;
3804
+ }).join("\n");
3805
+ }
3806
+ function parsePatchRecord(record) {
3807
+ const all = record.split(/\r?\n/);
3808
+ const open = all.indexOf("```diff");
3809
+ if (open < 0) return null;
3810
+ const close = all.lastIndexOf("```");
3811
+ const body = all.slice(open + 1, close > open ? close : all.length);
3812
+ const width = record.includes(PATCH_LINE_LEGEND) ? numberColumnWidth(body) : 0;
3813
+ const lines = [];
3814
+ const newLines = /* @__PURE__ */ new Set();
3815
+ for (const slot of walkPatch(body, width)) {
3816
+ if (!slot || slot.kind === "meta") continue;
3817
+ lines.push({
3818
+ kind: slot.kind,
3819
+ ...slot.newLine !== void 0 ? { newLine: slot.newLine } : {},
3820
+ text: slot.raw.slice(1)
3821
+ });
3822
+ if (slot.newLine !== void 0) newLines.add(slot.newLine);
3823
+ }
3824
+ return { lines, newLines };
3825
+ }
3826
+ function formatLineRanges(lines, limit = 8) {
3827
+ const sorted = [...lines].sort((a, b) => a - b);
3828
+ const ranges = [];
3829
+ let start = sorted[0];
3830
+ let previous = sorted[0];
3831
+ const close = () => {
3832
+ if (start === void 0 || previous === void 0) return;
3833
+ ranges.push(start === previous ? String(start) : `${start}-${previous}`);
3834
+ };
3835
+ for (const line of sorted.slice(1)) {
3836
+ if (previous !== void 0 && line === previous + 1) {
3837
+ previous = line;
3838
+ continue;
3839
+ }
3840
+ close();
3841
+ start = line;
3842
+ previous = line;
3843
+ }
3844
+ close();
3845
+ return ranges.length > limit ? `${ranges.slice(0, limit).join(", ")} and ${ranges.length - limit} more range(s)` : ranges.join(", ");
3846
+ }
3847
+ var PR_FINDING_START_RE = /^\s*(?:#{1,6}\s+|[-*]\s+)?(?:\*\*)?B(\d+)-(\d+)(?:\*\*)?\b/i;
3848
+ function prFindingBlocks(text) {
3849
+ const lines = text.split(/\r?\n/);
3850
+ const starts = [];
3851
+ for (let index = 0; index < lines.length; index++) {
3852
+ const match = PR_FINDING_START_RE.exec(lines[index]);
3853
+ if (!match) continue;
3854
+ starts.push({ index, batch: Number(match[1]), id: `B${match[1]}-${match[2]}` });
3855
+ }
3856
+ return starts.map((start, position) => {
3857
+ const next = starts[position + 1]?.index ?? lines.length;
3858
+ let end = next;
3859
+ for (let index = start.index + 1; index < next; index++) {
3860
+ if (/^\s*#{1,4}\s+/.test(lines[index])) {
3861
+ end = index;
3862
+ break;
3863
+ }
3864
+ }
3865
+ return { batch: start.batch, id: start.id, text: lines.slice(start.index, end).join("\n") };
3866
+ });
3867
+ }
3868
+ var NOT_A_DEFECT_RE = /\b(?:verified\s+ok|no\s+(?:defect|issue|finding|action\s+needed|functional\s+issue)|not\s+(?:a\s+bug|a\s+(?:functional|correctness)\s+defect|a\s+defect|introduced\s+by\s+this\s+patch|available\s+(?:in|for)\s+this\s+batch)|none\s+needed|acceptable(?:\s+as[- ]is)?|accept\s+as[- ]is|worth\s+noting|future\s+(?:optimization|hardening)|pre[- ]existing|functionally\s+harmless|intentional\s+limitation|needs?\s+(?:(?:central|cross[- ]file)\s+)?verification|requires?\s+(?:central\s+)?verification|central\s+verification|not\s+audited|implementation\s+(?:is\s+)?unknown|no\s+evidence\s+(?:of|that).{0,80}\bavailable|correct\s+(?:and\s+bounded\s+)?fallback|intent\s+is\s+correct|best[- ]effort|harmless\s+here|does\s+not\s+affect\s+runtime\s+behavior|(?:this\s+)?finding\s+is\s+contingent|risk\s+(?:is\s+)?low|(?:style|quoting|backslash)\s+(?:inconsistency|concern)|standardiz(?:e|ing)|verify\s+whether)\b/is;
3869
+ var HEDGE_RE = /\b(?:may|might|could|possibly|potential(?:ly)?|likely)\b/i;
3870
+ function prFindingWordingProblem(text) {
3871
+ const prose = text.replace(/```[\s\S]*?```/g, " ").replace(/`[^`\n]*`/g, " ");
3872
+ const notDefect = NOT_A_DEFECT_RE.exec(prose);
3873
+ if (notDefect) {
3874
+ return { kind: "not-a-defect", phrase: notDefect[0].replace(/\s+/g, " ") };
3875
+ }
3876
+ const hedge = HEDGE_RE.exec(prose);
3877
+ return hedge ? { kind: "hedge", phrase: hedge[0] } : null;
3878
+ }
3879
+ var PR_CANDIDATE_TEXT_LIMIT = 400;
3880
+ var PR_CANDIDATE_TEXT_REFUSED_OVER = 600;
3881
+ var PR_CANDIDATE_KEYS = ["id", "path", "line", "severity", "claim", "verify"];
3882
+ var PR_SEVERITIES = ["critical", "major", "minor", "nit"];
3883
+ function parsePrVerificationCandidates(text, batch, assignedPaths) {
3884
+ const none = (problem) => ({ candidates: [], problems: [problem] });
3885
+ const heading = /^#{1,6}\s+Verification candidates\s*$/im.exec(text);
3886
+ if (!heading) {
3887
+ return none(
3888
+ 'add a "Verification candidates" heading with one JSON block containing {"verificationCandidates":[]}'
3889
+ );
3890
+ }
3891
+ const afterHeading = text.slice(heading.index + heading[0].length);
3892
+ const nextHeadingOffset = afterHeading.search(/^#{1,6}\s+/m);
3893
+ const section = nextHeadingOffset >= 0 ? afterHeading.slice(0, nextHeadingOffset) : afterHeading;
3894
+ const blocks = [...section.matchAll(/```json\s*([\s\S]*?)```/gi)];
3895
+ const json = blocks[0]?.[1];
3896
+ if (blocks.length !== 1 || json === void 0) {
3897
+ return none(
3898
+ 'the "Verification candidates" section must contain exactly one fenced JSON block with a verificationCandidates array'
3899
+ );
3900
+ }
3901
+ let value;
3902
+ try {
3903
+ value = JSON.parse(json);
3904
+ } catch (error) {
3905
+ return none(
3906
+ `verificationCandidates JSON is invalid: ${error instanceof Error ? error.message : String(error)}`
3907
+ );
3908
+ }
3909
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
3910
+ return none("verificationCandidates JSON must be an object");
3911
+ }
3912
+ const topLevelKeys = Object.keys(value);
3913
+ if (topLevelKeys.length !== 1 || topLevelKeys[0] !== "verificationCandidates") {
3914
+ return none("verificationCandidates JSON must contain only the verificationCandidates key");
3915
+ }
3916
+ const raw = value.verificationCandidates;
3917
+ if (!Array.isArray(raw)) return none("verificationCandidates must be an array");
3918
+ if (raw.length > 12) return none("verificationCandidates must contain at most 12 entries");
3919
+ const candidates = [];
3920
+ const problems = [];
3921
+ for (let index = 0; index < raw.length; index++) {
3922
+ const candidate = raw[index];
3923
+ const expectedId = `V${batch}-${index + 1}`;
3924
+ if (!candidate || typeof candidate !== "object" || Array.isArray(candidate)) {
3925
+ problems.push(`verificationCandidates[${index}] must be an object`);
3926
+ continue;
3927
+ }
3928
+ const fields = candidate;
3929
+ const found = [];
3930
+ if (fields.id !== expectedId) {
3931
+ found.push(
3932
+ `id is ${JSON.stringify(fields.id)}; entry ${index + 1} must be "${expectedId}" (number them in order)`
3933
+ );
3934
+ }
3935
+ if (typeof fields.path !== "string" || !assignedPaths.includes(fields.path)) {
3936
+ found.push(`path ${JSON.stringify(fields.path)} is not one of this batch's changed paths`);
3937
+ }
3938
+ if (!Number.isSafeInteger(fields.line) || Number(fields.line) < 1) {
3939
+ found.push(`line must be a whole number above 0, not ${JSON.stringify(fields.line)}`);
3940
+ }
3941
+ if (!PR_SEVERITIES.includes(String(fields.severity))) {
3942
+ found.push(
3943
+ `severity ${JSON.stringify(fields.severity)} must be critical, major, minor, or nit`
3944
+ );
3945
+ }
3946
+ for (const [key, least, what] of [
3947
+ ["claim", 10, "one sentence stating the failure"],
3948
+ ["verify", 3, "the file, symbol, or route to inspect"]
3949
+ ]) {
3950
+ const body = fields[key];
3951
+ if (typeof body !== "string" || body.trim().length < least) {
3952
+ found.push(`${key} must be ${what}`);
3953
+ } else if (body.length > PR_CANDIDATE_TEXT_REFUSED_OVER) {
3954
+ found.push(
3955
+ `${key} is ${body.length} characters; cut it to ${PR_CANDIDATE_TEXT_LIMIT} or fewer`
3956
+ );
3957
+ }
3958
+ }
3959
+ const extra = Object.keys(fields).filter((key) => !PR_CANDIDATE_KEYS.includes(key));
3960
+ if (extra.length > 0) {
3961
+ found.push(`has extra key(s) ${extra.join(", ")}; keep only ${PR_CANDIDATE_KEYS.join(", ")}`);
3962
+ }
3963
+ if (found.length > 0) {
3964
+ problems.push(`${expectedId}: ${found.join("; ")}`);
3965
+ continue;
3966
+ }
3967
+ candidates.push({
3968
+ id: expectedId,
3969
+ path: fields.path,
3970
+ line: fields.line,
3971
+ severity: fields.severity,
3972
+ claim: fields.claim.trim(),
3973
+ verify: fields.verify.trim()
3974
+ });
3975
+ }
3976
+ return { candidates, problems };
3977
+ }
3978
+ var LOCKFILE_NAMES = /* @__PURE__ */ new Set([
3979
+ "bun.lock",
3980
+ "bun.lockb",
3981
+ "cargo.lock",
3982
+ "composer.lock",
3983
+ "deno.lock",
3984
+ "flake.lock",
3985
+ "gemfile.lock",
3986
+ "go.sum",
3987
+ "gradle.lockfile",
3988
+ "mix.lock",
3989
+ "npm-shrinkwrap.json",
3990
+ "package-lock.json",
3991
+ "package.resolved",
3992
+ "packages.lock.json",
3993
+ "pdm.lock",
3994
+ "pipfile.lock",
3995
+ "pnpm-lock.yaml",
3996
+ "podfile.lock",
3997
+ "poetry.lock",
3998
+ "pubspec.lock",
3999
+ "uv.lock",
4000
+ "yarn.lock"
4001
+ ]);
4002
+ var THIRD_PARTY_NOTICES_RE = /^third[-_ ]?party[-_ ]?(?:notices?|licen[cs]es?)(?:\.[a-z0-9]+)?$/i;
4003
+ function generatedFileKind(path) {
4004
+ const name = path.slice(path.lastIndexOf("/") + 1);
4005
+ if (LOCKFILE_NAMES.has(name.toLowerCase())) return "lockfile";
4006
+ if (THIRD_PARTY_NOTICES_RE.test(name)) return "third-party-notices";
4007
+ return null;
4008
+ }
4009
+ var GENERATED_KIND_LABEL = {
4010
+ lockfile: "Dependency lockfile",
4011
+ "third-party-notices": "Third-party notices"
4012
+ };
4013
+ var TARBALL_URL_RE = /https?:\/\/([^/\s"']+)\/(?:[^\s"']*?\/)??((?:@[^/\s"']+\/)?[^/\s"'@]+)\/-\/([^/\s"'#]+)\.tgz/;
4014
+ var PUBLIC_REGISTRY_HOSTS = /* @__PURE__ */ new Set(["registry.npmjs.org", "registry.yarnpkg.com"]);
4015
+ var PACKAGE_CHANGE_LIMIT = 200;
4016
+ function lockfileChanges(patch) {
4017
+ const added = /* @__PURE__ */ new Map();
4018
+ const removed = /* @__PURE__ */ new Map();
4019
+ const hosts = /* @__PURE__ */ new Map();
4020
+ for (const line of patch.lines) {
4021
+ if (line.kind === "context") continue;
4022
+ const match = TARBALL_URL_RE.exec(line.text);
4023
+ if (!match) continue;
4024
+ const host = match[1];
4025
+ const name = match[2];
4026
+ const base = `${name.slice(name.lastIndexOf("/") + 1)}-`;
4027
+ if (!match[3].startsWith(base)) continue;
4028
+ const version = match[3].slice(base.length);
4029
+ const side = line.kind === "add" ? added : removed;
4030
+ side.set(name, (side.get(name) ?? /* @__PURE__ */ new Set()).add(version));
4031
+ if (line.kind === "add" && !PUBLIC_REGISTRY_HOSTS.has(host) && line.newLine !== void 0) {
4032
+ const seen = hosts.get(host);
4033
+ if (seen) seen.packages += 1;
4034
+ else hosts.set(host, { line: line.newLine, packages: 1 });
4035
+ }
4036
+ }
4037
+ const changes = [];
4038
+ for (const name of [.../* @__PURE__ */ new Set([...added.keys(), ...removed.keys()])].sort()) {
4039
+ const now = [...added.get(name) ?? []].filter((v) => !removed.get(name)?.has(v)).sort();
4040
+ const before = [...removed.get(name) ?? []].filter((v) => !added.get(name)?.has(v)).sort();
4041
+ if (now.length > 0 && before.length > 0) {
4042
+ changes.push(`${name} ${before.join(", ")} to ${now.join(", ")}`);
4043
+ } else if (now.length > 0) {
4044
+ changes.push(`${name} ${now.join(", ")} added`);
4045
+ } else if (before.length > 0) {
4046
+ changes.push(`${name} ${before.join(", ")} removed`);
4047
+ }
4048
+ }
4049
+ return {
4050
+ changes,
4051
+ otherHosts: [...hosts].map(([host, seen]) => ({ host, ...seen }))
4052
+ };
4053
+ }
4054
+ function generatedBatchObservations(batch) {
4055
+ const out = [
4056
+ `# Batch ${batch.batchNumber} \u2014 files ${batch.start}\u2013${batch.end}`,
4057
+ "",
4058
+ "Generated files. The runtime summarized these from their patches; no reviewer read them line by line."
4059
+ ];
4060
+ const candidates = [];
4061
+ for (const file of batch.files) {
4062
+ out.push("", `## ${file.path}`, "");
4063
+ const patch = file.record === null ? null : parsePatchRecord(file.record);
4064
+ const label = GENERATED_KIND_LABEL[file.kind];
4065
+ if (!patch) {
4066
+ out.push(`${label}. No patch available.`);
4067
+ continue;
4068
+ }
4069
+ const addedLines = patch.lines.filter((line) => line.kind === "add").length;
4070
+ const removedLines = patch.lines.filter((line) => line.kind === "remove").length;
4071
+ out.push(`${label}: +${addedLines} / -${removedLines} lines.`);
4072
+ if (file.kind !== "lockfile") continue;
4073
+ const { changes, otherHosts } = lockfileChanges(patch);
4074
+ if (changes.length > 0) {
4075
+ out.push("", ...changes.slice(0, PACKAGE_CHANGE_LIMIT).map((change) => `- ${change}`));
4076
+ if (changes.length > PACKAGE_CHANGE_LIMIT) {
4077
+ out.push(`- and ${changes.length - PACKAGE_CHANGE_LIMIT} more package change(s)`);
4078
+ }
4079
+ }
4080
+ for (const other of otherHosts.slice(0, 3)) {
4081
+ candidates.push({
4082
+ id: `V${batch.batchNumber}-${candidates.length + 1}`,
4083
+ path: file.path,
4084
+ line: other.line,
4085
+ severity: "minor",
4086
+ claim: `The lockfile resolves ${other.packages} package(s) from ${other.host}, not the public npm registry.`,
4087
+ verify: `Confirm ${other.host} is a registry this repository intends to install from (.npmrc, publishConfig, or the package manager settings).`
4088
+ });
4089
+ }
4090
+ }
4091
+ out.push(
4092
+ "",
4093
+ "## Verification candidates",
4094
+ "",
4095
+ "```json",
4096
+ JSON.stringify({ verificationCandidates: candidates }, null, 2),
4097
+ "```",
4098
+ ""
4099
+ );
4100
+ return out.join("\n");
4101
+ }
4102
+
3713
4103
  // src/checks.ts
3714
4104
  function gateResult(ok, detail) {
3715
4105
  if (typeof ok !== "boolean") {
@@ -3736,6 +4126,9 @@ export {
3736
4126
  IMG_EXT,
3737
4127
  MIN_INLINE_JS_BYTES,
3738
4128
  MIN_JUDGE_EVIDENCE_SUBSTRING,
4129
+ PATCH_LINE_LEGEND,
4130
+ PR_CANDIDATE_TEXT_LIMIT,
4131
+ PR_FINDING_START_RE,
3739
4132
  buildJudgePrompt,
3740
4133
  checkFigures,
3741
4134
  citationsResolve,
@@ -3759,8 +4152,11 @@ export {
3759
4152
  fileMinBytes,
3760
4153
  fileMinLines,
3761
4154
  findImageRefs,
4155
+ formatLineRanges,
3762
4156
  frontmatterList,
3763
4157
  gateResult,
4158
+ generatedBatchObservations,
4159
+ generatedFileKind,
3764
4160
  grepMatches,
3765
4161
  htmlCompleteSniff,
3766
4162
  htmlGameSniff,
@@ -3777,10 +4173,15 @@ export {
3777
4173
  normalizeInlineEmphasis,
3778
4174
  normalizeTypography,
3779
4175
  notContainsPattern,
4176
+ numberUnifiedPatch,
3780
4177
  parseCsv,
3781
4178
  parseJudgeVerdict,
3782
4179
  parseMarkdownTable,
4180
+ parsePatchRecord,
4181
+ parsePrVerificationCandidates,
3783
4182
  planStructure,
4183
+ prFindingBlocks,
4184
+ prFindingWordingProblem,
3784
4185
  readingLevel,
3785
4186
  recordSchema,
3786
4187
  requireOrderedSections,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bendyline/gezel-sdk",
3
- "version": "1.1.18",
3
+ "version": "1.1.19",
4
4
  "description": "SDK for scripts that run in the Gezel sandbox: the gezel object and the defineScript helper.",
5
5
  "license": "MIT",
6
6
  "keywords": [
@@ -63,7 +63,7 @@
63
63
  "!dist/**/*.map"
64
64
  ],
65
65
  "devDependencies": {
66
- "@bendyline/gezel": "1.3.3",
66
+ "@bendyline/gezel": "1.3.4",
67
67
  "tsup": "^8.5.1",
68
68
  "typescript": "^6.0.3",
69
69
  "vitest": "^4.1.10"