From 0a6d66ac6912e25ff6bbdebc59e986109ad9f094 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Mon, 9 Nov 2026 06:35:36 -0500 Subject: [PATCH 1/3] Admit Git-proven comment-only production changes in high-risk readiness The evaluator now proves from the exact base and head blobs that an in-place Dart production edit only touches inert comments (identical tokens, no tool-read comment markers, no layout change outside edited comments) and drops the causal test-record obligation for that path. Classification, audit, matrix rows and structured-output minima are unchanged; evidence-only PRs with no production path still cite a test. Fixes #1669 Refs #1845 --- doc/high_risk_pre_merge_readiness.md | 50 +- .../tooling/high_risk_readiness_test.dart | 567 +++++++++++++++++- tool/testing/high_risk_readiness.dart | 194 +++++- 3 files changed, 804 insertions(+), 7 deletions(-) diff --git a/doc/high_risk_pre_merge_readiness.md b/doc/high_risk_pre_merge_readiness.md index 19e0a1edc..62118b5b2 100644 --- a/doc/high_risk_pre_merge_readiness.md +++ b/doc/high_risk_pre_merge_readiness.md @@ -101,7 +101,8 @@ observed results. The independent reviewer checks that the case really reaches the affected branch and that the failure is causal, not a setup error. Every changed production path under `lib/`, `tool/`, `hook/`, `packages/genkit_llamadart/lib/`, `.github/workflows/`, or `.github/actions/` -needs this coverage. Workflows and composite actions count because the +needs this coverage unless it is +[proven comment-only](#comment-only-production-changes). Workflows and composite actions count because the classifier treats each one as high-risk and the tooling tests that load them are their only durable proof; no other `.github/` or policy path is a production reference. The independent Genkit @@ -157,6 +158,50 @@ independent audit must inspect those semantics and results; do not invent a record for tests that were not run. Unknown or unproven reachability blocks the review even if local JSON validation succeeds. No new approval identity is added. +### Comment-only production changes + +A changed production path needs no `test_evidence` coverage when Git proves +the edit comment-only. When every changed production path is proven, +`affected_test_paths` and `test_evidence` may be empty. There is no caller +flag: the evaluator derives the proof from the exact base and head blobs +(`isCommentOnlyDartChange` in `tool/testing/high_risk_readiness.dart`). + +A path qualifies only if: + +- it is a `.dart` production path changed in place (`M`, no rename or copy) + and a regular non-executable blob at both revisions; +- both revisions parse without diagnostics and scan to identical tokens, type + and lexeme, so string contents, directives, annotations, imports, exports and + the script tag are compared; +- whitespace changes only between two tokens whose comments changed, and never + moves those tokens onto or off a shared line; +- every comment added, removed or moved is plain prose or Dartdoc. It contains + no control, invisible or bidirectional character and no tool marker: + language version (`// @dart`), `@docImport`, Dartdoc directives (`{@...}`, + `@nodoc`, any `@name`), `ignore:`/`ignore_for_file:`, `coverage:`, + `dart format`, excerpt regions (`#docregion`, any `#name`) or a security or + lint suppression (`nosemgrep`, `nosec`, `NOSONAR`, `lgtm`, `codeql`, `noqa`, + `nolint`, `expect_lint`, `pragma` and similar). An unchanged + `ignore_for_file:`, `coverage:ignore-file` or `// @dart=` comment may precede + an edited one at the same token; any other marker there fails closed; +- the file is not generated (a `.g`, `.freezed`, `.mocks`, `.gr` or protobuf + suffix, or an `AUTO GENERATED`, `GENERATED FILE/CODE`, `Generated by` or + `DO NOT EDIT` header comment). + +Code inside doc comments is inert and qualifies. Anything else, including +malformed source, an unreadable blob and non-Dart paths, keeps the ordinary +causal-test requirement. Stack-trace line numbers can still shift; nothing else +at runtime can. + +The route changes only that coverage obligation. Classification, surfaces, +matrix rows, the exact-pair independent audit and the zero-P1 and +zero-thread gates are unchanged. A comment-only structured-output path keeps +its minimum impacts, coverage axes and family evidence, and impact review must +still cite it. Other changed production paths in the same PR still need +coverage. A cited test may still reference only comment-only paths and must +pass every existing check. A PR with no changed production path at all still +cites a relevant test. + ### Schema migration New evidence uses `schema_version: 2.0.0`. The current evaluator rejects v1; @@ -317,7 +362,8 @@ LLAMADART_ANALYZER_COMPATIBILITY_VERSIONS=8.0.0,8.4.1,14.6.0 \ ``` This opt-in test resolves the full root dependency graph offline in scratch -packages and checks CLI compilation plus the namespace regressions. Missing +packages and checks CLI compilation plus the namespace and comment-only +regressions. Missing requested cached dependencies fail qualification; a skipped test is no proof. This proof bounds the additive namespace and existing loading dependencies; it diff --git a/test/unit/tooling/high_risk_readiness_test.dart b/test/unit/tooling/high_risk_readiness_test.dart index 4316b50b8..ca0ce3922 100644 --- a/test/unit/tooling/high_risk_readiness_test.dart +++ b/test/unit/tooling/high_risk_readiness_test.dart @@ -1474,6 +1474,566 @@ final segment = '${Object()}ImageEditingRequest${Object()}'; }); }); + group('Git-proven comment-only production changes', () { + const realSource = 'lib/src/backends/other_backend.dart'; + const commentBase = + '/// Backend entry point.\n' + 'bool productionCall() => false; // Keep the default.\n' + "const label = 'a // b /* c */';\n"; + const commentHead = + '/// Backend entry point, documented further.\n' + '///\n' + '/// ```dart\n' + '/// productionCall(); // returns true?\n' + '/// ```\n' + '/* Block comment\n spanning lines. */\n' + 'bool productionCall() => false; // Keep the default value.\n' + "const label = 'a // b /* c */';\n"; + + Map commentEvidence(List changes) { + final evidence = backendEvidence() + ..['affected_test_paths'] = [] + ..['test_evidence'] = {}; + final surfaces = assessHighRiskFiles([ + for (final change in changes) ...[ + change.path, + if (change.previousPath != null) change.previousPath!, + ], + ]).surfaces; + evidence['surfaces'] = [for (final surface in surfaces) surface.name]; + return evidence; + } + + Future evaluateComment({ + String? base = commentBase, + String? head = commentHead, + String path = backendSource, + String baseMode = '100644', + String headMode = '100644', + List? changes, + Map? evidence, + Map extraHead = const {}, + }) { + final inventory = + changes ?? + [RepositoryChange(path: path, kind: RepositoryChangeKind.modified)]; + final testFile = ( + mode: '100644', + contents: "test('regression case', () { productionCall(); });", + ); + final files = { + baseSha: { + if (base != null) path: (mode: baseMode, contents: base), + }, + headSha: { + if (head != null) path: (mode: headMode, contents: head), + backendTest: testFile, + ...extraHead, + }, + }; + return HighRiskReadinessEvaluator( + repositoryState: FakeRepositoryState( + changes: inventory, + existingPaths: files[headSha]!.keys.toSet(), + files: files, + ), + ).evaluate( + evidence: evidence ?? commentEvidence(inventory), + context: context, + ); + } + + void expectAdmitted(HighRiskReadinessResult result) { + expect(result.decision, ReadinessDecision.unverifiedPrerequisites); + expect( + result.failureClassification, + ReadinessFailureClassification.externalPrerequisitesUnavailable, + ); + expect(result.isReady, isFalse); + } + + test( + 'needs no causal test record but keeps high-risk audit gates', + () async { + final result = await evaluateComment(); + expectAdmitted(result); + expect(result.changedFiles.single.path, backendSource); + for (final mutate in )>[ + (evidence) => evidence['independent_audit'] = null, + (evidence) => + evidence['independent_audit']['audit_head_sha'] = otherSha, + (evidence) => evidence['independent_audit']['auditor_identity'] = + context.author, + (evidence) => + evidence['independent_audit']['known_pr_caused_p1_regressions'] = + 1, + (evidence) => + evidence['independent_audit']['unresolved_review_threads'] = 1, + (evidence) => evidence['classification'] = 'standard', + ]) { + final evidence = commentEvidence([ + const RepositoryChange( + path: backendSource, + kind: RepositoryChangeKind.modified, + ), + ]); + mutate(evidence); + expect( + (await evaluateComment(evidence: evidence)).decision, + ReadinessDecision.rejected, + ); + } + }, + ); + + test( + 'an optional record for the comment-only path is still checked', + () async { + final evidence = + commentEvidence([ + const RepositoryChange( + path: backendSource, + kind: RepositoryChangeKind.modified, + ), + ]) + ..['affected_test_paths'] = [backendTest] + ..['test_evidence'] = {backendTest: testProof(backendSource)}; + expectAdmitted(await evaluateComment(evidence: evidence)); + evidence['test_evidence'][backendTest]['production_refs'] = + productionRefs(realSource); + expectFailure( + await evaluateComment( + evidence: evidence, + extraHead: { + realSource: ( + mode: '100644', + contents: 'void run() { productionCall(); }\n', + ), + }, + ), + ReadinessFailureClassification.missingStructuredOutputEvidence, + ); + }, + ); + + test('tool and hook Dart sources use the same proof', () async { + for (final path in [ + 'tool/testing/high_risk_readiness.dart', + 'hook/build.dart', + ]) { + expectAdmitted(await evaluateComment(path: path)); + expectFailure( + await evaluateComment( + path: path, + head: commentHead.replaceFirst('=> false', '=> true'), + ), + ReadinessFailureClassification.missingTestPath, + ); + } + }); + + final executableChanges = { + 'executable token': commentHead.replaceFirst('=> false', '=> true'), + 'string contents resembling a line comment': commentHead.replaceFirst( + 'a // b', + 'a // x', + ), + 'string contents resembling a block comment': commentHead.replaceFirst( + '/* c */', + '/* x */', + ), + 'comment turned into code': + '${commentHead.replaceFirst('/// productionCall(); // returns true?\n', '')}' + 'final called = productionCall();\n', + 'block comment closed early': commentHead.replaceFirst( + '/* Block comment\n spanning lines. */\n', + '/* Block comment */ void spanning() {}\n', + ), + 'added import': "import 'dart:async';\n$commentHead", + 'added annotation': commentHead.replaceFirst( + 'bool productionCall', + "@pragma('vm:prefer-inline')\nbool productionCall", + ), + 'layout change without a comment change': commentHead.replaceFirst( + '=> false;', + '=> false;', + ), + 'tokens regrouped onto one line': commentBase.replaceFirst( + 'bool productionCall() => false; // Keep the default.\n' + "const label", + 'bool productionCall() => false; const label', + ), + 'malformed head': '$commentHead\nclass', + }; + for (final change in executableChanges.entries) { + test('${change.key} still demands a causal test record', () async { + expectFailure( + await evaluateComment(head: change.value), + ReadinessFailureClassification.missingTestPath, + ); + }); + } + + test('malformed source at both revisions fails closed', () async { + expectFailure( + await evaluateComment( + base: 'bool productionCall( => false; // a\n', + head: 'bool productionCall( => false; // b\n', + ), + ReadinessFailureClassification.missingTestPath, + ); + }); + + final activeComments = { + 'language version': '// @dart=2.19\n', + 'analyzer suppression': '// ignore: unused_element\n', + 'file analyzer suppression': '// ignore_for_file: avoid_print\n', + 'coverage directive': '// coverage:ignore-line\n', + 'formatter directive': '// dart format off\n', + 'doc import': "/// @docImport 'dart:async';\n", + 'Dartdoc directive': '/// {@template backend.entry}\n', + 'Dartdoc nodoc': '/// @nodoc\n', + 'security suppression': '// nosemgrep: dart.lang.security\n', + 'doc excerpt region': '// #docregion backend\n', + 'bidirectional control': '// Note \u202Eevil\u202C text.\n', + 'control character': '// Bell \u0007 text.\n', + }; + for (final comment in activeComments.entries) { + test('${comment.key} comments are rejected when added, removed or ' + 'moved', () async { + final added = commentHead.replaceFirst( + 'bool productionCall', + '${comment.value}bool productionCall', + ); + for (final pair in [ + (commentBase, added), + (added, commentBase), + ( + added, + commentHead.replaceFirst( + "const label", + '${comment.value}const label', + ), + ), + ]) { + expectFailure( + await evaluateComment(base: pair.$1, head: pair.$2), + ReadinessFailureClassification.missingTestPath, + ); + } + }); + } + + test('unchanged active comments do not block a prose edit', () async { + const header = + '// ignore_for_file: avoid_print\n// coverage:ignore-file\n'; + expectAdmitted( + await evaluateComment( + base: '$header$commentBase', + head: '$header$commentHead', + ), + ); + }); + + test('generated sources never qualify', () async { + expectFailure( + await evaluateComment( + base: '// AUTO GENERATED FILE, DO NOT EDIT.\n$commentBase', + head: '// AUTO GENERATED FILE, DO NOT EDIT.\n$commentHead', + ), + ReadinessFailureClassification.missingTestPath, + ); + expectFailure( + await evaluateComment(path: 'lib/src/backends/example_backend.g.dart'), + ReadinessFailureClassification.missingTestPath, + ); + }); + + test('non-Dart production paths never qualify', () async { + expectFailure( + await evaluateComment( + path: '.github/workflows/ci.yml', + base: '# Run CI.\non: push\n', + head: '# Run CI on every push.\non: push\n', + ), + ReadinessFailureClassification.missingTestPath, + ); + }); + + for (final mode in [('100755', '100644'), ('100644', '100755')]) { + test('mode ${mode.$1} to ${mode.$2} fails closed', () async { + expectFailure( + await evaluateComment(baseMode: mode.$1, headMode: mode.$2), + ReadinessFailureClassification.missingTestPath, + ); + }); + } + + test('unavailable base or head blobs fail closed', () async { + for (final pair in [(null, commentHead), (commentBase, null)]) { + expectFailure( + await evaluateComment(base: pair.$1, head: pair.$2), + ReadinessFailureClassification.missingTestPath, + ); + } + }); + + for (final change in const [ + RepositoryChange(path: backendSource, kind: RepositoryChangeKind.added), + RepositoryChange(path: backendSource, kind: RepositoryChangeKind.deleted), + RepositoryChange( + path: backendSource, + kind: RepositoryChangeKind.typeChanged, + ), + RepositoryChange( + path: backendSource, + previousPath: realSource, + kind: RepositoryChangeKind.renamed, + ), + RepositoryChange( + path: backendSource, + previousPath: realSource, + kind: RepositoryChangeKind.copied, + ), + ]) { + test('${change.kind.name} comment-only content fails closed', () async { + expectFailure( + await evaluateComment(changes: [change]), + ReadinessFailureClassification.missingTestPath, + ); + }); + } + + group('mixed with an executable change', () { + const changes = [ + RepositoryChange( + path: backendSource, + kind: RepositoryChangeKind.modified, + ), + RepositoryChange(path: realSource, kind: RepositoryChangeKind.modified), + ]; + final realFiles = { + realSource: ( + mode: '100644', + contents: 'void run() { productionCall(); }\n', + ), + }; + Future evaluateMixed(String refPath) { + final evidence = commentEvidence(changes) + ..['affected_test_paths'] = [backendTest] + ..['test_evidence'] = {backendTest: testProof(refPath)}; + return evaluateComment( + changes: changes, + evidence: evidence, + extraHead: realFiles, + ); + } + + test('the executable path alone needs coverage', () async { + expectAdmitted(await evaluateMixed(realSource)); + }); + + test('evidence for only the comment-only path leaves the executable path ' + 'uncovered', () async { + final result = await evaluateMixed(backendSource); + expectFailure( + result, + ReadinessFailureClassification.missingStructuredOutputEvidence, + ); + expect(result.message, contains('lack reviewed test reachability')); + }); + + test('no test record at all is rejected', () async { + expectFailure( + await evaluateComment(changes: changes, extraHead: realFiles), + ReadinessFailureClassification.missingTestPath, + ); + }); + }); + + test('changes without a production path stay conservative', () async { + const doc = 'doc/high_risk_pre_merge_readiness.md'; + expectFailure( + await evaluateComment( + path: doc, + base: '# Contract\n', + head: '# Contract\n\nClarified.\n', + ), + ReadinessFailureClassification.missingTestPath, + ); + }); + + test('structured-output impacts and coverage keep their minima', () async { + const changes = [ + RepositoryChange( + path: structuredSource, + kind: RepositoryChangeKind.modified, + ), + ]; + final files = { + baseSha: { + structuredSource: (mode: '100644', contents: commentBase), + }, + headSha: { + structuredSource: (mode: '100644', contents: commentHead), + compiledTest: ( + mode: '100644', + contents: "test('regression case', () { productionCall(); });", + ), + realSource: ( + mode: '100644', + contents: 'void run() { productionCall(); }\n', + ), + }, + }; + Future evaluate(Map evidence) => + HighRiskReadinessEvaluator( + repositoryState: FakeRepositoryState( + changes: changes, + existingPaths: files[headSha]!.keys.toSet(), + files: files, + ), + ).evaluate(evidence: evidence, context: context); + + expectAdmitted(await evaluate(structuredEvidence())); + final excluded = structuredEvidence(); + excluded['structured_output_evidence']['impacts']['grammarSchema']['applicable'] = + false; + final result = await evaluate(excluded); + expectFailure( + result, + ReadinessFailureClassification.missingStructuredOutputEvidence, + ); + expect(result.message, contains('cannot be excluded')); + final unreviewed = structuredEvidence(); + for (final impact in StructuredImpact.values) { + unreviewed['structured_output_evidence']['impacts'][impact + .name]['production_refs'] = productionRefs( + realSource, + ); + } + expectFailure( + await evaluate(unreviewed), + ReadinessFailureClassification.missingStructuredOutputEvidence, + ); + }); + + test('token proof edge cases', () { + bool proven(String base, String head) => + isCommentOnlyDartChange('lib/a.dart', base, head); + for (final pair in [ + ('/** Old. */\nvoid f() {}\n', '/** New\n * prose. */\nvoid f() {}\n'), + ( + '/* a /* nested */ b */\nvoid f() {}\n', + '/* a /* x */ b */\nvoid f() {}\n', + ), + ('void f() {}\r\n// a\r\n', 'void f() {}\r\n// b\r\n'), + ( + '#!/usr/bin/env dart\n// a\nvoid main() {}\n', + '#!/usr/bin/env dart\n// b\nvoid main() {}\n', + ), + (r"var s = '${1 /* a */}';", r"var s = '${1 /* b */}';"), + ( + '// ignore_for_file: x\n// a\nvoid f() {}\n', + '// ignore_for_file: x\n// b\nvoid f() {}\n', + ), + ('void f() {} // a\n', 'void f() {}\n'), + ('void f() {}', 'void f() {}'), + ]) { + expect(proven(pair.$1, pair.$2), isTrue, reason: pair.$2); + } + for (final pair in [ + ("var s = r'// a';", "var s = r'// b';"), + ("var s = '''\n// a\n''';", "var s = '''\n// b\n''';"), + ("var s = 'a' '// b';", "var s = 'a' '// c';"), + (r"var s = '${1 /* a */}';", r"var s = '${2 /* a */}';"), + ( + '#!/usr/bin/env dart\nvoid main() {}\n', + '#!/usr/bin/env -S dart\nvoid main() {}\n', + ), + ( + '// ignore: x\n// a\nvoid f() {}\n', + '// ignore: x\n// b\nvoid f() {}\n', + ), + ('// a\nvoid f() {}\n', '// GENERATED CODE - b\nvoid f() {}\n'), + ('void f() {}\n', 'void f() {}\n// @dart=2.19\n'), + ('void f() {}\n// a\n', 'void f() {}\n// a​\n'), + ('/* a */\nvoid f() {}\n', '/* a\nvoid f() {}\n'), + ('void f() {}\n', '// a\nvoid f() { }\n'), + ]) { + expect(proven(pair.$1, pair.$2), isFalse, reason: pair.$2); + } + expect(isCommentOnlyDartChange('lib/a.sh', '# a\n', '# b\n'), isFalse); + }); + + test('reads exact Git blobs, not the working tree', () async { + final repo = Directory.systemTemp.createTempSync('comment-only-git-'); + addTearDown(() => repo.deleteSync(recursive: true)); + String git(List args) { + final result = Process.runSync( + 'git', + args, + workingDirectory: repo.path, + ); + expect(result.exitCode, 0, reason: '${result.stderr}'); + return (result.stdout as String).trim(); + } + + final sourceFile = File('${repo.path}/$backendSource'); + String commit(String contents, String message) { + sourceFile.writeAsStringSync(contents); + git(['add', '.']); + git(['commit', '--quiet', '-m', message]); + return git(['rev-parse', 'HEAD']); + } + + git(['init', '--quiet']); + git(['config', 'user.name', 'Comment-only policy test']); + git(['config', 'user.email', 'comment-only@example.invalid']); + sourceFile.parent.createSync(recursive: true); + final base = commit(commentBase, 'base'); + final commentOnly = commit(commentHead, 'comment-only'); + final executable = commit( + commentHead.replaceFirst('=> false', '=> true'), + 'executable', + ); + Future evaluate(String head) { + final evidence = + commentEvidence(const [ + RepositoryChange( + path: backendSource, + kind: RepositoryChangeKind.modified, + ), + ]) + ..['expected_pr_head_sha'] = head + ..['current_base_sha'] = base; + evidence['independent_audit']['audit_head_sha'] = head; + evidence['independent_audit']['audit_base_sha'] = base; + return const HighRiskReadinessEvaluator().evaluate( + evidence: evidence, + context: PullRequestContext( + repository: context.repository, + prNumber: context.prNumber, + headSha: head, + baseSha: base, + author: context.author, + ), + workingDirectory: repo.path, + ); + } + + sourceFile.writeAsStringSync( + commentHead.replaceFirst('=> false', '=> true'), + ); + expectAdmitted(await evaluate(commentOnly)); + sourceFile.writeAsStringSync(commentHead); + expectFailure( + await evaluate(executable), + ReadinessFailureClassification.missingTestPath, + ); + }); + }); + test( 'readiness AST supports explicitly requested allowed analyzer versions', () async { @@ -1555,8 +2115,9 @@ final segment = '${Object()}ImageEditingRequest${Object()}'; '-j', '1', paths.last, - '--plain-name', - 'Git-bound additive image export impacts', + '--name', + 'Git-bound additive image export impacts|' + 'Git-proven comment-only production changes', '--exclude-tags', 'local-only', '--reporter', @@ -1570,7 +2131,7 @@ final segment = '${Object()}ImageEditingRequest${Object()}'; ); expect(probe.stdout, contains('All tests passed!')); print( - 'Qualified analyzer $version: full root offline resolution, CLI help, namespace cases passed.', + 'Qualified analyzer $version: full root offline resolution, CLI help, namespace and comment-only cases passed.', ); } }, diff --git a/tool/testing/high_risk_readiness.dart b/tool/testing/high_risk_readiness.dart index 6e09247f7..87f9a1cb8 100644 --- a/tool/testing/high_risk_readiness.dart +++ b/tool/testing/high_risk_readiness.dart @@ -325,6 +325,136 @@ List parseGitNameStatus(String output) { return changes; } +/// Whether a Dart source edit from [base] to [head] is provably comment-only. +/// +/// Both revisions must parse without diagnostics and scan to identical tokens +/// (type and lexeme, so string contents, directives and annotations count). +/// Whitespace may change only where the comments between two tokens change, +/// and never moves those tokens onto or off a shared line. A comment added, +/// removed or moved must not be a language-version, analyzer, coverage, +/// formatter, Dartdoc-directive, doc-import, suppression or excerpt marker, +/// nor contain control, invisible or bidirectional characters. Generated +/// sources never qualify. Callers bind both texts to exact Git blobs. +bool isCommentOnlyDartChange(String path, String base, String head) { + if (!path.endsWith('.dart') || _generatedDartPath.hasMatch(path)) { + return false; + } + final baseUnit = _parseCleanly(base); + final headUnit = _parseCleanly(head); + if (baseUnit == null || headUnit == null) return false; + var left = baseUnit.beginToken; + var right = headUnit.beginToken; + var leftEnd = 0; + var rightEnd = 0; + while (true) { + if (left.type != right.type || + left.lexeme != right.lexeme || + left.offset < leftEnd || + right.offset < rightEnd) { + return false; + } + final leftComments = _commentsBefore(left); + final rightComments = _commentsBefore(right); + if ([...leftComments, ...rightComments].any(_generatedMarker.hasMatch)) { + return false; + } + final leftGap = base.substring(leftEnd, left.offset); + final rightGap = head.substring(rightEnd, right.offset); + if (leftGap != rightGap && + !_isInertCommentEdit(leftComments, rightComments, leftGap, rightGap)) { + return false; + } + if (left.isEof) return true; + leftEnd = left.end; + rightEnd = right.end; + left = left.next!; + right = right.next!; + } +} + +final _generatedDartPath = RegExp( + r'\.(g|gr|freezed|mocks|pb|pbenum|pbgrpc|pbjson|pbserver)\.dart$', +); +final _generatedMarker = RegExp( + r'^(//+|/\*+)\s*(auto[- ]?generated|generated\s+(file|code|by)|' + r'code\s+generated|do\s+not\s+(edit|modify))', + caseSensitive: false, +); +// Comments that tools read: language version, doc imports and Dartdoc +// directives, analyzer/coverage/formatter/security suppressions, excerpts. +final _activeComment = RegExp( + r'@[a-z]|\bignore(_for_file)?\s*:|\bcoverage\s*:|\bdart\s+format\b|#[a-z]|' + r'\b(nosemgrep|nosec|nosonar|lgtm|codeql|noqa|nolint|expect_lint|eslint|' + r'istanbul|c8|pragma)\b', + caseSensitive: false, +); +// These apply to the whole file wherever they sit, so an unchanged one may +// precede an edited comment at the same token. +final _fileScopedDirective = RegExp( + r'^//\s*(ignore_for_file\s*:|coverage:ignore-file\b|@dart\s*=)', + caseSensitive: false, +); +final _unsafeCommentCharacter = RegExp( + '[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F\u0085\u061C' + '\u200B-\u200F\u2028\u2029\u202A-\u202E\u2060-\u2069\uFEFF]', +); +final _lineBreak = RegExp(r'[\r\n]'); + +CompilationUnit? _parseCleanly(String source) { + try { + final parsed = parseString(content: source, throwIfDiagnostics: false); + return parsed.errors.isEmpty ? parsed.unit : null; + } on Object { + return null; + } +} + +List _commentsBefore(Token token) { + final comments = []; + for ( + Token? comment = token.precedingComments; + comment != null && + (comment.type == TokenType.SINGLE_LINE_COMMENT || + comment.type == TokenType.MULTI_LINE_COMMENT); + comment = comment.next + ) { + comments.add(comment.lexeme); + } + return comments; +} + +bool _isInertCommentEdit( + List left, + List right, + String leftGap, + String rightGap, +) { + if (left.length == right.length && + Iterable.generate(left.length).every((i) => left[i] == right[i])) { + return false; + } + if (_lineBreak.hasMatch(leftGap) != _lineBreak.hasMatch(rightGap)) { + return false; + } + var prefix = 0; + while (prefix < left.length && + prefix < right.length && + left[prefix] == right[prefix]) { + prefix++; + } + for (final comments in [left, right]) { + for (var i = 0; i < comments.length; i++) { + final comment = comments[i]; + if (_unsafeCommentCharacter.hasMatch(comment) || + (_activeComment.hasMatch(comment) && + !(i < prefix && _fileScopedDirective.hasMatch(comment)))) { + return false; + } + } + } + return true; +} + /// Strictly decodes a JSON object, rejecting duplicate object keys. Map decodeStrictJsonObject(String source) { _DuplicateKeyScanner(source).scan(); @@ -906,6 +1036,17 @@ class HighRiskReadinessEvaluator { }; final affectedPaths = (evidence['affected_test_paths'] as List) .cast(); + final commentOnlyProduction = metadataClaim + ? const {} + : await _commentOnlyProductionPaths( + context, + changedFiles, + workingDirectory, + ); + final changedProduction = { + for (final path in classificationPaths) + if (_isProductionPath(path)) path, + }; if (metadataClaim) { if (actualSurfaces.length != 1 || !actualSurfaces.contains(HighRiskSurface.artifactConsumer.name) || @@ -990,7 +1131,9 @@ class HighRiskReadinessEvaluator { changedFiles: changedFiles, ); } - } else if (affectedPaths.isEmpty) { + } else if (affectedPaths.isEmpty && + (changedProduction.isEmpty || + !commentOnlyProduction.containsAll(changedProduction))) { return reject( ReadinessFailureClassification.missingTestPath, 'High-risk evidence must cite at least one relevant production test.', @@ -1029,6 +1172,7 @@ class HighRiskReadinessEvaluator { context, changedByPath, metadataClaim, + commentOnlyProduction, workingDirectory, ); if (error != null) { @@ -1242,6 +1386,7 @@ class HighRiskReadinessEvaluator { PullRequestContext context, Map changes, bool metadataClaim, + Set commentOnlyProduction, String? workingDirectory, ) async { final tests = evidence['test_evidence'] as Map; @@ -1264,6 +1409,9 @@ class HighRiskReadinessEvaluator { }; final inspectedPaths = {...changes.keys, ...renamedSources}; final changedProduction = inspectedPaths.where(_isProductionPath).toSet(); + final testedProduction = changedProduction.difference( + commentOnlyProduction, + ); Future refsExist(List refs) async { for (final ref in refs.cast>()) { final path = ref['path'] as String; @@ -1344,7 +1492,7 @@ class HighRiskReadinessEvaluator { } coveredProduction.addAll(referenced); } - if (!coveredProduction.containsAll(changedProduction)) { + if (!coveredProduction.containsAll(testedProduction)) { return 'Some changed production paths lack reviewed test reachability.'; } final structured = @@ -1394,6 +1542,48 @@ class HighRiskReadinessEvaluator { return null; } + // Only in-place edits of regular Dart blobs qualify. An unreadable blob + // keeps the ordinary causal-test route instead of failing the evaluation. + Future> _commentOnlyProductionPaths( + PullRequestContext context, + List changes, + String? workingDirectory, + ) async { + final proven = {}; + for (final change in changes) { + if (change.kind != RepositoryChangeKind.modified || + change.previousPath != null || + !_isProductionPath(change.path) || + !change.path.endsWith('.dart')) { + continue; + } + try { + final base = await repositoryState.fileAt( + context.baseSha, + change.path, + workingDirectory: workingDirectory, + ); + final head = await repositoryState.fileAt( + context.headSha, + change.path, + workingDirectory: workingDirectory, + ); + if (base?.mode == '100644' && + head?.mode == '100644' && + isCommentOnlyDartChange( + change.path, + base!.contents, + head!.contents, + )) { + proven.add(change.path); + } + } on Object { + continue; + } + } + return proven; + } + // This recognizes one reviewed export shape, not arbitrary "image paths". // It proves additive namespace/loading properties; the independent review // still owns the behavioral impact decisions and transitive callsite review. From 76ae76e50e08f90d8ba2a48457b9a4f946046a10 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Mon, 9 Nov 2026 09:26:31 -0500 Subject: [PATCH 2/3] Exclude raw-text-read sources and inline edits from the comment-only route Sources whose text repository tooling reads with regular expressions (release pins, bridge setup, LiteRT-LM runtime, build hook) never qualify, and edited comments must end their line so line-oriented scanners see unchanged code. Leading header comments mentioning "generated" or "do not edit" also exclude a file. Tests cover unreadable and non-UTF-8 blobs, parser exceptions, upper-case markers and lone-CR line endings. Refs #1669 --- doc/high_risk_pre_merge_readiness.md | 32 +++- .../tooling/high_risk_readiness_test.dart | 147 +++++++++++++++++- tool/testing/high_risk_readiness.dart | 38 ++++- 3 files changed, 196 insertions(+), 21 deletions(-) diff --git a/doc/high_risk_pre_merge_readiness.md b/doc/high_risk_pre_merge_readiness.md index 62118b5b2..22fc6f1b6 100644 --- a/doc/high_risk_pre_merge_readiness.md +++ b/doc/high_risk_pre_merge_readiness.md @@ -173,8 +173,9 @@ A path qualifies only if: - both revisions parse without diagnostics and scan to identical tokens, type and lexeme, so string contents, directives, annotations, imports, exports and the script tag are compared; -- whitespace changes only between two tokens whose comments changed, and never - moves those tokens onto or off a shared line; +- whitespace changes only between two tokens whose comments changed, and the + later token starts its line in both revisions: edited comments are full-line + or trailing, never inline before code; - every comment added, removed or moved is plain prose or Dartdoc. It contains no control, invisible or bidirectional character and no tool marker: language version (`// @dart`), `@docImport`, Dartdoc directives (`{@...}`, @@ -184,14 +185,29 @@ A path qualifies only if: `nolint`, `expect_lint`, `pragma` and similar). An unchanged `ignore_for_file:`, `coverage:ignore-file` or `// @dart=` comment may precede an edited one at the same token; any other marker there fails closed; -- the file is not generated (a `.g`, `.freezed`, `.mocks`, `.gr` or protobuf - suffix, or an `AUTO GENERATED`, `GENERATED FILE/CODE`, `Generated by` or - `DO NOT EDIT` header comment). +- the file is not generated: no `.g`, `.freezed`, `.mocks`, `.gr` or protobuf + suffix, no comment before the first token mentioning `generated` (including + `@generated`) or `do not edit`/`do not modify`, and no comment anywhere that + starts with `AUTO GENERATED`, `GENERATED FILE/CODE`, `Generated by`, + `Code generated` or `DO NOT EDIT`; +- the file is not in `rawTextConsumedSources`: production sources whose raw + text, comments included, repository tooling reads with regular expressions. + These are the release pins (`lib/src/hook/native_release_pins.dart`, read + by the release-docs verifier, the WebGPU bridge tag check, validation + bundles and the native sync scripts), `lib/src/web_setup/web_bridge_setup.dart` + (bridge tag check), and `lib/src/backends/litert_lm/litert_lm_runtime.dart` + and `hook/build.dart` (rewritten by `sync_native_release_pins.py`). A + commented-out pin there can change what a CI gate or sync script reads. A + test fails if a listed path disappears; add any new raw-text reader's source + to the list. Code inside doc comments is inert and qualifies. Anything else, including -malformed source, an unreadable blob and non-Dart paths, keeps the ordinary -causal-test requirement. Stack-trace line numbers can still shift; nothing else -at runtime can. +malformed source, an unreadable or non-UTF-8 blob and non-Dart paths, keeps +the ordinary causal-test requirement. The proof covers compiled behavior: +stack-trace line numbers can still shift, and tooling that reads source text +is handled only by the list above. `check_platform_boundaries.dart` also +scans raw lines for directives; because no edited comment can precede code on +its line, a comment edit can only add a violation there, never hide one. The route changes only that coverage obligation. Classification, surfaces, matrix rows, the exact-pair independent audit and the zero-P1 and diff --git a/test/unit/tooling/high_risk_readiness_test.dart b/test/unit/tooling/high_risk_readiness_test.dart index ca0ce3922..36985ead3 100644 --- a/test/unit/tooling/high_risk_readiness_test.dart +++ b/test/unit/tooling/high_risk_readiness_test.dart @@ -99,6 +99,31 @@ class FakeRepositoryState implements RepositoryStateReader { } } +class _UnreadableBlobState extends FakeRepositoryState { + _UnreadableBlobState({ + required this.sha, + required this.path, + required super.changes, + super.existingPaths, + super.files, + }); + + final String sha; + final String path; + + @override + Future fileAt( + String sha, + String path, { + String? workingDirectory, + }) { + if (sha == this.sha && path == this.path) { + throw const FormatException('Invalid UTF-8 blob.'); + } + return super.fileAt(sha, path, workingDirectory: workingDirectory); + } +} + const structuredSource = 'lib/src/core/template/chat_template_handler.dart'; const backendSource = 'lib/src/backends/example_backend.dart'; List> productionRefs(String path) => [ @@ -1619,7 +1644,7 @@ final segment = '${Object()}ImageEditingRequest${Object()}'; test('tool and hook Dart sources use the same proof', () async { for (final path in [ 'tool/testing/high_risk_readiness.dart', - 'hook/build.dart', + 'hook/link.dart', ]) { expectAdmitted(await evaluateComment(path: path)); expectFailure( @@ -1697,6 +1722,8 @@ final segment = '${Object()}ImageEditingRequest${Object()}'; 'doc excerpt region': '// #docregion backend\n', 'bidirectional control': '// Note \u202Eevil\u202C text.\n', 'control character': '// Bell \u0007 text.\n', + 'upper-case suppression': '// NOSONAR\n', + 'upper-case formatter directive': '// DART FORMAT OFF\n', }; for (final comment in activeComments.entries) { test('${comment.key} comments are rejected when added, removed or ' @@ -1736,12 +1763,26 @@ final segment = '${Object()}ImageEditingRequest${Object()}'; }); test('generated sources never qualify', () async { - expectFailure( + for (final header in [ + '// AUTO GENERATED FILE, DO NOT EDIT.\n', + '// @generated\n', + '// Copyright 2026.\n// This file is generated by tool/gen.dart.\n', + '/* Produced by a script; do not hand-edit. */\n', + '// Do not modify by hand.\n', + ]) { + expectFailure( + await evaluateComment( + base: '$header$commentBase', + head: '$header$commentHead', + ), + ReadinessFailureClassification.missingTestPath, + ); + } + expectAdmitted( await evaluateComment( - base: '// AUTO GENERATED FILE, DO NOT EDIT.\n$commentBase', - head: '// AUTO GENERATED FILE, DO NOT EDIT.\n$commentHead', + base: '$commentBase// Explains the generated grammar.\n', + head: '$commentHead// Explains the generated grammar.\n', ), - ReadinessFailureClassification.missingTestPath, ); expectFailure( await evaluateComment(path: 'lib/src/backends/example_backend.g.dart'), @@ -1749,6 +1790,69 @@ final segment = '${Object()}ImageEditingRequest${Object()}'; ); }); + test('sources whose raw text tooling reads never qualify', () async { + for (final path in rawTextConsumedSources) { + expect(File(path).existsSync(), isTrue, reason: path); + expect( + isCommentOnlyDartChange(path, commentBase, commentHead), + isFalse, + reason: path, + ); + if (assessHighRiskFiles([path]).isHighRisk) { + expectFailure( + await evaluateComment(path: path), + ReadinessFailureClassification.missingTestPath, + ); + } + } + const pins = 'lib/src/hook/native_release_pins.dart'; + const pinsBase = "const llamaCppTag = 'v0.9.0';\n"; + expectFailure( + await evaluateComment( + path: pins, + base: pinsBase, + head: "// const llamaCppTag = 'v0.8.0';\n$pinsBase", + ), + ReadinessFailureClassification.missingTestPath, + ); + // Split so the bridge tag gate does not read this fixture as a pin. + const bridgePin = + 'webBridge' + "AssetsTag = 'v9.9.9'"; + expect( + isCommentOnlyDartChange( + 'lib/src/web_setup/web_bridge_setup.dart', + pinsBase, + '/* const String $bridgePin; */\n$pinsBase', + ), + isFalse, + ); + }); + + test('an unreadable blob keeps the causal-test route', () async { + const changes = [ + RepositoryChange( + path: backendSource, + kind: RepositoryChangeKind.modified, + ), + ]; + for (final sha in [baseSha, headSha]) { + final result = await HighRiskReadinessEvaluator( + repositoryState: _UnreadableBlobState( + sha: sha, + path: backendSource, + changes: changes, + existingPaths: {backendSource, backendTest}, + files: { + baseSha: {backendSource: (mode: '100644', contents: commentBase)}, + headSha: {backendSource: (mode: '100644', contents: commentHead)}, + }, + ), + ).evaluate(evidence: commentEvidence(changes), context: context); + expectFailure(result, ReadinessFailureClassification.missingTestPath); + } + }); + test('non-Dart production paths never qualify', () async { expectFailure( await evaluateComment( @@ -1932,13 +2036,13 @@ final segment = '${Object()}ImageEditingRequest${Object()}'; '#!/usr/bin/env dart\n// a\nvoid main() {}\n', '#!/usr/bin/env dart\n// b\nvoid main() {}\n', ), - (r"var s = '${1 /* a */}';", r"var s = '${1 /* b */}';"), ( '// ignore_for_file: x\n// a\nvoid f() {}\n', '// ignore_for_file: x\n// b\nvoid f() {}\n', ), ('void f() {} // a\n', 'void f() {}\n'), ('void f() {}', 'void f() {}'), + ('void f() {}\r// a\r', 'void f() {}\r// b\r'), ]) { expect(proven(pair.$1, pair.$2), isTrue, reason: pair.$2); } @@ -1957,13 +2061,29 @@ final segment = '${Object()}ImageEditingRequest${Object()}'; ), ('// a\nvoid f() {}\n', '// GENERATED CODE - b\nvoid f() {}\n'), ('void f() {}\n', 'void f() {}\n// @dart=2.19\n'), - ('void f() {}\n// a\n', 'void f() {}\n// a​\n'), + ('void f() {}\n// a\n', 'void f() {}\n// a\u200B\n'), ('/* a */\nvoid f() {}\n', '/* a\nvoid f() {}\n'), ('void f() {}\n', '// a\nvoid f() { }\n'), + ('void f() {} // a\rvoid g() {}\r', 'void f() {} void g() {}\r'), + (r"var s = '${1 /* a */}';", r"var s = '${1 /* b */}';"), + ("import 'dart:io';\n", "/* a */ import 'dart:io';\n"), + ( + "import 'a.dart';\nimport 'b.dart';\n", + "import 'a.dart';\n/* a */ import 'b.dart';\n", + ), + ( + 'void f() {}\n// GENERATED CODE below.\n// a\nvoid g() {}\n', + 'void f() {}\n// GENERATED CODE below.\n// b\nvoid g() {}\n', + ), + ("import 'dart:io';\n", "import /* a */ 'dart:io';\n"), + ('void f() {}', 'void f() {} // a'), ]) { expect(proven(pair.$1, pair.$2), isFalse, reason: pair.$2); } expect(isCommentOnlyDartChange('lib/a.sh', '# a\n', '# b\n'), isFalse); + // Deep unary nesting overflows the analyzer parser's stack. + final overflowing = 'var x = ${'-' * 200000}1;'; + expect(proven(overflowing, overflowing), isFalse); }); test('reads exact Git blobs, not the working tree', () async { @@ -1997,6 +2117,15 @@ final segment = '${Object()}ImageEditingRequest${Object()}'; commentHead.replaceFirst('=> false', '=> true'), 'executable', ); + git(['checkout', '--quiet', base]); + sourceFile.writeAsBytesSync([ + ...utf8.encode(commentHead), + ...utf8.encode('// invalid '), + 0xff, + 0x0a, + ]); + git(['commit', '--quiet', '-am', 'invalid UTF-8 comment']); + final invalidUtf8 = git(['rev-parse', 'HEAD']); Future evaluate(String head) { final evidence = commentEvidence(const [ @@ -2031,6 +2160,10 @@ final segment = '${Object()}ImageEditingRequest${Object()}'; await evaluate(executable), ReadinessFailureClassification.missingTestPath, ); + expectFailure( + await evaluate(invalidUtf8), + ReadinessFailureClassification.missingTestPath, + ); }); }); diff --git a/tool/testing/high_risk_readiness.dart b/tool/testing/high_risk_readiness.dart index 87f9a1cb8..5a01fcddd 100644 --- a/tool/testing/high_risk_readiness.dart +++ b/tool/testing/high_risk_readiness.dart @@ -330,13 +330,16 @@ List parseGitNameStatus(String output) { /// Both revisions must parse without diagnostics and scan to identical tokens /// (type and lexeme, so string contents, directives and annotations count). /// Whitespace may change only where the comments between two tokens change, -/// and never moves those tokens onto or off a shared line. A comment added, +/// and the later token must start its line in both revisions. A comment added, /// removed or moved must not be a language-version, analyzer, coverage, /// formatter, Dartdoc-directive, doc-import, suppression or excerpt marker, /// nor contain control, invisible or bidirectional characters. Generated -/// sources never qualify. Callers bind both texts to exact Git blobs. +/// sources and [rawTextConsumedSources] never qualify. Callers bind both texts +/// to exact Git blobs. bool isCommentOnlyDartChange(String path, String base, String head) { - if (!path.endsWith('.dart') || _generatedDartPath.hasMatch(path)) { + if (!path.endsWith('.dart') || + _generatedDartPath.hasMatch(path) || + rawTextConsumedSources.contains(path)) { return false; } final baseUnit = _parseCleanly(base); @@ -355,7 +358,9 @@ bool isCommentOnlyDartChange(String path, String base, String head) { } final leftComments = _commentsBefore(left); final rightComments = _commentsBefore(right); - if ([...leftComments, ...rightComments].any(_generatedMarker.hasMatch)) { + final comments = [...leftComments, ...rightComments]; + if (comments.any(_generatedMarker.hasMatch) || + (leftEnd == 0 && comments.any(_generatedHeader.hasMatch))) { return false; } final leftGap = base.substring(leftEnd, left.offset); @@ -372,6 +377,17 @@ bool isCommentOnlyDartChange(String path, String base, String head) { } } +/// Production Dart sources whose raw text, comments included, repository +/// tooling reads with regular expressions (release pins, bridge tags, +/// template hashes). A comment there can change what a CI gate or sync +/// script sees, so these never use the comment-only route. +const rawTextConsumedSources = { + 'hook/build.dart', + 'lib/src/backends/litert_lm/litert_lm_runtime.dart', + 'lib/src/hook/native_release_pins.dart', + 'lib/src/web_setup/web_bridge_setup.dart', +}; + final _generatedDartPath = RegExp( r'\.(g|gr|freezed|mocks|pb|pbenum|pbgrpc|pbjson|pbserver)\.dart$', ); @@ -380,6 +396,10 @@ final _generatedMarker = RegExp( r'code\s+generated|do\s+not\s+(edit|modify))', caseSensitive: false, ); +final _generatedHeader = RegExp( + r'generated|do\s+not\s+(hand[- ])?(edit|modify)', + caseSensitive: false, +); // Comments that tools read: language version, doc imports and Dartdoc // directives, analyzer/coverage/formatter/security suppressions, excerpts. final _activeComment = RegExp( @@ -433,8 +453,14 @@ bool _isInertCommentEdit( Iterable.generate(left.length).every((i) => left[i] == right[i])) { return false; } - if (_lineBreak.hasMatch(leftGap) != _lineBreak.hasMatch(rightGap)) { - return false; + // Edited comments must end their line, so the next token still starts its + // line in both revisions. Line-oriented source scanners then see the same + // code at every line start, and no token joins or leaves another's line. + for (final gap in [leftGap, rightGap]) { + final lineStart = gap.lastIndexOf(_lineBreak) + 1; + if (lineStart == 0 || gap.substring(lineStart).trim().isNotEmpty) { + return false; + } } var prefix = 0; while (prefix < left.length && From b9263210cceb000e3f99feed06911ed53bfc714d Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Mon, 9 Nov 2026 09:33:35 -0500 Subject: [PATCH 3/3] Keep the raw-text source existence check out of the analyzer-compat probe The compatibility probe copies only the readiness sources into a scratch package, so the repository-path existence check runs as its own test. Refs #1669 --- test/unit/tooling/high_risk_readiness_test.dart | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/test/unit/tooling/high_risk_readiness_test.dart b/test/unit/tooling/high_risk_readiness_test.dart index 36985ead3..509037e36 100644 --- a/test/unit/tooling/high_risk_readiness_test.dart +++ b/test/unit/tooling/high_risk_readiness_test.dart @@ -1499,6 +1499,12 @@ final segment = '${Object()}ImageEditingRequest${Object()}'; }); }); + test('raw-text-consumed sources all exist in the repository', () { + for (final path in rawTextConsumedSources) { + expect(File(path).existsSync(), isTrue, reason: path); + } + }); + group('Git-proven comment-only production changes', () { const realSource = 'lib/src/backends/other_backend.dart'; const commentBase = @@ -1792,7 +1798,6 @@ final segment = '${Object()}ImageEditingRequest${Object()}'; test('sources whose raw text tooling reads never qualify', () async { for (final path in rawTextConsumedSources) { - expect(File(path).existsSync(), isTrue, reason: path); expect( isCommentOnlyDartChange(path, commentBase, commentHead), isFalse,