mirror of
https://github.com/stablyai/orca.git
synced 2026-10-30 16:47:34 +00:00
* [comment audit] Align legacy failure-read counts with cached display * [comment audit] Condense shared provider lifecycle and browser recovery comments [skip ci] * [comment audit] Condense shared generation, path and preview comments [skip ci] * [comment audit] Condense host, file and Git contract rationale [skip ci] * [comment audit] Tighten Git lifecycle and provider contract comments [skip ci] * [comment audit] Clarify shared host authority and launch isolation [skip ci] * [comment audit] simplify local access mobile and native chat contracts [skip ci] * [comment audit] simplify native chat presentation and state contracts [skip ci] * [comment audit] simplify native runtime and provider contracts [skip ci] * [comment audit] simplify migration and orchestration contracts [skip ci] * [comment audit] simplify plugin trust and process capture rationale [skip ci] * [comment audit] simplify terminal delivery and remote compatibility rationale [skip ci] * [comment audit] clarify remote recovery and launch wire rationale [skip ci] * [comment audit] shorten shared RPC compatibility and runtime evidence comments [skip ci] * [comment audit] simplify secure storage shell startup and sidebar rationale [skip ci] * [comment audit] clarify sidebar, skill and SSH invariants [skip ci] * [comment audit] condense structured chat delivery and timing rationale [skip ci] * [comment audit] condense terminal replay and telemetry invariants [skip ci] * [comment audit] clarify launch permission and terminal delivery rationale [skip ci] * [comment audit] clarify workspace ownership and layout contracts [skip ci] * [comment audit] wait for fitted and painted SSH terminal links * [comment audit] clarify layout persistence and session ownership [skip ci] * [comment audit] clarify host routing and workspace lifecycle contracts [skip ci] * [comment audit] clarify startup persistence and app lifetime comments [skip ci] * [comment audit] clarify recovery and activity boundaries [skip ci] * [comment audit] condense activity and artifact invariants [skip ci] * [comment audit] condense automation authority contracts [skip ci] * [comment audit] simplify automation scheduling and history contracts [skip ci] * [comment audit] clarify browser chrome and annotation lifecycles [skip ci] * [comment audit] clarify browser routing and retained guest ownership [skip ci] * [comment audit] clarify browser recovery and document ownership comments [skip ci] * [comment audit] restore hosted runners required by native IME fixtures * [comment audit] shorten preview, palette and dashboard invariants [skip ci] * [comment audit] clarify terminal preview, dashboard and retention comments [skip ci] * [comment audit] clarify diff-note recovery and editor lifecycle comments [skip ci] * [comment audit] shorten rich-text and combined-diff ownership comments [skip ci] * [comment audit] shorten autosave, draft recovery and model ownership comments [skip ci] * [comment audit] shorten save-queue, notebook and Markdown constraints [skip ci] * [comment audit] shorten Monaco, PDF and rich Markdown safeguards [skip ci] * [comment audit] clarify rich Markdown source and selection safeguards [skip ci] * [comment audit] clarify editor loading and emulator stream lifetimes [skip ci] * [comment audit] trim emulator and feature tour narration [skip ci] * [comment audit] clarify floating workspace and GitHub cache ownership [skip ci] * [comment audit] trim provider controls and Linear filter explanations [skip ci] * [comment audit] clarify pairing and chat resume lifetimes [skip ci] * [comment audit] clarify chat delivery and transcript lifetimes [skip ci] * [comment audit] clarify session options and host-owned status [skip ci] * [comment audit] clarify draft durability and live-status precedence [skip ci] * [comment audit] Trim chat send and model ownership explanations [skip ci] * [comment audit] Shorten transcript ownership and send recovery comments [skip ci] * [comment audit] Simplify native chat composer and transcript hook comments [skip ci] * [comment audit] Shorten native chat scroll and structured session explanations [skip ci] * [comment audit] Trim workspace picker and onboarding commentary [skip ci] * [comment audit] Simplify pet rendering, review cache and quick open comments [skip ci] * [comment audit] Trim sidebar and session history explanations [skip ci] * [comment audit] Condense session resume and review checks comments [skip ci] * [comment audit] Shorten checks state and file explorer refresh comments [skip ci] * [comment audit] Trim plugin bridge and source-control action rationale [skip ci] * [comment audit] Trim source-control listing and review rationale [skip ci] * [comment audit] Shorten sidebar lifecycle and explorer safeguards [skip ci] * [comment audit] Condense Settings account and appearance rationale [skip ci] * [comment audit] Trim pairing and repository Settings explanations [skip ci] * [comment audit] Condense Settings search SSH and terminal safeguards [skip ci] * [comment audit] Shorten Settings voice and provider ownership comments [skip ci] * [comment audit] Condense Settings draft persistence and host-state rationale [skip ci] * [comment audit] Trim Settings hooks and sidebar setup rationale [skip ci] * [comment audit] Condense sidebar deletion and board-filter safeguards [skip ci] * [comment audit] Condense worktree cards, host ownership and Markdown contracts [skip ci] * [comment audit] Condense sidebar drag, folder and filtering contracts [skip ci] * [comment audit] Condense sidebar parity, sleep and host ownership contracts [skip ci] * [comment audit] Prune focus-read baseline after comment cleanup * [comment audit] Clarify sidebar visibility, board drops and agent evidence [skip ci] * [comment audit] Tighten sidebar listing, drag and reveal contracts [skip ci] * [comment audit] Clarify viewport geometry and skill update safeguards [skip ci] * [comment audit] Tighten skill inventory, usage and host status comments [skip ci] * [comment audit] Clarify usage ownership and resource kill safeguards [skip ci] * [comment audit] Tighten tab selection, rename and search contracts [skip ci] * [comment audit] Tighten tab-strip geometry and drag ownership comments [skip ci] * [comment audit] Tighten Tasks recovery, pagination and mutation comments [skip ci] * [comment audit] Tighten provider loading and terminal recovery comments [skip ci] * [comment audit] Tighten completion, cadence and PTY ownership comments [skip ci] * [comment audit] Clarify terminal restore and parked-pane boundaries [skip ci] * [comment audit] Tighten PTY startup and replay explanations [skip ci] * [comment audit] Clarify PTY identity and delivery ownership [skip ci] * [comment audit] Shorten remote reconnect and input replay rationale [skip ci] * [comment audit] Condense terminal parking clipboard and file link comments [skip ci] * [comment audit] Clarify IME ownership and trim trace history [skip ci] * [comment audit] Shorten pane recovery and parked watcher explanations [skip ci] * [comment audit] Condense snapshot replay and visibility recovery rationale [skip ci] * [comment audit] Shorten terminal parking and keyboard ownership rationale [skip ci] * [comment audit] Trim renderer lifecycle and menu rationale [skip ci] * [comment audit] Condense workspace cleanup ownership and settlement notes [skip ci] * [comment audit] Clarify renderer hook evidence and source ownership [skip ci] * [comment audit] Tighten IPC ownership and reconnect explanations [skip ci] * [comment audit] Trim renderer focus, paste and attention comments [skip ci] * [comment audit] Shorten scroll, locale and agent lifecycle comments [skip ci] * [comment audit] Trim agent launch, resume and ownership commentary [skip ci] * [comment audit] Shorten account, browser and editor comments [skip ci] * [comment audit] Clarify host-mirror waits, previews and input ownership [skip ci] * [comment audit] Condense launch recovery and editor tokenization comments [skip ci] * [comment audit] Condense workspace selection and terminal pane rationale [skip ci] * [comment audit] Condense terminal fitting and rendering recovery comments [skip ci] * [comment audit] Condense terminal input and host routing explanations [skip ci] * [comment audit] Condense ownership and sleeping-session recovery rationale [skip ci] * [comment audit] Condense structured launch and terminal link explanations [skip ci] * [comment audit] Condense terminal ownership and workspace file routing rationale [skip ci] * [comment audit] Condense session persistence and workspace activation rationale [skip ci] * [comment audit] Condense workspace routing and browser ownership rationale [skip ci] * [comment audit] Condense mirror recovery and layout authority rationale [skip ci] * [comment audit] Condense runtime transport and file safety rationale [skip ci] * [comment audit] Condense runtime graph and structured session rationale [skip ci] * [comment audit] Condense browser creation and remote tab recovery rationale [skip ci] * [comment audit] Condense snapshot authority and publisher recovery rationale [skip ci] * [comment audit] Condense frame, startup and provider cache rationale [skip ci] * [comment audit] Condense host twin and agent lifecycle rationale [skip ci] * [comment audit] Condense browser authority and editor cleanup rationale [skip ci] * [comment audit] Condense editor buffer identity and review cache rationale [skip ci] * [comment audit] Condense provider lifetime and repository ownership rationale [skip ci] * [comment audit] Condense reconnect, hydration and terminal retirement rationale [skip ci] * [comment audit] Condense recovery, reconciliation and persistence rationale [skip ci] * [comment audit] Condense cleanup ownership and listing admission rationale [skip ci] * [comment audit] Condense teardown ordering and terminal ownership rationale [skip ci] * [comment audit] Condense recovery ledger and web host-boundary rationale [skip ci] * [comment audit] Condense web reconnect and credential lifecycle rationale [skip ci] * [comment audit] Condense cloud rollout and assignment safety rationale [skip ci] * [comment audit] Condense relay session and database recovery rationale [skip ci] * [comment audit] Condense relay placement and protocol compatibility rationale [skip ci] * [comment audit] Condense build and packaging constraints [skip ci] * [comment audit] Condense CI gates and validation isolation rationale [skip ci] * [comment audit] Condense catalog identity and browser validation rationale [skip ci] * [comment audit] Condense mobile browser and frame-budget rationale [skip ci] * [comment audit] Shorten mobile route and browser test explanations [skip ci] * [comment audit] Condense editor and session seam test rationale [skip ci] * [comment audit] Trim session and terminal closure history [skip ci] * [comment audit] Shorten terminal browser and census explanations [skip ci] * [comment audit] Preserve root-only E2E diagnostic baseline * [comment audit] Condense mobile seam and HTML preview test rationale [skip ci] * [comment audit] Condense preview instrumentation and render harness rationale [skip ci] * [comment audit] Condense bundle contracts and native-build constraints [skip ci] * [comment audit] Shorten native packaging and CI routing rationale [skip ci] * [comment audit] Condense release tooling and benchmark constraints [skip ci] * [comment audit] Condense packaging and platform gate rationale [skip ci] * [comment audit] Shorten mobile route and history rationale [skip ci] * [comment audit] Condense mobile browser and component rationale [skip ci] * [comment audit] Shorten drawer and workspace-form rationale [skip ci] * [comment audit] Trim mobile review and editor-document explanations [skip ci] * [comment audit] Condense editor lifecycle and Markdown explanations [skip ci] * [comment audit] Trim mobile file, diagnostics and dictation commentary [skip ci] * [comment audit] Simplify mobile host-list and workspace-view explanations [skip ci] * [comment audit] Clarify mobile shell lifetime and bridge delivery constraints [skip ci] * [comment audit] Condense bridge stream, native request and audio rationale [skip ci] * [comment audit] Reduce bridge schema and page-client commentary [skip ci] * [comment audit] Tighten mobile page bridge contracts [skip ci] * [comment audit] Clarify mobile cache and session constraints [skip ci] * [comment audit] Condense mobile route and lifecycle rationale [skip ci] * [comment audit] Tighten mobile shell hook timing rationale [skip ci] * [comment audit] Clarify route handoff and notification compatibility [skip ci] * [comment audit] Clarify push registration and dictation cleanup constraints [skip ci] * [comment audit] Condense keyboard geometry and native media ownership rationale [skip ci] * [comment audit] Tighten mobile chat scroll and composer concurrency rationale [skip ci] * [comment audit] Condense mobile reply compatibility and upload ownership rationale [skip ci] * [comment audit] Condense optimistic echo and scroll ownership rationale [skip ci] * [comment audit] Tighten stream replay and queued session ownership rationale [skip ci] * [comment audit] Condense mobile composer and reply-schema constraints [skip ci] * [comment audit] Clarify mobile transcript recovery and session ownership [skip ci] * [comment audit] Clarify mobile queue and source-control compatibility [skip ci] * [comment audit] Condense storage and task launch constraints [skip ci] * [comment audit] Clarify task schemas and terminal document ownership [skip ci] * [comment audit] Tighten terminal input and viewport rationale [skip ci] * [comment audit] Shorten terminal and RPC recorder contracts [skip ci] * [comment audit] Condense recorder engine and connection contracts [skip ci] * [comment audit] Shorten host credential and relay recovery comments [skip ci] * [comment audit] Tighten pairing recovery and bundle transport rationale [skip ci] * [comment audit] Clarify RPC delivery and workspace catalog boundaries [skip ci] * [comment audit] Condense catalog and relay entry contracts [skip ci] * [comment audit] Shorten shutdown and SSH relay delivery contracts [skip ci] * [comment audit] Condense WSL relay and E2E regression rationale [skip ci] * [comment audit] Shorten cross-version harness and renderer fixture explanations [skip ci] * [comment audit] Condense paired-host and E2E lifecycle rationale [skip ci] * [comment audit] Shorten layout oracle and regression explanations [skip ci] * [comment audit] Condense paired recovery and ownership regression contracts [skip ci] * [comment audit] Shorten restart, sidebar and SSH lifecycle contracts [skip ci] * [comment audit] Condense terminal rendering and IME regression rationale [skip ci] * [comment audit] Shorten terminal recovery and benchmark contracts [skip ci] * [comment audit] Condense tooling and Windows lifecycle proof rationale [skip ci] * [comment audit] Condense workflow routing and release rationale [skip ci] * [comment audit] Condense mobile security and installer contracts [skip ci] * [comment audit] Shorten native rationale and stylesheet workarounds [skip ci] * [comment audit] Shorten Windows visibility probe rationale [skip ci] * [comment audit] Condense embedded release and signing rationale [skip ci] * [comment audit] Retain current main test behavior in final reconciliation [skip ci] * [comment audit] Complete final comment review across current source inventory * [comment audit] Handle consolidated audit reports before final CI * [comment audit] Preserve credential storage census detail [skip ci] * [comment audit] Scale broad changed E2E selections with verified timing shards * [comment audit] Align E2E assertions with browser close and settled session metadata * [comment audit] Match existing E2Es to current resource and windowing contracts * [comment audit] Observe the shared server outage notice in reconnect coverage * [comment audit] Make existing renderer probes measure settled tab and PTY work * [comment audit] Align palette E2E selector with task search * [comment audit] Refresh remaining palette search selectors * [comment audit] Keep selector correction within selected audit specs * [comment audit] Await emoji fixture settings inside renderer evaluation * [comment audit] Cancel fixture fit retries between terminal tests --------- Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
622 lines
21 KiB
JavaScript
622 lines
21 KiB
JavaScript
import { execFileSync, spawnSync } from 'node:child_process'
|
||
import { existsSync, readFileSync } from 'node:fs'
|
||
import path from 'node:path'
|
||
import process from 'node:process'
|
||
import { pathToFileURL } from 'node:url'
|
||
import { runProcessSync } from '@orca/process-host'
|
||
import { scanAstGrep } from './ast-grep-scan.mjs'
|
||
import { resolvePullRequestDiffBase } from './git-pull-request-diff-base.mjs'
|
||
import { resolveOxlintInvocation } from './oxlint-cli-invocation.mjs'
|
||
|
||
const SOURCE_FILE_PATTERN = /\.(?:[cm]?[jt]sx?)$/
|
||
const ROOT_CODE_QUALITY_IGNORED_PREFIXES = ['cloud/']
|
||
const CASTING_RULE = 'typescript/consistent-type-assertions'
|
||
const CASTING_DISABLE_PATTERN =
|
||
/\/[/*]\s*(?:oxlint|eslint)-disable(?:-next-line|-line)?\s[^\n]*typescript\/consistent-type-assertions/
|
||
const ANTI_SLOP_DISABLE_PATTERN =
|
||
/\/[/*]\s*(?:oxlint|eslint)-disable(?:-next-line|-line)?\s[^\n]*\banti-slop\//
|
||
const REACT_DOCTOR_DISABLE_PATTERN =
|
||
/^\s*\/[/*]\s*(?:oxlint|eslint)-disable(?:-next-line|-line)?\s+react-doctor\/[\w-]+(?:\s*,\s*react-doctor\/[\w-]+)*\s*(?:--(?:(?!\*\/).)*)?(?:\*\/)?\s*$/
|
||
const JS_PLUGINS_CONFIG = 'config/oxlint-js-plugins.json'
|
||
// The root scan no longer loads these plugins, so their suppressions belong to the JS plugins scan.
|
||
const JS_PLUGIN_NAMES = JSON.parse(
|
||
readFileSync(new URL(`../../${JS_PLUGINS_CONFIG}`, import.meta.url), 'utf8')
|
||
).jsPlugins.map((plugin) => plugin.name)
|
||
const JS_PLUGIN_DISABLE_PATTERN = new RegExp(
|
||
String.raw`\/[/*]\s*(?:oxlint|eslint)-disable(?:-next-line|-line)?\s[^\n]*\b(?:${JS_PLUGIN_NAMES.join('|')})\/`
|
||
)
|
||
const EXPLICIT_DISABLE_RULE_PATTERN = /(?:-disable(?:-next-line|-line)?\s+|^)[\w-]+(?:\/[\w-]+)?/
|
||
export const OXLINT_SCANS = [
|
||
{
|
||
// Leave config discovery enabled so mobile’s nested config can disable root rules.
|
||
label: 'code quality',
|
||
args: ['--report-unused-disable-directives-severity', 'warn']
|
||
},
|
||
{
|
||
// Keep JS plugins in gates: transferring every AST to Node slows the default native scan.
|
||
label: 'JS plugins',
|
||
args: ['--config', JS_PLUGINS_CONFIG]
|
||
},
|
||
{
|
||
label: 'casting code quality',
|
||
args: ['--config', 'config/oxlint-code-quality-casting.json']
|
||
},
|
||
{
|
||
// CI native audit runs before mobile install and cannot see its cycles; keep local changed gate aligned.
|
||
label: 'focused plugins',
|
||
args: [
|
||
'--config',
|
||
'config/oxlint-code-quality-native-plugins.json',
|
||
'--allow',
|
||
'import/no-cycle'
|
||
]
|
||
},
|
||
{
|
||
label: 'type-aware code quality',
|
||
args: ['--type-aware', '--config', 'config/oxlint-code-quality-type-aware.json']
|
||
},
|
||
{
|
||
label: 'React Doctor',
|
||
args: [
|
||
'--config',
|
||
'config/oxlint-react-doctor.json',
|
||
'--report-unused-disable-directives-severity',
|
||
'warn'
|
||
]
|
||
},
|
||
{
|
||
// Gate added lines against existing renderer design debt (~4.7k findings).
|
||
label: 'design system',
|
||
args: ['--config', 'config/oxlint-design-system.json']
|
||
}
|
||
]
|
||
|
||
const SUPPRESSED_REACT_DOCTOR_DIAGNOSTICS = new Map([
|
||
[
|
||
'react-doctor(no-adjust-state-on-prop-change)',
|
||
new Set([
|
||
'src/renderer/src/components/task-page/github/use-task-page-github-issue-draft.ts',
|
||
'src/renderer/src/components/use-task-page-jira-creation-state.ts'
|
||
])
|
||
],
|
||
[
|
||
'react-doctor(no-derived-state-effect)',
|
||
new Set([
|
||
'src/renderer/src/components/editor/combined-diff/review-controls/use-combined-diff-view-preferences.ts',
|
||
// The open-cycle reset effect predates this entry; it surfaced when its body changed.
|
||
'src/renderer/src/components/right-sidebar/useSourceControlAgentActionDialog.ts'
|
||
])
|
||
],
|
||
[
|
||
// Existing timer effects clean variable handle sets through addTimer; rule expects one named handle and falsely reports both.
|
||
// Exemption is per-file, covering those two effects; this file has no other timer effects.
|
||
'react-doctor(effect-needs-cleanup)',
|
||
new Set(['mobile/src/session/use-mobile-session-startup.ts'])
|
||
]
|
||
])
|
||
|
||
export function parseAddedLineRanges(diff) {
|
||
const ranges = []
|
||
const hunkPattern = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/
|
||
for (const line of diff.split(/\r?\n/)) {
|
||
const match = hunkPattern.exec(line)
|
||
if (!match) {
|
||
continue
|
||
}
|
||
const start = Number.parseInt(match[1], 10)
|
||
const count = match[2] === undefined ? 1 : Number.parseInt(match[2], 10)
|
||
if (count > 0) {
|
||
ranges.push({ start, end: start + count - 1 })
|
||
}
|
||
}
|
||
return ranges
|
||
}
|
||
|
||
export function overlapsAddedLines(startLine, endLine, ranges) {
|
||
return ranges.some((range) => startLine <= range.end && endLine >= range.start)
|
||
}
|
||
|
||
function runGit(root, args, options = {}) {
|
||
return execFileSync('git', args, {
|
||
cwd: root,
|
||
encoding: options.encoding ?? 'utf8',
|
||
maxBuffer: 64 * 1024 * 1024
|
||
})
|
||
}
|
||
|
||
function splitNullDelimited(output) {
|
||
return output.split('\0').filter(Boolean)
|
||
}
|
||
|
||
export function isRootCodeQualityPath(file) {
|
||
return !ROOT_CODE_QUALITY_IGNORED_PREFIXES.some((prefix) => file.startsWith(prefix))
|
||
}
|
||
|
||
function resolveBase(root, requestedBase) {
|
||
for (const candidate of [
|
||
requestedBase,
|
||
process.env.ORCA_CODE_QUALITY_BASE,
|
||
'origin/main',
|
||
'main'
|
||
]) {
|
||
if (!candidate) {
|
||
continue
|
||
}
|
||
const result = spawnSync('git', ['rev-parse', '--verify', `${candidate}^{commit}`], {
|
||
cwd: root,
|
||
stdio: 'ignore'
|
||
})
|
||
if (result.status === 0) {
|
||
return candidate
|
||
}
|
||
}
|
||
throw new Error('Pass the pull request base SHA or make origin/main available locally.')
|
||
}
|
||
|
||
export function collectAddedLineRanges(
|
||
root,
|
||
requestedBase,
|
||
{ includePath = (file) => isRootCodeQualityPath(file) && SOURCE_FILE_PATTERN.test(file) } = {}
|
||
) {
|
||
// PR checkout HEAD is the merge commit: first parent identifies base without shallow-clone missing payload ancestry.
|
||
// Local branch tips still need merge-base to isolate their changes.
|
||
const comparisonBase =
|
||
resolvePullRequestDiffBase(root, null) ??
|
||
runGit(root, ['merge-base', resolveBase(root, requestedBase), 'HEAD']).trim()
|
||
const changedEntries = splitNullDelimited(
|
||
runGit(root, ['diff', '--name-status', '--find-renames', '-z', comparisonBase, '--'])
|
||
)
|
||
const changedFiles = []
|
||
const renamedSources = new Map()
|
||
for (let index = 0; index < changedEntries.length;) {
|
||
const status = changedEntries[index++]
|
||
const source = changedEntries[index++]
|
||
if (status.startsWith('R') || status.startsWith('C')) {
|
||
const destination = changedEntries[index++]
|
||
changedFiles.push(destination)
|
||
if (status.startsWith('R') && includePath(source)) {
|
||
renamedSources.set(destination, source)
|
||
}
|
||
} else if (status !== 'D') {
|
||
changedFiles.push(source)
|
||
}
|
||
}
|
||
const untrackedFiles = splitNullDelimited(
|
||
runGit(root, ['ls-files', '--others', '--exclude-standard', '-z'])
|
||
)
|
||
const rangesByFile = new Map()
|
||
|
||
for (const file of changedFiles) {
|
||
if (!includePath(file) || !existsSync(path.join(root, file))) {
|
||
continue
|
||
}
|
||
const source = renamedSources.get(file)
|
||
const paths = source ? [source, file] : [file]
|
||
const diff = runGit(root, [
|
||
'diff',
|
||
'--find-renames',
|
||
'--unified=0',
|
||
'--no-color',
|
||
comparisonBase,
|
||
'--',
|
||
...paths
|
||
])
|
||
const ranges = parseAddedLineRanges(diff)
|
||
if (ranges.length > 0) {
|
||
rangesByFile.set(file, ranges)
|
||
}
|
||
}
|
||
|
||
for (const file of untrackedFiles) {
|
||
const absolutePath = path.join(root, file)
|
||
if (!includePath(file) || !existsSync(absolutePath)) {
|
||
continue
|
||
}
|
||
const lineCount = readFileSync(absolutePath, 'utf8').split(/\r?\n/).length
|
||
rangesByFile.set(file, [{ start: 1, end: lineCount }])
|
||
}
|
||
return { comparisonBase, rangesByFile }
|
||
}
|
||
|
||
function parseOxlintOutput(stdout, label) {
|
||
const start = stdout.indexOf('{')
|
||
const end = stdout.lastIndexOf('}')
|
||
if (start === -1 || end === -1) {
|
||
throw new Error(`${label} did not return Oxlint JSON output.`)
|
||
}
|
||
return JSON.parse(stdout.slice(start, end + 1))
|
||
}
|
||
|
||
function normalizedDiagnosticPath(root, filename) {
|
||
const absolutePath = path.isAbsolute(filename) ? filename : path.join(root, filename)
|
||
return path.relative(root, absolutePath).split(path.sep).join('/')
|
||
}
|
||
|
||
function diagnosticLineRange(root, filename, span) {
|
||
const startLine = span.line
|
||
if (!Number.isInteger(startLine)) {
|
||
return null
|
||
}
|
||
if (!Number.isInteger(span.offset) || !Number.isInteger(span.length) || span.length === 0) {
|
||
return { start: startLine, end: startLine }
|
||
}
|
||
const absolutePath = path.isAbsolute(filename) ? filename : path.join(root, filename)
|
||
const source = readFileSync(absolutePath)
|
||
const highlighted = source.subarray(span.offset, span.offset + span.length).toString('utf8')
|
||
return { start: startLine, end: startLine + (highlighted.match(/\n/g)?.length ?? 0) }
|
||
}
|
||
|
||
// Split files mark moved code added; exempt diagnostic blocks already verbatim/contiguous in touched base files to avoid demanding unrelated edits.
|
||
function normalizeSourceLine(line) {
|
||
return line.replace(/\s+/g, ' ').trim()
|
||
}
|
||
|
||
function readBaseSourceBatch(root, comparisonBase, files) {
|
||
// Git 2.25 supports --batch; its newline protocol cannot represent newline paths.
|
||
if (files.some((file) => /[\r\n]/.test(`${comparisonBase}:${file}`))) {
|
||
return null
|
||
}
|
||
try {
|
||
const result = runProcessSync({
|
||
program: 'git',
|
||
args: ['cat-file', '--batch'],
|
||
cwd: root,
|
||
input: files.map((file) => `${comparisonBase}:${file}\n`).join(''),
|
||
captureStdoutAsBytes: true,
|
||
maxOutputBytes: 64 * 1024 * 1024,
|
||
timeoutMs: null
|
||
})
|
||
if (result.code !== 0 || !result.stdoutBytes) {
|
||
return null
|
||
}
|
||
const output = result.stdoutBytes
|
||
const sources = []
|
||
let offset = 0
|
||
for (const file of files) {
|
||
const end = output.indexOf(10, offset)
|
||
if (end === -1) {
|
||
return null
|
||
}
|
||
const header = output.subarray(offset, end).toString('utf8')
|
||
offset = end + 1
|
||
if (header === `${comparisonBase}:${file} missing`) {
|
||
continue
|
||
}
|
||
const match = /^[0-9a-f]{40}(?:[0-9a-f]{24})? blob (\d+)$/.exec(header)
|
||
if (!match) {
|
||
return null
|
||
}
|
||
const size = Number(match[1])
|
||
if (!Number.isSafeInteger(size) || output[offset + size] !== 10) {
|
||
return null
|
||
}
|
||
sources.push(output.subarray(offset, offset + size).toString('utf8'))
|
||
offset += size + 1
|
||
}
|
||
return offset === output.length ? sources : null
|
||
} catch {
|
||
// Preserve per-file reads when a batch exceeds the output limit or cannot run.
|
||
return null
|
||
}
|
||
}
|
||
|
||
export function collectBaseLineBlocks(root, comparisonBase, files = null) {
|
||
// Read all touched base paths including deletions/rename sources; split code may no longer exist under current paths.
|
||
const paths =
|
||
files ??
|
||
splitNullDelimited(
|
||
runGit(root, ['diff', '--name-only', '--no-renames', '-z', comparisonBase, '--'])
|
||
).filter((file) => SOURCE_FILE_PATTERN.test(file))
|
||
const blocks = []
|
||
for (let start = 0; start < paths.length; start += 32) {
|
||
const batch = paths.slice(start, start + 32)
|
||
let sources = readBaseSourceBatch(root, comparisonBase, batch)
|
||
if (sources === null) {
|
||
sources = []
|
||
for (const file of batch) {
|
||
try {
|
||
const result = runProcessSync({
|
||
program: 'git',
|
||
args: ['show', `${comparisonBase}:${file}`],
|
||
cwd: root,
|
||
maxOutputBytes: 64 * 1024 * 1024,
|
||
timeoutMs: null
|
||
})
|
||
if (result.code === 0) {
|
||
sources.push(result.stdout)
|
||
}
|
||
} catch {
|
||
// Failed source reads were already skipped by the per-file implementation.
|
||
continue
|
||
}
|
||
}
|
||
}
|
||
for (const source of sources) {
|
||
blocks.push(source.split(/\r?\n/).map(normalizeSourceLine).filter(Boolean))
|
||
}
|
||
}
|
||
return blocks
|
||
}
|
||
|
||
export function isMovedCode(highlightedLines, baseBlocks) {
|
||
return createMovedCodeMatcher(baseBlocks)(highlightedLines)
|
||
}
|
||
|
||
export function createMovedCodeMatcher(baseBlocks) {
|
||
// Base-revision blocks stay fixed for the gate run; normalize each visited block once.
|
||
const normalizedBlocks = new Map()
|
||
return (highlightedLines) => matchMovedCode(highlightedLines, baseBlocks, normalizedBlocks)
|
||
}
|
||
|
||
function matchMovedCode(highlightedLines, baseBlocks, normalizedBlocks) {
|
||
const needle = highlightedLines.map(normalizeSourceLine).filter((line) => line !== '')
|
||
if (needle.length === 0) {
|
||
return false
|
||
}
|
||
// Moved diagnostics can extend into changed dependency arrays; require same base anchor, preserved order and near-complete span rather than exact whole-block equality.
|
||
const MIN_COVERAGE = 0.9
|
||
return baseBlocks.some((block) => {
|
||
let haystack = normalizedBlocks.get(block)
|
||
if (!haystack) {
|
||
haystack = block.map(normalizeSourceLine).filter((line) => line !== '')
|
||
normalizedBlocks.set(block, haystack)
|
||
}
|
||
for (let start = 0; start < haystack.length; start += 1) {
|
||
if (haystack[start] !== needle[0]) {
|
||
continue
|
||
}
|
||
let matched = 1
|
||
let cursor = start + 1
|
||
for (let index = 1; index < needle.length && cursor < haystack.length; index += 1) {
|
||
while (cursor < haystack.length && haystack[cursor] !== needle[index]) {
|
||
cursor += 1
|
||
}
|
||
if (cursor < haystack.length) {
|
||
matched += 1
|
||
cursor += 1
|
||
}
|
||
}
|
||
if (matched / needle.length >= MIN_COVERAGE) {
|
||
return true
|
||
}
|
||
}
|
||
return false
|
||
})
|
||
}
|
||
|
||
function diagnosticHighlightedLines(root, filename, span) {
|
||
const absolutePath = path.isAbsolute(filename) ? filename : path.join(root, filename)
|
||
const source = readFileSync(absolutePath, 'utf8').split(/\r?\n/)
|
||
const range = diagnosticLineRange(root, filename, span)
|
||
if (range === null) {
|
||
return []
|
||
}
|
||
return source.slice(range.start - 1, range.end)
|
||
}
|
||
|
||
export function diagnosticTouchesAddedLines(
|
||
diagnostic,
|
||
rangesByFile,
|
||
root = process.cwd(),
|
||
baseBlocks = [],
|
||
movedCodeMatcher = isMovedCode
|
||
) {
|
||
const file = normalizedDiagnosticPath(root, diagnostic.filename)
|
||
const ranges = rangesByFile.get(file)
|
||
if (!ranges) {
|
||
return false
|
||
}
|
||
return (diagnostic.labels ?? []).some((label) => {
|
||
const lineRange = diagnosticLineRange(root, diagnostic.filename, label.span)
|
||
if (lineRange === null || !overlapsAddedLines(lineRange.start, lineRange.end, ranges)) {
|
||
return false
|
||
}
|
||
return !movedCodeMatcher(
|
||
diagnosticHighlightedLines(root, diagnostic.filename, label.span),
|
||
baseBlocks
|
||
)
|
||
})
|
||
}
|
||
|
||
function annotationValue(value) {
|
||
return String(value).replaceAll('%', '%25').replaceAll('\r', '%0D').replaceAll('\n', '%0A')
|
||
}
|
||
|
||
function printDiagnostic(diagnostic, root) {
|
||
const file = normalizedDiagnosticPath(root, diagnostic.filename)
|
||
const line = diagnostic.labels?.[0]?.span?.line ?? 1
|
||
const code = diagnostic.code ?? 'oxlint'
|
||
console.error(
|
||
`::error file=${annotationValue(file)},line=${line},title=${annotationValue(code)}::${annotationValue(diagnostic.message)}`
|
||
)
|
||
console.error(`${file}:${line} ${code}: ${diagnostic.message}`)
|
||
}
|
||
|
||
// Why: only the casting scan enforces `assertionStyle: never`, so under the root config an
|
||
// `as` cast is legal and the SAFETY: directive AGENTS.md mandates reads as unused. The untyped
|
||
// scan reports that as a warning, which the gate counts, so exempt exactly those directives.
|
||
export function isCastingDirectiveUnusedWarning(diagnostic, root) {
|
||
if (!/^Unused (?:oxlint|eslint)-disable/.test(diagnostic.message ?? '')) {
|
||
return false
|
||
}
|
||
return (diagnostic.labels ?? []).some((label) =>
|
||
diagnosticHighlightedLines(root, diagnostic.filename, label.span).some((line) =>
|
||
CASTING_DISABLE_PATTERN.test(line)
|
||
)
|
||
)
|
||
}
|
||
|
||
// Unloaded plugin directives are checked by their owning scan.
|
||
export function isUnloadedPluginDirectiveUnusedWarning(diagnostic, root, scanLabel) {
|
||
if (!/^Unused (?:oxlint|eslint)-disable/.test(diagnostic.message ?? '')) {
|
||
return false
|
||
}
|
||
if (scanLabel === 'React Doctor') {
|
||
const labels = diagnostic.labels ?? []
|
||
return (
|
||
labels.length > 0 &&
|
||
labels.every(({ span }) => {
|
||
if (span.offset === undefined || span.length === undefined) {
|
||
return false
|
||
}
|
||
const file = path.isAbsolute(diagnostic.filename)
|
||
? diagnostic.filename
|
||
: path.join(root, diagnostic.filename)
|
||
// Oxlint spans use UTF-8 byte offsets, including before non-ASCII comments.
|
||
const directive = readFileSync(file)
|
||
.subarray(span.offset, span.offset + span.length)
|
||
.toString('utf8')
|
||
const rules = directive.split('--')[0]
|
||
return EXPLICIT_DISABLE_RULE_PATTERN.test(rules) && !/\breact-doctor\//.test(rules)
|
||
})
|
||
)
|
||
}
|
||
return (diagnostic.labels ?? []).some((label) =>
|
||
diagnosticHighlightedLines(root, diagnostic.filename, label.span).some(
|
||
(line) =>
|
||
ANTI_SLOP_DISABLE_PATTERN.test(line) ||
|
||
REACT_DOCTOR_DISABLE_PATTERN.test(line) ||
|
||
JS_PLUGIN_DISABLE_PATTERN.test(line)
|
||
)
|
||
)
|
||
}
|
||
|
||
// Why: oxlint cannot see the AGENTS.md requirement that every casting suppression carry a
|
||
// line-specific SAFETY: rationale, so the directive text itself is checked over added lines.
|
||
export function findCastingDirectivesMissingSafety(root, rangesByFile) {
|
||
const findings = []
|
||
for (const [file, ranges] of rangesByFile) {
|
||
const absolutePath = path.join(root, file)
|
||
if (!existsSync(absolutePath)) {
|
||
continue
|
||
}
|
||
readFileSync(absolutePath, 'utf8')
|
||
.split(/\r?\n/)
|
||
.forEach((text, index) => {
|
||
const line = index + 1
|
||
if (
|
||
CASTING_DISABLE_PATTERN.test(text) &&
|
||
!text.includes('SAFETY:') &&
|
||
overlapsAddedLines(line, line, ranges)
|
||
) {
|
||
findings.push({
|
||
filename: file,
|
||
code: `${CASTING_RULE} (missing SAFETY:)`,
|
||
message: `Suppressing ${CASTING_RULE} requires a line-specific "SAFETY:" explanation.`,
|
||
labels: [{ span: { line } }]
|
||
})
|
||
}
|
||
})
|
||
}
|
||
return findings
|
||
}
|
||
|
||
function isSuppressedDiagnostic(diagnostic, root) {
|
||
const files = SUPPRESSED_REACT_DOCTOR_DIAGNOSTICS.get(diagnostic.code)
|
||
return files?.has(normalizedDiagnosticPath(root, diagnostic.filename)) ?? false
|
||
}
|
||
|
||
function runOxlintScan(root, scan, files) {
|
||
const { command, prefixArgs } = resolveOxlintInvocation(root)
|
||
const result = spawnSync(command, [...prefixArgs, ...scan.args, '--format', 'json', ...files], {
|
||
cwd: root,
|
||
encoding: 'utf8',
|
||
maxBuffer: 128 * 1024 * 1024,
|
||
windowsHide: true
|
||
})
|
||
if (result.error) {
|
||
throw result.error
|
||
}
|
||
if (!result.stdout.trim()) {
|
||
process.stderr.write(result.stderr)
|
||
throw new Error(`${scan.label} failed before producing diagnostics.`)
|
||
}
|
||
return parseOxlintOutput(result.stdout, scan.label).diagnostics ?? []
|
||
}
|
||
|
||
/** ast-grep matches as Oxlint-shaped diagnostics; `info` flaky-test rules are owned by their ratchet. */
|
||
export function runAstGrepScan(root, files) {
|
||
return scanAstGrep(root, { minSeverity: 'warning', paths: files }).map((match) => ({
|
||
filename: match.file,
|
||
code: `ast-grep(${match.ruleId})`,
|
||
message: match.message,
|
||
labels: [
|
||
{
|
||
span: {
|
||
line: match.range.start.line + 1,
|
||
offset: match.range.byteOffset.start,
|
||
length: match.range.byteOffset.end - match.range.byteOffset.start
|
||
}
|
||
}
|
||
]
|
||
}))
|
||
}
|
||
|
||
export function main(
|
||
root = process.cwd(),
|
||
requestedBase = process.argv.slice(2).find((argument) => argument !== '--')
|
||
) {
|
||
const { comparisonBase, rangesByFile } = collectAddedLineRanges(root, requestedBase)
|
||
const files = [...rangesByFile.keys()]
|
||
if (files.length === 0) {
|
||
console.log(
|
||
`Changed-code quality gate: no changed JavaScript or TypeScript since ${comparisonBase.slice(0, 12)}.`
|
||
)
|
||
return 0
|
||
}
|
||
|
||
const baseBlocks = collectBaseLineBlocks(root, comparisonBase)
|
||
const movedCodeMatcher = createMovedCodeMatcher(baseBlocks)
|
||
|
||
let failures = 0
|
||
for (const scan of OXLINT_SCANS) {
|
||
const diagnostics = runOxlintScan(root, scan, files).filter(
|
||
(diagnostic) =>
|
||
!isSuppressedDiagnostic(diagnostic, root) &&
|
||
!isCastingDirectiveUnusedWarning(diagnostic, root) &&
|
||
!isUnloadedPluginDirectiveUnusedWarning(diagnostic, root, scan.label) &&
|
||
diagnosticTouchesAddedLines(diagnostic, rangesByFile, root, baseBlocks, movedCodeMatcher)
|
||
)
|
||
for (const diagnostic of diagnostics) {
|
||
printDiagnostic(diagnostic, root)
|
||
}
|
||
failures += diagnostics.length
|
||
console.log(
|
||
`${scan.label}: ${diagnostics.length} new finding(s) across ${files.length} changed file(s).`
|
||
)
|
||
}
|
||
|
||
const astGrepFindings = runAstGrepScan(root, files).filter((diagnostic) =>
|
||
diagnosticTouchesAddedLines(diagnostic, rangesByFile, root, baseBlocks, movedCodeMatcher)
|
||
)
|
||
for (const diagnostic of astGrepFindings) {
|
||
printDiagnostic(diagnostic, root)
|
||
}
|
||
failures += astGrepFindings.length
|
||
console.log(
|
||
`ast-grep: ${astGrepFindings.length} new finding(s) across ${files.length} changed file(s).`
|
||
)
|
||
|
||
const missingSafety = findCastingDirectivesMissingSafety(root, rangesByFile)
|
||
for (const diagnostic of missingSafety) {
|
||
printDiagnostic(diagnostic, root)
|
||
}
|
||
failures += missingSafety.length
|
||
console.log(
|
||
`casting SAFETY: rationale: ${missingSafety.length} new finding(s) across ${files.length} changed file(s).`
|
||
)
|
||
|
||
if (failures > 0) {
|
||
console.error(
|
||
`Changed-code quality gate failed with ${failures} finding(s) since ${comparisonBase.slice(0, 12)}.`
|
||
)
|
||
return 1
|
||
}
|
||
console.log(`Changed-code quality gate passed since ${comparisonBase.slice(0, 12)}.`)
|
||
return 0
|
||
}
|
||
|
||
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
||
process.exit(main())
|
||
}
|