@quikit/quikpilot-runner 9.2.0-rc.7 → 9.2.0-rc.8
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/README.md +14 -0
- package/dist/index.js +9202 -216
- package/dist/index.js.map +4 -4
- package/package.json +4 -1
package/dist/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/env.ts", "../src/quiktrackError.ts", "../src/callback.ts", "../src/commands.ts", "../src/commandEnv.ts", "../src/git.ts", "../src/commit.ts", "../src/codegen.ts", "../src/deniedPaths.ts", "../src/editsApply.ts", "../src/runtimeReplyError.ts", "../src/envelope.ts", "../src/importContext.ts", "../src/retryFetch.ts", "../src/codegenMode.ts", "../src/codegenLoopRecord.ts", "../src/codegenLoopContext.ts", "../src/overlapCheck.ts", "../src/addOnly.ts", "../src/targetingPaths.ts", "../src/targetingTools.ts", "../src/workspaceOverlay.ts", "../src/codegenTools.ts", "../src/targetingErrors.ts", "../src/tokenEstimate.ts", "../src/targetingLoop.ts", "../src/codegenLoop.ts", "../src/codegenStep.ts", "../src/dependencyCheck.ts", "../src/guardrail.ts", "../src/installationToken.ts", "../src/oidc.ts", "../src/packet.ts", "../src/phase0.ts", "../src/quiktest.ts", "../src/baselineCheck.ts", "../src/regressionCheck.ts", "../src/failureArtifact.ts", "../src/failureReason.ts", "../src/scopeCheck.ts", "../src/targeting.ts", "../src/targetingMode.ts", "../src/targetingRecord.ts", "../src/testPlacementCheck.ts", "../src/tokenExchange.ts", "../src/vanishedTests.ts", "../src/run.ts", "../src/readinessCheck.ts", "../src/index.ts"],
|
|
4
|
-
"sourcesContent": ["/** The `workflow_dispatch` inputs QuikTrack's `dispatch.ts` sends, unchanged by QUIKTR-572 \u2014 the\r\n * generated workflow file still passes them through as job-level env vars under these exact\r\n * names. QUIKTR-805: `runToken`/`RUN_TOKEN` (a bearer, visible in the Actions UI as a dispatch\r\n * input) was replaced with `tokenUrl`/`TOKEN_URL` \u2014 the runner now exchanges a GitHub OIDC ID\r\n * token there for a run token at runtime; see `oidc.ts` and `tokenExchange.ts`. QUIKTR-804 adds\r\n * `installationTokenUrl`/`INSTALLATION_TOKEN_URL` \u2014 the run token is exchanged there for a\r\n * repo-scoped GitHub push credential; see `installationToken.ts`. */\r\nexport interface PilotRunEnv {\r\n mode: \"run\";\r\n runId: string;\r\n callbackUrl: string;\r\n packetUrl: string;\r\n tokenUrl: string;\r\n installationTokenUrl: string;\r\n /** GitHub Actions built-ins, read directly from `process.env` rather than threaded through here\r\n * individually. */\r\n githubRunId: string;\r\n githubServerUrl: string;\r\n githubRepository: string;\r\n}\r\n\r\n/**\r\n * QUIKTR-1084 \u2014 the readiness dry-run branch. Deliberately carries none of `PilotRunEnv`'s\r\n * fields: no packet fetch, no OIDC/run-token exchange, no design/codegen/commit/push. It only\r\n * needs the two commands to run and where to report the result.\r\n *\r\n * `readinessToken`/`READINESS_TOKEN` travels as a plain dispatch input, unlike the pilot-run\r\n * token \u2014 deliberately. QUIKTR-805 stopped doing that for the run token because a leaked one\r\n * could spend money through the LLM gateway; this token can only POST a\r\n * `{ junitFound, junitPath }` result for the one `QtPilotConfig` it was minted for (see\r\n * `readiness-dispatch.ts`), which is the same blast radius the pre-805 run token had. Splitting\r\n * out a second OIDC-exchange endpoint to protect a credential this narrow isn't worth the new\r\n * surface.\r\n */\r\nexport interface ReadinessCheckEnv {\r\n mode: \"readiness_check\";\r\n readinessToken: string;\r\n readinessCallbackUrl: string;\r\n setupCmd: string;\r\n testCmd: string;\r\n githubRunId: string;\r\n githubServerUrl: string;\r\n githubRepository: string;\r\n}\r\n\r\nexport type RunnerEnv = PilotRunEnv | ReadinessCheckEnv;\r\n\r\nexport function required(name: string, value: string | undefined): string {\r\n if (!value) {\r\n throw new Error(`Missing required environment variable: ${name}`);\r\n }\r\n return value;\r\n}\r\n\r\nexport function readRunnerEnv(env: NodeJS.ProcessEnv = process.env): RunnerEnv {\r\n const githubRunId = required(\"GITHUB_RUN_ID\", env.GITHUB_RUN_ID);\r\n const githubServerUrl = env.GITHUB_SERVER_URL ?? \"https://github.com\";\r\n const githubRepository = required(\"GITHUB_REPOSITORY\", env.GITHUB_REPOSITORY);\r\n\r\n if (env.MODE === \"readiness_check\") {\r\n return {\r\n mode: \"readiness_check\",\r\n readinessToken: required(\"READINESS_TOKEN\", env.READINESS_TOKEN),\r\n readinessCallbackUrl: required(\"READINESS_CALLBACK_URL\", env.READINESS_CALLBACK_URL),\r\n setupCmd: env.SETUP_CMD ?? \"\",\r\n testCmd: required(\"TEST_CMD\", env.TEST_CMD),\r\n githubRunId,\r\n githubServerUrl,\r\n githubRepository,\r\n };\r\n }\r\n\r\n return {\r\n mode: \"run\",\r\n runId: required(\"RUN_ID\", env.RUN_ID),\r\n callbackUrl: required(\"CALLBACK_URL\", env.CALLBACK_URL),\r\n packetUrl: required(\"PACKET_URL\", env.PACKET_URL),\r\n tokenUrl: required(\"TOKEN_URL\", env.TOKEN_URL),\r\n installationTokenUrl: required(\"INSTALLATION_TOKEN_URL\", env.INSTALLATION_TOKEN_URL),\r\n githubRunId,\r\n githubServerUrl,\r\n githubRepository,\r\n };\r\n}\r\n", "/**\r\n * QUIKTR-1080 \u2014 QuikTrack's internal pilot routes return a stable `reason_code` in the body on\r\n * every `pilotError()`-shaped failure (401/403/409/429); the generic 500 catch-all has none, and a\r\n * non-2xx response isn't guaranteed to be JSON at all (a proxy/gateway error can produce a\r\n * non-JSON body). Best effort: falls back to bare status/statusText when `reason_code` is absent\r\n * or the body doesn't parse \u2014 never throws itself.\r\n *\r\n * Unrelated to envelope.ts's `errorCode` \u2014 that's the AI Runtime's own, separate `/ai/execute`\r\n * contract. Two different services, two different field names; not to be conflated.\r\n */\r\nexport async function describeQuikTrackFailure(res: Response): Promise<string> {\r\n try {\r\n const body = await res.json();\r\n if (body && typeof body === \"object\" && typeof (body as Record<string, unknown>).reason_code === \"string\") {\r\n return `${res.status} ${res.statusText} (${(body as Record<string, unknown>).reason_code})`;\r\n }\r\n } catch {\r\n // not JSON, no json() method at all, or already consumed \u2014 fall back below\r\n }\r\n return `${res.status} ${res.statusText}`;\r\n}\r\n", "import { describeQuikTrackFailure } from \"./quiktrackError\";\r\nimport type { BaselineFindings } from \"./baselineCheck\";\r\nimport type { CodegenLoopRecord } from \"./codegenLoopRecord\";\r\nimport type { TargetingRecord } from \"./targetingRecord\";\r\nimport type { VanishedTests } from \"./vanishedTests\";\r\n\r\nexport type RunStatus = \"completed\" | \"failed\";\r\n\r\n/** Always fires, regardless of what failed upstream \u2014 a run that fails silently is worse than one\r\n * that fails loudly. `branch` is omitted entirely (not sent as null/empty) when no push happened,\r\n * matching the original `jq ... | with_entries(select(.value != null and .value != \"\"))`. Same\r\n * treatment for `warnings` (QUIKTR-1064) \u2014 non-fatal findings like a targeting overlap, omitted\r\n * when there are none rather than sent as an empty array. */\r\nexport async function reportBack(params: {\r\n callbackUrl: string;\r\n runToken: string;\r\n status: RunStatus;\r\n branch?: string;\r\n warnings?: string[];\r\n /** QUIKTR-1421 \u2014 what pilot.targeting decided (paths and case ids only). Omitted when targeting never\r\n * produced a result; an older QuikTrack strips the unknown key silently. */\r\n targeting?: TargetingRecord;\r\n /** QUIKTR-1402 \u2014 test cases that passed against the unmodified code (ids only). Omitted when the check\r\n * flagged nothing or did not run; QuikTrack validates it separately and drops a bad one. */\r\n baselineFindings?: BaselineFindings;\r\n /** QUIKTR-1448 \u2014 tests that ran before the change and are missing from the final report. Test titles are the\r\n * customer's own text, so QuikTrack puts them in the pull request description only and stores none. Omitted when\r\n * nothing is missing; an older QuikTrack ignores the unknown key. */\r\n vanishedTests?: VanishedTests;\r\n /** QUIKTR-1458 \u00A724 \u2014 what the code-writing loop did (paths, counts and the AI's short reasoning), when it ran or was tried. Omitted\r\n * otherwise; an older QuikTrack ignores the unknown key. */\r\n codegenLoop?: CodegenLoopRecord;\r\n /** Why a failed run stopped (already written on one line, cut and scrubbed of credentials). Omitted when there is\r\n * nothing to say; an older QuikTrack accepts it and ignores it for a failed run. */\r\n unresolved?: string[];\r\n}): Promise<void> {\r\n const { callbackUrl, runToken, status, branch, warnings, targeting, baselineFindings, vanishedTests, codegenLoop, unresolved } = params;\r\n const body: Record<string, unknown> = { status };\r\n if (branch) body.branch = branch;\r\n if (warnings && warnings.length > 0) body.warnings = warnings;\r\n if (unresolved && unresolved.length > 0) body.unresolved = unresolved;\r\n if (targeting) body.targeting = targeting;\r\n if (baselineFindings) body.baselineFindings = baselineFindings;\r\n if (vanishedTests) body.vanishedTests = vanishedTests;\r\n if (codegenLoop) body.codegenLoop = codegenLoop;\r\n const res = await fetch(callbackUrl, {\r\n method: \"POST\",\r\n headers: { Authorization: `Bearer ${runToken}`, \"Content-Type\": \"application/json\" },\r\n body: JSON.stringify(body),\r\n });\r\n if (!res.ok) {\r\n throw new Error(`Report back to QuikTrack failed: ${await describeQuikTrackFailure(res)}`);\r\n }\r\n}\r\n", "import { execSync, spawn } from \"node:child_process\";\r\nimport { commandEnv, withheldNames } from \"./commandEnv\";\r\n\r\n/** QUIKTR-1502 \u2014 every repository command runs with this, never with the runner's own environment.\r\n * The names withheld are logged once per process (names only), so a command that needed something\r\n * is diagnosable from the job log. */\r\nlet withheldLogged = false;\r\nfunction repositoryCommandEnv(): NodeJS.ProcessEnv {\r\n if (!withheldLogged) {\r\n withheldLogged = true;\r\n const names = withheldNames();\r\n if (names.length > 0) {\r\n console.log(`Repository commands run without ${names.length} environment variable(s): ${names.join(\", \")}`);\r\n }\r\n }\r\n return commandEnv();\r\n}\r\n\r\n/** Runs a packet-supplied command through bash \u2014 same interpreter GitHub's own `run:` steps used,\r\n * so a command written against that shell (e.g. `set -o pipefail`-reliant) behaves the same way.\r\n * A null/empty command is a no-op, matching the original `[ -n \"$CMD\" ]` guard. */\r\nexport function runCommand(command: string | null, label: string): void {\r\n if (!command) return;\r\n try {\r\n execSync(command, { shell: \"/bin/bash\", stdio: \"inherit\", env: repositoryCommandEnv() });\r\n } catch (err) {\r\n throw new Error(`${label} failed: ${err instanceof Error ? err.message : String(err)}`);\r\n }\r\n}\r\n\r\nexport type TestOutcome = \"success\" | \"failure\";\r\n\r\n/** The Test step alone is soft \u2014 a failing suite must not hide the rest of the run (guardrail,\r\n * commit, push) from happening, and must not flip the final callback to `failed`. QuikTest owns\r\n * per-test outcomes; this is only ever logged, never reported. QUIKTR-1036: this is still correct\r\n * for a NO_TARGET run (nothing was generated, so there's nothing to regress against) \u2014 a\r\n * codegen'd run's Test step is decided by regressionCheck.ts instead, using the async twin below. */\r\nexport function runTestCommand(command: string | null): TestOutcome {\r\n if (!command) return \"success\";\r\n try {\r\n execSync(command, { shell: \"/bin/bash\", stdio: \"inherit\", env: repositoryCommandEnv() });\r\n return \"success\";\r\n } catch {\r\n return \"failure\";\r\n }\r\n}\r\n\r\n/** Same contract as `runTestCommand`, but non-blocking: `execSync` blocks the event loop, which\r\n * would serialize the baseline test run behind (or in front of) codegen's network-bound calls\r\n * instead of letting them overlap. QUIKTR-1036 \u2014 the baseline run is the only caller today. */\r\nexport function runTestCommandAsync(command: string | null): Promise<TestOutcome> {\r\n if (!command) return Promise.resolve(\"success\");\r\n return new Promise((resolve) => {\r\n const child = spawn(command, { shell: \"/bin/bash\", stdio: \"inherit\", env: repositoryCommandEnv() });\r\n child.on(\"exit\", (code) => resolve(code === 0 ? \"success\" : \"failure\"));\r\n child.on(\"error\", () => resolve(\"failure\"));\r\n });\r\n}\r\n\r\nexport type TimedRunOutcome = \"exited\" | \"timeout\" | \"error\";\r\n\r\n/**\r\n * QUIKTR-1402 \u2014 runs a command through bash with a hard time limit, for the baseline check's single-file\r\n * run. A command that HANGS produces no error, so \"any failure means no flag\" cannot cover it: without a\r\n * limit it would hold the run until the job's own limit and look like QuikPilot being slow. The exit code\r\n * is deliberately not reported \u2014 a failing test is the normal outcome of running a generated test against\r\n * code that does not have the change yet; only \"finished\", \"timed out\" and \"could not start\" matter.\r\n *\r\n * The command runs in its own process group (`detached`) so a timeout can kill the test runner AND\r\n * whatever it started; killing only the shell would leave the runner holding the job open.\r\n */\r\nexport function runCommandWithTimeout(command: string, timeoutMs: number): Promise<TimedRunOutcome> {\r\n return new Promise((resolve) => {\r\n let settled = false;\r\n const finish = (outcome: TimedRunOutcome) => {\r\n if (settled) return;\r\n settled = true;\r\n clearTimeout(timer);\r\n resolve(outcome);\r\n };\r\n const child = spawn(command, {\r\n shell: \"/bin/bash\",\r\n stdio: \"inherit\",\r\n detached: true,\r\n env: repositoryCommandEnv(),\r\n });\r\n const timer = setTimeout(() => {\r\n try {\r\n if (child.pid !== undefined) process.kill(-child.pid, \"SIGKILL\");\r\n else child.kill(\"SIGKILL\");\r\n } catch {\r\n try {\r\n child.kill(\"SIGKILL\");\r\n } catch {\r\n // already gone\r\n }\r\n }\r\n finish(\"timeout\");\r\n }, timeoutMs);\r\n child.on(\"exit\", () => finish(\"exited\"));\r\n child.on(\"error\", () => finish(\"error\"));\r\n });\r\n}\r\n", "/**\r\n * QUIKTR-1502 \u2014 the environment a repository command runs with.\r\n *\r\n * Setup, Test, Lint, Format and the baseline checks run code nobody has reviewed yet: AI-written\r\n * tests, and whatever a dependency's install script does. Handing them the runner's own environment\r\n * hands them `ACTIONS_ID_TOKEN_REQUEST_URL` and `_TOKEN` (GitHub adds both to every step of a job\r\n * with `id-token: write`), which request an OIDC token that QuikProjects exchanges for a run token.\r\n * The server now refuses a second exchange per dispatch, which is what actually closes that path;\r\n * this is the second layer, and it also keeps the artifact/cache service credentials, the ambient\r\n * job token and the runner's own addresses out of reach.\r\n *\r\n * An allow-list, not a block-list: a variable GitHub or the runner image adds next year is withheld\r\n * until someone decides it is needed. What it cannot do is hide the runner's own environment from a\r\n * child that reads `/proc/<parent>/environ` (same user, same job); that is why the server-side\r\n * rule exists.\r\n *\r\n * What is withheld is reported by NAME (never value) so a command that needed something is\r\n * diagnosable; see `commands.ts`.\r\n */\r\n\r\n/** Names kept exactly. */\r\nconst ALLOWED_NAMES = new Set([\r\n // Identity, locale and scratch space.\r\n \"PATH\", \"Path\", \"HOME\", \"USER\", \"USERNAME\", \"LOGNAME\", \"SHELL\", \"HOSTNAME\",\r\n \"TMPDIR\", \"TMP\", \"TEMP\", \"TZ\", \"LANG\", \"LANGUAGE\", \"TERM\", \"COLORTERM\", \"NO_COLOR\", \"FORCE_COLOR\",\r\n \"DISPLAY\", \"CI\",\r\n // Windows system variables, for the developer machine.\r\n \"SystemRoot\", \"SYSTEMROOT\", \"windir\", \"COMSPEC\", \"PATHEXT\", \"USERPROFILE\", \"APPDATA\", \"LOCALAPPDATA\",\r\n // Network settings a hosted or self-hosted runner may rely on.\r\n \"HTTP_PROXY\", \"HTTPS_PROXY\", \"NO_PROXY\", \"ALL_PROXY\",\r\n \"http_proxy\", \"https_proxy\", \"no_proxy\", \"all_proxy\",\r\n \"SSL_CERT_FILE\", \"SSL_CERT_DIR\", \"NODE_EXTRA_CA_CERTS\", \"REQUESTS_CA_BUNDLE\", \"CURL_CA_BUNDLE\",\r\n // Toolchain locations the setup-* actions and the runner image export.\r\n \"NODE_OPTIONS\", \"NODE_PATH\", \"NVM_DIR\", \"ImageOS\", \"ImageVersion\", \"AGENT_TOOLSDIRECTORY\",\r\n \"CONDA\", \"pythonLocation\", \"PKG_CONFIG_PATH\", \"LD_LIBRARY_PATH\",\r\n \"CARGO_HOME\", \"RUSTUP_HOME\", \"GOPATH\", \"GOMODCACHE\", \"GOCACHE\", \"GOFLAGS\",\r\n \"JAVA_HOME\", \"GRADLE_HOME\", \"GRADLE_USER_HOME\", \"MAVEN_HOME\", \"M2_HOME\",\r\n \"ANDROID_HOME\", \"ANDROID_SDK_ROOT\",\r\n \"GEM_HOME\", \"GEM_PATH\", \"BUNDLE_PATH\", \"PIPX_HOME\", \"PIPX_BIN_DIR\", \"POETRY_HOME\",\r\n \"PNPM_HOME\", \"BUN_INSTALL\", \"DENO_INSTALL\", \"DENO_DIR\", \"VOLTA_HOME\", \"COREPACK_HOME\", \"PYENV_ROOT\", \"RBENV_ROOT\",\r\n]);\r\n\r\n/** Families kept by prefix. Case matters: toolchains export these exact spellings. */\r\nconst ALLOWED_PREFIXES = [\r\n \"LC_\",\r\n \"RUNNER_\",\r\n \"GITHUB_\",\r\n \"JAVA_HOME_\",\r\n \"GOROOT\",\r\n \"ANDROID_NDK\",\r\n \"Python\", // Python_ROOT_DIR, Python2_ROOT_DIR, Python3_ROOT_DIR\r\n \"XDG_\",\r\n \"DOTNET_\",\r\n \"VCPKG_\",\r\n \"npm_config_\",\r\n \"NPM_CONFIG_\",\r\n];\r\n\r\n/** Dropped even though a family above would keep them: the ambient job token, and the files a\r\n * command could append to in order to steer the job's LATER steps (the upload-artifact step runs\r\n * after the runner). */\r\nconst ALWAYS_WITHHELD = new Set([\r\n \"GITHUB_TOKEN\", \"GITHUB_ENV\", \"GITHUB_PATH\", \"GITHUB_OUTPUT\", \"GITHUB_STATE\", \"GITHUB_STEP_SUMMARY\",\r\n]);\r\n\r\n/** A name that reads like a credential is dropped even inside an allowed family or under an\r\n * allowed name. */\r\nconst CREDENTIAL_NAME = /(token|secret|password|passwd|credential|private_?key|api_?key)/i;\r\n\r\nfunction isAllowed(name: string): boolean {\r\n if (ALWAYS_WITHHELD.has(name) || CREDENTIAL_NAME.test(name)) return false;\r\n if (ALLOWED_NAMES.has(name)) return true;\r\n return ALLOWED_PREFIXES.some((prefix) => name.startsWith(prefix));\r\n}\r\n\r\n/** A fresh environment for a repository command: the allow-listed variables of `source` and nothing else. */\r\nexport function commandEnv(source: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {\r\n const out: NodeJS.ProcessEnv = {};\r\n for (const [name, value] of Object.entries(source)) {\r\n if (value === undefined) continue;\r\n if (isAllowed(name)) out[name] = value;\r\n }\r\n return out;\r\n}\r\n\r\n/** The names `commandEnv` drops, sorted. Names only: a value never leaves this module. */\r\nexport function withheldNames(source: NodeJS.ProcessEnv = process.env): string[] {\r\n return Object.entries(source)\r\n .filter(([name, value]) => value !== undefined && !isAllowed(name))\r\n .map(([name]) => name)\r\n .sort();\r\n}\r\n", "import { execFileSync } from \"node:child_process\";\r\n\r\n/** Thin wrapper around `execFileSync` \u2014 args passed as an array, never through a shell, so a\r\n * branch name or guardrail pattern can never be interpreted as shell syntax. `extraEnv` layers\r\n * on top of the inherited environment; every existing call site is unaffected since it defaults\r\n * to empty. */\r\nfunction git(args: string[], extraEnv: NodeJS.ProcessEnv = {}): string {\r\n return execFileSync(\"git\", args, {\r\n encoding: \"utf8\",\r\n env: { ...process.env, ...extraEnv },\r\n }).trim();\r\n}\r\n\r\nexport function currentBranch(): string {\r\n return git([\"rev-parse\", \"--abbrev-ref\", \"HEAD\"]);\r\n}\r\n\r\n/** Only fetches + checks out when the packet names a target branch different from the one the\r\n * workflow_dispatch already put us on \u2014 dispatch always runs against the default branch (the\r\n * only place `workflow_dispatch` can find the file), but the PR base may differ. */\r\nexport function checkoutTargetBranch(targetBranch: string | null): void {\r\n if (!targetBranch || targetBranch === currentBranch()) return;\r\n git([\"fetch\", \"origin\", targetBranch]);\r\n git([\"checkout\", targetBranch]);\r\n}\r\n\r\nexport function addAll(): void {\r\n git([\"add\", \"-A\"]);\r\n}\r\n\r\n/** `:(glob)` pathspec \u2014 same semantics `**` needs that a hand-rolled glob-to-regex would risk\r\n * getting wrong. */\r\nexport function diffCachedNamesMatching(pattern: string): string[] {\r\n const out = git([\"diff\", \"--cached\", \"--name-only\", \"--\", `:(glob)${pattern}`]);\r\n return out ? out.split(\"\\n\").filter(Boolean) : [];\r\n}\r\n\r\n/** Tracked files under `pathspec`, relative to cwd \u2014 same cwd every other export here already\r\n * assumes is the checkout root, so a caller can feed these straight to readFileSync/writeFileSync\r\n * with no translation. QUIKTR-1035 \u2014 `pathspec` is always concrete; \"null means repo root\" is\r\n * targeting.ts's workspaceRoot concept, not a generic git one. */\r\nexport function listFiles(pathspec: string): string[] {\r\n const out = git([\"ls-files\", \"--\", pathspec]);\r\n return out ? out.split(\"\\n\").filter(Boolean) : [];\r\n}\r\n\r\nexport function hasStagedChanges(): boolean {\r\n try {\r\n execFileSync(\"git\", [\"diff\", \"--cached\", \"--quiet\"]);\r\n return false;\r\n } catch {\r\n return true;\r\n }\r\n}\r\n\r\nexport function configureCommitIdentity(): void {\r\n git([\"config\", \"user.name\", \"quikpilot[bot]\"]);\r\n git([\"config\", \"user.email\", \"quikpilot@users.noreply.github.com\"]);\r\n}\r\n\r\nexport function checkoutNewBranch(branch: string): void {\r\n git([\"checkout\", \"-b\", branch]);\r\n}\r\n\r\nexport function commit(message: string): void {\r\n git([\"commit\", \"-m\", message]);\r\n}\r\n\r\n/**\r\n * Push, authenticated with a repo-scoped GitHub installation token (QUIKTR-804, D16) rather than\r\n * whatever ambient credential checkout configured. `x-access-token:<token>` Basic-auth, GitHub's\r\n * documented scheme for installation tokens over HTTPS git.\r\n *\r\n * Carried via `GIT_CONFIG_COUNT`/`GIT_CONFIG_KEY_0`/`GIT_CONFIG_VALUE_0` env vars rather than a\r\n * `-c http.extraheader=...` argv flag or a `.git/config` write: env vars are not visible to `ps`,\r\n * argv is \u2014 the same class of exposure `packet.ts`'s own header comment already avoids for this\r\n * runner's other credential. Scoped to this one invocation only; never persisted.\r\n *\r\n * QUIKTR-943 rehearsal, 7.0.1 \u2014 the key MUST be `http.https://github.com/.extraheader`\r\n * (URL-scoped), not the unscoped `http.extraheader`. `actions/checkout` persists its own\r\n * credential under the URL-scoped key, pointing at the job's ambient token (contents: read since\r\n * QUIKTR-804 dropped it). Git prefers the more specific URL-scoped key, so an unscoped header here\r\n * silently loses to checkout's read-only one \u2014 the push then fails with \"denied to\r\n * github-actions[bot]\" even though this token itself has write access and the exchange succeeded.\r\n *\r\n * QUIKTR-943 rehearsal, 7.0.2 \u2014 url-scoping alone re-broke the push a second way:\r\n * `http.<url>.extraheader` is multi-valued (git appends, it doesn't replace), so checkout's\r\n * `.git/config` entry and this call's env-var entry are BOTH sent, and GitHub 400s with\r\n * `Duplicate header: \"Authorization\"`. `--unset-all` clears checkout's entry from `.git/config`\r\n * first, so our env-var header (scoped to this one invocation, never written to disk) is the only\r\n * one on the wire. Tolerates the key already being absent (exit 5) \u2014 nothing to clear is not a\r\n * failure, and a workflow that ever runs with `persist-credentials: false` shouldn't crash here.\r\n */\r\nfunction clearCheckoutExtraHeader(): void {\r\n try {\r\n git([\"config\", \"--unset-all\", \"http.https://github.com/.extraheader\"]);\r\n } catch (err: unknown) {\r\n const status = (err as { status?: number }).status;\r\n if (status !== 5) throw err;\r\n }\r\n}\r\n\r\nexport function push(branch: string, installationToken: string): void {\r\n clearCheckoutExtraHeader();\r\n const basicAuth = Buffer.from(`x-access-token:${installationToken}`).toString(\"base64\");\r\n git([\"push\", \"--set-upstream\", \"origin\", branch], {\r\n GIT_CONFIG_COUNT: \"1\",\r\n GIT_CONFIG_KEY_0: \"http.https://github.com/.extraheader\",\r\n GIT_CONFIG_VALUE_0: `AUTHORIZATION: basic ${basicAuth}`,\r\n });\r\n}\r\n", "import {\r\n checkoutNewBranch,\r\n commit,\r\n configureCommitIdentity,\r\n hasStagedChanges,\r\n push,\r\n} from \"./git\";\r\n\r\nexport interface CommitResult {\r\n changed: boolean;\r\n branch?: string;\r\n}\r\n\r\n/**\r\n * QUIKTR-1067 \u2014 \"QuikPilot Phase 0 skeleton\" used to be hardcoded for every commit, including one\r\n * carrying a real generated fix (PR #19) \u2014 indistinguishable from the genuinely-empty NO_TARGET\r\n * marker commit without opening the diff, and git history is permanent. `targeted: false` is the\r\n * one case that message is still accurate for. `issueKey`/`issueTitle` null with `targeted: true`\r\n * is defensive only \u2014 dispatch never reaches commit before Gate 1, which always attaches an issue.\r\n */\r\nexport function buildCommitMessage(\r\n runId: string,\r\n targeted: boolean,\r\n issueKey: string | null,\r\n issueTitle: string | null,\r\n): string {\r\n if (!targeted) return `QuikPilot Phase 0 skeleton (run ${runId})`;\r\n if (issueKey && issueTitle) return `${issueKey}: ${issueTitle}\\n\\nQuikPilot run ${runId}`;\r\n return `QuikPilot generated changes (run ${runId})`;\r\n}\r\n\r\n/** Runs regardless of the Test step's outcome \u2014 a failing suite must not hide the generated diff\r\n * from a reviewer (the whole reason Test alone is a soft failure). Only reached when Setup, Lint,\r\n * and the guardrail check all passed. The branch name comes from the packet, not `runId`: QuikTrack\r\n * already computed and stored it, and two sources for one value will eventually disagree.\r\n * `installationToken` (QUIKTR-804) is the repo-scoped GitHub credential the push authenticates\r\n * with \u2014 see git.ts's `push` for why. */\r\nexport function commitAndPush(\r\n branch: string | null,\r\n runId: string,\r\n installationToken: string,\r\n targeted: boolean,\r\n issueKey: string | null,\r\n issueTitle: string | null,\r\n): CommitResult {\r\n if (!hasStagedChanges()) return { changed: false };\r\n if (!branch) {\r\n throw new Error(\"packet carried no branch name\");\r\n }\r\n configureCommitIdentity();\r\n checkoutNewBranch(branch);\r\n commit(buildCommitMessage(runId, targeted, issueKey, issueTitle));\r\n push(branch, installationToken);\r\n return { changed: true, branch };\r\n}\r\n", "import { readFileSync, writeFileSync, mkdirSync } from \"node:fs\";\r\nimport { dirname } from \"node:path\";\r\nimport { findDeniedContextPath, matchesDeniedPath } from \"./deniedPaths\";\r\nimport { applyEdits, detectLineEnding, fromLf, toLf, type AnchorRefusal, type LineEnding } from \"./editsApply\";\r\nimport { checkHardFailure, unwrapExecute } from \"./envelope\";\r\nimport { ACTIONABLE_IMPORT_SKIPS, collectImportContext } from \"./importContext\";\r\nimport { RuntimeReplyError } from \"./runtimeReplyError\";\r\nimport type { PilotPacket } from \"./packet\";\r\nimport { fetchWithRetry } from \"./retryFetch\";\r\nimport type { CodegenContextRecord } from \"./targetingRecord\";\r\nimport type { PilotTarget, SkippedCase } from \"./targeting\";\r\n\r\n/**\r\n * QUIKTR-823 \u2014 one `/ai/execute` call per file, proven working against a real request this\r\n * morning (Suyash): `x-run-token` header carrying the packet's `gateway.token`, full file content\r\n * in and out. Never a patch \u2014 a failed apply would cost a whole extra call against a tight budget,\r\n * and a patch that can't apply is exactly the kind of failure this loop can't safely paper over.\r\n *\r\n * QUIKTR-1035 \u2014 `targets` (with per-target `planStepsImplemented`) replaces the old\r\n * `targetPaths: string[]` plus a single `design`-derived `planSteps` shared across every file.\r\n * Merging targeting's per-target steps back into one shared list would destroy the reason they're\r\n * per-target: the route file and the service file need different instructions.\r\n *\r\n * \u2500\u2500 ALL-OR-NOTHING \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n *\r\n * The first failed or REFUSED file throws, and `run.ts`'s existing hard-failure handling takes it\r\n * from there: no branch, no pull request. A pull request is a claim the work is done; a\r\n * partially-applied change compiles sometimes, passes tests sometimes, and looks complete either\r\n * way. Already decided twice elsewhere for the same reason \u2014 Gate 1's spec commit is one\r\n * transaction, and `create_issue` with `testCases` is explicitly all-or-nothing. Retrying the\r\n * failed file instead of discarding the rest is the better long-run answer and belongs with\r\n * self-heal (Phase 3, unscoped) \u2014 not silently attempted here.\r\n *\r\n * `CODEGEN_FILE_TOO_LARGE` and `CODEGEN_CONTEXT_TOO_LARGE` are the AI Runtime's own distinct error\r\n * codes, checked on their side before dispatch \u2014 retrying hits the identical wall every time, so\r\n * both are deliberately not retried, same as every other failure here.\r\n *\r\n * \u2500\u2500 CONTEXT CONTRACT (contextPaths \u2192 contextContents) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n *\r\n * pilot.targeting now names, per target, which other files pilot.codegen should read\r\n * (`target.contextPaths`) \u2014 replacing the old `siblingContent` guess (nearest file by directory),\r\n * which only ever ran for NEW_FILE targets and was never more than a stated assumption about this\r\n * repo's own layout. `contextContents: [{ path, content }]` is now sent for EXISTING targets too,\r\n * not just NEW_FILE. Empty/absent contextPaths means empty contextContents \u2014 no fallback.\r\n * `workspaceListing` still goes out for NEW_FILE only, unchanged.\r\n *\r\n * \u2500\u2500 BUFFERED WRITES (QUIKTR-1035) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n *\r\n * `runCodegen` no longer writes anything \u2014 it collects `{targetPath, newContent}` in memory and\r\n * `flushCodegenResults` writes them all, only once every call has succeeded. Two independent\r\n * reasons: it makes all-or-nothing literally true for the working tree, not just the pull request\r\n * (today a failure on file 3 leaves files 1-2 already written even though the throw stops the\r\n * commit); and it lets the test baseline run against an untouched tree while codegen's network-\r\n * bound calls are still in flight (QUIKTR-1036 is what actually wires that concurrency up \u2014 this\r\n * only makes it possible).\r\n */\r\nconst FILE_TOO_LARGE_CODE = \"CODEGEN_FILE_TOO_LARGE\";\r\nconst CONTEXT_TOO_LARGE_CODE = \"CODEGEN_CONTEXT_TOO_LARGE\";\r\n/** \u00A716.7 \u2014 the AI Runtime's OWN output-cap guard telling us directly, distinct from\r\n * `looksLikeTruncatedRewrite` below (this file's interim heuristic guess at the same problem). */\r\nconst OUTPUT_TOO_LARGE_CODE = \"CODEGEN_OUTPUT_TOO_LARGE\";\r\nconst NOT_RETRIED_CODES = new Set([FILE_TOO_LARGE_CODE, CONTEXT_TOO_LARGE_CODE, OUTPUT_TOO_LARGE_CODE]);\r\n/** \u00A718.8.1 \u2014 the ONE retried refusal in this file, deliberately not in `NOT_RETRIED_CODES` above:\r\n * unlike the three sibling TOO_LARGE codes (which hit the identical wall on any retry), this one\r\n * is retried exactly once, with `judgedBy` narrowed to only the cases a test target's own\r\n * `contextPaths` ties to this code target \u2014 see `narrowJudgedByForTarget` below. */\r\nconst JUDGED_BY_TOO_LARGE_CODE = \"CODEGEN_JUDGED_BY_TOO_LARGE\";\r\n\r\n/**\r\n * QUIKTR-1419 \u2014 a test target is written against whatever files pilot.targeting listed for it (model\r\n * output), so it can be handed nothing of the code the run is changing. The runner therefore also gives it\r\n * the run's OTHER existing code targets. Bounded on purpose (Suyash): files changed in this run only, never\r\n * the files THEY import.\r\n *\r\n * QUIKTR-1454 \u2014 separately, EVERY existing target is also shown the files IT imports, one hop (importContext.ts).\r\n * That is a different rule from the one above, not an exception to it: an import is a fact the file states,\r\n * so it is parsed rather than left to targeting's judgement (the first real 9.0.0 run failed twice on a file\r\n * targeting never listed). Suyash, 5 Oct: one hop, what was added and skipped is logged with the reason, and\r\n * targeting's own list is never replaced. The run files above still never bring THEIR imports with them.\r\n *\r\n * The contract states no numeric limit for CODEGEN_CONTEXT_TOO_LARGE (only 200,000 chars for\r\n * `currentContent`), and that budget is shared with `currentContent` and `workspaceListing`. These are our\r\n * own conservative numbers, in characters like every other runner number (real targets seen: ~38.5k and\r\n * ~39.5k). Going over skips a file; it never fails the run.\r\n */\r\nexport const MAX_ADDED_FILE_CHARS = 40_000;\r\nexport const MAX_ADDED_CONTEXT_CHARS = 60_000;\r\n\r\nexport interface AddedContext {\r\n entries: { path: string; content: string }[];\r\n skipped: { path: string; reason: \"too large\" | \"over budget\" | \"unreadable\" }[];\r\n}\r\n\r\n/**\r\n * The extra `contextContents` entries for one target. Empty unless it is a TEST target (one with\r\n * `automationIds`); a code target's context stays exactly what targeting asked for. Candidates are the run's\r\n * other EXISTING targets that are not tests: a NEW_FILE has nothing on disk yet, and another test file adds\r\n * size for no help. `alreadyNamed` are the paths targeting already listed, so nothing is sent twice.\r\n *\r\n * Content is what is on disk NOW, i.e. before this run's edit \u2014 writes are buffered until every call has\r\n * succeeded. A route the change is adding is therefore visible to the test only through the plan steps.\r\n */\r\nexport function collectRunContext(\r\n target: PilotTarget,\r\n targets: PilotTarget[],\r\n alreadyNamed: Set<string>,\r\n deniedPaths: string[],\r\n readFile: (path: string) => string = (p) => readFileSync(p, \"utf8\"),\r\n): AddedContext {\r\n const added: AddedContext = { entries: [], skipped: [] };\r\n if (!target.automationIds?.length) return added;\r\n\r\n const seen = new Set(alreadyNamed);\r\n seen.add(target.path);\r\n let total = 0;\r\n for (const candidate of targets) {\r\n if (candidate.kind !== \"EXISTING\" || candidate.automationIds?.length) continue;\r\n if (seen.has(candidate.path)) continue;\r\n seen.add(candidate.path);\r\n // validateTarget already rejects a denied target, so this is defence in depth: a path in context is\r\n // read and sent to the LLM provider.\r\n if (matchesDeniedPath(candidate.path, deniedPaths)) continue;\r\n\r\n let content: string;\r\n try {\r\n content = readFile(candidate.path);\r\n } catch {\r\n added.skipped.push({ path: candidate.path, reason: \"unreadable\" });\r\n continue;\r\n }\r\n if (content.length > MAX_ADDED_FILE_CHARS) {\r\n added.skipped.push({ path: candidate.path, reason: \"too large\" });\r\n } else if (total + content.length > MAX_ADDED_CONTEXT_CHARS) {\r\n added.skipped.push({ path: candidate.path, reason: \"over budget\" });\r\n } else {\r\n total += content.length;\r\n added.entries.push({ path: candidate.path, content });\r\n }\r\n }\r\n return added;\r\n}\r\n\r\n/**\r\n * \u00A716.7 \u2014 interim runner-side guard, live under \u00A715 today (not gated on self-heal or on the AI\r\n * Runtime's own `CODEGEN_OUTPUT_TOO_LARGE` check, which isn't deployed yet). Codegen's output is\r\n * capped around 8,192 tokens; `CODEGEN_FILE_TOO_LARGE` only checks the ~200k-char *input*, so a\r\n * rewrite of a file well under that can still get truncated on the way out. The dangerous case is\r\n * a retry that comes back as valid, `success: true` JSON with the file quietly abbreviated \u2014\r\n * codegen's contract is that anything missing from `newContent` is deleted, so that reads as a\r\n * clean success while silently destroying code. \u00A716.7 names this exact heuristic as QuikTrack's\r\n * own stopgap until the real guard (a pre-dispatch prediction plus a finish-reason check) ships on\r\n * the runtime side.\r\n */\r\nconst SUSPECT_PLACEHOLDER_RE =\r\n /rest(?: of the)? (?:file|code) unchanged|remainder unchanged|\\/\\/\\s*\\.\\.\\.\\s*(?:rest|remaining)/i;\r\n/** Below 60% of its original length, an EXISTING rewrite is suspect rather than a real edit \u2014 a\r\n * targeted fix (planStepsImplemented) trims, it doesn't gut a file to a stub. Raised from 0.5 to\r\n * 0.6 after the AI Runtime's 2026-09-24 incident: a real pilot-chat.ts rewrite came back 38,500 ->\r\n * 22,585 chars (58.67% remaining) with success: true and no placeholder text \u2014 the old 0.5 ratio\r\n * only fires below 50% remaining, so that exact silent deletion sailed through undetected. */\r\nconst SUSPECT_LENGTH_DROP_RATIO = 0.6;\r\n/** A drop in character count can hide behind reformatting (fewer, longer lines) \u2014 this catches\r\n * the opposite failure: a rewrite that removes a large share of *lines* without a matching drop\r\n * in characters. 30% is a deliberately conservative starting point, not a calibrated number \u2014 no\r\n * incident has been observed on this signal alone yet. Tighten once real call metrics exist. */\r\nconst SUSPECT_REMOVED_LINE_RATIO = 0.3;\r\n/** Below this many lines, the multiset diff's \"changed line looks like removed+added\" blind spot\r\n * makes the ratio check unreliable \u2014 skip it rather than false-positive on small/single-line files. */\r\nconst MIN_LINES_FOR_REMOVED_LINE_CHECK = 10;\r\n/** Exported symbols removed silently are exactly the \"code vanishes, response still looks valid\"\r\n * failure mode \u2014 TS/JS only, since this parses no grammar beyond an `export` declaration. */\r\nconst JS_TS_EXTENSION_RE = /\\.(?:ts|tsx|js|jsx|mjs|cjs)$/;\r\nconst EXPORTED_SYMBOL_RE =\r\n /^export\\s+(?:default\\s+)?(?:async\\s+)?(?:function\\*?|class|const|let|var|interface|type|enum)\\s+([A-Za-z_$][\\w$]*)/gm;\r\n\r\n/** Language-neutral, line-based multiset diff \u2014 not an LCS/AST diff. Counts lines present in\r\n * `currentContent` with no matching occurrence left in `newContent`; good enough to flag \"lines\r\n * vanished\" without claiming to be a minimal diff. */\r\nfunction countRemovedLines(currentContent: string, newContent: string): number {\r\n const remaining = new Map<string, number>();\r\n for (const line of newContent.split(\"\\n\")) {\r\n remaining.set(line, (remaining.get(line) ?? 0) + 1);\r\n }\r\n let removed = 0;\r\n for (const line of currentContent.split(\"\\n\")) {\r\n const count = remaining.get(line) ?? 0;\r\n if (count > 0) {\r\n remaining.set(line, count - 1);\r\n } else {\r\n removed++;\r\n }\r\n }\r\n return removed;\r\n}\r\n\r\nfunction extractExportedSymbols(content: string): Set<string> {\r\n const symbols = new Set<string>();\r\n for (const match of content.matchAll(EXPORTED_SYMBOL_RE)) {\r\n symbols.add(match[1]);\r\n }\r\n return symbols;\r\n}\r\n\r\n/** Symbols removed by the rewrite that the plan text never names \u2014 a naive substring check, not a\r\n * reference-tracking one: it undercounts (a symbol renamed to match a plan word would slip past)\r\n * rather than overcounts, which is the right side to err on for a hard-failing guard. */\r\nfunction removedUnexplainedSymbols(targetPath: string, planText: string, currentContent: string, newContent: string): string[] {\r\n if (!JS_TS_EXTENSION_RE.test(targetPath)) return [];\r\n const before = extractExportedSymbols(currentContent);\r\n const after = extractExportedSymbols(newContent);\r\n const lowerPlan = planText.toLowerCase();\r\n return [...before].filter((symbol) => !after.has(symbol) && !lowerPlan.includes(symbol.toLowerCase()));\r\n}\r\n\r\nexport function looksLikeTruncatedRewrite(target: PilotTarget, currentContent: string, newContent: string): string | null {\r\n if (SUSPECT_PLACEHOLDER_RE.test(newContent)) {\r\n return \"contains placeholder text suggesting an abbreviated rewrite\";\r\n }\r\n if (currentContent.length > 0 && newContent.length < currentContent.length * SUSPECT_LENGTH_DROP_RATIO) {\r\n return `sharp length drop (${currentContent.length} -> ${newContent.length} chars)`;\r\n }\r\n\r\n // A multiset line diff can't tell \"line changed\" from \"line removed\" \u2014 on a short/single-line\r\n // file, one edited line reads as 100% removed. Require a real line count before trusting it.\r\n const currentLineCount = currentContent.length > 0 ? currentContent.split(\"\\n\").length : 0;\r\n if (currentLineCount >= MIN_LINES_FOR_REMOVED_LINE_CHECK) {\r\n const removedLines = countRemovedLines(currentContent, newContent);\r\n if (removedLines > currentLineCount * SUSPECT_REMOVED_LINE_RATIO) {\r\n const pct = ((removedLines / currentLineCount) * 100).toFixed(0);\r\n return `removed ${removedLines} of ${currentLineCount} lines (${pct}%) without a matching drop in character count`;\r\n }\r\n }\r\n\r\n const planText = target.planStepsImplemented.join(\" \");\r\n const unexplainedSymbols = removedUnexplainedSymbols(target.path, planText, currentContent, newContent);\r\n if (unexplainedSymbols.length > 0) {\r\n return `removed exported symbol(s) the plan steps don't mention: ${unexplainedSymbols.join(\", \")}`;\r\n }\r\n\r\n return null;\r\n}\r\n\r\n/** QUIKTR-1083 (\u00A715.6) \u2014 sent on every codegen call, same reasoning as targeting.ts's own constant. */\r\nconst CONTRACT_VERSION = \"test-targets-1\";\r\n/** 9.0.0, Doc 62 \u00A72 \u2014 cumulative over test-targets-1. For an EXISTING target the reply is anchored `edits` the runner\r\n * applies, not a whole file. A NEW_FILE target has nothing to anchor against and never asks for it. */\r\nconst CONTRACT_VERSION_EDITS = \"edits-1\";\r\n/** The runtime's code for anchors the ONE regeneration still could not place (Doc 62 \u00A72.1). Our remedy is our own:\r\n * re-request the whole file without edits-1. The fallback is the runner's, so it shows in the run trail. */\r\nconst ANCHOR_REFUSED_CODE = \"CODEGEN_ANCHOR_REFUSED\";\r\n\r\n/** The shape at `envelope.structuredJson` for `pilot.codegen` \u2014 NOT the envelope itself. A\r\n * refusal's reason is `refusalReason`; the envelope has no `code`/`message` fields (those were\r\n * never real \u2014 see envelope.ts). Under edits-1 an EXISTING target's GENERATED reply carries `edits`, not `newContent`. */\r\ninterface CodegenResult {\r\n outcome?: \"GENERATED\" | \"REFUSED\";\r\n newContent?: string;\r\n edits?: unknown;\r\n summary?: string;\r\n refusalReason?: string;\r\n}\r\n\r\n/** Which way a call went, for the one log line per call. `edits`: anchored edits applied. `fallback`: edits were\r\n * refused or did not place, so the whole file was requested. `whole_file`: no edits were asked for, or the reply was\r\n * a whole file anyway. */\r\ntype EditsPath = \"edits\" | \"fallback\" | \"whole_file\";\r\n\r\n/** What a refusal may say about itself: counts and kinds, never the text of an anchor. These strings end up in the\r\n * run's warnings, which reach QuikTrack. */\r\ninterface RefusalSummary {\r\n text: string;\r\n matchCounts: number[];\r\n}\r\n\r\nfunction summariseLocalRefusals(refusals: AnchorRefusal[]): RefusalSummary {\r\n const parts: string[] = [];\r\n const matchCounts: number[] = [];\r\n for (const r of refusals) {\r\n if (r.kind === \"ambiguous\") {\r\n parts.push(`an anchor matched ${r.matchCount} times`);\r\n if (r.matchCount !== null) matchCounts.push(r.matchCount);\r\n } else if (r.kind === \"no_match\") {\r\n parts.push(\"an anchor matched nothing\");\r\n } else if (r.kind === \"overlap\") {\r\n parts.push(`edits ${r.edits.join(\" and \")} overlap`);\r\n } else if (r.kind === \"no_edits\") {\r\n parts.push(\"the reply had no edits\");\r\n } else {\r\n parts.push(\"an edit was missing its anchor or replacement\");\r\n }\r\n }\r\n return { text: [...new Set(parts)].join(\"; \"), matchCounts };\r\n}\r\n\r\n/** The runtime's own refusal text quotes the anchor (\"The anchor was: \u2026\"), so it is read for its counts and never passed on. */\r\nfunction summariseRuntimeRefusal(error: unknown): RefusalSummary {\r\n const text = typeof error === \"string\" ? error : \"\";\r\n const matchCounts = [...text.matchAll(/anchor matched (\\d+) times/g)].map((m) => Number(m[1]));\r\n const parts: string[] = matchCounts.map((n) => `an anchor matched ${n} times`);\r\n if (/no match/i.test(text)) parts.push(\"an anchor matched nothing\");\r\n if (/overlap/i.test(text)) parts.push(\"edits overlapped\");\r\n if (/empty anchor|missing a string/i.test(text)) parts.push(\"an edit was missing its anchor or replacement\");\r\n return { text: parts.length > 0 ? [...new Set(parts)].join(\"; \") : \"the runtime could not place the edits\", matchCounts };\r\n}\r\n\r\n/** The two hard stops a reply can carry after any retry: a code that is never retried, and a judgedBy overflow that is\r\n * still too large after narrowing. One place so the whole-file fallback holds the same line as the first call. */\r\nfunction throwOnTerminalRefusal(envelope: any, targetPath: string): void {\r\n if (typeof envelope?.errorCode === \"string\" && NOT_RETRIED_CODES.has(envelope.errorCode)) {\r\n const detail = envelope.error ? `: ${envelope.error}` : \"\";\r\n throw new RuntimeReplyError(\r\n `Codegen refused ${targetPath}: ${envelope.errorCode} (not retried)${detail}`,\r\n `Codegen refused ${targetPath}: ${envelope.errorCode} (not retried)`,\r\n );\r\n }\r\n if (envelope?.errorCode === JUDGED_BY_TOO_LARGE_CODE) {\r\n // Still too large after narrowing (or the retry hit some other JUDGED_BY_TOO_LARGE cause) \u2014\r\n // no further retry, same all-or-nothing posture as every other codegen failure here.\r\n const detail = envelope.error ? `: ${envelope.error}` : \"\";\r\n throw new RuntimeReplyError(\r\n `Codegen refused ${targetPath}: ${envelope.errorCode} (after narrowing)${detail}`,\r\n `Codegen refused ${targetPath}: ${envelope.errorCode} (after narrowing)`,\r\n );\r\n }\r\n}\r\n\r\nfunction codegenRefusedError(targetPath: string, body: CodegenResult): RuntimeReplyError {\r\n return new RuntimeReplyError(\r\n `Codegen refused ${targetPath}${body.refusalReason ? `: ${body.refusalReason}` : \"\"}`,\r\n `Codegen refused ${targetPath}`,\r\n );\r\n}\r\n\r\nexport interface CodegenFileResult {\r\n targetPath: string;\r\n newContent: string;\r\n}\r\n\r\n/** \u00A718 `judgedBy` \u2014 the internal (runner-only) shape, keeping `automationId` for the\r\n * overflow-narrowing filter below; stripped down to `{title, given, when, then}` only when\r\n * actually serialized onto the wire (\u00A718.9 refuses any other key on an entry). */\r\nexport interface JudgedByCase {\r\n automationId: string;\r\n title: string;\r\n given: string;\r\n when: string;\r\n then: string;\r\n}\r\n\r\n/**\r\n * \u00A718 \u2014 every case claimed by SOME target in this run (not scoped to `contextPaths` matches \u2014\r\n * that's `narrowJudgedByForTarget`'s overflow-fallback job only, not the primary rule), minus\r\n * targeting's own `skippedCases` (\u00A715.3's `NO_BEHAVIOUR` skip), minus any entry still missing\r\n * given/when/then \u2014 defensive: a non-skipped case should already have all three by construction,\r\n * but \u00A718.9 refuses `CONTRACT_REJECTED` on any entry outside the declared shape, so this never\r\n * trusts that invariant blindly. Built once per run, in `run.ts`, and passed into `runCodegen`.\r\n */\r\nexport function buildJudgedByPool(\r\n requiredTests: PilotPacket[\"requiredTests\"],\r\n targets: PilotTarget[],\r\n skippedCases: SkippedCase[],\r\n): JudgedByCase[] {\r\n const claimedIds = new Set<string>();\r\n for (const t of targets) {\r\n for (const id of t.automationIds ?? []) claimedIds.add(id);\r\n }\r\n const skippedIds = new Set(skippedCases.map((s) => s.automationId));\r\n\r\n const pool: JudgedByCase[] = [];\r\n for (const tc of requiredTests) {\r\n if (!claimedIds.has(tc.automationId) || skippedIds.has(tc.automationId)) continue;\r\n if (!tc.given || !tc.when || !tc.then) continue;\r\n pool.push({ automationId: tc.automationId, title: tc.title, given: tc.given, when: tc.when, then: tc.then });\r\n }\r\n return pool;\r\n}\r\n\r\n/** \u00A718.8.1's overflow fallback \u2014 narrow the full pool down to only cases claimed by a test target\r\n * whose own `contextPaths` names this code target's path. Not the primary rule (a claiming test\r\n * target's `contextPaths` is model output and can be missing/wrong), only the retry narrowing. */\r\nfunction narrowJudgedByForTarget(pool: JudgedByCase[], targets: PilotTarget[], codeTargetPath: string): JudgedByCase[] {\r\n const narrowedIds = new Set<string>();\r\n for (const t of targets) {\r\n if (!t.automationIds?.length || !t.contextPaths?.includes(codeTargetPath)) continue;\r\n for (const id of t.automationIds) narrowedIds.add(id);\r\n }\r\n return pool.filter((c) => narrowedIds.has(c.automationId));\r\n}\r\n\r\n/** Strips `automationId` for the wire \u2014 \u00A718.9 refuses any key outside `{title, given, when, then}`. */\r\nfunction toWireJudgedBy(pool: JudgedByCase[]): { title: string; given: string; when: string; then: string }[] {\r\n return pool.map(({ automationId: _automationId, ...rest }) => rest);\r\n}\r\n\r\n/**\r\n * Run codegen for exactly the targets named, in order, stopping at the first failure. Throws\r\n * rather than returning a partial result \u2014 see the ALL-OR-NOTHING note above; a caller that wants\r\n * to know how far it got before failing should catch and inspect the message, not branch on a\r\n * return value that implies partial success is a valid state. Writes nothing \u2014 call\r\n * `flushCodegenResults` with the return value once this resolves.\r\n *\r\n * `warnings` is a shared, mutable array \u2014 same convention `run.ts` already uses for\r\n * QUIKTR-1064/1374's non-blocking findings \u2014 pushed into directly rather than returned, so this\r\n * function's return type stays `CodegenFileResult[]`.\r\n */\r\nexport async function runCodegen(\r\n gateway: PilotPacket[\"gateway\"],\r\n targets: PilotTarget[],\r\n workspaceListing: string[],\r\n requiredTests: PilotPacket[\"requiredTests\"],\r\n deniedPaths: string[],\r\n judgedByPool: JudgedByCase[],\r\n warnings: string[],\r\n /** QUIKTR-1421 \u2014 a caller-owned array this fills with one entry per call (what targeting named, what the\r\n * runner added, what it skipped), so run.ts can report it to QuikTrack. Optional and last: every existing\r\n * caller is unchanged. Entries are pushed BEFORE the call, so they survive a later throw. */\r\n contextLog?: CodegenContextRecord[],\r\n /** QUIKTR-1401 (\u00A720) \u2014 what the reviewer approved the change must NOT touch, sent on every call (code and test\r\n * targets alike) when non-empty. Optional and last: every existing caller is unchanged. */\r\n outOfScope: string[] = [],\r\n): Promise<CodegenFileResult[]> {\r\n const results: CodegenFileResult[] = [];\r\n const listing = new Set(workspaceListing);\r\n\r\n for (const target of targets) {\r\n const isNewFile = target.kind === \"NEW_FILE\";\r\n const currentContent = isNewFile ? \"\" : readFileSync(target.path, \"utf8\");\r\n // 9.0.0, Doc 62 \u00A72 \u2014 an EXISTING file asks for anchored edits against its LF form, and gets its own convention back\r\n // when written. A file with BOTH conventions cannot be restored faithfully, so it keeps the whole-file path.\r\n const lineEnding: LineEnding = isNewFile ? \"LF\" : detectLineEnding(currentContent);\r\n const wantsEdits = !isNewFile && lineEnding !== \"mixed\";\r\n\r\n // targeting names its own context needs per target \u2014 an invented contextPath is the same\r\n // class of bug as an invented EXISTING target (targeting.ts's validateTarget): fail loudly\r\n // rather than silently sending less context than the model asked for.\r\n const contextPaths = target.contextPaths ?? [];\r\n // QUIKTR-1420 \u2014 the egress point: this is where a context file is READ and put in the request.\r\n // runTargeting re-checks too; this holds even for a target that did not come through it, and it runs\r\n // before the not-found check so a denied path is never reported as merely missing.\r\n const deniedContext = findDeniedContextPath(contextPaths, deniedPaths);\r\n if (deniedContext) {\r\n throw new Error(\r\n `pilot.codegen contextPaths cited a denied path (${deniedContext.pattern}): ${deniedContext.path} (target ${target.path})`,\r\n );\r\n }\r\n for (const contextPath of contextPaths) {\r\n if (!listing.has(contextPath)) {\r\n throw new Error(\r\n `pilot.codegen contextPaths named a file not found in the checkout: ${contextPath} (target ${target.path})`,\r\n );\r\n }\r\n }\r\n const namedContents = contextPaths.map((path) => ({ path, content: readFileSync(path, \"utf8\") }));\r\n\r\n // QUIKTR-1419 \u2014 for a test target, also the run's other existing code files (see collectRunContext).\r\n const runFiles = collectRunContext(target, targets, new Set(contextPaths), deniedPaths);\r\n for (const s of runFiles.skipped) {\r\n warnings.push(`not shown to the test for ${target.path}: ${s.path} (${s.reason})`);\r\n }\r\n // QUIKTR-1454 \u2014 and the files this target itself imports, one hop. Added AFTER what targeting named and what the\r\n // run's files brought, never instead of them. A NEW_FILE has no content to read imports from.\r\n const imports = isNewFile\r\n ? { entries: [], skipped: [], importedPaths: [], aliasImports: 0 }\r\n : collectImportContext({\r\n targetPath: target.path,\r\n source: currentContent,\r\n alreadyNamed: new Set([...contextPaths, ...runFiles.entries.map((e) => e.path)]),\r\n deniedPaths,\r\n listing,\r\n readFile: (p) => readFileSync(p, \"utf8\"),\r\n maxFileChars: MAX_ADDED_FILE_CHARS,\r\n maxTotalChars: MAX_ADDED_CONTEXT_CHARS,\r\n spentChars: runFiles.entries.reduce((n, e) => n + e.content.length, 0),\r\n });\r\n for (const s of imports.skipped) {\r\n if (ACTIONABLE_IMPORT_SKIPS.has(s.reason)) {\r\n warnings.push(`not shown with ${target.path}: ${s.path} (imported by it; ${s.reason.replace(/^import: /, \"\")})`);\r\n }\r\n }\r\n const added: Pick<AddedContext, \"entries\"> & { skipped: { path: string; reason: string }[] } = {\r\n entries: [...runFiles.entries, ...imports.entries],\r\n skipped: [...runFiles.skipped, ...imports.skipped],\r\n };\r\n const contextContents = [...namedContents, ...added.entries];\r\n // One line per call: which files targeting named and which the runner added. Without it, \"was the\r\n // file even in front of the model?\" cannot be answered from this runner's own log (run 25). QUIKTR-1454: and\r\n // which of those came from imports, what was skipped and why, and how many path aliases were not followed.\r\n const contextRecord: CodegenContextRecord = {\r\n targetPath: target.path,\r\n contextPaths,\r\n addedPaths: added.entries.map((e) => e.path),\r\n skipped: added.skipped,\r\n ...(imports.importedPaths.length > 0 ? { importedPaths: imports.importedPaths } : {}),\r\n ...(imports.aliasImports > 0 ? { aliasImports: imports.aliasImports } : {}),\r\n };\r\n console.log(JSON.stringify({ event: \"codegen.context\", ...contextRecord }));\r\n // QUIKTR-1421 \u2014 the same facts, handed back so they reach QuikTrack's run trail, not just this job's log.\r\n contextLog?.push(contextRecord);\r\n\r\n const contextData: Record<string, unknown> = {\r\n targetPath: target.path,\r\n // Every anchor and replacement is LF, always (Doc 62 \u00A72), so the file is sent as LF.\r\n currentContent: wantsEdits ? toLf(currentContent) : currentContent,\r\n planSteps: target.planStepsImplemented,\r\n kind: target.kind,\r\n contextContents,\r\n // QUIKTR-1083 (\u00A715.6) \u2014 required on every call on the versioned path.\r\n contractVersion: wantsEdits ? CONTRACT_VERSION_EDITS : CONTRACT_VERSION,\r\n };\r\n if (isNewFile) {\r\n // Bounds WHAT EXISTS \u2014 stops an invented import like hooks/useGroups \u2014 only meaningful for\r\n // a file that doesn't exist yet to compare against.\r\n contextData.workspaceListing = workspaceListing;\r\n }\r\n if (deniedPaths.length > 0) {\r\n contextData.deniedPaths = deniedPaths;\r\n }\r\n // QUIKTR-1401, \u00A720 \u2014 omitted rather than sent empty, same as deniedPaths. Free text: told, never checked.\r\n if (outOfScope.length > 0) {\r\n contextData.outOfScope = outOfScope;\r\n }\r\n // QUIKTR-1083 (\u00A715.4) \u2014 only for a test target (one targeting named automationIds for), and\r\n // only that target's own subset \u2014 never the full list, and never for a code target at all.\r\n if (target.automationIds && target.automationIds.length > 0) {\r\n const wanted = new Set(target.automationIds);\r\n contextData.requiredTests = requiredTests.filter((tc) => wanted.has(tc.automationId));\r\n } else if (judgedByPool.length > 0) {\r\n // \u00A718 \u2014 a code target (no automationIds of its own) gets the run's claimed cases as\r\n // judging context instead. Mutually exclusive with requiredTests per call, by construction:\r\n // this is the else branch of the exact same condition. Omitted entirely when the pool is\r\n // empty, never sent as `[]`.\r\n contextData.judgedBy = toWireJudgedBy(judgedByPool);\r\n }\r\n\r\n // QUIKTR-1069 \u2014 retries a transport-level failure only (502/503/504, a dropped connection);\r\n // a real refusal always arrives as a 200 with the refusal inside the envelope, below.\r\n const callCodegen = () =>\r\n fetchWithRetry(`${gateway.baseUrl}/ai/execute`, {\r\n method: \"POST\",\r\n headers: { \"content-type\": \"application/json\", \"x-run-token\": gateway.token },\r\n body: JSON.stringify({\r\n appId: \"quiktrack\",\r\n useCase: \"pilot.codegen\",\r\n expectedOutputType: \"json\",\r\n userPrompt: \"\",\r\n contextData,\r\n }),\r\n });\r\n\r\n let res = await callCodegen();\r\n if (!res.ok) {\r\n throw new Error(`Codegen call failed for ${target.path}: ${res.status} ${res.statusText}`);\r\n }\r\n\r\n // /ai/execute wraps every result in an envelope \u2014 the use-case result lives at\r\n // structuredJson, and a failure can arrive as success:false in an HTTP 200 (see envelope.ts).\r\n // CODEGEN_FILE_TOO_LARGE / CODEGEN_CONTEXT_TOO_LARGE are checked on the RAW envelope, before\r\n // unwrapping: they arrive as a failure (success:false), so unwrapping first would throw the\r\n // generic envelope error and lose the not-retried distinction this check exists to preserve.\r\n let envelope: any = await res.json();\r\n // QUIKTR-1083 \u2014 SEMANTIC_MISMATCH/CONTRACT_REJECTED, same \"raw envelope, before unwrap\" point\r\n // as the CODEGEN_* check right below.\r\n checkHardFailure(envelope, \"pilot.codegen\", target.path);\r\n\r\n // \u00A718.8.1 \u2014 the one retried refusal here: narrow judgedBy to only the cases a test target's\r\n // own contextPaths ties to this file, then retry ONCE. Recorded on the run's trail either way\r\n // (even if the retry still fails) so the trail shows what was attempted.\r\n if (envelope?.errorCode === JUDGED_BY_TOO_LARGE_CODE && contextData.judgedBy) {\r\n const before = (contextData.judgedBy as unknown[]).length;\r\n const narrowed = narrowJudgedByForTarget(judgedByPool, targets, target.path);\r\n if (narrowed.length > 0) {\r\n contextData.judgedBy = toWireJudgedBy(narrowed);\r\n } else {\r\n delete contextData.judgedBy;\r\n }\r\n warnings.push(`judgedBy narrowed for ${target.path}: ${before} \u2192 ${narrowed.length} cases`);\r\n\r\n res = await callCodegen();\r\n if (!res.ok) {\r\n throw new Error(`Codegen call failed for ${target.path}: ${res.status} ${res.statusText}`);\r\n }\r\n envelope = await res.json();\r\n checkHardFailure(envelope, \"pilot.codegen\", target.path);\r\n }\r\n\r\n // QUIKTR-1419 \u2014 the runner's own additions must never turn a run that would have passed into a\r\n // failure. If the runtime refuses the context as too large AND we added files, retry ONCE with only\r\n // what targeting named; if it still refuses, that overflow is real and falls through to the throw below.\r\n if (envelope?.errorCode === CONTEXT_TOO_LARGE_CODE && added.entries.length > 0) {\r\n contextData.contextContents = namedContents;\r\n warnings.push(`context for ${target.path} was too large with the run's other files; retried without them`);\r\n // QUIKTR-1421 \u2014 the record must not claim files were shown that the retry dropped. The same object is\r\n // already in `contextLog`, so mutating it updates what gets reported.\r\n contextRecord.addedPaths = [];\r\n delete contextRecord.importedPaths;\r\n contextRecord.retriedWithoutAdded = true;\r\n\r\n res = await callCodegen();\r\n if (!res.ok) {\r\n throw new Error(`Codegen call failed for ${target.path}: ${res.status} ${res.statusText}`);\r\n }\r\n envelope = await res.json();\r\n checkHardFailure(envelope, \"pilot.codegen\", target.path);\r\n }\r\n\r\n throwOnTerminalRefusal(envelope, target.path);\r\n\r\n // 9.0.0, Doc 62 \u00A72/\u00A72.1 \u2014 what became of the edits. `newContent` is the file to write; `failedEdits` is set when the\r\n // edits could not be used, and there is exactly ONE answer to that: ask again for the whole file, without edits-1.\r\n let newContent: string | null = null;\r\n let failedEdits: { reason: \"anchor_refused\" | \"local_refusal\"; summary: RefusalSummary } | null = null;\r\n let editCount: number | undefined;\r\n let path: EditsPath = \"whole_file\";\r\n let reason: string | undefined = isNewFile ? \"new_file\" : wantsEdits ? undefined : \"mixed_line_endings\";\r\n\r\n if (wantsEdits && envelope?.errorCode === ANCHOR_REFUSED_CODE) {\r\n // Arrives only after the runtime's own ONE regeneration, so \"this was already retried\" is unambiguous.\r\n failedEdits = { reason: \"anchor_refused\", summary: summariseRuntimeRefusal(envelope.error) };\r\n } else {\r\n const body = unwrapExecute<CodegenResult>(envelope, \"pilot.codegen\");\r\n if (wantsEdits) {\r\n // A genuine refusal is the runtime's answer, not a malformed one: it ends the run exactly as it always has.\r\n if (body.outcome === \"REFUSED\") throw codegenRefusedError(target.path, body);\r\n // We asked for edits-1, so check we GOT edits-1 before using anything (Suyash, 5 Oct). `newContent` is valid under\r\n // test-targets-1, which is exactly why it must not be applied here: the call would succeed having asked for edits\r\n // and silently got something else. The runtime turns a malformed reply into SCHEMA_MISMATCH, so this should never\r\n // arrive; if it does it is a failure, not a candidate for the fallback, which is for anchors only (Suyash).\r\n if (body.outcome !== \"GENERATED\" || typeof body.newContent === \"string\") {\r\n throw new RuntimeReplyError(\r\n `Codegen reply for ${target.path} was not in the edits-1 shape and was not applied`,\r\n `Codegen reply for ${target.path} was not in the edits-1 shape`,\r\n );\r\n }\r\n // Every anchor is resolved against the content we sent, by the same rules the runtime held: exactly once, no\r\n // overlap. The runner writes the file, so it does not take the runtime's word for it.\r\n const applied = applyEdits(toLf(currentContent), body.edits);\r\n if (applied.ok) {\r\n newContent = fromLf(applied.content, lineEnding);\r\n path = \"edits\";\r\n editCount = applied.editCount;\r\n } else if (applied.refusals.some((r) => r.kind === \"no_edits\")) {\r\n // GENERATED with nothing to apply: a model that changed nothing while saying it did. The runtime's own answer to\r\n // that is SEMANTIC_MISMATCH, which is never retried; asking again here would only spend a bigger call on it.\r\n throw new RuntimeReplyError(\r\n `Codegen reply for ${target.path} carried no edits (not retried)`,\r\n `Codegen reply for ${target.path} carried no edits`,\r\n );\r\n } else {\r\n // Anchors that could not be placed: the one thing the whole-file fallback is for.\r\n failedEdits = { reason: \"local_refusal\", summary: summariseLocalRefusals(applied.refusals) };\r\n }\r\n } else {\r\n if (body.outcome !== \"GENERATED\" || typeof body.newContent !== \"string\") {\r\n throw codegenRefusedError(target.path, body);\r\n }\r\n newContent = body.newContent;\r\n }\r\n }\r\n\r\n if (failedEdits) {\r\n // The saving is lost on this call; the run survives, so edits-1 is never a new way to fail. It is also VISIBLE: this\r\n // warning reaches QuikTrack's run trail, which a runtime-side fallback could not do. Counts only, never an anchor.\r\n warnings.push(\r\n `edits for ${target.path} could not be placed (${failedEdits.summary.text}); asked again for the whole file`,\r\n );\r\n contextData.currentContent = currentContent;\r\n contextData.contractVersion = CONTRACT_VERSION;\r\n try {\r\n res = await callCodegen();\r\n if (!res.ok) {\r\n throw new Error(`Codegen call failed for ${target.path}: ${res.status} ${res.statusText}`);\r\n }\r\n envelope = await res.json();\r\n checkHardFailure(envelope, \"pilot.codegen\", target.path);\r\n throwOnTerminalRefusal(envelope, target.path);\r\n const whole = unwrapExecute<CodegenResult>(envelope, \"pilot.codegen\");\r\n if (whole.outcome !== \"GENERATED\" || typeof whole.newContent !== \"string\") {\r\n throw codegenRefusedError(target.path, whole);\r\n }\r\n newContent = whole.newContent;\r\n } catch (error: unknown) {\r\n // Honest, not a retry: the whole file is a BIGGER request, so where the provider cannot serve a large one\r\n // (AI_UNAVAILABLE) this can only fail the same way, and that is not transient. Say what happened and in which\r\n // order, so the failure is not read as a plain provider hiccup. Names and codes only in the reported summary.\r\n if (error instanceof RuntimeReplyError) {\r\n throw new RuntimeReplyError(\r\n `${error.message} (this was the whole-file request made after the edits for ${target.path} were refused: ${failedEdits.summary.text})`,\r\n `${error.summary} (the whole-file request, made after the edits were refused)`,\r\n );\r\n }\r\n throw error;\r\n }\r\n path = \"fallback\";\r\n reason = failedEdits.reason;\r\n }\r\n\r\n if (newContent === null) throw new Error(`Codegen produced no content for ${target.path}`);\r\n\r\n if (!isNewFile) {\r\n // Which path each call took (Doc 62 \u00A72.1): without it nobody can tell whether the retry earns its place, and the\r\n // measurement is free if collected from the start. Counts and outcomes only: no anchor, no replacement.\r\n console.log(\r\n JSON.stringify({\r\n event: \"codegen.edits_path\",\r\n targetPath: target.path,\r\n path,\r\n ...(reason ? { reason } : {}),\r\n ...(editCount !== undefined ? { editCount } : {}),\r\n ...(failedEdits && failedEdits.summary.matchCounts.length > 0 ? { matchCounts: failedEdits.summary.matchCounts } : {}),\r\n lineEnding,\r\n }),\r\n );\r\n }\r\n\r\n if (!isNewFile) {\r\n const suspectReason = looksLikeTruncatedRewrite(target, currentContent, newContent);\r\n if (suspectReason) {\r\n throw new Error(\r\n `Codegen output for ${target.path} looks like a truncated/abbreviated rewrite (${suspectReason}) ` +\r\n `\u2014 refusing to apply it. Interim guard per \u00A716.7; the AI Runtime's own output-cap check is not live yet.`,\r\n );\r\n }\r\n }\r\n\r\n // AI Runtime, 2026-09-24 \u2014 one structured line per call, to build the input/output/removed-line\r\n // distribution SUSPECT_LENGTH_DROP_RATIO and SUSPECT_REMOVED_LINE_RATIO were guessed without.\r\n // Not itself a safety check \u2014 plain data collection for calibrating the two guards above.\r\n console.log(\r\n JSON.stringify({\r\n event: \"codegen.metrics\",\r\n targetPath: target.path,\r\n kind: target.kind,\r\n inputLength: currentContent.length,\r\n outputLength: newContent.length,\r\n removedLines: isNewFile ? null : countRemovedLines(currentContent, newContent),\r\n }),\r\n );\r\n\r\n results.push({ targetPath: target.path, newContent });\r\n }\r\n\r\n return results;\r\n}\r\n\r\n/** Writes every result to disk. Only ever call this after every `runCodegen` call succeeded \u2014\r\n * see the buffered-writes note above. Creates the parent directory first: a NEW_FILE target can\r\n * legitimately name a directory that doesn't exist yet (e.g. a repo's first hooks/ file). */\r\nexport function flushCodegenResults(results: CodegenFileResult[]): void {\r\n for (const { targetPath, newContent } of results) {\r\n mkdirSync(dirname(targetPath), { recursive: true });\r\n writeFileSync(targetPath, newContent);\r\n }\r\n}\r\n", "/**\r\n * QUIKTR-1083 (\u00A715.3) \u2014 layer 2 of the three denied-path layers the contract describes: after\r\n * `pilot.targeting` responds, every proposed target's path is checked against `deniedPaths` here,\r\n * before any codegen spend. (Layer 1 is the AI Runtime's own targeting validator; layer 3 is\r\n * `guardrail.ts`'s post-commit check on the actually-staged diff.)\r\n *\r\n * Hand-rolled rather than a `minimatch`/`picomatch` dependency: this package is published\r\n * publicly and carries no secrets or heavy deps on purpose (see workflow-template.ts's own\r\n * docblock), and the denied-path patterns in real use (a dotfile glob under a double-star prefix,\r\n * a workflows directory suffixed with a double star, a bare lockfile name under a double-star\r\n * prefix) never need brace expansion, character classes, or `?` \u2014 only a double star (any depth,\r\n * including none) and a single star (anything but a path separator). A dependency for two glob\r\n * tokens is not worth the weight.\r\n */\r\nfunction globToRegExp(pattern: string): RegExp {\r\n const escaped = pattern\r\n .split(\"\")\r\n .map((c) => (/[.+^${}()|[\\]\\\\]/.test(c) ? `\\\\${c}` : c))\r\n .join(\"\");\r\n // Order matters: the more specific `**/` token first, so the generic `**`/`*` passes below\r\n // don't consume it first and lose the \"zero directories is also a match\" behaviour every\r\n // default pattern (`**/*.env*`, `**/package-lock.json`, ...) actually depends on \u2014 a repo-root\r\n // `.env` must match `**/*.env*` exactly as a nested one does, the same way `.gitignore`'s own\r\n // `**/` prefix works.\r\n const withGlobs = escaped\r\n .replace(/\\*\\*\\//g, \" SLASH \")\r\n .replace(/\\*\\*/g, \" STAR \")\r\n .replace(/\\*/g, \"[^/]*\")\r\n .replace(/ SLASH /g, \"(?:.*/)?\")\r\n .replace(/ STAR /g, \".*\");\r\n return new RegExp(`^${withGlobs}$`);\r\n}\r\n\r\n/** The first pattern `path` matches, or `null`. `path` is repo-relative, matching how every\r\n * `deniedPaths` entry and every target's `path` are already written elsewhere in this package. */\r\nexport function matchesDeniedPath(path: string, patterns: string[]): string | null {\r\n for (const pattern of patterns) {\r\n if (globToRegExp(pattern).test(path)) return pattern;\r\n }\r\n return null;\r\n}\r\n\r\n/**\r\n * QUIKTR-1420 \u2014 the first path in a list that matches a denied pattern, with the pattern it matched, or\r\n * `null`. For `contextPaths`: the runner reads each one and puts its content in the request to the model\r\n * provider, so a protected file cited as context is the same egress as one named as a target. The AI Runtime\r\n * refuses these itself (pilot_targeting.py:374, per Suyash), but for targets this package deliberately\r\n * re-checks rather than trusting that, and context was the one gap.\r\n */\r\nexport function findDeniedContextPath(\r\n contextPaths: string[],\r\n patterns: string[],\r\n): { path: string; pattern: string } | null {\r\n for (const path of contextPaths) {\r\n const pattern = matchesDeniedPath(path, patterns);\r\n if (pattern) return { path, pattern };\r\n }\r\n return null;\r\n}\r\n", "/**\r\n * Doc 62 \u00A72 / \u00A72.1 (\"edits-1\") \u2014 applying the AI Runtime's anchored edits to a file the runner is about to write.\r\n *\r\n * The runtime validates anchors against the content it was sent and splices only to measure the result; the RUNNER\r\n * writes the real file, so it applies the edits itself and holds the same rules rather than trusting the reply:\r\n * - every `find` matches the ORIGINAL content exactly once. Zero or several is a refusal, never a guess;\r\n * - every range is resolved before anything is applied, so a whole response is validated or refused;\r\n * - overlapping ranges refuse the WHOLE response; adjacent ranges do not overlap;\r\n * - application is order-independent, because ranges are spliced by position, not applied in sequence.\r\n *\r\n * Line endings: the content handed to `applyEdits` is LF. `toLf` / `detectLineEnding` / `fromLf` normalise a file before it\r\n * is sent and restore its own convention when it is written. Nothing else is normalised: in Python and YAML whitespace is\r\n * semantics, not formatting.\r\n *\r\n * Refusal messages carry counts and edit numbers only, never the text of an anchor or a replacement: they end up in the\r\n * run's warnings, which reach QuikTrack, and customer code does not.\r\n */\r\n\r\nexport type LineEnding = \"LF\" | \"CRLF\" | \"mixed\";\r\n\r\n/** The convention of `text` as read from disk. A lone CR is not a line ending, so it is counted neither way. */\r\nexport function detectLineEnding(text: string): LineEnding {\r\n const crlf = text.split(\"\\r\\n\").length - 1;\r\n const bareLf = text.split(\"\\n\").length - 1 - crlf;\r\n if (crlf > 0 && bareLf > 0) return \"mixed\";\r\n return crlf > 0 ? \"CRLF\" : \"LF\";\r\n}\r\n\r\nexport function toLf(text: string): string {\r\n return text.replace(/\\r\\n/g, \"\\n\");\r\n}\r\n\r\n/** Restores a convention on LF text. `mixed` cannot be restored faithfully, so callers never ask for it. */\r\nexport function fromLf(text: string, ending: LineEnding): string {\r\n return ending === \"CRLF\" ? text.replace(/\\n/g, \"\\r\\n\") : text;\r\n}\r\n\r\nexport type AnchorRefusalKind = \"ambiguous\" | \"no_match\" | \"empty\" | \"overlap\" | \"no_edits\";\r\n\r\nexport interface AnchorRefusal {\r\n kind: AnchorRefusalKind;\r\n /** 1-based numbers of the edits involved: one, or two for an overlap; empty for `no_edits`. */\r\n edits: number[];\r\n /** How many times the anchor matched; null when that does not apply. */\r\n matchCount: number | null;\r\n message: string;\r\n}\r\n\r\nexport type EditsOutcome =\r\n | { ok: true; content: string; editCount: number }\r\n | { ok: false; refusals: AnchorRefusal[]; editCount: number };\r\n\r\n/** Every start index of `needle` in `haystack`, overlapping occurrences included: \"aa\" occurs twice in \"aaa\", and an\r\n * anchor that can be placed two ways identifies no place. */\r\nfunction occurrences(haystack: string, needle: string): number[] {\r\n const found: number[] = [];\r\n let index = haystack.indexOf(needle);\r\n while (index !== -1) {\r\n found.push(index);\r\n index = haystack.indexOf(needle, index + 1);\r\n }\r\n return found;\r\n}\r\n\r\ninterface PlacedRange {\r\n start: number;\r\n end: number;\r\n number: number;\r\n replace: string;\r\n}\r\n\r\n/** Resolve every edit against `originalLf`, then either refuse the whole response or splice. Pure. */\r\nexport function applyEdits(originalLf: string, edits: unknown): EditsOutcome {\r\n if (!Array.isArray(edits) || edits.length === 0) {\r\n return {\r\n ok: false,\r\n editCount: 0,\r\n refusals: [{ kind: \"no_edits\", edits: [], matchCount: null, message: \"the response carried no edits\" }],\r\n };\r\n }\r\n\r\n const refusals: AnchorRefusal[] = [];\r\n const ranges: PlacedRange[] = [];\r\n\r\n edits.forEach((edit: unknown, index: number) => {\r\n const number = index + 1;\r\n const record = edit !== null && typeof edit === \"object\" ? (edit as Record<string, unknown>) : null;\r\n const find = record?.find;\r\n const replace = record?.replace;\r\n if (typeof find !== \"string\" || typeof replace !== \"string\") {\r\n refusals.push({\r\n kind: \"empty\",\r\n edits: [number],\r\n matchCount: null,\r\n message: `edit ${number} is missing a string find or replace`,\r\n });\r\n return;\r\n }\r\n if (find === \"\") {\r\n refusals.push({ kind: \"empty\", edits: [number], matchCount: null, message: `edit ${number} has an empty anchor` });\r\n return;\r\n }\r\n const starts = occurrences(originalLf, find);\r\n if (starts.length === 0) {\r\n refusals.push({ kind: \"no_match\", edits: [number], matchCount: 0, message: `edit ${number}: the anchor matched nothing` });\r\n } else if (starts.length > 1) {\r\n refusals.push({\r\n kind: \"ambiguous\",\r\n edits: [number],\r\n matchCount: starts.length,\r\n message: `edit ${number}: the anchor matched ${starts.length} times`,\r\n });\r\n } else {\r\n ranges.push({ start: starts[0]!, end: starts[0]! + find.length, number, replace });\r\n }\r\n });\r\n\r\n // Every overlapping pair, among the anchors that did place. Adjacent ranges (one ends where the next starts) are fine.\r\n for (let i = 0; i < ranges.length; i++) {\r\n for (let j = i + 1; j < ranges.length; j++) {\r\n const a = ranges[i]!;\r\n const b = ranges[j]!;\r\n if (a.start < b.end && b.start < a.end) {\r\n const [first, second] = a.number < b.number ? [a.number, b.number] : [b.number, a.number];\r\n refusals.push({\r\n kind: \"overlap\",\r\n edits: [first, second],\r\n matchCount: null,\r\n message: `edits ${first} and ${second} overlap`,\r\n });\r\n }\r\n }\r\n }\r\n\r\n if (refusals.length > 0) return { ok: false, refusals, editCount: edits.length };\r\n\r\n const pieces: string[] = [];\r\n let cursor = 0;\r\n for (const range of [...ranges].sort((x, y) => x.start - y.start)) {\r\n pieces.push(originalLf.slice(cursor, range.start), range.replace);\r\n cursor = range.end;\r\n }\r\n pieces.push(originalLf.slice(cursor));\r\n return { ok: true, content: pieces.join(\"\"), editCount: edits.length };\r\n}\r\n", "/** An error whose message quotes something the AI Runtime sent back: its explanation, a refusal reason, or the reply\r\n * itself. That text can carry case text or generated code, so the full `message` stays in the job log (where it has\r\n * always gone) and only `summary` \u2014 the error's name and code \u2014 may leave the job in the failed callback. Truncating\r\n * the message would bound its size, not its kind. */\r\nexport class RuntimeReplyError extends Error {\r\n readonly summary: string;\r\n\r\n constructor(message: string, summary: string) {\r\n super(message);\r\n this.name = \"RuntimeReplyError\";\r\n this.summary = summary;\r\n }\r\n}\r\n", "import { RuntimeReplyError } from \"./runtimeReplyError\";\r\n\r\n/**\r\n * QUIKTR-1046 \u2014 `/ai/execute` wraps every use-case result in an envelope; the use-case's own result\r\n * lives at `envelope.structuredJson`, not at the top level. Both `targeting.ts` and `codegen.ts`\r\n * read the raw response directly and have never worked against a real reply \u2014 this is the one\r\n * place that unwraps it, so there is exactly one place to get it right.\r\n *\r\n * A failed call can arrive as `success: false` in an HTTP 200 body \u2014 `res.ok` alone is not enough.\r\n * Observed live 2026-09-18/19/21, including a real RUN_CREDENTIAL_SCOPE refusal shaped exactly\r\n * like this.\r\n */\r\n/**\r\n * QUIKTR-1083 (\u00A715 of the spec-phase contract) \u2014 two hard-failure codes the AI Runtime raises on\r\n * the versioned `pilot.targeting`/`pilot.codegen` path, neither ever retried: `SEMANTIC_MISMATCH`\r\n * (the JSON shape was valid, a rule failed \u2014 e.g. a generated test file missing its\r\n * `[<automationId>]` marker) and `CONTRACT_REJECTED` (the request itself was refused \u2014 an unknown\r\n * or removed `contextData` key, or an unrecognised `contractVersion`). Both carry the explanation\r\n * in `envelope.error`.\r\n *\r\n * Checked on the RAW envelope, before `unwrapExecute` \u2014 same reason codegen.ts's existing\r\n * `CODEGEN_FILE_TOO_LARGE`/`CODEGEN_CONTEXT_TOO_LARGE` check already runs there: unwrapping first\r\n * would throw `unwrapExecute`'s generic `success:false` error and lose the distinction. No custom\r\n * error class \u2014 `run.ts`'s top-level catch already prints any thrown error's message, and\r\n * `fetchWithRetry` never retries a 200 response regardless of body, so \"print the violation list\"\r\n * and \"never retried\" both already hold once this throws a message that names the code and detail.\r\n */\r\nconst HARD_FAILURE_CODES = new Set([\"SEMANTIC_MISMATCH\", \"CONTRACT_REJECTED\"]);\r\n\r\n/** `target`, when the call is scoped to one file (codegen), is named in the message: the AI\r\n * Runtime's explanation says what broke but not in which file. */\r\nexport function checkHardFailure(envelope: any, useCase: string, target?: string): void {\r\n const code = envelope?.errorCode;\r\n if (typeof code === \"string\" && HARD_FAILURE_CODES.has(code)) {\r\n const detail = envelope.error ?? envelope.normalizedText ?? \"no detail\";\r\n const where = target ? ` for ${target}` : \"\";\r\n throw new RuntimeReplyError(\r\n `${useCase} failed${where} (${code}, not retried): ${detail}`,\r\n `${useCase} failed${where} (${code}, not retried)`,\r\n );\r\n }\r\n}\r\n\r\n/** Every error below quotes the AI Runtime's reply in its message (the job log keeps it); `RuntimeReplyError.summary`\r\n * is the name and code only, which is all that may be reported to QuikTrack. */\r\nexport function unwrapExecute<T>(envelope: any, useCase: string): T {\r\n if (envelope?.success === false) {\r\n const code = envelope.errorCode ?? \"UNKNOWN\";\r\n throw new RuntimeReplyError(\r\n `${useCase} failed: ${code} \u2014 ${envelope.error ?? envelope.normalizedText ?? \"no message\"}`,\r\n `${useCase} failed: ${code}`,\r\n );\r\n }\r\n if (!envelope?.structuredJson || typeof envelope.structuredJson !== \"object\") {\r\n throw new RuntimeReplyError(\r\n `${useCase} returned no structuredJson: ${JSON.stringify(envelope)}`,\r\n `${useCase} returned no structuredJson`,\r\n );\r\n }\r\n return envelope.structuredJson as T;\r\n}\r\n", "import { posix } from \"node:path\";\r\nimport { matchesDeniedPath } from \"./deniedPaths\";\r\n\r\n/**\r\n * QUIKTR-1454 \u2014 the files a changed file imports, shown to the code-writing step alongside the ones targeting\r\n * named. First real 9.0.0 run (QUIKSPL-35): `validation.js` imports from `exchange.js`, targeting did not list\r\n * it, and the model invented a name that file does not export. An import is a fact the file states, so it is\r\n * parsed here rather than asked of a model (Suyash, 5 Oct). Three rules from him: ONE hop (never what an\r\n * imported file imports), what was added and skipped is logged with the reason, and targeting's own list is\r\n * never replaced \u2014 this only adds to it.\r\n *\r\n * Pure: the caller hands over the repo listing and a reader. JavaScript/TypeScript only for now; any other kind\r\n * of file simply yields nothing.\r\n */\r\n\r\n// \u2500\u2500 reading imports out of source \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\ntype Token = { k: \"id\" | \"str\" | \"num\" | \"p\" | \"tpl\"; v: string };\r\n\r\nconst REGEX_PRECEDING_KEYWORDS = new Set([\r\n \"return\", \"typeof\", \"instanceof\", \"in\", \"of\", \"new\", \"delete\", \"void\", \"throw\", \"case\", \"do\", \"else\", \"yield\", \"await\",\r\n]);\r\n\r\n/** ASCII space characters plus the Unicode ones editors leave in files: byte-order mark, no-break space, line and\r\n * paragraph separators. A leading BOM read as part of the word \"import\" hid the first import of 72 repository files. */\r\nconst SPACE_CODES = new Set([0x20, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0xa0, 0x1680, 0x2028, 0x2029, 0x202f, 0x205f, 0x3000, 0xfeff]);\r\nconst isSpace = (c: string) => {\r\n const code = c.charCodeAt(0);\r\n return SPACE_CODES.has(code) || (code >= 0x2000 && code <= 0x200a);\r\n};\r\nconst isIdStart = (c: string) => !isSpace(c) && (/[A-Za-z_$]/.test(c) || c.charCodeAt(0) > 0x7f);\r\nconst isIdPart = (c: string) => !isSpace(c) && (/[A-Za-z0-9_$]/.test(c) || c.charCodeAt(0) > 0x7f);\r\n\r\n/**\r\n * Splits source into the tokens that matter and drops what must not be mistaken for code: comments, string\r\n * contents, template text and regular-expression literals. A quote that never closes on its line ends at the\r\n * line break, as a real scanner reports it \u2014 a JSX apostrophe (\"Don't\") must not swallow the rest of the file.\r\n * `${ \u2026 }` inside a template is code and is scanned (an `import()` can sit there).\r\n */\r\nfunction tokenize(src: string): Token[] {\r\n const out: Token[] = [];\r\n const n = src.length;\r\n\r\n function regexAllowed(): boolean {\r\n const prev = out[out.length - 1];\r\n if (!prev) return true;\r\n if (prev.k === \"p\") return prev.v !== \")\" && prev.v !== \"]\" && prev.v !== \"}\";\r\n if (prev.k === \"id\") return REGEX_PRECEDING_KEYWORDS.has(prev.v);\r\n return false;\r\n }\r\n\r\n /** Scans code from `i`; when `inSubstitution`, stops after the `}` that closes the `${`. Returns the next index. */\r\n function scan(start: number, inSubstitution: boolean): number {\r\n let i = start;\r\n let depth = 0;\r\n while (i < n) {\r\n const c = src[i]!;\r\n if (isSpace(c)) {\r\n i++;\r\n continue;\r\n }\r\n if (c === \"/\" && src[i + 1] === \"/\") {\r\n while (i < n && src[i] !== \"\\n\") i++;\r\n continue;\r\n }\r\n if (c === \"/\" && src[i + 1] === \"*\") {\r\n const end = src.indexOf(\"*/\", i + 2);\r\n i = end === -1 ? n : end + 2;\r\n continue;\r\n }\r\n if (c === \"'\" || c === '\"') {\r\n let j = i + 1;\r\n let closed = false;\r\n while (j < n) {\r\n const d = src[j]!;\r\n if (d === \"\\\\\") {\r\n j += 2;\r\n continue;\r\n }\r\n if (d === c) {\r\n closed = true;\r\n break;\r\n }\r\n if (d === \"\\n\" || d === \"\\r\") break;\r\n j++;\r\n }\r\n if (closed) out.push({ k: \"str\", v: src.slice(i + 1, j) });\r\n i = closed ? j + 1 : j;\r\n continue;\r\n }\r\n if (c === \"`\") {\r\n let j = i + 1;\r\n let hasSubstitution = false;\r\n let closed = false;\r\n const textStart = j;\r\n let textEnd = j;\r\n while (j < n) {\r\n const d = src[j]!;\r\n if (d === \"\\\\\") {\r\n j += 2;\r\n continue;\r\n }\r\n if (d === \"`\") {\r\n closed = true;\r\n textEnd = hasSubstitution ? textEnd : j;\r\n break;\r\n }\r\n if (d === \"$\" && src[j + 1] === \"{\") {\r\n hasSubstitution = true;\r\n j = scan(j + 2, true);\r\n continue;\r\n }\r\n j++;\r\n }\r\n if (closed) out.push(hasSubstitution ? { k: \"tpl\", v: \"\" } : { k: \"str\", v: src.slice(textStart, textEnd) });\r\n i = closed ? j + 1 : n;\r\n continue;\r\n }\r\n if (c === \"/\" && regexAllowed()) {\r\n let j = i + 1;\r\n let inClass = false;\r\n let closed = false;\r\n while (j < n) {\r\n const d = src[j]!;\r\n if (d === \"\\\\\") {\r\n j += 2;\r\n continue;\r\n }\r\n if (d === \"\\n\" || d === \"\\r\") break;\r\n if (d === \"[\") inClass = true;\r\n else if (d === \"]\") inClass = false;\r\n else if (d === \"/\" && !inClass) {\r\n closed = true;\r\n break;\r\n }\r\n j++;\r\n }\r\n if (closed) {\r\n j++;\r\n while (j < n && /[a-z]/i.test(src[j]!)) j++;\r\n out.push({ k: \"num\", v: \"/re/\" });\r\n i = j;\r\n continue;\r\n }\r\n out.push({ k: \"p\", v: \"/\" });\r\n i++;\r\n continue;\r\n }\r\n if (/[0-9]/.test(c)) {\r\n let j = i + 1;\r\n while (j < n && /[0-9A-Za-z_.]/.test(src[j]!)) j++;\r\n out.push({ k: \"num\", v: src.slice(i, j) });\r\n i = j;\r\n continue;\r\n }\r\n if (isIdStart(c)) {\r\n let j = i + 1;\r\n while (j < n && isIdPart(src[j]!)) j++;\r\n out.push({ k: \"id\", v: src.slice(i, j) });\r\n i = j;\r\n continue;\r\n }\r\n if (inSubstitution) {\r\n if (c === \"{\") depth++;\r\n else if (c === \"}\") {\r\n if (depth === 0) return i + 1;\r\n depth--;\r\n }\r\n }\r\n out.push({ k: \"p\", v: c });\r\n i++;\r\n }\r\n return n;\r\n }\r\n\r\n scan(0, false);\r\n return out;\r\n}\r\n\r\n/**\r\n * The module specifiers a JavaScript/TypeScript file names, in order of first appearance, each once: static\r\n * `import \u2026 from`, side-effect `import \"x\"`, `export \u2026 from`, `import(\"x\")`, `require(\"x\")` and\r\n * `import x = require(\"x\")`. Only string literals (or a template with no substitution) count; an expression is\r\n * ignored, as are comments, text inside strings and a method that merely happens to be called `require`.\r\n */\r\nexport function extractImportSpecifiers(source: string): string[] {\r\n const t = tokenize(source);\r\n const found: string[] = [];\r\n const seen = new Set<string>();\r\n const add = (s: string) => {\r\n if (!seen.has(s)) {\r\n seen.add(s);\r\n found.push(s);\r\n }\r\n };\r\n const isP = (tok: Token | undefined, v: string) => tok?.k === \"p\" && tok.v === v;\r\n\r\n for (let i = 0; i < t.length; i++) {\r\n const tok = t[i]!;\r\n if (tok.k !== \"id\") continue;\r\n if (isP(t[i - 1], \".\")) continue; // obj.import / obj.require \u2014 a property, not the keyword\r\n\r\n if (tok.v === \"require\") {\r\n if (isP(t[i + 1], \"(\") && t[i + 2]?.k === \"str\" && isP(t[i + 3], \")\")) add(t[i + 2]!.v);\r\n continue;\r\n }\r\n if (tok.v !== \"import\" && tok.v !== \"export\") continue;\r\n\r\n const next = t[i + 1];\r\n if (tok.v === \"import\") {\r\n if (next?.k === \"str\") {\r\n add(next.v);\r\n continue;\r\n }\r\n if (isP(next, \"(\")) {\r\n if (t[i + 2]?.k === \"str\" && (isP(t[i + 3], \")\") || isP(t[i + 3], \",\"))) add(t[i + 2]!.v);\r\n continue;\r\n }\r\n }\r\n // import <clause> from \"x\" / export <clause> from \"x\". The scan ends at the next import or export, so a long\r\n // chain of back-to-back statements (`export{a}export{b}\u2026`, no semicolons) is read once, not once per statement.\r\n for (let j = i + 1; j < t.length; j++) {\r\n const c = t[j]!;\r\n if (c.k === \"id\") {\r\n if (c.v === \"import\" || c.v === \"export\") break;\r\n if (c.v === \"from\" && t[j + 1]?.k === \"str\") {\r\n add(t[j + 1]!.v);\r\n break;\r\n }\r\n continue;\r\n }\r\n if (c.k === \"p\" && (c.v === \"{\" || c.v === \"}\" || c.v === \",\" || c.v === \"*\")) continue;\r\n break;\r\n }\r\n }\r\n return found;\r\n}\r\n\r\n/** Files the scanner understands. */\r\nexport function supportsImportScan(path: string): boolean {\r\n return /\\.(?:[cm]?[jt]sx?)$/i.test(path);\r\n}\r\n\r\n// \u2500\u2500 turning a specifier into a file in the repository \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\nexport type ResolvedImport =\r\n | { kind: \"repo\"; path: string }\r\n | { kind: \"external\" }\r\n | { kind: \"unresolved\"; reason: \"alias\" | \"not found\" | \"asset\"; attempted?: string };\r\n\r\nconst CODE_EXTS = [\".ts\", \".tsx\", \".js\", \".jsx\", \".mjs\", \".cjs\", \".mts\", \".cts\", \".json\"];\r\nconst ASSET_EXTS = new Set([\r\n \".css\", \".scss\", \".sass\", \".less\", \".svg\", \".png\", \".jpg\", \".jpeg\", \".gif\", \".webp\", \".avif\", \".ico\", \".bmp\",\r\n \".woff\", \".woff2\", \".ttf\", \".otf\", \".eot\", \".mp3\", \".mp4\", \".webm\", \".wav\", \".pdf\", \".zip\", \".wasm\",\r\n]);\r\n/** TypeScript's ESM habit: `./x.js` written in source, `x.ts` on disk. */\r\nconst TS_SIBLINGS: Record<string, string[]> = { \".js\": [\".ts\", \".tsx\"], \".jsx\": [\".tsx\"], \".mjs\": [\".mts\"], \".cjs\": [\".cts\"] };\r\n\r\n/**\r\n * Where a specifier points. `listing` is the repository's file list (the same notion of \"what exists\" targeting's\r\n * context paths are checked against), so nothing is probed on disk and nothing outside it is ever followed.\r\n */\r\nexport function resolveImport(fromPath: string, specifier: string, listing: ReadonlySet<string>): ResolvedImport {\r\n if (/^(?:@\\/|~\\/|#|\\$|\\/)/.test(specifier)) return { kind: \"unresolved\", reason: \"alias\" };\r\n const clean = specifier.replace(/[?#].*$/, \"\");\r\n const relative = clean === \".\" || clean === \"..\" || clean.startsWith(\"./\") || clean.startsWith(\"../\");\r\n if (!relative) return { kind: \"external\" };\r\n\r\n const base = posix.normalize(posix.join(posix.dirname(fromPath), clean));\r\n if (base === \"..\" || base.startsWith(\"../\") || posix.isAbsolute(base)) return { kind: \"unresolved\", reason: \"not found\" };\r\n\r\n const ext = posix.extname(base);\r\n if (ASSET_EXTS.has(ext.toLowerCase())) return { kind: \"unresolved\", reason: \"asset\" };\r\n\r\n const candidates: string[] = [];\r\n if (CODE_EXTS.includes(ext)) {\r\n candidates.push(base);\r\n for (const sibling of TS_SIBLINGS[ext] ?? []) candidates.push(base.slice(0, -ext.length) + sibling);\r\n }\r\n for (const e of CODE_EXTS) candidates.push(base + e);\r\n candidates.push(base + \".d.ts\");\r\n for (const e of CODE_EXTS) candidates.push(`${base}/index${e}`);\r\n\r\n for (const candidate of candidates) {\r\n if (listing.has(candidate)) return { kind: \"repo\", path: candidate };\r\n }\r\n return { kind: \"unresolved\", reason: \"not found\", attempted: base };\r\n}\r\n\r\n// \u2500\u2500 what gets added \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\nexport interface ImportContextParams {\r\n targetPath: string;\r\n /** The target's content on disk now. */\r\n source: string;\r\n /** Paths already in front of the model for this call (targeting's list and the run's other files). */\r\n alreadyNamed: ReadonlySet<string>;\r\n deniedPaths: string[];\r\n listing: ReadonlySet<string>;\r\n readFile: (path: string) => string;\r\n maxFileChars: number;\r\n maxTotalChars: number;\r\n /** Characters the run's other added files already spent against `maxTotalChars`. */\r\n spentChars: number;\r\n}\r\n\r\nexport interface ImportContext {\r\n entries: { path: string; content: string }[];\r\n skipped: { path: string; reason: string }[];\r\n /** The paths of `entries`, for the context log. */\r\n importedPaths: string[];\r\n /** Path-alias imports (`@/x`) seen and not followed. Counted, not listed: they can be many. */\r\n aliasImports: number;\r\n}\r\n\r\n/** Skips worth a line in the run's notes: the file mattered and could not be shown. The rest stay in the log. */\r\nexport const ACTIONABLE_IMPORT_SKIPS = new Set([\"import: too large\", \"import: over budget\", \"import: unreadable\"]);\r\n\r\n/**\r\n * The direct imports of one target, read and sized like the run's other added files (same per-file and total\r\n * limits, shared). Order is first appearance in the file. A path already named, already added, or the target\r\n * itself is never repeated; a denied path is never read.\r\n */\r\nexport function collectImportContext(p: ImportContextParams): ImportContext {\r\n const out: ImportContext = { entries: [], skipped: [], importedPaths: [], aliasImports: 0 };\r\n if (!supportsImportScan(p.targetPath)) return out;\r\n\r\n const seen = new Set<string>(p.alreadyNamed);\r\n seen.add(p.targetPath);\r\n let total = p.spentChars;\r\n\r\n for (const specifier of extractImportSpecifiers(p.source)) {\r\n const resolved = resolveImport(p.targetPath, specifier, p.listing);\r\n if (resolved.kind === \"external\") continue;\r\n if (resolved.kind === \"unresolved\") {\r\n if (resolved.reason === \"alias\") out.aliasImports++;\r\n else if (resolved.reason === \"not found\") {\r\n const path = resolved.attempted ?? specifier;\r\n if (!seen.has(path)) {\r\n seen.add(path);\r\n out.skipped.push({ path, reason: \"import: not in workspace\" });\r\n }\r\n }\r\n continue;\r\n }\r\n\r\n const path = resolved.path;\r\n if (seen.has(path)) continue;\r\n seen.add(path);\r\n // Defence in depth, like the run-file collector: a path in context is read and sent to the model provider.\r\n if (matchesDeniedPath(path, p.deniedPaths)) {\r\n out.skipped.push({ path, reason: \"import: denied\" });\r\n continue;\r\n }\r\n let content: string;\r\n try {\r\n content = p.readFile(path);\r\n } catch {\r\n out.skipped.push({ path, reason: \"import: unreadable\" });\r\n continue;\r\n }\r\n if (content.length > p.maxFileChars) {\r\n out.skipped.push({ path, reason: \"import: too large\" });\r\n } else if (total + content.length > p.maxTotalChars) {\r\n out.skipped.push({ path, reason: \"import: over budget\" });\r\n } else {\r\n total += content.length;\r\n out.entries.push({ path, content });\r\n out.importedPaths.push(path);\r\n }\r\n }\r\n return out;\r\n}\r\n", "/**\r\n * QUIKTR-1069 \u2014 a gateway timeout in front of the AI Runtime is not a refusal: the demo rehearsal\r\n * hit a 504 from a devtunnel/load balancer, not the runtime, and the same call succeeded on retry.\r\n * Retries ONLY transport-level signals \u2014 HTTP 502/503/504, or a thrown network error\r\n * (ECONNRESET/ETIMEDOUT) \u2014 twice, with a short fixed backoff. Every other failure (a real refusal,\r\n * CODEGEN_FILE_TOO_LARGE, success:false+errorCode, any 4xx) arrives as a normal HTTP 200 with the\r\n * refusal inside the envelope body, or a genuine non-transient 4xx \u2014 neither ever matches this\r\n * function's retry condition, so nothing here needs to special-case them.\r\n *\r\n * Spend: a retried call the runtime actually completed has been paid for twice. maxRunUsd already\r\n * caps the run (enforced at the gateway, per packet.ts's own comment), so this fails safe \u2014 the\r\n * worst case is hitting the budget wall slightly sooner, never an uncapped spend.\r\n */\r\nconst RETRYABLE_STATUS_CODES = new Set([502, 503, 504]);\r\nconst RETRYABLE_NETWORK_ERROR_CODES = new Set([\"ECONNRESET\", \"ETIMEDOUT\"]);\r\n\r\nfunction isRetryableNetworkError(err: unknown): boolean {\r\n const code =\r\n (err as { cause?: { code?: string } } | undefined)?.cause?.code ??\r\n (err as { code?: string } | undefined)?.code;\r\n return typeof code === \"string\" && RETRYABLE_NETWORK_ERROR_CODES.has(code);\r\n}\r\n\r\nexport async function fetchWithRetry(\r\n url: string,\r\n init: RequestInit,\r\n { retries = 2, backoffMs = 250 }: { retries?: number; backoffMs?: number } = {},\r\n): Promise<Response> {\r\n for (let attempt = 0; ; attempt++) {\r\n try {\r\n const res = await fetch(url, init);\r\n if (RETRYABLE_STATUS_CODES.has(res.status) && attempt < retries) {\r\n await new Promise((r) => setTimeout(r, backoffMs));\r\n continue;\r\n }\r\n return res;\r\n } catch (err) {\r\n if (isRetryableNetworkError(err) && attempt < retries) {\r\n await new Promise((r) => setTimeout(r, backoffMs));\r\n continue;\r\n }\r\n throw err;\r\n }\r\n }\r\n}\r\n", "/**\r\n * QUIKTR-1458 \u00A724 \u2014 which way the code is written.\r\n *\r\n * `single` is today's behaviour: one AI call per target file. `loop` lets the AI look, edit and write through tools over several\r\n * turns (codegenLoop.ts), and falls back to `single` if it cannot finish. It is OFF unless asked for, and only the exact word\r\n * `loop` asks. Like the targeting mode, today the switch is an environment variable in the workflow; `packetSetting` is the\r\n * seam for a per-project setting later, with the precedence (setting, then environment, then off) already settled.\r\n */\r\nexport type CodegenMode = \"single\" | \"loop\";\r\n\r\nexport const CODEGEN_MODE_ENV = \"QUIKPILOT_CODEGEN_MODE\";\r\n\r\nfunction parse(value: string | null | undefined): CodegenMode | null {\r\n if (typeof value !== \"string\") return null;\r\n const v = value.trim().toLowerCase();\r\n if (v === \"loop\") return \"loop\";\r\n if (v === \"single\") return \"single\";\r\n return null;\r\n}\r\n\r\nexport function resolveCodegenMode(env: NodeJS.ProcessEnv = process.env, packetSetting?: string | null): CodegenMode {\r\n return parse(packetSetting) ?? parse(env[CODEGEN_MODE_ENV]) ?? \"single\";\r\n}\r\n", "import type { CodegenLoopSummary } from \"./codegenLoop\";\r\n\r\n/**\r\n * QUIKTR-1458 \u00A724 \u2014 what the code-writing loop did, for the run's audit record that goes to QuikProjects.\r\n *\r\n * PATHS, COUNTS, A CLOSED VOCABULARY OF STATUSES, AND THE AI'S OWN SHORT REASONING \u2014 never file content, an anchor, a\r\n * replacement or a search text. The reasoning is model-written text about the customer's code (like `noTargetReason`), cut to a\r\n * short length and flagged when cut, so a reviewer can see why the AI went where it went without anything from a file.\r\n *\r\n * These caps must match QuikProjects' schema. A path longer than the cap is DROPPED, not shortened (a cut-off path is a wrong\r\n * path), and the cut is flagged.\r\n */\r\nexport const MAX_RECORD_PATHS = 50;\r\nexport const MAX_RECORD_PATH_CHARS = 300;\r\nexport const MAX_RECORD_REASONING_TURNS = 30;\r\nexport const MAX_RECORD_REASONING_CHARS = 500;\r\nexport const MAX_RECORD_FALLBACK_REASON_CHARS = 40;\r\nconst MAX_STATUS_KEYS = 20;\r\nconst MAX_STATUS_KEY_CHARS = 40;\r\n\r\nexport interface CodegenLoopRecord {\r\n turns: number;\r\n toolCalls: number;\r\n refused: number;\r\n stopReason: string;\r\n fellBack?: true;\r\n fallbackReason?: string;\r\n reads: { path: string; startLine?: number; endLine?: number; chars: number; refused?: true }[];\r\n edits: { path: string; count: number }[];\r\n created: { path: string; chars: number }[];\r\n statusCounts: Record<string, number>;\r\n reasoning: { turn: number; text: string; truncated?: true }[];\r\n /** Something was left out to fit the caps above. */\r\n truncated?: true;\r\n}\r\n\r\nfunction whole(n: unknown): number {\r\n return typeof n === \"number\" && Number.isInteger(n) && n >= 0 ? n : 0;\r\n}\r\n\r\nfunction pathOk(p: unknown): p is string {\r\n return typeof p === \"string\" && p.length > 0 && p.length <= MAX_RECORD_PATH_CHARS;\r\n}\r\n\r\nexport function buildCodegenLoopRecord(loop: CodegenLoopSummary): CodegenLoopRecord {\r\n let cut = false;\r\n const room = <T extends { path: string }>(rows: T[]): T[] => {\r\n const kept: T[] = [];\r\n for (const r of rows) {\r\n if (kept.length >= MAX_RECORD_PATHS) {\r\n cut = true;\r\n break;\r\n }\r\n if (!pathOk(r.path)) {\r\n cut = true;\r\n continue;\r\n }\r\n kept.push(r);\r\n }\r\n return kept;\r\n };\r\n\r\n const reads = room(loop.reads).map((r) => ({\r\n path: r.path.trim(),\r\n ...(Number.isInteger(r.startLine) ? { startLine: r.startLine } : {}),\r\n ...(Number.isInteger(r.endLine) ? { endLine: r.endLine } : {}),\r\n chars: whole(r.chars),\r\n ...(r.refused ? { refused: true as const } : {}),\r\n }));\r\n const edits = room(loop.edits).map((e) => ({ path: e.path, count: whole(e.count) }));\r\n const created = room(loop.created).map((c) => ({ path: c.path, chars: whole(c.chars) }));\r\n\r\n const statusCounts: Record<string, number> = {};\r\n for (const [k, v] of Object.entries(loop.statusCounts).slice(0, MAX_STATUS_KEYS)) {\r\n if (k.length > 0 && k.length <= MAX_STATUS_KEY_CHARS) statusCounts[k] = whole(v);\r\n else cut = true;\r\n }\r\n if (Object.keys(loop.statusCounts).length > MAX_STATUS_KEYS) cut = true;\r\n\r\n const reasoning: CodegenLoopRecord[\"reasoning\"] = [];\r\n for (const r of loop.reasoning) {\r\n if (reasoning.length >= MAX_RECORD_REASONING_TURNS) {\r\n cut = true;\r\n break;\r\n }\r\n const text = typeof r.text === \"string\" ? r.text.trim() : \"\";\r\n if (text.length === 0) continue;\r\n const over = text.length > MAX_RECORD_REASONING_CHARS;\r\n reasoning.push({ turn: whole(r.turn), text: over ? text.slice(0, MAX_RECORD_REASONING_CHARS) : text, ...(over ? { truncated: true as const } : {}) });\r\n }\r\n\r\n return {\r\n turns: whole(loop.turns),\r\n toolCalls: whole(loop.toolCalls),\r\n refused: whole(loop.refused),\r\n stopReason: loop.stopReason,\r\n ...(loop.fellBack ? { fellBack: true as const } : {}),\r\n ...(loop.fallbackReason ? { fallbackReason: String(loop.fallbackReason).slice(0, MAX_RECORD_FALLBACK_REASON_CHARS) } : {}),\r\n reads,\r\n edits,\r\n created,\r\n statusCounts,\r\n reasoning,\r\n ...(cut ? { truncated: true as const } : {}),\r\n };\r\n}\r\n", "import { readFileSync } from \"node:fs\";\r\nimport { MAX_ADDED_CONTEXT_CHARS, MAX_ADDED_FILE_CHARS } from \"./codegen\";\r\nimport { matchesDeniedPath } from \"./deniedPaths\";\r\nimport { toLf } from \"./editsApply\";\r\nimport { collectImportContext } from \"./importContext\";\r\nimport { isTestTarget } from \"./overlapCheck\";\r\nimport type { PilotTarget } from \"./targeting\";\r\nimport type { CodegenContextRecord } from \"./targetingRecord\";\r\n\r\n/**\r\n * QUIKTR-1458 \u00A724 \u2014 the files the code-writing loop is SHOWN before its first turn.\r\n *\r\n * Without this the loop starts blind and has to decide for itself to read the file that defines a value. In three smoke runs on\r\n * 7 Oct it read that file once: the other two times it wrote its own list of supported currencies (QUIKSPL-47) or its own\r\n * expected amounts (QUIKSPL-49) from a guess. A prompt line asking it to look helped once and not twice, so the same facts the\r\n * one-file-at-a-time path has always shown are now put in front of it, by the runner, every time:\r\n *\r\n * - the files targeting named for each target (`contextPaths`), then\r\n * - the files each EXISTING target itself imports, one hop (`importContext.ts`, QUIKTR-1454).\r\n *\r\n * and, FIRST after what targeting named, the EXISTING TESTS of the code being changed (below). Never the other targets: the AI reads\r\n * those with its own tools, and showing them again would count twice against the turn ceiling.\r\n *\r\n * Why the tests come first: in the ten runs of 8 Oct, every run that broke an existing test read that test file AFTER it had edited\r\n * the code, and every run that read it first passed. The existing tests are the executable statement of what the code does today (the\r\n * default for a missing currency, the message for a code that is not three letters), and they are the one thing the AI could not\r\n * have read in the one-file-at-a-time path at all. They are shown as LF text, because that is the form an edit has to match. A denied path is never read. The limits are the one-file path's (40,000 characters a file, 60,000 in all), shared\r\n * across the whole run, and the per-turn token ceiling still applies on top.\r\n */\r\n\r\nexport interface LoopContext {\r\n entries: { path: string; content: string }[];\r\n /** The part of `entries` that are existing tests (they also appear in `entries`). Log line only. */\r\n testPaths: string[];\r\n /** One record per target, in the shape the run's `codegenContext` record already uses, so QuikProjects shows it unchanged. */\r\n records: CodegenContextRecord[];\r\n}\r\n\r\nexport interface LoopContextParams {\r\n targets: PilotTarget[];\r\n listing: string[];\r\n deniedPaths: string[];\r\n readFile?: (path: string) => string;\r\n}\r\n\r\nconst TEST_NAME_RE = /^(.+)\\.(?:test|spec)\\.[cm]?[jt]sx?$/i;\r\nconst CODE_NAME_RE = /^(.+)\\.[cm]?[jt]sx?$/i;\r\n\r\nfunction dirOf(path: string): string {\r\n const i = path.lastIndexOf(\"/\");\r\n return i === -1 ? \"\" : path.slice(0, i);\r\n}\r\n\r\nfunction baseOf(path: string): string {\r\n return path.slice(path.lastIndexOf(\"/\") + 1);\r\n}\r\n\r\nfunction parentOf(dir: string): string {\r\n return dir === \"\" ? \"\" : dirOf(dir);\r\n}\r\n\r\n/**\r\n * The existing test files of a code file, by the usual naming (`name.test.ext`, `name.spec.ext`) and the usual places: beside it, in\r\n * a `__tests__` folder beside it, or in the `__tests__`, `tests` or `test` folder of its parent. Only files in the listing, sorted.\r\n * A same-named test elsewhere in a monorepo is not this file's.\r\n */\r\nexport function pairedTestPaths(codePath: string, listing: ReadonlySet<string>): string[] {\r\n if (isTestTarget(codePath)) return [];\r\n const m = CODE_NAME_RE.exec(baseOf(codePath));\r\n if (!m) return [];\r\n const stem = m[1]!.toLowerCase();\r\n const dir = dirOf(codePath);\r\n const parent = parentOf(dir);\r\n const join = (d: string, leaf: string) => (d === \"\" ? leaf : `${d}/${leaf}`);\r\n const homes = new Set<string>([dir, join(dir, \"__tests__\"), join(parent, \"__tests__\"), join(parent, \"tests\"), join(parent, \"test\")]);\r\n const found: string[] = [];\r\n for (const path of listing) {\r\n if (!homes.has(dirOf(path))) continue;\r\n const t = TEST_NAME_RE.exec(baseOf(path));\r\n if (t && t[1]!.toLowerCase() === stem) found.push(path);\r\n }\r\n return found.sort();\r\n}\r\n\r\nfunction asLf(text: string): string {\r\n return toLf(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);\r\n}\r\n\r\nexport function collectLoopContext(p: LoopContextParams): LoopContext {\r\n const readFile = p.readFile ?? ((path: string) => readFileSync(path, \"utf8\"));\r\n const listing = new Set(p.listing);\r\n // Every target is left to the AI's own tools, except an existing TEST target: its content is the thing to show first.\r\n const seen = new Set<string>(p.targets.filter((t) => !(t.kind === \"EXISTING\" && isTestTarget(t.path))).map((t) => t.path));\r\n const entries: LoopContext[\"entries\"] = [];\r\n const testPaths: string[] = [];\r\n const records: CodegenContextRecord[] = [];\r\n let total = 0;\r\n\r\n for (const target of p.targets) {\r\n const named = target.contextPaths ?? [];\r\n const added: string[] = [];\r\n const skipped: { path: string; reason: string }[] = [];\r\n\r\n for (const path of named) {\r\n if (seen.has(path)) continue;\r\n seen.add(path);\r\n if (matchesDeniedPath(path, p.deniedPaths)) {\r\n skipped.push({ path, reason: \"denied\" });\r\n continue;\r\n }\r\n if (!listing.has(path)) {\r\n skipped.push({ path, reason: \"not in workspace\" });\r\n continue;\r\n }\r\n let content: string;\r\n try {\r\n content = readFile(path);\r\n } catch {\r\n skipped.push({ path, reason: \"unreadable\" });\r\n continue;\r\n }\r\n if (content.length > MAX_ADDED_FILE_CHARS) skipped.push({ path, reason: \"too large\" });\r\n else if (total + content.length > MAX_ADDED_CONTEXT_CHARS) skipped.push({ path, reason: \"over budget\" });\r\n else {\r\n entries.push({ path, content });\r\n added.push(path);\r\n total += content.length;\r\n }\r\n }\r\n\r\n // The existing tests of this target: itself when it is an existing test file, or the tests that sit beside the code it changes.\r\n const wantedTests = target.kind !== \"EXISTING\" ? [] : isTestTarget(target.path) ? [target.path] : pairedTestPaths(target.path, listing);\r\n for (const path of wantedTests) {\r\n if (seen.has(path)) continue;\r\n seen.add(path);\r\n if (matchesDeniedPath(path, p.deniedPaths)) {\r\n skipped.push({ path, reason: \"denied\" });\r\n continue;\r\n }\r\n let content: string;\r\n try {\r\n content = asLf(readFile(path));\r\n } catch {\r\n skipped.push({ path, reason: \"unreadable\" });\r\n continue;\r\n }\r\n if (content.length > MAX_ADDED_FILE_CHARS) skipped.push({ path, reason: \"too large\" });\r\n else if (total + content.length > MAX_ADDED_CONTEXT_CHARS) skipped.push({ path, reason: \"over budget\" });\r\n else {\r\n entries.push({ path, content });\r\n added.push(path);\r\n testPaths.push(path);\r\n total += content.length;\r\n }\r\n }\r\n\r\n let importedPaths: string[] = [];\r\n let aliasImports = 0;\r\n if (target.kind === \"EXISTING\") {\r\n let source: string | null = null;\r\n try {\r\n source = readFile(target.path);\r\n } catch {\r\n skipped.push({ path: target.path, reason: \"import: unreadable\" });\r\n }\r\n if (source !== null) {\r\n const imports = collectImportContext({\r\n targetPath: target.path,\r\n source,\r\n alreadyNamed: seen,\r\n deniedPaths: p.deniedPaths,\r\n listing,\r\n readFile,\r\n maxFileChars: MAX_ADDED_FILE_CHARS,\r\n maxTotalChars: MAX_ADDED_CONTEXT_CHARS,\r\n spentChars: total,\r\n });\r\n for (const e of imports.entries) {\r\n entries.push(e);\r\n added.push(e.path);\r\n seen.add(e.path);\r\n total += e.content.length;\r\n }\r\n skipped.push(...imports.skipped);\r\n importedPaths = imports.importedPaths;\r\n aliasImports = imports.aliasImports;\r\n }\r\n }\r\n\r\n records.push({\r\n targetPath: target.path,\r\n contextPaths: named,\r\n addedPaths: added,\r\n skipped,\r\n ...(importedPaths.length > 0 ? { importedPaths } : {}),\r\n ...(aliasImports > 0 ? { aliasImports } : {}),\r\n });\r\n }\r\n\r\n return { entries, testPaths, records };\r\n}\r\n", "import type { PilotTarget } from \"./targeting\";\r\n\r\n/**\r\n * QUIKTR-1064 \u2014 QUIKSP-3's first live run implemented \"reject negative amounts\" twice: once in\r\n * src/server.js against raw input, once in src/validation.js against parsed minor units. Targeting\r\n * split the work across two files and gave each its own planStepsImplemented describing the same\r\n * rule; codegen faithfully built both. Per-target steps are meant to be DISJOINT (QUIKTR-1035) \u2014\r\n * nothing checked that they are.\r\n *\r\n * The real fix is `pilot.targeting`'s prompt \u2014 an AI Runtime change, not this package's. This is\r\n * the cheap half the ticket assigns here: a non-blocking warning, not semantic analysis. A\r\n * significant-word overlap between two steps in DIFFERENT targets is treated as the same rule\r\n * described twice. Same-target steps are never compared \u2014 one file legitimately implementing\r\n * several related steps is normal and not what this looks for.\r\n */\r\nexport interface OverlapWarning {\r\n targetA: string;\r\n stepA: string;\r\n targetB: string;\r\n stepB: string;\r\n /** QUIKTR-1081 \u2014 \"identical\" (the exact same instruction, modulo case/whitespace) is blocking;\r\n * \"similar\" (the existing Jaccard-threshold match, reworded but not the same text) stays a\r\n * warning. Two legitimate halves of one change never share the literal same instruction. */\r\n severity: \"identical\" | \"similar\";\r\n}\r\n\r\n// QUIKTR-1081 \u2014 a path-convention heuristic, not a real \"is this a test\" signal: nothing in this\r\n// package (or apps/quiktrack/lib/services/pilot) tags a PilotTarget as covering a test today. A\r\n// behaviour appearing in both a file and its test is correct, so a pair is exempt from this check\r\n// entirely \u2014 not merely from blocking \u2014 whenever either side looks like a test file.\r\nconst TEST_PATH_RE = /(\\.(test|spec)\\.[jt]sx?$)|(^|\\/)(__tests__|tests?)\\//i;\r\n\r\nexport function isTestTarget(path: string): boolean {\r\n return TEST_PATH_RE.test(path);\r\n}\r\n\r\nconst STOPWORDS = new Set([\r\n \"a\", \"an\", \"the\", \"is\", \"are\", \"was\", \"were\", \"be\", \"been\", \"being\",\r\n \"of\", \"to\", \"in\", \"on\", \"for\", \"with\", \"at\", \"by\", \"from\", \"as\",\r\n \"and\", \"or\", \"not\", \"no\", \"nor\",\r\n \"this\", \"that\", \"these\", \"those\", \"it\", \"its\",\r\n \"cannot\", \"can't\", \"should\", \"must\", \"may\", \"will\", \"shall\",\r\n \"when\", \"if\", \"than\", \"then\", \"so\", \"do\", \"does\", \"did\",\r\n]);\r\n\r\n// Ignore words this short too \u2014 they add noise to the overlap without carrying meaning (\"id\",\r\n// \"an\", two-letter fragments from punctuation stripping).\r\nconst MIN_WORD_LENGTH = 3;\r\n\r\nfunction significantWords(step: string): Set<string> {\r\n return new Set(\r\n step\r\n .toLowerCase()\r\n .replace(/[^a-z0-9\\s]/g, \" \")\r\n .split(/\\s+/)\r\n .filter((w) => w.length >= MIN_WORD_LENGTH && !STOPWORDS.has(w)),\r\n );\r\n}\r\n\r\nfunction jaccard(a: Set<string>, b: Set<string>): number {\r\n if (a.size === 0 || b.size === 0) return 0;\r\n let intersection = 0;\r\n for (const w of a) if (b.has(w)) intersection++;\r\n const union = a.size + b.size - intersection;\r\n return intersection / union;\r\n}\r\n\r\n// QUIKTR-1081 \u2014 stricter than significantWords' normalization (which drops stopwords/short words\r\n// entirely): this only ignores case and incidental whitespace, so \"identical\" means the actual\r\n// same instruction, not merely \"shares enough meaningful words.\"\r\nfunction normalizedStep(step: string): string {\r\n return step.trim().toLowerCase().replace(/\\s+/g, \" \");\r\n}\r\n\r\n// Cheap and deliberately generous \u2014 a false positive here costs a reviewer one glance at a warning\r\n// line; a false negative is exactly the bug this exists to catch.\r\nconst OVERLAP_THRESHOLD = 0.5;\r\n\r\n/** Every cross-target pair of plan steps whose significant words overlap enough to plausibly be the\r\n * same rule described twice. Steps within the same target are never compared. */\r\nexport function findOverlappingSteps(targets: PilotTarget[]): OverlapWarning[] {\r\n const items = targets.flatMap((target) =>\r\n target.planStepsImplemented.map((step) => ({\r\n target: target.path,\r\n step,\r\n words: significantWords(step),\r\n })),\r\n );\r\n\r\n const warnings: OverlapWarning[] = [];\r\n for (let i = 0; i < items.length; i++) {\r\n for (let j = i + 1; j < items.length; j++) {\r\n if (items[i].target === items[j].target) continue;\r\n if (isTestTarget(items[i].target) || isTestTarget(items[j].target)) continue;\r\n if (jaccard(items[i].words, items[j].words) >= OVERLAP_THRESHOLD) {\r\n warnings.push({\r\n targetA: items[i].target,\r\n stepA: items[i].step,\r\n targetB: items[j].target,\r\n stepB: items[j].step,\r\n severity: normalizedStep(items[i].step) === normalizedStep(items[j].step) ? \"identical\" : \"similar\",\r\n });\r\n }\r\n }\r\n }\r\n return warnings;\r\n}\r\n\r\nexport function describeOverlapWarnings(warnings: OverlapWarning[]): string[] {\r\n return warnings.map(\r\n (w) =>\r\n `${w.targetA} and ${w.targetB} both implement what looks like the same rule \u2014 \"${w.stepA}\" / \"${w.stepB}\". Check these aren't two independent implementations of the same behavior.`,\r\n );\r\n}\r\n", "/**\r\n * QUIKTR-1458 \u00A724 \u2014 \"an existing test file may only be added to\".\r\n *\r\n * The code-writing loop edits by replacing one piece of text (`find`) with another (`replace`). For a test file that already\r\n * existed, the only change allowed is ADDING: every character of `find` has to stay in `replace`, in the same order, with ONE new\r\n * block of whole lines put somewhere in it. Anything else (changing a line, deleting one, commenting one out, wrapping the lot in\r\n * a comment) would let the AI make code pass by weakening the test that checks it, which is the one thing it must never do.\r\n *\r\n * The first version of this rule only allowed the new text at either END of `find`. That refused the natural way to add a test to\r\n * an existing `describe` block (match the end of the last test and the block's closing line, and put the new test between them),\r\n * and the refusal ended a whole run (QUIKSPL-48, 7 Oct). So the new text may also go BETWEEN two lines of `find`, with these\r\n * guards, because inside a test body a plain \"insert some lines\" is exactly how a test gets switched off (`return;`, `it.skip`):\r\n *\r\n * - the new text is whole lines: it ends with a newline, and it goes at a line boundary of `find` (at the very end, it has to\r\n * start a new line instead);\r\n * - the new text is new TEST code, not arbitrary code: it declares a test (`it(`, `test(` or `describe(` at the start of a line)\r\n * and its brackets balance, so it is a self-contained block; or it is nothing but `import` lines.\r\n *\r\n * Only JavaScript and TypeScript test files get the looser rule. For anything else the old rule stands, because the guards above\r\n * read the language.\r\n */\r\n\r\nconst JS_FAMILY = /\\.(?:[cm]?[jt]sx?)$/i;\r\nconst DECLARES_TEST = /^[ \\t]*(?:it|test|describe)\\b/m;\r\nconst IMPORT_LINE = /^\\s*import\\b/;\r\n\r\n/** True when `path` is a test file this module knows how to read. */\r\nexport function usesLooseRule(path: string): boolean {\r\n return JS_FAMILY.test(path);\r\n}\r\n\r\n/**\r\n * Whether every bracket opened in `text` is closed in it, ignoring brackets inside strings, template literals and comments. A new\r\n * test is self-contained; a fragment that opens or closes something that was already there is not.\r\n */\r\nexport function bracketsBalance(text: string): boolean {\r\n const stack: string[] = [];\r\n const pairs: Record<string, string> = { \")\": \"(\", \"]\": \"[\", \"}\": \"{\" };\r\n let i = 0;\r\n while (i < text.length) {\r\n const c = text[i]!;\r\n const next = text[i + 1];\r\n if (c === \"/\" && next === \"/\") {\r\n const nl = text.indexOf(\"\\n\", i);\r\n i = nl === -1 ? text.length : nl + 1;\r\n continue;\r\n }\r\n if (c === \"/\" && next === \"*\") {\r\n const end = text.indexOf(\"*/\", i + 2);\r\n if (end === -1) return false;\r\n i = end + 2;\r\n continue;\r\n }\r\n if (c === '\"' || c === \"'\" || c === \"`\") {\r\n let j = i + 1;\r\n while (j < text.length && text[j] !== c) {\r\n if (text[j] === \"\\\\\") j++;\r\n if (c !== \"`\" && text[j] === \"\\n\") return false;\r\n j++;\r\n }\r\n if (j >= text.length) return false;\r\n i = j + 1;\r\n continue;\r\n }\r\n if (c === \"(\" || c === \"[\" || c === \"{\") stack.push(c);\r\n else if (c === \")\" || c === \"]\" || c === \"}\") {\r\n if (stack.pop() !== pairs[c]) return false;\r\n }\r\n i++;\r\n }\r\n return stack.length === 0;\r\n}\r\n\r\nfunction onlyImports(text: string): boolean {\r\n const lines = text.split(\"\\n\").filter((l) => l.trim().length > 0);\r\n return lines.length > 0 && lines.every((l) => IMPORT_LINE.test(l));\r\n}\r\n\r\nfunction isNewTestCode(added: string): boolean {\r\n return (DECLARES_TEST.test(added) && bracketsBalance(added)) || onlyImports(added);\r\n}\r\n\r\n/** Where the new text sits is acceptable, and what it is is acceptable. */\r\nfunction placementOk(find: string, k: number, added: string): boolean {\r\n if (added === \"\") return true;\r\n const wholeLines =\r\n k === 0\r\n ? added.endsWith(\"\\n\") // before the matched text: whole lines\r\n : k === find.length\r\n ? find.endsWith(\"\\n\") || added.startsWith(\"\\n\") // after it: it has to start a new line\r\n : find[k - 1] === \"\\n\" && added.endsWith(\"\\n\"); // between two of its lines\r\n return wholeLines && isNewTestCode(added);\r\n}\r\n\r\n/**\r\n * The old rule, kept for languages this module cannot read: the new text goes before or after `find`, which stays intact at one end.\r\n * (It lets an arbitrary prefix through, which is the hole the JavaScript rule closes.)\r\n */\r\nfunction strictEndsRule(find: string, replace: string): boolean {\r\n return replace.startsWith(find) || replace.endsWith(find);\r\n}\r\n\r\n/** True when `replace` is `find` with one block of new lines added and nothing else changed. */\r\nexport function isAddOnly(path: string, find: string, replace: string): boolean {\r\n if (replace === find) return true;\r\n if (!usesLooseRule(path)) return strictEndsRule(find, replace);\r\n if (replace.length <= find.length) return false;\r\n const addedLength = replace.length - find.length;\r\n let common = 0;\r\n while (common < find.length && find.charCodeAt(common) === replace.charCodeAt(common)) common++;\r\n for (let k = common; k >= 0; k--) {\r\n if (!replace.endsWith(find.slice(k))) continue;\r\n if (placementOk(find, k, replace.slice(k, k + addedLength))) return true;\r\n }\r\n return false;\r\n}\r\n", "import { posix } from \"node:path\";\r\nimport { matchesDeniedPath } from \"./deniedPaths\";\r\n\r\n/**\r\n * QUIKTR-1458 \u2014 the first gate for every path the AI names in the read-only targeting loop.\r\n *\r\n * This decides only whether a string could be a repo-relative path at all. Whether it is a tracked,\r\n * allowed file is the next gate's job: membership in the checkout listing, then the denied list.\r\n * (`deniedPaths.ts` does no normalising of its own and matches case-sensitively against a\r\n * forward-slash, repo-relative path exactly as `git ls-files` prints it, so everything has to be\r\n * brought to that shape first, or refused.)\r\n *\r\n * Order matters and is pinned by tests: a `..` segment is refused BEFORE the path is normalised,\r\n * because normalising `a/../b.js` quietly turns it into `b.js`, which would look perfectly fine.\r\n */\r\n\r\nexport type PathRefusal = \"path_invalid\" | \"outside_workspace\";\r\n\r\nexport type NormalisedPath = { ok: true; path: string } | { ok: false; reason: PathRefusal };\r\n\r\nconst MAX_PATH_CHARS = 300;\r\n\r\n// Any ASCII control character (NUL, newline, BEL, ESC, DEL, ...).\r\nfunction hasControlChar(s: string): boolean {\r\n for (let i = 0; i < s.length; i++) {\r\n const c = s.charCodeAt(i);\r\n if (c < 0x20 || c === 0x7f) return true;\r\n }\r\n return false;\r\n}\r\n\r\nexport function normaliseToolPath(raw: unknown, options: { allowRoot?: boolean } = {}): NormalisedPath {\r\n const allowRoot = options.allowRoot === true;\r\n\r\n if ((raw === undefined || raw === null || raw === \"\") && allowRoot) return { ok: true, path: \"\" };\r\n if (typeof raw !== \"string\" || raw.length === 0 || raw.length > MAX_PATH_CHARS) {\r\n return { ok: false, reason: \"path_invalid\" };\r\n }\r\n if (hasControlChar(raw)) return { ok: false, reason: \"path_invalid\" };\r\n // Never convert backslashes: a path the AI wrote with them is not a git path, and quietly\r\n // \"fixing\" it would hide that it is guessing.\r\n if (raw.includes(\"\\\\\")) return { ok: false, reason: \"path_invalid\" };\r\n if (raw.startsWith(\"/\") || /^[A-Za-z]:/.test(raw)) return { ok: false, reason: \"path_invalid\" };\r\n\r\n // Before normalising, on purpose (see the header).\r\n if (raw.split(\"/\").includes(\"..\")) return { ok: false, reason: \"outside_workspace\" };\r\n\r\n const normalised = posix.normalize(raw).replace(/\\/+$/, \"\");\r\n if (normalised === \"\" || normalised === \".\") {\r\n return allowRoot ? { ok: true, path: \"\" } : { ok: false, reason: \"path_invalid\" };\r\n }\r\n return { ok: true, path: normalised };\r\n}\r\n\r\n/** True when `path` is `prefix` or lives under it, on a whole path segment (`src` is not `srcx`). */\r\nexport function matchesPrefix(path: string, prefix: string): boolean {\r\n if (prefix === \"\") return true;\r\n return path === prefix || path.startsWith(`${prefix}/`);\r\n}\r\n\r\n/**\r\n * The listing with every denied path removed, sorted. Anything the AI is told about files comes\r\n * from this, so a protected file is never named, counted or hinted at. Sorting makes every answer\r\n * deterministic. The input is not changed.\r\n */\r\nexport function buildVisibleListing(listing: readonly string[], deniedPaths: string[]): string[] {\r\n return listing.filter((p) => !matchesDeniedPath(p, deniedPaths)).sort();\r\n}\r\n", "import { lstatSync, readFileSync, realpathSync } from \"node:fs\";\r\nimport { isAbsolute, join, relative } from \"node:path\";\r\nimport { matchesDeniedPath } from \"./deniedPaths\";\r\nimport { matchesPrefix, normaliseToolPath } from \"./targetingPaths\";\r\n\r\n/**\r\n * QUIKTR-1458 \u2014 the three READ-ONLY tools the AI may use while it chooses which files to change:\r\n * `list_files`, `read_file`, `grep`. Nothing here can write, run or fetch anything.\r\n *\r\n * The AI's arguments are untrusted input and the files are a customer's, so every rule below is\r\n * about safety first:\r\n * - a protected (denied) path is never read, listed, searched, counted or hinted at;\r\n * - nothing outside the checkout is reachable (no `..`, no absolute paths, no symlinks);\r\n * - only files git tracks can be named, so a made-up path simply is not found;\r\n * - every limit turns into a plain RESULT the AI can act on (`refused`, `budget_exhausted`, ...),\r\n * never an exception, and never echoes what the AI sent or what a file contained into an error;\r\n * - `grep` is a FIXED-STRING search. The pattern is model-supplied and runs over customer files in\r\n * CI; a regular expression there is a way to hang the job, and a name like `validateExpense` is\r\n * all the AI needs.\r\n *\r\n * File access goes through `ToolFs` so tests can simulate symlinks, escapes and binary files\r\n * without touching a real checkout; `createNodeToolFs` is the real one.\r\n */\r\n\r\nexport type ToolName = \"list_files\" | \"read_file\" | \"grep\";\r\n\r\nexport interface ToolCall {\r\n id: string;\r\n name: string;\r\n args: unknown;\r\n}\r\n\r\nexport type ToolStatus =\r\n | \"ok\"\r\n | \"refused\"\r\n | \"not_found\"\r\n | \"unreadable\"\r\n | \"bad_args\"\r\n | \"unknown_tool\"\r\n | \"duplicate\"\r\n | \"budget_exhausted\"\r\n // QUIKTR-1458 \u00A724 \u2014 the write tools' own answers (codegenTools.ts). A refused edit is information for the AI, not a\r\n // failure: it changes its anchor and tries again.\r\n | \"no_match\"\r\n | \"ambiguous\"\r\n | \"protected\"\r\n | \"exists\"\r\n | \"too_large\";\r\n\r\nexport interface ToolResult {\r\n id: string;\r\n name: string;\r\n status: ToolStatus;\r\n /** A fixed vocabulary word (or, for `duplicate`, the id of the earlier call). Never model or file text. */\r\n reason?: string;\r\n /** Runner-authored fixed text. Never echoes the AI's input or a file's content. */\r\n message?: string;\r\n output?: unknown;\r\n}\r\n\r\nexport interface ToolLimits {\r\n maxTurns: number;\r\n maxToolCalls: number;\r\n maxCallsPerTurn: number;\r\n readCharsPerRead: number;\r\n readCharsTotal: number;\r\n resultCharsTotal: number;\r\n /** The per-turn ceiling on one request, in estimated TOKENS (`tokenEstimate.ts`). */\r\n maxRequestTokens: number;\r\n grepMaxMatches: number;\r\n grepLineChars: number;\r\n grepFileBytes: number;\r\n grepMaxFiles: number;\r\n grepMaxBytes: number;\r\n fileBytesMax: number;\r\n listMaxEntries: number;\r\n maxReasoningChars: number;\r\n maxPatternChars: number;\r\n}\r\n\r\n/** Starting values; to be tuned by measurement (QUIKTR-1458). */\r\nexport const DEFAULT_LIMITS: ToolLimits = {\r\n maxTurns: 12,\r\n maxToolCalls: 25,\r\n maxCallsPerTurn: 8,\r\n readCharsPerRead: 20_000,\r\n // The per-run read cap stops the COST; the per-turn ceiling below stops the FAILURE. Different jobs.\r\n readCharsTotal: 60_000,\r\n resultCharsTotal: 80_000,\r\n // 131,072 (the smallest 128k-class window) - 8,192 reserved output - a 3,741-token real request leaves\r\n // ~116,000; 90,000 keeps ~26,000 for a repository whose listing is thousands of paths, and stays well\r\n // clear of the per-minute quota, which binds before the window does. Set by the AI Runtime owner.\r\n maxRequestTokens: 90_000,\r\n grepMaxMatches: 40,\r\n grepLineChars: 200,\r\n grepFileBytes: 262_144,\r\n grepMaxFiles: 3_000,\r\n grepMaxBytes: 20_000_000,\r\n fileBytesMax: 1_000_000,\r\n listMaxEntries: 500,\r\n maxReasoningChars: 500,\r\n maxPatternChars: 200,\r\n};\r\n\r\nexport interface ToolFs {\r\n /** The real path of the checkout root. */\r\n rootReal: string;\r\n /** Throws if the file is gone. Never follows a symlink. */\r\n lstat(rel: string): { isSymlink: boolean; isFile: boolean; size: number };\r\n /** True when the file's real location (after following any links) is inside the checkout. */\r\n realpathInside(rel: string): boolean;\r\n readBytes(rel: string): Uint8Array;\r\n}\r\n\r\nexport function createNodeToolFs(rootDir: string = process.cwd()): ToolFs {\r\n const rootReal = realpathSync(rootDir);\r\n return {\r\n rootReal,\r\n lstat(rel) {\r\n const s = lstatSync(join(rootDir, rel));\r\n return { isSymlink: s.isSymbolicLink(), isFile: s.isFile(), size: s.size };\r\n },\r\n realpathInside(rel) {\r\n const real = realpathSync(join(rootDir, rel));\r\n const r = relative(rootReal, real);\r\n return r !== \"\" && !r.startsWith(\"..\") && !isAbsolute(r);\r\n },\r\n readBytes(rel) {\r\n return readFileSync(join(rootDir, rel));\r\n },\r\n };\r\n}\r\n\r\nexport interface ToolEnv {\r\n /** Every tracked file, exactly as `git ls-files` printed it (membership gate). */\r\n listing: ReadonlySet<string>;\r\n /** The listing with denied paths removed, sorted: the only thing the AI is ever told about. */\r\n visible: readonly string[];\r\n deniedPaths: string[];\r\n fs: ToolFs;\r\n limits: ToolLimits;\r\n /**\r\n * QUIKTR-1458 \u00A724 \u2014 tools beyond the three read-only ones (`edit_file`, `write_file`), supplied by the code-writing\r\n * loop. They go through exactly the same budget, duplicate and accounting path as a read; absent for targeting.\r\n */\r\n extraTools?: Readonly<Record<string, ExtraToolPreparer>>;\r\n}\r\n\r\nexport type ExtraToolPreparer = (args: Record<string, unknown>, env: ToolEnv, ledger: ToolLedger) => Prepared;\r\n\r\nexport interface ToolLedger {\r\n toolCalls: number;\r\n readChars: number;\r\n resultChars: number;\r\n refused: number;\r\n /** canonical call -> id of the first call that made it */\r\n seen: Map<string, string>;\r\n}\r\n\r\nexport function newLedger(): ToolLedger {\r\n return { toolCalls: 0, readChars: 0, resultChars: 0, refused: 0, seen: new Map() };\r\n}\r\n\r\n/** What was read, for the run's audit record. Paths only, never content. */\r\nexport interface ReadRecord {\r\n path: string;\r\n startLine?: number;\r\n endLine?: number;\r\n chars: number;\r\n refused?: true;\r\n}\r\n\r\nexport type Partial_ = Omit<ToolResult, \"id\" | \"name\">;\r\nexport type Executed = { result: Partial_; read?: ReadRecord };\r\nexport type Prepared =\r\n | { fail: Partial_; read?: ReadRecord }\r\n | { key: string; exec: () => Executed };\r\n\r\nconst INVALID_PATH = \"(invalid path)\";\r\nconst CUT = \"\u2026[line cut]\";\r\n\r\nfunction isPlainObject(x: unknown): x is Record<string, unknown> {\r\n return typeof x === \"object\" && x !== null && !Array.isArray(x);\r\n}\r\n\r\nfunction bad(message: string): { fail: Partial_ } {\r\n return { fail: { status: \"bad_args\", message } };\r\n}\r\n\r\nfunction optionalInt(v: unknown): number | undefined | \"bad\" {\r\n if (v === undefined || v === null) return undefined;\r\n return typeof v === \"number\" && Number.isInteger(v) ? v : \"bad\";\r\n}\r\n\r\nfunction hasNul(bytes: Uint8Array): boolean {\r\n const n = Math.min(bytes.length, 8000);\r\n for (let i = 0; i < n; i++) if (bytes[i] === 0) return true;\r\n return false;\r\n}\r\n\r\n/** Path gates shared by read_file: shape, then denied, then membership. No file is touched. */\r\nfunction gatePath(raw: unknown, env: ToolEnv): { ok: true; path: string } | { ok: false; fail: Partial_; path: string } {\r\n const n = normaliseToolPath(raw);\r\n if (!n.ok) {\r\n return { ok: false, path: INVALID_PATH, fail: { status: \"refused\", reason: n.reason, message: \"That path is not allowed.\" } };\r\n }\r\n // Denied BEFORE membership: a protected file and a made-up file inside a protected folder give the\r\n // same answer, so the answer cannot be used to find out what exists there.\r\n if (matchesDeniedPath(n.path, env.deniedPaths)) {\r\n return { ok: false, path: n.path, fail: { status: \"refused\", reason: \"denied\", message: \"That path is protected and cannot be read.\" } };\r\n }\r\n if (!env.listing.has(n.path)) {\r\n return { ok: false, path: n.path, fail: { status: \"not_found\", message: \"Not a tracked file. Use list_files to see the available paths.\" } };\r\n }\r\n return { ok: true, path: n.path };\r\n}\r\n\r\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 read_file \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\nfunction prepareReadFile(args: Record<string, unknown>, env: ToolEnv, ledger: ToolLedger): Prepared {\r\n const start = optionalInt(args.startLine);\r\n const end = optionalInt(args.endLine);\r\n if (start === \"bad\" || end === \"bad\") return bad(\"startLine and endLine must be whole numbers.\");\r\n if (start !== undefined && end !== undefined && end < start) return bad(\"endLine must not be before startLine.\");\r\n\r\n if (typeof args.path !== \"string\") return bad(\"path must be a string.\");\r\n const gate = gatePath(args.path, env);\r\n if (!gate.ok) {\r\n const read: ReadRecord | undefined = gate.fail.status === \"refused\" ? { path: gate.path, chars: 0, refused: true } : undefined;\r\n return { fail: gate.fail, ...(read ? { read } : {}) };\r\n }\r\n const path = gate.path;\r\n const key = JSON.stringify({ path, startLine: start ?? null, endLine: end ?? null });\r\n\r\n return {\r\n key,\r\n exec: () => {\r\n let size: number;\r\n try {\r\n const st = env.fs.lstat(path);\r\n if (st.isSymlink) {\r\n return { result: { status: \"refused\", reason: \"symlink\", message: \"Links are not followed.\" }, read: { path, chars: 0, refused: true } };\r\n }\r\n if (!st.isFile) return { result: { status: \"unreadable\", reason: \"not_a_file\", message: \"That entry is not a regular file.\" } };\r\n size = st.size;\r\n if (size > env.limits.fileBytesMax) {\r\n return { result: { status: \"unreadable\", reason: \"too_large\", message: \"That file is too large to read.\" } };\r\n }\r\n if (!env.fs.realpathInside(path)) {\r\n return { result: { status: \"refused\", reason: \"outside_workspace\", message: \"That path is not allowed.\" }, read: { path, chars: 0, refused: true } };\r\n }\r\n } catch {\r\n return { result: { status: \"unreadable\", reason: \"io\", message: \"That file could not be read.\" } };\r\n }\r\n\r\n let bytes: Uint8Array;\r\n try {\r\n bytes = env.fs.readBytes(path);\r\n } catch {\r\n return { result: { status: \"unreadable\", reason: \"io\", message: \"That file could not be read.\" } };\r\n }\r\n if (hasNul(bytes)) return { result: { status: \"unreadable\", reason: \"binary\", message: \"That file is binary.\" } };\r\n let text: string;\r\n try {\r\n text = new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\r\n } catch {\r\n return { result: { status: \"unreadable\", reason: \"not_utf8\", message: \"That file is not valid UTF-8 text.\" } };\r\n }\r\n if (text.charCodeAt(0) === 0xfeff) text = text.slice(1);\r\n text = text.replace(/\\r\\n/g, \"\\n\");\r\n\r\n const lines = text === \"\" ? [] : text.split(\"\\n\");\r\n if (lines.length > 0 && lines[lines.length - 1] === \"\") lines.pop();\r\n const totalLines = lines.length;\r\n\r\n const startLine = Math.max(1, start ?? 1);\r\n const endWanted = Math.min(totalLines, end ?? totalLines);\r\n if (startLine > totalLines) {\r\n return {\r\n result: { status: \"ok\", output: { path, startLine, endLine: totalLines, totalLines, truncated: false, content: \"\" } },\r\n read: { path, startLine, endLine: totalLines, chars: 0 },\r\n };\r\n }\r\n\r\n const budget = Math.max(0, Math.min(env.limits.readCharsPerRead, env.limits.readCharsTotal - ledger.readChars));\r\n const out: string[] = [];\r\n let used = 0;\r\n let endLine = startLine - 1;\r\n let truncated = false;\r\n for (let n = startLine; n <= endWanted; n++) {\r\n const line = `${n}\\t${lines[n - 1]}`;\r\n const cost = line.length + (out.length > 0 ? 1 : 0);\r\n if (used + cost <= budget) {\r\n out.push(line);\r\n used += cost;\r\n endLine = n;\r\n continue;\r\n }\r\n truncated = true;\r\n if (out.length === 0) {\r\n // One line on its own is bigger than the whole allowance: cut inside it.\r\n const keep = Math.max(0, budget - CUT.length);\r\n out.push(line.slice(0, keep) + CUT);\r\n used = out[0].length;\r\n endLine = n;\r\n }\r\n break;\r\n }\r\n\r\n let content = out.join(\"\\n\");\r\n ledger.readChars += used;\r\n const output: Record<string, unknown> = { path, startLine, endLine, totalLines, truncated };\r\n if (truncated) {\r\n if (endLine < totalLines) {\r\n output.nextStartLine = endLine + 1;\r\n content += `\\n[truncated: showing lines ${startLine}-${endLine} of ${totalLines}; call read_file with startLine=${endLine + 1}]`;\r\n } else {\r\n content += `\\n[truncated: line ${endLine} was cut]`;\r\n }\r\n }\r\n output.content = content;\r\n return { result: { status: \"ok\", output }, read: { path, startLine, endLine, chars: used } };\r\n },\r\n };\r\n}\r\n\r\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 list_files \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\nfunction prepareListFiles(args: Record<string, unknown>, env: ToolEnv): Prepared {\r\n const max = optionalInt(args.maxEntries);\r\n if (max === \"bad\" || (max !== undefined && max < 1)) return bad(\"maxEntries must be a whole number of at least 1.\");\r\n if (args.prefix !== undefined && args.prefix !== null && typeof args.prefix !== \"string\") return bad(\"prefix must be a string.\");\r\n const n = normaliseToolPath(args.prefix, { allowRoot: true });\r\n if (!n.ok) return { fail: { status: \"refused\", reason: n.reason, message: \"That path is not allowed.\" } };\r\n const prefix = n.path;\r\n const cap = Math.min(max ?? env.limits.listMaxEntries, env.limits.listMaxEntries);\r\n\r\n return {\r\n key: JSON.stringify({ prefix, maxEntries: cap }),\r\n exec: () => {\r\n const matching = env.visible.filter((p) => matchesPrefix(p, prefix));\r\n const entries = matching.slice(0, cap);\r\n const truncated = matching.length > cap;\r\n const output: Record<string, unknown> = { entries, total: matching.length, truncated };\r\n if (truncated) {\r\n const counts = new Map<string, number>();\r\n for (const p of matching) {\r\n const rest = prefix === \"\" ? p : p.slice(prefix.length + 1);\r\n const slash = rest.indexOf(\"/\");\r\n if (slash > 0) counts.set(rest.slice(0, slash), (counts.get(rest.slice(0, slash)) ?? 0) + 1);\r\n }\r\n output.subdirs = [...counts.entries()]\r\n .map(([name, count]) => ({ name, count }))\r\n .sort((a, b) => b.count - a.count || (a.name < b.name ? -1 : 1))\r\n .slice(0, 50);\r\n }\r\n return { result: { status: \"ok\", output } };\r\n },\r\n };\r\n}\r\n\r\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 grep \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\nconst WORD_CHAR = /[A-Za-z0-9_$]/;\r\n\r\nfunction lineMatches(line: string, needle: string, ignoreCase: boolean, wholeWord: boolean): number {\r\n const hay = ignoreCase ? line.toLowerCase() : line;\r\n let from = 0;\r\n for (;;) {\r\n const i = hay.indexOf(needle, from);\r\n if (i === -1) return -1;\r\n if (!wholeWord) return i;\r\n const before = i > 0 ? hay[i - 1] : \"\";\r\n const after = i + needle.length < hay.length ? hay[i + needle.length] : \"\";\r\n if (!(before && WORD_CHAR.test(before)) && !(after && WORD_CHAR.test(after))) return i;\r\n from = i + 1;\r\n }\r\n}\r\n\r\n/** Trim a matching line and, when it is long, show the stretch around the match. */\r\nfunction excerpt(line: string, at: number, max: number): string {\r\n const t = line.trim();\r\n if (t.length <= max) return t;\r\n const lead = line.length - line.trimStart().length;\r\n const pos = Math.max(0, at - lead);\r\n const from = Math.max(0, Math.min(pos - 40, t.length - max));\r\n const piece = t.slice(from, from + max);\r\n return `${from > 0 ? \"\u2026\" : \"\"}${piece}${from + max < t.length ? \"\u2026\" : \"\"}`;\r\n}\r\n\r\nfunction prepareGrep(args: Record<string, unknown>, env: ToolEnv): Prepared {\r\n const pattern = args.pattern;\r\n if (typeof pattern !== \"string\" || pattern.length === 0 || pattern.length > env.limits.maxPatternChars) {\r\n return bad(\"pattern must be a non-empty string within the length limit.\");\r\n }\r\n if (/[\\u0000\\r\\n]/.test(pattern)) return bad(\"pattern must be a single line of plain text.\");\r\n for (const flag of [\"ignoreCase\", \"wholeWord\"] as const) {\r\n if (args[flag] !== undefined && typeof args[flag] !== \"boolean\") return bad(`${flag} must be true or false.`);\r\n }\r\n const maxIn = optionalInt(args.maxResults);\r\n if (maxIn === \"bad\" || (maxIn !== undefined && maxIn < 1)) return bad(\"maxResults must be a whole number of at least 1.\");\r\n if (args.pathPrefix !== undefined && args.pathPrefix !== null && typeof args.pathPrefix !== \"string\") return bad(\"pathPrefix must be a string.\");\r\n const n = normaliseToolPath(args.pathPrefix, { allowRoot: true });\r\n if (!n.ok) return { fail: { status: \"refused\", reason: n.reason, message: \"That path is not allowed.\" } };\r\n\r\n const prefix = n.path;\r\n const ignoreCase = args.ignoreCase === true;\r\n const wholeWord = args.wholeWord === true;\r\n const maxMatches = Math.min(maxIn ?? env.limits.grepMaxMatches, env.limits.grepMaxMatches);\r\n const needle = ignoreCase ? pattern.toLowerCase() : pattern;\r\n\r\n return {\r\n key: JSON.stringify({ pattern, pathPrefix: prefix, maxResults: maxMatches, ignoreCase, wholeWord }),\r\n exec: () => {\r\n const matches: { path: string; line: number; text: string }[] = [];\r\n const skipped = { large: 0, binary: 0 };\r\n let filesScanned = 0;\r\n let bytesScanned = 0;\r\n let scanCapped = false;\r\n let truncated = false;\r\n\r\n scan: for (const path of env.visible) {\r\n if (!matchesPrefix(path, prefix)) continue;\r\n if (filesScanned >= env.limits.grepMaxFiles || bytesScanned >= env.limits.grepMaxBytes) {\r\n scanCapped = true;\r\n break;\r\n }\r\n filesScanned += 1;\r\n let bytes: Uint8Array;\r\n try {\r\n const st = env.fs.lstat(path);\r\n if (st.isSymlink || !st.isFile) continue;\r\n if (st.size > env.limits.grepFileBytes) {\r\n skipped.large += 1;\r\n continue;\r\n }\r\n if (!env.fs.realpathInside(path)) continue;\r\n bytes = env.fs.readBytes(path);\r\n } catch {\r\n continue;\r\n }\r\n bytesScanned += bytes.length;\r\n if (hasNul(bytes)) {\r\n skipped.binary += 1;\r\n continue;\r\n }\r\n const lines = new TextDecoder(\"utf-8\").decode(bytes).replace(/\\r\\n/g, \"\\n\").split(\"\\n\");\r\n for (let i = 0; i < lines.length; i++) {\r\n const at = lineMatches(lines[i], needle, ignoreCase, wholeWord);\r\n if (at === -1) continue;\r\n if (matches.length >= maxMatches) {\r\n truncated = true;\r\n break scan;\r\n }\r\n matches.push({ path, line: i + 1, text: excerpt(lines[i], at, env.limits.grepLineChars) });\r\n }\r\n }\r\n\r\n const output: Record<string, unknown> = { matches, truncated, filesScanned, skipped };\r\n if (scanCapped) output.scanCapped = true;\r\n return { result: { status: \"ok\", output } };\r\n },\r\n };\r\n}\r\n\r\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 the entry point \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\nfunction budgetResult(reason: string): Partial_ {\r\n return { status: \"budget_exhausted\", reason, message: \"That limit has been reached; give your answer from what you have.\" };\r\n}\r\n\r\n/**\r\n * Run one tool call. Never throws for a tool-level problem: every outcome is a result the AI is told\r\n * about. Every call counts toward the total (refused, invalid and repeated ones too, so probing is\r\n * bounded), except one turned away because the budget is already gone.\r\n */\r\nexport function executeToolCall(call: ToolCall, env: ToolEnv, ledger: ToolLedger): { result: ToolResult; read?: ReadRecord } {\r\n const wrap = (r: Partial_): ToolResult => ({ id: call.id, name: call.name, ...r });\r\n const finish = (r: Partial_, read?: ReadRecord) => {\r\n const result = wrap(r);\r\n ledger.resultChars += JSON.stringify(result).length;\r\n if (result.status === \"refused\") ledger.refused += 1;\r\n return read ? { result, read } : { result };\r\n };\r\n\r\n if (ledger.toolCalls >= env.limits.maxToolCalls) return finish(budgetResult(\"tool_calls\"));\r\n if (ledger.resultChars >= env.limits.resultCharsTotal) return finish(budgetResult(\"result_chars\"));\r\n if (call.name === \"read_file\" && ledger.readChars >= env.limits.readCharsTotal) return finish(budgetResult(\"read_chars\"));\r\n\r\n ledger.toolCalls += 1;\r\n\r\n let prepared: Prepared;\r\n try {\r\n const extra = env.extraTools && Object.prototype.hasOwnProperty.call(env.extraTools, call.name) ? env.extraTools[call.name] : undefined;\r\n if (call.name !== \"read_file\" && call.name !== \"list_files\" && call.name !== \"grep\" && !extra) {\r\n return finish({ status: \"unknown_tool\", message: \"Unknown tool. Use list_files, read_file or grep.\" });\r\n }\r\n if (!isPlainObject(call.args)) return finish({ status: \"bad_args\", message: \"Arguments must be an object.\" });\r\n prepared = extra\r\n ? extra(call.args, env, ledger)\r\n : call.name === \"read_file\"\r\n ? prepareReadFile(call.args, env, ledger)\r\n : call.name === \"list_files\"\r\n ? prepareListFiles(call.args, env)\r\n : prepareGrep(call.args, env);\r\n } catch {\r\n return finish({ status: \"bad_args\", message: \"Those arguments could not be used.\" });\r\n }\r\n\r\n if (\"fail\" in prepared) return finish(prepared.fail, prepared.read);\r\n\r\n const dupKey = `${call.name}:${prepared.key}`;\r\n const earlier = ledger.seen.get(dupKey);\r\n if (earlier !== undefined) {\r\n return finish({ status: \"duplicate\", reason: earlier, message: \"Identical call already made; see its result.\" });\r\n }\r\n ledger.seen.set(dupKey, call.id);\r\n\r\n let executed: Executed;\r\n try {\r\n executed = prepared.exec();\r\n } catch {\r\n executed = { result: { status: \"unreadable\", reason: \"io\", message: \"That could not be read.\" } };\r\n }\r\n return finish(executed.result, executed.read);\r\n}\r\n", "import { lstatSync, realpathSync } from \"node:fs\";\r\nimport { dirname, isAbsolute, join, relative } from \"node:path\";\r\nimport { detectLineEnding, fromLf, toLf, type LineEnding } from \"./editsApply\";\r\nimport { createNodeToolFs, type Partial_, type ToolFs } from \"./targetingTools\";\r\n\r\n/**\r\n * QUIKTR-1458 \u00A724 \u2014 where the code-writing loop keeps its changes.\r\n *\r\n * Nothing the AI edits or creates touches the checkout. Every change lives here, in memory, on top of the files on disk, and\r\n * the AI sees its own work when it reads or searches (`createOverlayFs`). When the loop ends the overlay becomes the same\r\n * `{targetPath, newContent}` list the per-file path produces, so every check after codegen is unchanged \u2014 and a loop that fails\r\n * is thrown away without a trace, which is what lets the run fall back to the per-file path.\r\n *\r\n * Text is held with LF endings and no BOM, exactly as `read_file` shows it, because that is what the AI copies its anchors\r\n * from. The file's own convention (CRLF, BOM) is remembered and put back when the result is produced.\r\n */\r\n\r\n/** A file system the code-writing loop can use: the read-only one plus the two questions a write has to ask. */\r\nexport interface WriteFs extends ToolFs {\r\n /** True when the nearest existing ancestor directory of `rel` really lies inside the checkout (no link leads out). */\r\n parentInside(rel: string): boolean;\r\n /** True when anything exists at `rel` (a file, a link, a directory), tracked or not. */\r\n exists(rel: string): boolean;\r\n}\r\n\r\nexport function createNodeWriteFs(rootDir: string = process.cwd()): WriteFs {\r\n const base = createNodeToolFs(rootDir);\r\n const inside = (real: string): boolean => {\r\n const r = relative(base.rootReal, real);\r\n return !r.startsWith(\"..\") && !isAbsolute(r);\r\n };\r\n return {\r\n ...base,\r\n parentInside(rel) {\r\n let dir = dirname(join(rootDir, rel));\r\n for (;;) {\r\n try {\r\n return inside(realpathSync(dir));\r\n } catch {\r\n const up = dirname(dir);\r\n if (up === dir) return false;\r\n dir = up;\r\n }\r\n }\r\n },\r\n exists(rel) {\r\n try {\r\n lstatSync(join(rootDir, rel));\r\n return true;\r\n } catch {\r\n return false;\r\n }\r\n },\r\n };\r\n}\r\n\r\nexport interface OverlayEntry {\r\n /** What the AI sees and edits: LF, no BOM. */\r\n lf: string;\r\n ending: LineEnding;\r\n bom: boolean;\r\n /** True for a file the loop created; false for an existing file it edited. */\r\n created: boolean;\r\n /** The file as it was on disk (LF, no BOM) before the first edit; null for a created file. */\r\n originalLf: string | null;\r\n}\r\n\r\nexport class WorkspaceOverlay {\r\n private readonly entries = new Map<string, OverlayEntry>();\r\n\r\n get(path: string): OverlayEntry | undefined {\r\n return this.entries.get(path);\r\n }\r\n\r\n has(path: string): boolean {\r\n return this.entries.has(path);\r\n }\r\n\r\n isCreated(path: string): boolean {\r\n return this.entries.get(path)?.created === true;\r\n }\r\n\r\n /** Record new text for an existing file. The first call remembers the original; later calls only replace the text. */\r\n setEdited(path: string, lf: string, base: { ending: LineEnding; bom: boolean; originalLf: string }): void {\r\n const current = this.entries.get(path);\r\n if (current) {\r\n current.lf = lf;\r\n return;\r\n }\r\n this.entries.set(path, { lf, ending: base.ending, bom: base.bom, created: false, originalLf: base.originalLf });\r\n }\r\n\r\n /** Create a file, or replace one the loop itself created earlier. */\r\n setCreated(path: string, lf: string): void {\r\n this.entries.set(path, { lf, ending: \"LF\", bom: false, created: true, originalLf: null });\r\n }\r\n\r\n /** Paths whose final text differs from what is on disk, in the order they were first touched. */\r\n changedPaths(): string[] {\r\n return [...this.entries.entries()].filter(([, e]) => e.created || e.lf !== e.originalLf).map(([p]) => p);\r\n }\r\n\r\n /** The full text of an entry as it would be written to disk. */\r\n fullText(path: string): string | undefined {\r\n const e = this.entries.get(path);\r\n return e ? `${e.bom ? \"\uFEFF\" : \"\"}${fromLf(e.lf, e.ending)}` : undefined;\r\n }\r\n\r\n results(): { targetPath: string; newContent: string }[] {\r\n return this.changedPaths().map((path) => ({ targetPath: path, newContent: this.fullText(path) as string }));\r\n }\r\n}\r\n\r\n/** Reads and writes through the overlay first, the real checkout second. */\r\nexport function createOverlayFs(base: WriteFs, overlay: WorkspaceOverlay): WriteFs {\r\n const encode = (path: string): Uint8Array => new TextEncoder().encode(overlay.fullText(path) as string);\r\n return {\r\n rootReal: base.rootReal,\r\n lstat(rel) {\r\n if (overlay.has(rel)) return { isSymlink: false, isFile: true, size: encode(rel).length };\r\n return base.lstat(rel);\r\n },\r\n realpathInside(rel) {\r\n if (overlay.isCreated(rel)) return base.parentInside(rel);\r\n return base.realpathInside(rel);\r\n },\r\n readBytes(rel) {\r\n return overlay.has(rel) ? encode(rel) : base.readBytes(rel);\r\n },\r\n parentInside: (rel) => base.parentInside(rel),\r\n exists: (rel) => overlay.has(rel) || base.exists(rel),\r\n };\r\n}\r\n\r\nexport type LoadedText =\r\n | { ok: true; lf: string; ending: LineEnding; bom: boolean }\r\n | { ok: false; result: Partial_ };\r\n\r\nfunction hasNul(bytes: Uint8Array): boolean {\r\n const n = Math.min(bytes.length, 8000);\r\n for (let i = 0; i < n; i++) if (bytes[i] === 0) return true;\r\n return false;\r\n}\r\n\r\n/**\r\n * Load a file for editing, with the same refusals `read_file` has (a link, a binary or non-UTF-8 file, one too large, one that\r\n * leads outside the checkout) plus one more: a file with MIXED line endings cannot be written back faithfully, so it is not\r\n * edited at all. Never throws; every outcome is a result the AI is told about, with fixed text.\r\n */\r\nexport function loadTextForEdit(fs: ToolFs, path: string, maxBytes: number): LoadedText {\r\n let bytes: Uint8Array;\r\n try {\r\n const st = fs.lstat(path);\r\n if (st.isSymlink) return { ok: false, result: { status: \"refused\", reason: \"symlink\", message: \"Links are not followed.\" } };\r\n if (!st.isFile) return { ok: false, result: { status: \"unreadable\", reason: \"not_a_file\", message: \"That entry is not a regular file.\" } };\r\n if (st.size > maxBytes) return { ok: false, result: { status: \"too_large\", reason: \"too_large\", message: \"That file is too large to edit.\" } };\r\n if (!fs.realpathInside(path)) {\r\n return { ok: false, result: { status: \"refused\", reason: \"outside_workspace\", message: \"That path is not allowed.\" } };\r\n }\r\n bytes = fs.readBytes(path);\r\n } catch {\r\n return { ok: false, result: { status: \"unreadable\", reason: \"io\", message: \"That file could not be read.\" } };\r\n }\r\n if (hasNul(bytes)) return { ok: false, result: { status: \"unreadable\", reason: \"binary\", message: \"That file is binary.\" } };\r\n let text: string;\r\n try {\r\n text = new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\r\n } catch {\r\n return { ok: false, result: { status: \"unreadable\", reason: \"not_utf8\", message: \"That file is not valid UTF-8 text.\" } };\r\n }\r\n // The decoder drops a leading BOM without saying so, so it is read from the bytes: a file that had one must get it back.\r\n const bom = bytes.length >= 3 && bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf;\r\n if (text.charCodeAt(0) === 0xfeff) text = text.slice(1);\r\n const ending = detectLineEnding(text);\r\n if (ending === \"mixed\") {\r\n return {\r\n ok: false,\r\n result: { status: \"refused\", reason: \"mixed_line_endings\", message: \"That file mixes line endings and cannot be edited faithfully.\" },\r\n };\r\n }\r\n return { ok: true, lf: toLf(text), ending, bom };\r\n}\r\n", "import { isAddOnly } from \"./addOnly\";\r\nimport { matchesDeniedPath } from \"./deniedPaths\";\r\nimport { applyEdits, toLf, type LineEnding } from \"./editsApply\";\r\nimport { normaliseToolPath, buildVisibleListing } from \"./targetingPaths\";\r\nimport {\r\n DEFAULT_LIMITS,\r\n newLedger,\r\n type ExtraToolPreparer,\r\n type Partial_,\r\n type Prepared,\r\n type ToolEnv,\r\n type ToolLedger,\r\n type ToolLimits,\r\n} from \"./targetingTools\";\r\nimport { createNodeWriteFs, createOverlayFs, loadTextForEdit, WorkspaceOverlay, type WriteFs } from \"./workspaceOverlay\";\r\n\r\n/**\r\n * QUIKTR-1458 \u00A724 \u2014 the two WRITE tools of the code-writing loop, `edit_file` and `write_file`, and the workspace they act on.\r\n *\r\n * Nothing here writes to the checkout. Both tools change the in-memory overlay (`workspaceOverlay.ts`), and every change goes\r\n * through one funnel of rules, in this order, each one a plain RESULT the AI can act on rather than an exception:\r\n * 1. the path is a well-formed, in-workspace path (`normaliseToolPath`: no `..`, no absolute path, no control characters);\r\n * 2. it is not a protected (denied) path \u2014 BEFORE anything about the file is looked at, so the answer cannot be used to find\r\n * out what exists there;\r\n * 3. `edit_file` names a file git tracks or one this run created; `write_file` names a file that does NOT exist yet;\r\n * 4. `write_file` cannot reach outside the checkout through a link in a parent directory, or put a file where a file or a\r\n * folder already is;\r\n * 5. an existing TEST file is only ever added to: the replacement must start or end with the anchor, so what is there is\r\n * never weakened (doc 62 \u00A74: \"a test is NEVER edited to make generated code pass\");\r\n * 6. the anchor matches exactly once in the file as the AI last saw it (`applyEdits`);\r\n * 7. the run's budget for written characters.\r\n *\r\n * Results never echo what the AI sent or what a file contained.\r\n */\r\n\r\nexport interface CodegenLimits extends ToolLimits {\r\n /** Characters the AI may write in all (every `replace` and every `content`). */\r\n writeCharsTotal: number;\r\n findChars: number;\r\n replaceChars: number;\r\n contentChars: number;\r\n}\r\n\r\n/** Starting values; to be tuned by measurement (\u00A724.14). */\r\nexport const CODEGEN_LIMITS: CodegenLimits = {\r\n ...DEFAULT_LIMITS,\r\n maxTurns: 20,\r\n maxToolCalls: 40,\r\n writeCharsTotal: 120_000,\r\n findChars: 8_000,\r\n replaceChars: 20_000,\r\n contentChars: 200_000,\r\n};\r\n\r\nexport interface CodegenLedger extends ToolLedger {\r\n writeChars: number;\r\n}\r\n\r\nexport function newCodegenLedger(): CodegenLedger {\r\n return { ...newLedger(), writeChars: 0 };\r\n}\r\n\r\nexport interface CodegenWorkspace {\r\n env: ToolEnv;\r\n ledger: CodegenLedger;\r\n overlay: WorkspaceOverlay;\r\n limits: CodegenLimits;\r\n /** Successful edits per path, for the run's audit record. Paths and counts only. */\r\n edits: Map<string, number>;\r\n /** Files created, with their size. */\r\n created: Map<string, number>;\r\n}\r\n\r\nexport interface CodegenWorkspaceArgs {\r\n /** Every tracked file, as `git ls-files` printed it. */\r\n listing: string[];\r\n deniedPaths: string[];\r\n /** Existing test files: they accept only additions (rule 5). */\r\n protectedTestPaths: string[];\r\n fs?: WriteFs;\r\n limits?: Partial<CodegenLimits>;\r\n}\r\n\r\nfunction bad(message: string): { fail: Partial_ } {\r\n return { fail: { status: \"bad_args\", message } };\r\n}\r\n\r\nfunction refused(reason: string, message: string): { fail: Partial_ } {\r\n return { fail: { status: \"refused\", reason, message } };\r\n}\r\n\r\nfunction countLines(text: string): number {\r\n if (text === \"\") return 0;\r\n const n = text.split(\"\\n\").length;\r\n return text.endsWith(\"\\n\") ? n - 1 : n;\r\n}\r\n\r\nexport function createCodegenWorkspace(args: CodegenWorkspaceArgs): CodegenWorkspace {\r\n const limits: CodegenLimits = { ...CODEGEN_LIMITS, ...args.limits };\r\n const baseFs = args.fs ?? createNodeWriteFs();\r\n const overlay = new WorkspaceOverlay();\r\n const listing = new Set(args.listing);\r\n const visible = buildVisibleListing(args.listing, args.deniedPaths);\r\n const protectedTests = new Set(args.protectedTestPaths);\r\n const edits = new Map<string, number>();\r\n const created = new Map<string, number>();\r\n\r\n const noteCreated = (path: string): void => {\r\n listing.add(path);\r\n if (!visible.includes(path)) {\r\n visible.push(path);\r\n visible.sort();\r\n }\r\n };\r\n\r\n // A change makes any earlier read, search or listing stale: forget them so the AI can look again without being told \"duplicate\".\r\n const forgetReads = (ledger: ToolLedger): void => {\r\n for (const key of [...ledger.seen.keys()]) {\r\n if (key.startsWith(\"read_file:\") || key.startsWith(\"grep:\") || key.startsWith(\"list_files:\")) ledger.seen.delete(key);\r\n }\r\n };\r\n\r\n const gate = (raw: unknown, deniedPaths: string[]): { ok: true; path: string } | { ok: false; fail: Partial_ } => {\r\n const n = normaliseToolPath(raw);\r\n if (!n.ok) return { ok: false, fail: { status: \"refused\", reason: n.reason, message: \"That path is not allowed.\" } };\r\n if (matchesDeniedPath(n.path, deniedPaths)) {\r\n return { ok: false, fail: { status: \"refused\", reason: \"denied\", message: \"That path is protected and cannot be changed.\" } };\r\n }\r\n return { ok: true, path: n.path };\r\n };\r\n\r\n const prepareEdit: ExtraToolPreparer = (a, env, ledger): Prepared => {\r\n if (typeof a.path !== \"string\") return bad(\"path must be a string.\");\r\n if (typeof a.find !== \"string\" || a.find.length === 0 || a.find.length > limits.findChars) {\r\n return bad(\"find must be a non-empty string within the length limit.\");\r\n }\r\n if (typeof a.replace !== \"string\" || a.replace.length > limits.replaceChars) return bad(\"replace must be a string within the length limit.\");\r\n const g = gate(a.path, env.deniedPaths);\r\n if (!g.ok) return { fail: g.fail };\r\n const path = g.path;\r\n if (!env.listing.has(path)) {\r\n return { fail: { status: \"not_found\", message: \"Not a tracked file. Use edit_file on an existing file, or write_file for a new one.\" } };\r\n }\r\n const find = a.find;\r\n const replace = a.replace;\r\n return {\r\n key: JSON.stringify({ path, find, replace }),\r\n exec: () => {\r\n const cl = ledger as CodegenLedger;\r\n if (cl.writeChars + replace.length > limits.writeCharsTotal) {\r\n return { result: { status: \"budget_exhausted\", reason: \"write_chars\", message: \"The limit on text written has been reached; finish with what you have.\" } };\r\n }\r\n const entry = overlay.get(path);\r\n let lf: string;\r\n let base: { ending: LineEnding; bom: boolean; originalLf: string };\r\n if (entry) {\r\n lf = entry.lf;\r\n base = { ending: entry.ending, bom: entry.bom, originalLf: entry.originalLf ?? entry.lf };\r\n } else {\r\n const loaded = loadTextForEdit(baseFs, path, limits.fileBytesMax);\r\n if (!loaded.ok) return { result: loaded.result };\r\n lf = loaded.lf;\r\n base = { ending: loaded.ending, bom: loaded.bom, originalLf: loaded.lf };\r\n }\r\n // A file that existed before this run and holds tests may be added to, never changed (`isAddOnly`: one block of whole new\r\n // lines, a new test, before the matched text, after it or between two of its lines). `protected` is an ordinary answer: the\r\n // AI reads the message and sends the edit again, so one misplaced edit never ends the run.\r\n if (protectedTests.has(path) && !isAddOnly(path, find, replace)) {\r\n return {\r\n result: {\r\n status: \"protected\",\r\n reason: \"existing_test\",\r\n message:\r\n \"An existing test can only be added to. Keep every character of the text you matched, in the same order, and add only whole new lines that declare a new test (it, test or describe), before the text, after it, or between two of its lines. To add a test to a block, match the last lines of that block and put the new test after them.\",\r\n },\r\n };\r\n }\r\n const applied = applyEdits(lf, [{ find, replace }]);\r\n if (!applied.ok) {\r\n const refusal = applied.refusals[0];\r\n if (refusal?.kind === \"no_match\") {\r\n return { result: { status: \"no_match\", message: \"That text was not found in the file. Read it again and copy it exactly.\" } };\r\n }\r\n if (refusal?.kind === \"ambiguous\") {\r\n const n = refusal.matchCount ?? 0;\r\n return { result: { status: \"ambiguous\", message: `That text matches ${n} places. Include more surrounding text so it matches exactly once.` } };\r\n }\r\n return { result: { status: \"bad_args\", message: \"That edit could not be applied.\" } };\r\n }\r\n overlay.setEdited(path, applied.content, base);\r\n cl.writeChars += replace.length;\r\n edits.set(path, (edits.get(path) ?? 0) + 1);\r\n forgetReads(ledger);\r\n return { result: { status: \"ok\", output: { path, replaced: 1, totalLines: countLines(applied.content) } } };\r\n },\r\n };\r\n };\r\n\r\n const prepareWrite: ExtraToolPreparer = (a, env, ledger): Prepared => {\r\n if (typeof a.path !== \"string\") return bad(\"path must be a string.\");\r\n if (typeof a.content !== \"string\") return bad(\"content must be a string.\");\r\n const g = gate(a.path, env.deniedPaths);\r\n if (!g.ok) return { fail: g.fail };\r\n const path = g.path;\r\n if (a.content.length > limits.contentChars) return { fail: { status: \"too_large\", message: \"That file is too large to write.\" } };\r\n const own = overlay.isCreated(path);\r\n if (!own && (env.listing.has(path) || baseFs.exists(path))) {\r\n return { fail: { status: \"exists\", message: \"That file already exists. Use edit_file to change it.\" } };\r\n }\r\n // A new file cannot sit inside a file, or on top of a folder.\r\n const parts = path.split(\"/\");\r\n for (let i = 1; i < parts.length; i++) {\r\n if (env.listing.has(parts.slice(0, i).join(\"/\"))) return refused(\"parent_is_file\", \"That path is not allowed.\");\r\n }\r\n if (env.visible.some((p) => p.startsWith(`${path}/`))) return refused(\"is_directory\", \"That path is not allowed.\");\r\n if (!baseFs.parentInside(path)) return refused(\"outside_workspace\", \"That path is not allowed.\");\r\n const content = a.content;\r\n return {\r\n key: JSON.stringify({ path, content }),\r\n exec: () => {\r\n const cl = ledger as CodegenLedger;\r\n if (cl.writeChars + content.length > limits.writeCharsTotal) {\r\n return { result: { status: \"budget_exhausted\", reason: \"write_chars\", message: \"The limit on text written has been reached; finish with what you have.\" } };\r\n }\r\n const lf = toLf(content);\r\n overlay.setCreated(path, lf);\r\n noteCreated(path);\r\n cl.writeChars += content.length;\r\n created.set(path, content.length);\r\n forgetReads(ledger);\r\n return { result: { status: \"ok\", output: { path, totalLines: countLines(lf), chars: content.length } } };\r\n },\r\n };\r\n };\r\n\r\n const env: ToolEnv = {\r\n listing,\r\n visible,\r\n deniedPaths: args.deniedPaths,\r\n fs: createOverlayFs(baseFs, overlay),\r\n limits,\r\n extraTools: { edit_file: prepareEdit, write_file: prepareWrite },\r\n };\r\n return { env, ledger: newCodegenLedger(), overlay, limits, edits, created };\r\n}\r\n", "/**\r\n * Error types shared by `targeting.ts` and the read-only targeting loop (QUIKTR-1458). They live in\r\n * a module of their own so the loop can recognise them without importing `targeting.ts`, which\r\n * imports the loop.\r\n */\r\n\r\n/**\r\n * A proposed target, or a cited context file, that matches a denied path. A class of its own so the\r\n * read-only loop can tell \"the AI asked for something we never allow\" - which must never be retried\r\n * by falling back - from \"the AI's answer was merely invalid\". The message text is exactly what it\r\n * was before, so nothing that read it changes.\r\n */\r\nexport class DeniedPathError extends Error {\r\n constructor(message: string) {\r\n super(message);\r\n this.name = \"DeniedPathError\";\r\n }\r\n}\r\n\r\n/** The call itself came back non-2xx (after retryFetch's own retries). Same message as ever. */\r\nexport class TargetingHttpError extends Error {\r\n readonly status: number;\r\n constructor(status: number, statusText: string) {\r\n super(`Targeting call failed: ${status} ${statusText}`);\r\n this.name = \"TargetingHttpError\";\r\n this.status = status;\r\n }\r\n}\r\n", "/**\r\n * QUIKTR-1458 \u2014 an estimate of what a request costs in TOKENS (contract section 23.5).\r\n *\r\n * The per-turn ceiling is in tokens and has to be counted the way the provider counts them. A character\r\n * budget is wrong, and so is chars / 4: measured against Gemini's own `count_tokens`, chars / 4\r\n * undercounts a path listing at 0.5x-0.9x and non-ASCII text at 0.5x-0.8x, so a repository with a long\r\n * listing or non-ASCII paths and comments would blow the cap while appearing inside it.\r\n *\r\n * So: a per-character-CLASS estimate. The weights were fitted against `count_tokens` on 14 real samples\r\n * (gemini-2.5-flash, 6 Oct 2026: real repository path listings of 40 to 3,000 paths, TypeScript plain and\r\n * wrapped in the JSON a tool result travels in, non-ASCII comments and paths), then rounded UP. Every\r\n * sample came out 1.14x to 1.50x ABOVE the real count; none under. Over-counting is the safe direction \u2014\r\n * the loop stops sooner and a run falls back to today's single call \u2014 so do not tidy these toward the\r\n * fitted values (0.26 / 0.16 / 0 / 0.92 / 0.66) without re-measuring.\r\n *\r\n * The AI Runtime carries the SAME estimator (`pilot_targeting_loop.estimate_tokens`) and both are pinned\r\n * to the same reference values. Class counts are integers and the weights are applied in one fixed order,\r\n * so the two agree to the token. A change to either is a change to both.\r\n */\r\n\r\nexport const TOKENS_PER_ALPHA_CHAR = 0.3;\r\nexport const TOKENS_PER_DIGIT_CHAR = 0.18;\r\nexport const TOKENS_PER_SPACE_CHAR = 0.05;\r\nexport const TOKENS_PER_PUNCTUATION_CHAR = 1.05;\r\nexport const TOKENS_PER_NON_ASCII_CHAR = 1.0;\r\n\r\n/**\r\n * What a request costs beyond the JSON `contextData` it carries: the system prompt, the loop\r\n * instruction, the response schema and the user turn. Measured at roughly 3,300 to 3,600 tokens, then\r\n * rounded up.\r\n */\r\nexport const PROMPT_OVERHEAD_TOKENS = 5_000;\r\n\r\n/** A deliberately high estimate of what `text` costs in tokens. Counts code points, not UTF-16 units. */\r\nexport function estimateTokens(text: string): number {\r\n let alpha = 0;\r\n let digit = 0;\r\n let space = 0;\r\n let punct = 0;\r\n let nonAscii = 0;\r\n for (const ch of text) {\r\n const code = ch.codePointAt(0)!;\r\n if (code >= 128) nonAscii++;\r\n else if ((code >= 65 && code <= 90) || (code >= 97 && code <= 122)) alpha++;\r\n else if (code >= 48 && code <= 57) digit++;\r\n else if (code === 32 || code === 9 || code === 13 || code === 10) space++;\r\n else punct++;\r\n }\r\n return Math.ceil(\r\n alpha * TOKENS_PER_ALPHA_CHAR +\r\n digit * TOKENS_PER_DIGIT_CHAR +\r\n space * TOKENS_PER_SPACE_CHAR +\r\n punct * TOKENS_PER_PUNCTUATION_CHAR +\r\n nonAscii * TOKENS_PER_NON_ASCII_CHAR,\r\n );\r\n}\r\n\r\n/**\r\n * The estimated size of the model request one loop turn becomes: the prompt overhead plus the context as\r\n * the runtime renders it (indent 2, non-ASCII kept \u2014 never escaped, which would turn every non-ASCII\r\n * character into six ASCII ones and flatter the count).\r\n */\r\nexport function estimateRequestTokens(contextData: unknown): number {\r\n return PROMPT_OVERHEAD_TOKENS + estimateTokens(JSON.stringify(contextData ?? {}, null, 2));\r\n}\r\n", "import { checkHardFailure, unwrapExecute } from \"./envelope\";\r\nimport { RuntimeReplyError } from \"./runtimeReplyError\";\r\nimport { TargetingHttpError } from \"./targetingErrors\";\r\nimport { buildVisibleListing } from \"./targetingPaths\";\r\nimport {\r\n DEFAULT_LIMITS,\r\n createNodeToolFs,\r\n executeToolCall,\r\n newLedger,\r\n type ReadRecord,\r\n type ToolEnv,\r\n type ToolFs,\r\n type ToolLimits,\r\n type ToolResult,\r\n} from \"./targetingTools\";\r\nimport { estimateRequestTokens } from \"./tokenEstimate\";\r\n\r\n/**\r\n * QUIKTR-1458 \u2014 the read-only targeting loop.\r\n *\r\n * Instead of one call answered from the file listing alone, the runner and the AI Runtime talk in\r\n * turns. Each turn the runner POSTs to the same `/ai/execute`, carrying everything said so far (the\r\n * runtime keeps no state); the runtime answers either \"run these read-only tools\" or the final\r\n * targeting answer, in exactly the shape the single call returns. The runner runs the tools locally,\r\n * on the checkout, and sends the results with the next turn.\r\n *\r\n * The loop is built so it cannot run away and cannot go quiet:\r\n * - it ends with a final answer or a `LoopFailure`; the last turn is always one where the AI is told\r\n * to answer now, and a runtime that still asks for tools then is a failure, not a hang;\r\n * - every limit and every refusal is reported to the AI as a tool RESULT, not an exception;\r\n * - nothing it logs contains file content, a search text or the AI's reasoning.\r\n *\r\n * A `LoopFailure` is an EXPECTED way for this to not work (an older runtime, a timeout, a malformed\r\n * reply), and the caller falls back to the single call. A `SafetyRefusalError` is not: it means the\r\n * runtime refused the run itself (spend cap, credential), and a second call would only be refused or\r\n * paid for again.\r\n *\r\n * The wire shape here is a proposal until the AI Runtime side is built to match it; it is isolated in\r\n * this file so it can change in one place.\r\n */\r\n\r\nexport const LOOP_CONTRACT_VERSION = \"targeting-loop-1\";\r\n\r\nexport type LoopFinalReason = \"max_turns\" | \"tool_budget\" | \"read_budget\" | \"no_progress\";\r\n\r\nexport type LoopStopReason =\r\n | \"model_final\"\r\n | \"forced_max_turns\"\r\n | \"forced_tool_budget\"\r\n | \"forced_read_budget\"\r\n | \"forced_no_progress\"\r\n | \"fallback\";\r\n\r\nexport type FallbackReason =\r\n | \"contract_rejected\"\r\n | \"semantic_mismatch\"\r\n | \"http_error\"\r\n | \"transport\"\r\n | \"turn_timeout\"\r\n | \"loop_deadline\"\r\n | \"runtime_failed\"\r\n | \"bad_reply\"\r\n | \"duplicate_call_ids\"\r\n | \"final_not_produced\"\r\n | \"final_invalid\"\r\n | \"token_ceiling\"\r\n | \"executor_error\"\r\n | \"internal_error\";\r\n\r\nexport interface LoopSummary {\r\n turns: number;\r\n toolCalls: number;\r\n readChars: number;\r\n refused: number;\r\n stopReason: LoopStopReason;\r\n fellBack?: true;\r\n fallbackReason?: FallbackReason;\r\n reads: ReadRecord[];\r\n}\r\n\r\nexport class LoopFailure extends Error {\r\n readonly reason: FallbackReason;\r\n readonly runtimeCode?: string;\r\n /** What the loop had done when it failed, so reads made before the failure are not lost. */\r\n summary?: LoopSummary;\r\n constructor(reason: FallbackReason, runtimeCode?: string, cause?: unknown) {\r\n super(`pilot.targeting loop failed: ${reason}${runtimeCode ? ` (${runtimeCode})` : \"\"}`);\r\n this.name = \"LoopFailure\";\r\n this.reason = reason;\r\n this.runtimeCode = runtimeCode;\r\n if (cause !== undefined) (this as { cause?: unknown }).cause = cause;\r\n }\r\n}\r\n\r\n/** The runtime refused the RUN (not just this turn). Never answered by falling back. */\r\nexport class SafetyRefusalError extends RuntimeReplyError {\r\n constructor(message: string, summary: string) {\r\n super(message, summary);\r\n this.name = \"SafetyRefusalError\";\r\n }\r\n}\r\n\r\n/**\r\n * Runtime error codes that mean the run itself was refused: out of money, or the run credential does\r\n * not cover this. The single call would be refused too, or paid for twice.\r\n */\r\nexport const NO_FALLBACK_CODES: ReadonlySet<string> = new Set([\"RUN_BUDGET_EXCEEDED\", \"RUN_CREDENTIAL_SCOPE\"]);\r\n\r\nexport interface LoopDeps {\r\n /** One POST of `pilot.targeting`; resolves to the RAW `/ai/execute` envelope. */\r\n post(contextData: Record<string, unknown>, signal: AbortSignal): Promise<unknown>;\r\n fs?: ToolFs;\r\n limits?: Partial<ToolLimits>;\r\n now?: () => number;\r\n log?: (event: Record<string, unknown>) => void;\r\n turnTimeoutMs?: number;\r\n deadlineMs?: number;\r\n}\r\n\r\nexport interface LoopArgs {\r\n /** Exactly today's contextData for the single call. */\r\n baseContext: Record<string, unknown>;\r\n listing: string[];\r\n deniedPaths: string[];\r\n}\r\n\r\nconst TOOL_NAMES = new Set([\"list_files\", \"read_file\", \"grep\"]);\r\nconst MAX_ID_CHARS = 64;\r\nconst MAX_CALLS_IN_A_REPLY = 50;\r\nconst MAX_ARGS_JSON_CHARS = 1_000;\r\n\r\nfunction isPlainObject(x: unknown): x is Record<string, unknown> {\r\n return typeof x === \"object\" && x !== null && !Array.isArray(x);\r\n}\r\n\r\nfunction safeArgs(args: unknown): unknown {\r\n try {\r\n return JSON.stringify(args).length <= MAX_ARGS_JSON_CHARS ? args : { _omitted: \"too large\" };\r\n } catch {\r\n return { _omitted: \"unreadable\" };\r\n }\r\n}\r\n\r\nfunction classifyTransport(err: unknown): LoopFailure {\r\n if (err instanceof TargetingHttpError) return new LoopFailure(\"http_error\", undefined, err);\r\n const name = (err as { name?: unknown })?.name;\r\n if (name === \"TimeoutError\" || name === \"AbortError\") return new LoopFailure(\"turn_timeout\", undefined, err);\r\n return new LoopFailure(\"transport\", undefined, err);\r\n}\r\n\r\nexport async function runTargetingLoop(args: LoopArgs, deps: LoopDeps): Promise<{ body: unknown; summary: LoopSummary }> {\r\n const limits: ToolLimits = { ...DEFAULT_LIMITS, ...deps.limits };\r\n const now = deps.now ?? Date.now;\r\n const log = deps.log ?? ((e: Record<string, unknown>) => console.log(JSON.stringify(e)));\r\n const turnTimeoutMs = deps.turnTimeoutMs ?? 180_000;\r\n const deadlineMs = deps.deadlineMs ?? 600_000;\r\n\r\n const env: ToolEnv = {\r\n listing: new Set(args.listing),\r\n visible: buildVisibleListing(args.listing, args.deniedPaths),\r\n deniedPaths: args.deniedPaths,\r\n fs: deps.fs ?? createNodeToolFs(),\r\n limits,\r\n };\r\n const ledger = newLedger();\r\n const reads: ReadRecord[] = [];\r\n const transcript: Record<string, unknown>[] = [];\r\n const toolResults: ToolResult[] = [];\r\n const usedIds = new Set<string>();\r\n\r\n let turns = 0;\r\n let noProgressStreak = 0;\r\n let forced: LoopFinalReason | null = null;\r\n const started = now();\r\n\r\n // Spread then override: `contractVersion` keeps the position it has in today's request.\r\n const buildContext = (turn: number, isFinal: boolean, finalReason: LoopFinalReason): Record<string, unknown> => ({\r\n ...args.baseContext,\r\n contractVersion: LOOP_CONTRACT_VERSION,\r\n loop: {\r\n turn,\r\n maxTurns: limits.maxTurns,\r\n final: isFinal,\r\n ...(isFinal ? { finalReason } : {}),\r\n remaining: {\r\n toolCalls: Math.max(0, limits.maxToolCalls - ledger.toolCalls),\r\n readChars: Math.max(0, limits.readCharsTotal - ledger.readChars),\r\n },\r\n transcript,\r\n toolResults,\r\n },\r\n });\r\n\r\n const snapshot = (stopReason: LoopStopReason): LoopSummary => ({\r\n turns,\r\n toolCalls: ledger.toolCalls,\r\n readChars: ledger.readChars,\r\n refused: ledger.refused,\r\n stopReason,\r\n reads: [...reads],\r\n });\r\n\r\n log({ event: \"targeting.loop_start\", mode: \"loop\", maxTurns: limits.maxTurns, maxToolCalls: limits.maxToolCalls, listingFiles: args.listing.length });\r\n\r\n try {\r\n for (let turn = 1; turn <= limits.maxTurns; turn++) {\r\n turns = turn;\r\n if (now() - started > deadlineMs) throw new LoopFailure(\"loop_deadline\");\r\n\r\n const isFinal = forced !== null || turn === limits.maxTurns;\r\n const finalReason: LoopFinalReason = forced ?? \"max_turns\";\r\n const contextData = buildContext(turn, isFinal, finalReason);\r\n const requestChars = JSON.stringify(contextData).length;\r\n // The ceiling is enforced HERE because nothing else does: the runtime has no pre-dispatch size check\r\n // for targeting, and an oversized turn does not refuse cleanly \u2014 it fails at the provider.\r\n const requestTokens = estimateRequestTokens(contextData);\r\n if (requestTokens > limits.maxRequestTokens) {\r\n log({ event: \"targeting.loop_ceiling\", turn, action: \"not_sent\", projectedTokens: requestTokens, ceiling: limits.maxRequestTokens });\r\n throw new LoopFailure(\"token_ceiling\");\r\n }\r\n\r\n const turnStarted = now();\r\n let envelope: unknown;\r\n try {\r\n envelope = await deps.post(contextData, AbortSignal.timeout(turnTimeoutMs));\r\n } catch (err) {\r\n throw classifyTransport(err);\r\n }\r\n\r\n const code = (envelope as { errorCode?: unknown } | null)?.errorCode;\r\n try {\r\n checkHardFailure(envelope, \"pilot.targeting\");\r\n } catch (err) {\r\n throw new LoopFailure(code === \"CONTRACT_REJECTED\" ? \"contract_rejected\" : \"semantic_mismatch\", String(code), err);\r\n }\r\n if ((envelope as { success?: unknown } | null)?.success === false) {\r\n const runtimeCode = typeof code === \"string\" ? code : undefined;\r\n if (runtimeCode && NO_FALLBACK_CODES.has(runtimeCode)) {\r\n let inner: RuntimeReplyError | undefined;\r\n try {\r\n unwrapExecute(envelope, \"pilot.targeting\");\r\n } catch (e) {\r\n inner = e instanceof RuntimeReplyError ? e : undefined;\r\n }\r\n const fallbackText = `pilot.targeting failed: ${runtimeCode}`;\r\n throw new SafetyRefusalError(inner?.message ?? fallbackText, inner?.summary ?? fallbackText);\r\n }\r\n throw new LoopFailure(\"runtime_failed\", runtimeCode);\r\n }\r\n\r\n let body: Record<string, unknown>;\r\n try {\r\n body = unwrapExecute<Record<string, unknown>>(envelope, \"pilot.targeting\");\r\n } catch (err) {\r\n throw new LoopFailure(\"bad_reply\", undefined, err);\r\n }\r\n\r\n if (body.outcome === \"TARGETED\" || body.outcome === \"NO_TARGET\") {\r\n log({ event: \"targeting.loop_turn\", turn, outcome: \"final\", requestChars, requestTokens, elapsedMs: now() - turnStarted, calls: [] });\r\n const stopReason: LoopStopReason = isFinal ? (`forced_${finalReason}` as LoopStopReason) : \"model_final\";\r\n log({ event: \"targeting.loop_done\", turns, toolCalls: ledger.toolCalls, readChars: ledger.readChars, refused: ledger.refused, stopReason });\r\n return { body, summary: snapshot(stopReason) };\r\n }\r\n if (body.outcome !== \"TOOL_CALLS\") throw new LoopFailure(\"bad_reply\");\r\n if (isFinal) throw new LoopFailure(\"final_not_produced\");\r\n\r\n const rawCalls = body.toolCalls;\r\n if (!Array.isArray(rawCalls) || rawCalls.length === 0 || rawCalls.length > MAX_CALLS_IN_A_REPLY) {\r\n throw new LoopFailure(\"bad_reply\");\r\n }\r\n const calls: { id: string; name: string; args: unknown }[] = [];\r\n for (const c of rawCalls) {\r\n if (!isPlainObject(c) || typeof c.id !== \"string\" || c.id.length === 0 || c.id.length > MAX_ID_CHARS || typeof c.name !== \"string\") {\r\n throw new LoopFailure(\"bad_reply\");\r\n }\r\n if (usedIds.has(c.id) || calls.some((x) => x.id === c.id)) throw new LoopFailure(\"duplicate_call_ids\");\r\n calls.push({ id: c.id, name: c.name, args: c.args });\r\n }\r\n for (const c of calls) usedIds.add(c.id);\r\n\r\n const results: ToolResult[] = [];\r\n const logged: Record<string, unknown>[] = [];\r\n const turnReads: (ReadRecord | undefined)[] = [];\r\n calls.forEach((call, index) => {\r\n let result: ToolResult;\r\n let read: ReadRecord | undefined;\r\n if (index >= limits.maxCallsPerTurn) {\r\n result = {\r\n id: call.id,\r\n name: call.name,\r\n status: \"budget_exhausted\",\r\n reason: \"too_many_calls\",\r\n message: \"Too many calls in one turn; this one was not run.\",\r\n };\r\n } else {\r\n try {\r\n ({ result, read } = executeToolCall(call, env, ledger));\r\n } catch (err) {\r\n throw new LoopFailure(\"executor_error\", undefined, err);\r\n }\r\n }\r\n results.push(result);\r\n turnReads[index] = read;\r\n if (read) reads.push(read);\r\n const tool = TOOL_NAMES.has(call.name) ? call.name : \"unknown\";\r\n const path = read && read.path !== \"(invalid path)\" ? { path: read.path } : {};\r\n logged.push({ tool, status: result.status, ...(result.reason && result.status !== \"duplicate\" ? { reason: result.reason } : {}), ...path });\r\n if (result.status === \"refused\") {\r\n log({ event: \"targeting.loop_refused\", turn, tool, reason: result.reason, ...path });\r\n }\r\n });\r\n\r\n const reasoning = typeof body.reasoning === \"string\" ? body.reasoning.slice(0, limits.maxReasoningChars) : undefined;\r\n transcript.push({\r\n turn,\r\n ...(reasoning ? { reasoning } : {}),\r\n toolCalls: calls.map((c) => ({ id: c.id, name: c.name, args: safeArgs(c.args) })),\r\n });\r\n toolResults.push(...results);\r\n\r\n noProgressStreak = results.every((r) => r.status === \"duplicate\") ? noProgressStreak + 1 : 0;\r\n if (noProgressStreak >= 2) forced = \"no_progress\";\r\n else if (ledger.toolCalls >= limits.maxToolCalls) forced = \"tool_budget\";\r\n else if (ledger.readChars >= limits.readCharsTotal || ledger.resultChars >= limits.resultCharsTotal) forced = \"read_budget\";\r\n\r\n // Would the NEXT request still fit? A loop accumulates, so it is this, not a total, that can break.\r\n // If not: do not deliver what this turn found, tell the AI so (a result it already understands:\r\n // `budget_exhausted`), and make the next turn its last. If even that cannot fit, give up to the\r\n // single call rather than send something the provider will fail on.\r\n const nextTurn = turn + 1;\r\n if (nextTurn <= limits.maxTurns) {\r\n const nextFinal = forced !== null || nextTurn === limits.maxTurns;\r\n const projected = estimateRequestTokens(buildContext(nextTurn, nextFinal, forced ?? \"max_turns\"));\r\n if (projected > limits.maxRequestTokens) {\r\n results.forEach((r, idx) => {\r\n if (r.status !== \"ok\") return;\r\n toolResults[toolResults.indexOf(r)] = {\r\n id: r.id,\r\n name: r.name,\r\n status: \"budget_exhausted\",\r\n reason: \"token_ceiling\",\r\n message: \"Too large to include; answer from what you have.\",\r\n };\r\n const dropped = turnReads[idx];\r\n if (dropped) {\r\n const at = reads.indexOf(dropped);\r\n if (at >= 0) reads.splice(at, 1);\r\n }\r\n logged[idx].status = \"budget_exhausted\";\r\n logged[idx].reason = \"token_ceiling\";\r\n });\r\n forced = \"read_budget\";\r\n const trimmed = estimateRequestTokens(buildContext(nextTurn, true, \"read_budget\"));\r\n const fits = trimmed <= limits.maxRequestTokens;\r\n log({\r\n event: \"targeting.loop_ceiling\",\r\n turn,\r\n action: fits ? \"dropped_results\" : \"fallback\",\r\n projectedTokens: projected,\r\n ceiling: limits.maxRequestTokens,\r\n });\r\n if (!fits) throw new LoopFailure(\"token_ceiling\");\r\n }\r\n }\r\n log({ event: \"targeting.loop_turn\", turn, outcome: \"tool_calls\", requestChars, requestTokens, elapsedMs: now() - turnStarted, calls: logged });\r\n }\r\n throw new LoopFailure(\"final_not_produced\");\r\n } catch (err) {\r\n if (err instanceof SafetyRefusalError) throw err;\r\n const failure = err instanceof LoopFailure ? err : new LoopFailure(\"internal_error\", undefined, err);\r\n failure.summary ??= snapshot(\"fallback\");\r\n throw failure;\r\n }\r\n}\r\n", "import { looksLikeTruncatedRewrite, type CodegenFileResult } from \"./codegen\";\r\nimport { createCodegenWorkspace, type CodegenLimits } from \"./codegenTools\";\r\nimport { checkHardFailure, unwrapExecute } from \"./envelope\";\r\nimport { RuntimeReplyError } from \"./runtimeReplyError\";\r\nimport { NO_FALLBACK_CODES, SafetyRefusalError } from \"./targetingLoop\";\r\nimport { TargetingHttpError } from \"./targetingErrors\";\r\nimport type { PilotTarget } from \"./targeting\";\r\nimport { executeToolCall, type ReadRecord, type ToolResult } from \"./targetingTools\";\r\nimport { estimateRequestTokens } from \"./tokenEstimate\";\r\nimport type { WriteFs } from \"./workspaceOverlay\";\r\n\r\n/**\r\n * QUIKTR-1458 \u00A724 \u2014 the code-writing loop (doc 62 Phase 2, first slice).\r\n *\r\n * Instead of one call per file, the runner and the AI Runtime talk in turns. Each turn the runner POSTs to `/ai/execute`\r\n * carrying everything said so far (the runtime keeps no state); the runtime answers with tool calls to run, or with `DONE`, or\r\n * with `CANNOT_COMPLETE`. The runner runs the tools on the checkout through an in-memory overlay (`codegenTools.ts`), so NOTHING is\r\n * written to disk, and what comes out is the same `{targetPath, newContent}` list the per-file path produces: every check after\r\n * codegen in `run.ts` is unchanged, and a loop that fails is thrown away without a trace so the caller can fall back.\r\n *\r\n * It is built, like the read-only targeting loop it grew from, so it cannot run away and cannot go quiet:\r\n * - it ends with a result or a `CodegenLoopFailure`; the last turn is always one where the AI is told to finish, and a runtime\r\n * that still asks for tools then is a failure, not a hang;\r\n * - every limit and every refusal reaches the AI as a tool RESULT, not an exception;\r\n * - nothing it logs contains file content, an anchor, a replacement, a search text or the AI's reasoning.\r\n *\r\n * Unlike the targeting loop it keeps the AI's own write arguments in the transcript in full (it has to see what it wrote), and\r\n * when a request grows past the ceiling it drops the OLDEST read outputs first (the AI can read again) before anything else.\r\n */\r\n\r\nexport const CODEGEN_LOOP_CONTRACT_VERSION = \"codegen-loop-1\";\r\n\r\nexport type CodegenFinalReason = \"max_turns\" | \"tool_budget\" | \"read_budget\" | \"write_budget\" | \"no_progress\";\r\n\r\nexport type CodegenStopReason =\r\n | \"model_done\"\r\n | \"forced_max_turns\"\r\n | \"forced_tool_budget\"\r\n | \"forced_read_budget\"\r\n | \"forced_write_budget\"\r\n | \"forced_no_progress\"\r\n | \"fallback\";\r\n\r\nexport type CodegenFallbackReason =\r\n | \"contract_rejected\"\r\n | \"semantic_mismatch\"\r\n | \"http_error\"\r\n | \"transport\"\r\n | \"turn_timeout\"\r\n | \"loop_deadline\"\r\n | \"runtime_failed\"\r\n | \"bad_reply\"\r\n | \"duplicate_call_ids\"\r\n | \"final_not_produced\"\r\n | \"token_ceiling\"\r\n | \"executor_error\"\r\n | \"internal_error\"\r\n | \"cannot_complete\"\r\n | \"no_writes\"\r\n | \"coverage_missing\"\r\n | \"truncation_guard\";\r\n\r\nexport interface CodegenLoopSummary {\r\n turns: number;\r\n toolCalls: number;\r\n refused: number;\r\n stopReason: CodegenStopReason;\r\n fellBack?: true;\r\n fallbackReason?: CodegenFallbackReason;\r\n /** Everything read, in order. Paths and sizes only. */\r\n reads: ReadRecord[];\r\n /** Successful edits per path. */\r\n edits: { path: string; count: number }[];\r\n /** Files created, with their size. */\r\n created: { path: string; chars: number }[];\r\n /** How many results of each status the AI was given. A closed vocabulary. */\r\n statusCounts: Record<string, number>;\r\n /** The AI's own one-or-two sentences per turn, so a reviewer can see why it went where it went. Model-written. */\r\n reasoning: { turn: number; text: string }[];\r\n}\r\n\r\nexport class CodegenLoopFailure extends Error {\r\n readonly reason: CodegenFallbackReason;\r\n readonly runtimeCode?: string;\r\n /** Short, runner-written (or, for CANNOT_COMPLETE, the AI's own summary cut to 300 characters). Never file content. */\r\n readonly detail?: string;\r\n summary?: CodegenLoopSummary;\r\n constructor(reason: CodegenFallbackReason, runtimeCode?: string, cause?: unknown, detail?: string) {\r\n super(`pilot.codegen loop failed: ${reason}${runtimeCode ? ` (${runtimeCode})` : \"\"}`);\r\n this.name = \"CodegenLoopFailure\";\r\n this.reason = reason;\r\n this.runtimeCode = runtimeCode;\r\n this.detail = detail;\r\n if (cause !== undefined) (this as { cause?: unknown }).cause = cause;\r\n }\r\n}\r\n\r\nexport interface CodegenLoopDeps {\r\n /** One POST of `pilot.codegen`; resolves to the RAW `/ai/execute` envelope. */\r\n post(contextData: Record<string, unknown>, signal: AbortSignal): Promise<unknown>;\r\n fs?: WriteFs;\r\n limits?: Partial<CodegenLimits>;\r\n now?: () => number;\r\n log?: (event: Record<string, unknown>) => void;\r\n turnTimeoutMs?: number;\r\n deadlineMs?: number;\r\n}\r\n\r\nexport interface CodegenLoopArgs {\r\n /** Everything the request carries besides `contractVersion` and `loop` (targets, requiredTests, workspaceListing, ...). */\r\n baseContext: Record<string, unknown>;\r\n /** The plan, for the truncated-rewrite guard (its plan text is the union of every target's steps). */\r\n targets: PilotTarget[];\r\n /** Every case that must end up bracketed in some written text; skipped cases are not in here. */\r\n requiredAutomationIds: string[];\r\n listing: string[];\r\n deniedPaths: string[];\r\n /** Existing test files: they accept only additions. */\r\n protectedTestPaths: string[];\r\n}\r\n\r\nconst MAX_ID_CHARS = 64;\r\nconst MAX_CALLS_IN_A_REPLY = 50;\r\nconst MAX_SUMMARY_CHARS = 300;\r\nconst READ_TOOLS = new Set([\"list_files\", \"read_file\", \"grep\"]);\r\nconst WRITE_TOOLS = new Set([\"edit_file\", \"write_file\"]);\r\nconst TOOL_NAMES = new Set([...READ_TOOLS, ...WRITE_TOOLS]);\r\n\r\nfunction isPlainObject(x: unknown): x is Record<string, unknown> {\r\n return typeof x === \"object\" && x !== null && !Array.isArray(x);\r\n}\r\n\r\nfunction classifyTransport(err: unknown): CodegenLoopFailure {\r\n if (err instanceof TargetingHttpError) return new CodegenLoopFailure(\"http_error\", undefined, err);\r\n const name = (err as { name?: unknown })?.name;\r\n if (name === \"TimeoutError\" || name === \"AbortError\") return new CodegenLoopFailure(\"turn_timeout\", undefined, err);\r\n return new CodegenLoopFailure(\"transport\", undefined, err);\r\n}\r\n\r\nconst DROPPED_OUTPUT = { dropped: true, note: \"Dropped to keep the request small. Read the file again if you need it.\" };\r\n\r\nexport async function runCodegenLoop(\r\n args: CodegenLoopArgs,\r\n deps: CodegenLoopDeps,\r\n): Promise<{ results: CodegenFileResult[]; summary: CodegenLoopSummary; doneSummary: string }> {\r\n const ws = createCodegenWorkspace({\r\n listing: args.listing,\r\n deniedPaths: args.deniedPaths,\r\n protectedTestPaths: args.protectedTestPaths,\r\n fs: deps.fs,\r\n limits: deps.limits,\r\n });\r\n const { env, ledger, overlay, limits } = ws;\r\n const now = deps.now ?? Date.now;\r\n const log = deps.log ?? ((e: Record<string, unknown>) => console.log(JSON.stringify(e)));\r\n const turnTimeoutMs = deps.turnTimeoutMs ?? 300_000;\r\n const deadlineMs = deps.deadlineMs ?? 1_500_000;\r\n\r\n const reads: ReadRecord[] = [];\r\n const reasoning: { turn: number; text: string }[] = [];\r\n const statusCounts: Record<string, number> = {};\r\n const transcript: { turn: number; reasoning?: string; toolCalls: { id: string; name: string; args: unknown }[] }[] = [];\r\n const toolResults: ToolResult[] = [];\r\n const usedIds = new Set<string>();\r\n\r\n let turns = 0;\r\n let noProgressStreak = 0;\r\n let forced: CodegenFinalReason | null = null;\r\n const started = now();\r\n\r\n const buildContext = (turn: number, isFinal: boolean, finalReason: CodegenFinalReason): Record<string, unknown> => ({\r\n ...args.baseContext,\r\n contractVersion: CODEGEN_LOOP_CONTRACT_VERSION,\r\n loop: {\r\n turn,\r\n maxTurns: limits.maxTurns,\r\n final: isFinal,\r\n ...(isFinal ? { finalReason } : {}),\r\n remaining: {\r\n toolCalls: Math.max(0, limits.maxToolCalls - ledger.toolCalls),\r\n readChars: Math.max(0, limits.readCharsTotal - ledger.readChars),\r\n writeChars: Math.max(0, limits.writeCharsTotal - ledger.writeChars),\r\n },\r\n transcript,\r\n toolResults,\r\n },\r\n });\r\n\r\n const snapshot = (stopReason: CodegenStopReason): CodegenLoopSummary => ({\r\n turns,\r\n toolCalls: ledger.toolCalls,\r\n refused: ledger.refused,\r\n stopReason,\r\n reads: [...reads],\r\n edits: [...ws.edits.entries()].map(([path, count]) => ({ path, count })),\r\n created: [...ws.created.entries()].map(([path, chars]) => ({ path, chars })),\r\n statusCounts: { ...statusCounts },\r\n reasoning: [...reasoning],\r\n });\r\n\r\n /** Make room: oldest read outputs first (the AI can read again), then the text of the oldest writes. Returns true if it fits. */\r\n const makeRoom = (nextTurn: number, nextFinal: boolean, finalReason: CodegenFinalReason): boolean => {\r\n const fits = (): boolean => estimateRequestTokens(buildContext(nextTurn, nextFinal, finalReason)) <= limits.maxRequestTokens;\r\n if (fits()) return true;\r\n for (let i = 0; i < toolResults.length && !fits(); i++) {\r\n const r = toolResults[i]!;\r\n if (READ_TOOLS.has(r.name) && r.status === \"ok\" && r.output !== DROPPED_OUTPUT) toolResults[i] = { ...r, output: DROPPED_OUTPUT };\r\n }\r\n for (const key of [...ledger.seen.keys()]) {\r\n if (key.startsWith(\"read_file:\") || key.startsWith(\"grep:\") || key.startsWith(\"list_files:\")) ledger.seen.delete(key);\r\n }\r\n for (const entry of transcript) {\r\n if (fits()) break;\r\n entry.toolCalls = entry.toolCalls.map((c) => {\r\n if (!WRITE_TOOLS.has(c.name) || !isPlainObject(c.args) || \"_omitted\" in c.args) return c;\r\n const path = typeof c.args.path === \"string\" ? { path: c.args.path } : {};\r\n return { ...c, args: { ...path, _omitted: \"written earlier; read the file to see it\" } };\r\n });\r\n }\r\n return fits();\r\n };\r\n\r\n log({ event: \"codegen.loop_start\", maxTurns: limits.maxTurns, maxToolCalls: limits.maxToolCalls, listingFiles: args.listing.length });\r\n\r\n try {\r\n for (let turn = 1; turn <= limits.maxTurns; turn++) {\r\n turns = turn;\r\n if (now() - started > deadlineMs) throw new CodegenLoopFailure(\"loop_deadline\");\r\n\r\n const isFinal = forced !== null || turn === limits.maxTurns;\r\n const finalReason: CodegenFinalReason = forced ?? \"max_turns\";\r\n const contextData = buildContext(turn, isFinal, finalReason);\r\n const requestTokens = estimateRequestTokens(contextData);\r\n if (requestTokens > limits.maxRequestTokens) {\r\n log({ event: \"codegen.loop_ceiling\", turn, action: \"not_sent\", projectedTokens: requestTokens, ceiling: limits.maxRequestTokens });\r\n throw new CodegenLoopFailure(\"token_ceiling\");\r\n }\r\n\r\n const turnStarted = now();\r\n let envelope: unknown;\r\n try {\r\n envelope = await deps.post(contextData, AbortSignal.timeout(turnTimeoutMs));\r\n } catch (err) {\r\n throw classifyTransport(err);\r\n }\r\n\r\n const code = (envelope as { errorCode?: unknown } | null)?.errorCode;\r\n try {\r\n checkHardFailure(envelope, \"pilot.codegen\");\r\n } catch (err) {\r\n throw new CodegenLoopFailure(code === \"CONTRACT_REJECTED\" ? \"contract_rejected\" : \"semantic_mismatch\", String(code), err);\r\n }\r\n if ((envelope as { success?: unknown } | null)?.success === false) {\r\n const runtimeCode = typeof code === \"string\" ? code : undefined;\r\n if (runtimeCode && NO_FALLBACK_CODES.has(runtimeCode)) {\r\n let inner: RuntimeReplyError | undefined;\r\n try {\r\n unwrapExecute(envelope, \"pilot.codegen\");\r\n } catch (e) {\r\n inner = e instanceof RuntimeReplyError ? e : undefined;\r\n }\r\n const fallbackText = `pilot.codegen failed: ${runtimeCode}`;\r\n throw new SafetyRefusalError(inner?.message ?? fallbackText, inner?.summary ?? fallbackText);\r\n }\r\n throw new CodegenLoopFailure(\"runtime_failed\", runtimeCode);\r\n }\r\n\r\n let body: Record<string, unknown>;\r\n try {\r\n body = unwrapExecute<Record<string, unknown>>(envelope, \"pilot.codegen\");\r\n } catch (err) {\r\n throw new CodegenLoopFailure(\"bad_reply\", undefined, err);\r\n }\r\n\r\n const reasonText = typeof body.reasoning === \"string\" ? body.reasoning.slice(0, limits.maxReasoningChars) : undefined;\r\n\r\n if (body.outcome === \"CANNOT_COMPLETE\") {\r\n log({ event: \"codegen.loop_turn\", turn, outcome: \"cannot_complete\", requestTokens, elapsedMs: now() - turnStarted, calls: [] });\r\n const said = typeof body.summary === \"string\" ? body.summary.slice(0, MAX_SUMMARY_CHARS) : undefined;\r\n throw new CodegenLoopFailure(\"cannot_complete\", undefined, undefined, said);\r\n }\r\n\r\n if (body.outcome === \"DONE\") {\r\n log({ event: \"codegen.loop_turn\", turn, outcome: \"done\", requestTokens, elapsedMs: now() - turnStarted, calls: [] });\r\n const changed = overlay.changedPaths();\r\n if (changed.length === 0) throw new CodegenLoopFailure(\"no_writes\");\r\n const texts = changed.map((p) => overlay.get(p)?.lf ?? \"\");\r\n const missing = args.requiredAutomationIds.filter((id) => !texts.some((t) => t.includes(`[${id}]`)));\r\n if (missing.length > 0) {\r\n log({ event: \"codegen.loop_refused\", turn, reason: \"coverage_missing\", missing: missing.length });\r\n throw new CodegenLoopFailure(\"coverage_missing\", undefined, undefined, `${missing.length} required test case(s) not written`);\r\n }\r\n const planSteps = args.targets.flatMap((t) => t.planStepsImplemented);\r\n for (const path of changed) {\r\n const entry = overlay.get(path);\r\n if (!entry || entry.created || entry.originalLf === null) continue;\r\n const pseudo: PilotTarget = { path, kind: \"EXISTING\", planStepsImplemented: planSteps };\r\n const suspect = looksLikeTruncatedRewrite(pseudo, entry.originalLf, entry.lf);\r\n if (suspect) {\r\n log({ event: \"codegen.loop_refused\", turn, reason: \"truncation_guard\", path });\r\n throw new CodegenLoopFailure(\"truncation_guard\", undefined, undefined, `${path}: ${suspect}`);\r\n }\r\n }\r\n const stopReason: CodegenStopReason = isFinal ? (`forced_${finalReason}` as CodegenStopReason) : \"model_done\";\r\n const doneSummary = typeof body.summary === \"string\" ? body.summary.slice(0, MAX_SUMMARY_CHARS) : \"\";\r\n log({ event: \"codegen.loop_done\", turns, toolCalls: ledger.toolCalls, edits: ws.edits.size, created: ws.created.size, stopReason });\r\n return { results: overlay.results(), summary: snapshot(stopReason), doneSummary };\r\n }\r\n\r\n if (body.outcome !== \"TOOL_CALLS\") throw new CodegenLoopFailure(\"bad_reply\");\r\n if (isFinal) throw new CodegenLoopFailure(\"final_not_produced\");\r\n\r\n const rawCalls = body.toolCalls;\r\n if (!Array.isArray(rawCalls) || rawCalls.length === 0 || rawCalls.length > MAX_CALLS_IN_A_REPLY) throw new CodegenLoopFailure(\"bad_reply\");\r\n const calls: { id: string; name: string; args: unknown }[] = [];\r\n for (const c of rawCalls) {\r\n if (!isPlainObject(c) || typeof c.id !== \"string\" || c.id.length === 0 || c.id.length > MAX_ID_CHARS || typeof c.name !== \"string\") {\r\n throw new CodegenLoopFailure(\"bad_reply\");\r\n }\r\n if (usedIds.has(c.id) || calls.some((x) => x.id === c.id)) throw new CodegenLoopFailure(\"duplicate_call_ids\");\r\n calls.push({ id: c.id, name: c.name, args: c.args });\r\n }\r\n for (const c of calls) usedIds.add(c.id);\r\n\r\n const results: ToolResult[] = [];\r\n const logged: Record<string, unknown>[] = [];\r\n calls.forEach((call, index) => {\r\n let result: ToolResult;\r\n let read: ReadRecord | undefined;\r\n if (index >= limits.maxCallsPerTurn) {\r\n result = { id: call.id, name: call.name, status: \"budget_exhausted\", reason: \"too_many_calls\", message: \"Too many calls in one turn; this one was not run.\" };\r\n } else {\r\n try {\r\n ({ result, read } = executeToolCall(call, env, ledger));\r\n } catch (err) {\r\n throw new CodegenLoopFailure(\"executor_error\", undefined, err);\r\n }\r\n }\r\n results.push(result);\r\n if (read) reads.push(read);\r\n statusCounts[result.status] = (statusCounts[result.status] ?? 0) + 1;\r\n const tool = TOOL_NAMES.has(call.name) ? call.name : \"unknown\";\r\n const pathArg = isPlainObject(call.args) && typeof call.args.path === \"string\" && result.status !== \"refused\" ? { path: call.args.path } : {};\r\n logged.push({ tool, status: result.status, ...(result.reason && result.status !== \"duplicate\" ? { reason: result.reason } : {}), ...pathArg });\r\n if (result.status === \"refused\" || result.status === \"protected\") {\r\n log({ event: \"codegen.loop_refused\", turn, tool, status: result.status, reason: result.reason });\r\n }\r\n });\r\n\r\n if (reasonText) reasoning.push({ turn, text: reasonText });\r\n transcript.push({ turn, ...(reasonText ? { reasoning: reasonText } : {}), toolCalls: calls.map((c) => ({ id: c.id, name: c.name, args: c.args })) });\r\n toolResults.push(...results);\r\n\r\n noProgressStreak = results.every((r) => r.status === \"duplicate\") ? noProgressStreak + 1 : 0;\r\n if (noProgressStreak >= 2) forced = \"no_progress\";\r\n else if (ledger.toolCalls >= limits.maxToolCalls) forced = \"tool_budget\";\r\n else if (ledger.writeChars >= limits.writeCharsTotal) forced = \"write_budget\";\r\n else if (ledger.readChars >= limits.readCharsTotal || ledger.resultChars >= limits.resultCharsTotal) forced = \"read_budget\";\r\n\r\n const nextTurn = turn + 1;\r\n if (nextTurn <= limits.maxTurns) {\r\n const nextFinal = forced !== null || nextTurn === limits.maxTurns;\r\n if (!makeRoom(nextTurn, nextFinal, forced ?? \"max_turns\")) {\r\n // Even with the oldest reads and writes dropped it does not fit: make the next turn the last, and if that cannot\r\n // fit either, give up to the per-file path rather than send something the provider will fail on.\r\n forced = forced ?? \"read_budget\";\r\n const fits = makeRoom(nextTurn, true, forced);\r\n log({ event: \"codegen.loop_ceiling\", turn, action: fits ? \"forced_final\" : \"fallback\", ceiling: limits.maxRequestTokens });\r\n if (!fits) throw new CodegenLoopFailure(\"token_ceiling\");\r\n }\r\n }\r\n log({ event: \"codegen.loop_turn\", turn, outcome: \"tool_calls\", requestTokens, elapsedMs: now() - turnStarted, calls: logged });\r\n }\r\n throw new CodegenLoopFailure(\"final_not_produced\");\r\n } catch (err) {\r\n if (err instanceof SafetyRefusalError) throw err;\r\n const failure = err instanceof CodegenLoopFailure ? err : new CodegenLoopFailure(\"internal_error\", undefined, err);\r\n failure.summary ??= snapshot(\"fallback\");\r\n throw failure;\r\n }\r\n}\r\n", "import { runCodegen, type CodegenFileResult, type JudgedByCase } from \"./codegen\";\r\nimport { buildCodegenLoopRecord, type CodegenLoopRecord } from \"./codegenLoopRecord\";\r\nimport { collectLoopContext, type LoopContext } from \"./codegenLoopContext\";\r\nimport { CodegenLoopFailure, runCodegenLoop, type CodegenLoopArgs, type CodegenLoopDeps, type CodegenLoopSummary } from \"./codegenLoop\";\r\nimport type { CodegenMode } from \"./codegenMode\";\r\nimport { isTestTarget } from \"./overlapCheck\";\r\nimport type { PilotPacket } from \"./packet\";\r\nimport { fetchWithRetry } from \"./retryFetch\";\r\nimport type { PilotTarget, SkippedCase } from \"./targeting\";\r\nimport { TargetingHttpError } from \"./targetingErrors\";\r\nimport { SafetyRefusalError } from \"./targetingLoop\";\r\nimport type { CodegenContextRecord } from \"./targetingRecord\";\r\n\r\n/**\r\n * QUIKTR-1458 \u00A724 \u2014 the one place that decides HOW the code is written: the loop, or the per-file calls it replaces.\r\n *\r\n * With the loop switched on (`codegenMode.ts`) it tries the loop first. If the loop cannot finish for an ordinary reason it\r\n * is thrown away (it wrote nothing to disk) and the files are written one at a time, exactly as before, with a warning that\r\n * says so out loud: a run that quietly stopped using the loop would make every comparison between the two ways meaningless.\r\n * It NEVER falls back when the runtime refused the run itself (spend cap, credential): a second attempt would be refused again,\r\n * or paid for twice.\r\n */\r\n\r\nexport interface CodegenStepParams {\r\n mode: CodegenMode;\r\n gateway: PilotPacket[\"gateway\"];\r\n targets: PilotTarget[];\r\n workspaceListing: string[];\r\n requiredTests: PilotPacket[\"requiredTests\"];\r\n deniedPaths: string[];\r\n judgedByPool: JudgedByCase[];\r\n warnings: string[];\r\n contextLog: CodegenContextRecord[];\r\n outOfScope: string[];\r\n testDiscovery: PilotPacket[\"testDiscovery\"];\r\n skippedCases: SkippedCase[];\r\n /** Filled when the loop ran or was tried: what it did, for the run's record. */\r\n out: { loop?: CodegenLoopRecord };\r\n /** For tests: replace the network, the file system or the limits. */\r\n deps?: Partial<CodegenLoopDeps>;\r\n /** For tests: how a context file is read (default: from the checkout). */\r\n readFile?: (path: string) => string;\r\n}\r\n\r\n/** The cap on how many protected test paths go on the wire; the runner enforces the full list itself. */\r\nconst MAX_PROTECTED_PATHS_ON_WIRE = 300;\r\n\r\nexport async function postCodegenTurn(\r\n gateway: PilotPacket[\"gateway\"],\r\n contextData: Record<string, unknown>,\r\n signal?: AbortSignal,\r\n): Promise<unknown> {\r\n const res = await fetchWithRetry(`${gateway.baseUrl}/ai/execute`, {\r\n method: \"POST\",\r\n headers: { \"content-type\": \"application/json\", \"x-run-token\": gateway.token },\r\n body: JSON.stringify({\r\n appId: \"quiktrack\",\r\n useCase: \"pilot.codegen\",\r\n expectedOutputType: \"json\",\r\n userPrompt: \"\",\r\n contextData,\r\n }),\r\n ...(signal ? { signal } : {}),\r\n });\r\n if (!res.ok) throw new TargetingHttpError(res.status, res.statusText);\r\n return res.json();\r\n}\r\n\r\n/** Existing test files: the ones that look like tests by path, and the ones the last test report says the runner discovers. */\r\nexport function protectedTestFiles(listing: string[], testDiscovery: PilotPacket[\"testDiscovery\"]): string[] {\r\n const inListing = new Set(listing);\r\n const found = new Set<string>(listing.filter((p) => isTestTarget(p)));\r\n if (testDiscovery.report === \"PRESENT\") {\r\n for (const p of testDiscovery.discoveredTestFiles) if (inListing.has(p)) found.add(p);\r\n }\r\n return [...found].sort();\r\n}\r\n\r\nexport function buildCodegenLoopArgs(\r\n p: CodegenStepParams,\r\n context: LoopContext = collectLoopContext({ targets: p.targets, listing: p.workspaceListing, deniedPaths: p.deniedPaths, ...(p.readFile ? { readFile: p.readFile } : {}) }),\r\n): CodegenLoopArgs {\r\n const skipped = new Set(p.skippedCases.map((s) => s.automationId));\r\n const claimed = new Set<string>();\r\n for (const t of p.targets) for (const id of t.automationIds ?? []) if (!skipped.has(id)) claimed.add(id);\r\n const requiredTests = p.requiredTests.filter((tc) => claimed.has(tc.automationId));\r\n const protectedTestPaths = protectedTestFiles(p.workspaceListing, p.testDiscovery);\r\n\r\n const baseContext: Record<string, unknown> = {\r\n targets: p.targets.map((t) => ({\r\n path: t.path,\r\n kind: t.kind,\r\n role: (t.automationIds?.length ?? 0) > 0 || isTestTarget(t.path) ? \"test\" : \"code\",\r\n planSteps: t.planStepsImplemented,\r\n automationIds: t.automationIds ?? [],\r\n })),\r\n requiredTests,\r\n workspaceListing: p.workspaceListing,\r\n };\r\n // The files the plan named and the files the changed files import, shown before the first turn (`codegenLoopContext.ts`).\r\n if (context.entries.length > 0) baseContext.contextContents = context.entries;\r\n if (p.deniedPaths.length > 0) baseContext.deniedPaths = p.deniedPaths;\r\n if (protectedTestPaths.length > 0) baseContext.protectedTestPaths = protectedTestPaths.slice(0, MAX_PROTECTED_PATHS_ON_WIRE);\r\n if (p.outOfScope.length > 0) baseContext.outOfScope = p.outOfScope;\r\n\r\n return {\r\n baseContext,\r\n targets: p.targets,\r\n requiredAutomationIds: requiredTests.map((tc) => tc.automationId),\r\n listing: p.workspaceListing,\r\n deniedPaths: p.deniedPaths,\r\n protectedTestPaths,\r\n };\r\n}\r\n\r\nconst NO_SUMMARY: CodegenLoopSummary = {\r\n turns: 0,\r\n toolCalls: 0,\r\n refused: 0,\r\n stopReason: \"fallback\",\r\n reads: [],\r\n edits: [],\r\n created: [],\r\n statusCounts: {},\r\n reasoning: [],\r\n};\r\n\r\nfunction perFile(p: CodegenStepParams): Promise<CodegenFileResult[]> {\r\n return runCodegen(\r\n p.gateway,\r\n p.targets,\r\n p.workspaceListing,\r\n p.requiredTests,\r\n p.deniedPaths,\r\n p.judgedByPool,\r\n p.warnings,\r\n p.contextLog,\r\n p.outOfScope,\r\n );\r\n}\r\n\r\nexport async function runCodegenStep(p: CodegenStepParams): Promise<CodegenFileResult[]> {\r\n if (p.mode !== \"loop\") return perFile(p);\r\n\r\n const context = collectLoopContext({ targets: p.targets, listing: p.workspaceListing, deniedPaths: p.deniedPaths, ...(p.readFile ? { readFile: p.readFile } : {}) });\r\n // Same record the one-file path writes, so the run's record and the log say what was in front of the AI. Paths and counts only.\r\n p.contextLog.push(...context.records);\r\n console.log(\r\n JSON.stringify({\r\n event: \"codegen.loop_context\",\r\n files: context.entries.length,\r\n chars: context.entries.reduce((n, e) => n + e.content.length, 0),\r\n paths: context.entries.map((e) => e.path),\r\n existingTests: context.testPaths,\r\n }),\r\n );\r\n try {\r\n const { results, summary } = await runCodegenLoop(buildCodegenLoopArgs(p, context), {\r\n post: (contextData, signal) => postCodegenTurn(p.gateway, contextData, signal),\r\n ...p.deps,\r\n });\r\n p.out.loop = buildCodegenLoopRecord(summary);\r\n // The loop may touch a file the plan did not name. That is allowed (the checks after it still apply), but it is said\r\n // out loud: a reviewer reading the plan should not be surprised by a file it never mentioned.\r\n const planned = new Set(p.targets.map((t) => t.path));\r\n for (const r of results) {\r\n if (!planned.has(r.targetPath)) {\r\n const w = `QuikPilot changed ${r.targetPath}, which the plan did not name.`;\r\n p.warnings.push(w);\r\n console.warn(`QuikPilot codegen warning (not blocking): ${w}`);\r\n }\r\n }\r\n return results;\r\n } catch (err) {\r\n if (err instanceof SafetyRefusalError) throw err;\r\n const failure = err instanceof CodegenLoopFailure ? err : new CodegenLoopFailure(\"internal_error\", undefined, err);\r\n p.out.loop = buildCodegenLoopRecord({\r\n ...(failure.summary ?? NO_SUMMARY),\r\n stopReason: \"fallback\",\r\n fellBack: true,\r\n fallbackReason: failure.reason,\r\n });\r\n const said = failure.detail ? `: ${failure.detail}` : \"\";\r\n const w = `The code-writing loop could not finish (${failure.reason}${said}), so the files were written one at a time instead.`;\r\n p.warnings.push(w);\r\n console.warn(`QuikPilot codegen warning (not blocking): ${w}`);\r\n return perFile(p);\r\n }\r\n}\r\n", "import { readFileSync } from \"node:fs\";\r\nimport { resolve, join } from \"node:path\";\r\nimport type { CodegenFileResult } from \"./codegen\";\r\n\r\n/**\r\n * QUIKTR-1045 \u2014 codegen importing a package the repository doesn't have currently fails safely\r\n * (setup already ran, so the package genuinely isn't installed, and the regression check catches\r\n * the resulting test failure) but with the WRONG diagnosis: it reads as \"the generated logic is\r\n * broken\" when the real problem is a fabricated import. This names that failure correctly instead.\r\n *\r\n * Only a minimal regex import-scanner \u2014 not a real JS/TS parser. Same reasoning\r\n * `regressionCheck.ts` already states for its own hand-rolled JUnit scanner: this package is\r\n * dependency-free on purpose (published outside the monorepo, bundled into a single CLI file with\r\n * no externals \u2014 see build.mjs), so a real parser is off the table, not merely unused.\r\n *\r\n * Explicitly scoped to JS/TS: it only acts when a `package.json` is found. A repo in another\r\n * language has none, `readDeclaredDependencies` returns null, and the check no-ops \u2014 this is what\r\n * keeps it from looking like a general \"detect the repo's language\" mechanism, which it isn't.\r\n */\r\nexport interface DependencyViolation {\r\n file: string;\r\n packages: string[];\r\n}\r\n\r\nexport interface DependencyCheck {\r\n blocked: boolean;\r\n violations: DependencyViolation[];\r\n}\r\n\r\nconst SCANNABLE_EXTENSIONS = [\".ts\", \".tsx\", \".js\", \".jsx\", \".mjs\", \".cjs\", \".mts\", \".cts\"];\r\n\r\n// import ... from \"x\" / import \"x\" / export ... from \"x\" / require(\"x\") / import(\"x\")\r\nconst IMPORT_RE = /(?:\\bimport\\b[^'\"]*?\\bfrom\\s*|\\bimport\\s*\\(\\s*|\\bexport\\b[^'\"]*?\\bfrom\\s*|\\brequire\\s*\\(\\s*|\\bimport\\s+)(['\"])([^'\"]+)\\1/g;\r\n\r\n// Not exhaustive \u2014 same \"minimal, not exhaustive\" treatment regressionCheck.ts's own scanner uses.\r\nconst NODE_BUILTINS = new Set([\r\n \"assert\", \"buffer\", \"child_process\", \"cluster\", \"crypto\", \"dgram\", \"dns\", \"domain\", \"events\",\r\n \"fs\", \"http\", \"http2\", \"https\", \"net\", \"os\", \"path\", \"perf_hooks\", \"process\", \"punycode\",\r\n \"querystring\", \"readline\", \"repl\", \"stream\", \"string_decoder\", \"sys\", \"timers\", \"tls\", \"tty\",\r\n \"url\", \"util\", \"v8\", \"vm\", \"worker_threads\", \"zlib\", \"inspector\", \"async_hooks\",\r\n]);\r\n\r\n// QUIKTR-1063 \u2014 the two path-alias conventions common enough to assume even\r\n// when a repo's tsconfig can't be read or parsed: \"@/...\" (QuikTrack,\r\n// QuikChat, and most of this monorepo's own apps) and \"~/...\". Without this,\r\n// \"@/lib/x\" was parsed as the scoped package \"@/lib\" \u2014 a real package.json\r\n// entry it could never actually match \u2014 and every aliased import in a repo\r\n// using either convention was reported as an invented dependency.\r\n//\r\n// QUIKTR-1068 \u2014 this is now a FLOOR, not the whole answer: `resolveAliasPrefixes`\r\n// below adds whatever a real tsconfig.json/jsconfig.json actually declares in\r\n// `compilerOptions.paths`, for repos using some other convention entirely.\r\n// Always unioned in regardless of what a config says, so a repo with no\r\n// config (or an unparseable one) keeps exactly today's behavior.\r\nconst DEFAULT_ALIAS_PREFIXES = [\"@/\", \"~/\"];\r\n\r\nfunction packageNameFromSpecifier(specifier: string, aliasPrefixes: string[] = DEFAULT_ALIAS_PREFIXES): string | null {\r\n if (specifier.startsWith(\".\") || specifier.startsWith(\"/\")) return null; // relative/absolute\r\n if (specifier.startsWith(\"node:\")) return null; // explicit builtin\r\n if (aliasPrefixes.some((prefix) => specifier.startsWith(prefix))) return null; // path alias\r\n const segments = specifier.split(\"/\");\r\n const name = specifier.startsWith(\"@\") ? segments.slice(0, 2).join(\"/\") : segments[0];\r\n if (NODE_BUILTINS.has(name)) return null;\r\n return name;\r\n}\r\n\r\nfunction scanImports(source: string, aliasPrefixes: string[] = DEFAULT_ALIAS_PREFIXES): string[] {\r\n const found = new Set<string>();\r\n let match: RegExpExecArray | null;\r\n IMPORT_RE.lastIndex = 0;\r\n while ((match = IMPORT_RE.exec(source))) {\r\n const name = packageNameFromSpecifier(match[2], aliasPrefixes);\r\n if (name) found.add(name);\r\n }\r\n return [...found];\r\n}\r\n\r\n/** Pure \u2014 no fs, trivially unit-testable. `declaredDependencies === null` means \"couldn't tell\r\n * what this repo declares\" (no package.json, or unparseable) \u2014 the check no-ops rather than\r\n * blocking on a question it can't actually answer. `aliasPrefixes` defaults to the floor above;\r\n * callers with a real tsconfig read (see `resolveAliasPrefixes`) pass the fuller list. */\r\nexport function checkImportDependencies(\r\n results: CodegenFileResult[],\r\n declaredDependencies: Set<string> | null,\r\n aliasPrefixes: string[] = DEFAULT_ALIAS_PREFIXES,\r\n): DependencyCheck {\r\n if (!declaredDependencies) return { blocked: false, violations: [] };\r\n\r\n const violations: DependencyViolation[] = [];\r\n for (const { targetPath, newContent } of results) {\r\n if (!SCANNABLE_EXTENSIONS.some((ext) => targetPath.endsWith(ext))) continue;\r\n const invented = scanImports(newContent, aliasPrefixes).filter((pkg) => !declaredDependencies.has(pkg));\r\n if (invented.length > 0) violations.push({ file: targetPath, packages: invented });\r\n }\r\n return { blocked: violations.length > 0, violations };\r\n}\r\n\r\ninterface PackageJson {\r\n dependencies?: Record<string, string>;\r\n devDependencies?: Record<string, string>;\r\n peerDependencies?: Record<string, string>;\r\n}\r\n\r\nfunction dependencyNames(pkg: PackageJson): Set<string> {\r\n // devDependencies included deliberately \u2014 a generated test file may legitimately import one.\r\n return new Set([\r\n ...Object.keys(pkg.dependencies ?? {}),\r\n ...Object.keys(pkg.devDependencies ?? {}),\r\n ...Object.keys(pkg.peerDependencies ?? {}),\r\n ]);\r\n}\r\n\r\n/**\r\n * Reads the target repo's declared dependencies. Checks `results` FIRST for a generated\r\n * `package.json` \u2014 codegen may have legitimately added the very dependency it's about to import,\r\n * and reading the pre-generation file on disk would false-flag that. Falls back to the on-disk\r\n * file, and to `null` (\u2192 the check no-ops) when neither exists or parses.\r\n */\r\nexport function readDeclaredDependencies(\r\n results: CodegenFileResult[],\r\n workspaceRoot: string | null,\r\n): Set<string> | null {\r\n const packageJsonPath = join(resolve(workspaceRoot ?? \".\"), \"package.json\");\r\n const generated = results.find((r) => resolve(r.targetPath) === packageJsonPath);\r\n\r\n let raw: string | null;\r\n if (generated) {\r\n raw = generated.newContent;\r\n } else {\r\n try {\r\n raw = readFileSync(packageJsonPath, \"utf8\");\r\n } catch {\r\n raw = null;\r\n }\r\n }\r\n if (raw === null) return null;\r\n\r\n try {\r\n return dependencyNames(JSON.parse(raw) as PackageJson);\r\n } catch {\r\n return null;\r\n }\r\n}\r\n\r\n/**\r\n * QUIKTR-1068 \u2014 strips line and block comments plus trailing commas from a JSON(C) string, best\r\n * effort. Not a real JSONC parser: a character scanner rather than a regex replace (a regex would\r\n * corrupt a string VALUE containing `//`, e.g. a URL), but anything it can't cleanly handle just\r\n * fails `JSON.parse` afterward \u2014 `resolveAliasPrefixes` below treats that the same as no config at\r\n * all and falls back to the floor. Never throws itself.\r\n */\r\nfunction stripJsonComments(text: string): string {\r\n let out = \"\";\r\n let inString = false;\r\n let inLineComment = false;\r\n let inBlockComment = false;\r\n for (let i = 0; i < text.length; i++) {\r\n const c = text[i];\r\n const next = text[i + 1];\r\n if (inLineComment) {\r\n if (c === \"\\n\") {\r\n inLineComment = false;\r\n out += c;\r\n }\r\n continue;\r\n }\r\n if (inBlockComment) {\r\n if (c === \"*\" && next === \"/\") {\r\n inBlockComment = false;\r\n i++;\r\n }\r\n continue;\r\n }\r\n if (inString) {\r\n out += c;\r\n if (c === \"\\\\\") {\r\n out += next;\r\n i++;\r\n continue;\r\n }\r\n if (c === '\"') inString = false;\r\n continue;\r\n }\r\n if (c === '\"') {\r\n inString = true;\r\n out += c;\r\n continue;\r\n }\r\n if (c === \"/\" && next === \"/\") {\r\n inLineComment = true;\r\n i++;\r\n continue;\r\n }\r\n if (c === \"/\" && next === \"*\") {\r\n inBlockComment = true;\r\n i++;\r\n continue;\r\n }\r\n out += c;\r\n }\r\n return out.replace(/,(\\s*[}\\]])/g, \"$1\");\r\n}\r\n\r\ninterface TsOrJsConfig {\r\n compilerOptions?: { paths?: Record<string, unknown> };\r\n}\r\n\r\n/**\r\n * QUIKTR-1068 \u2014 `DEFAULT_ALIAS_PREFIXES` is a floor, not the whole answer: a repo may declare its\r\n * own alias conventions in `compilerOptions.paths`. Tries `tsconfig.json` then `jsconfig.json` at\r\n * the workspace root (same results-first-then-disk precedence as `readDeclaredDependencies` \u2014 a\r\n * generated config this run legitimately wrote should win over a stale on-disk one), unions any\r\n * `paths` keys (wildcard stripped: `\"@/*\"` \u2192 `\"@/\"`) with the floor, and dedupes. Never throws and\r\n * never returns fewer than the floor \u2014 an unreadable or malformed config is exactly the same as no\r\n * config, not a reason to block a run that could otherwise pass.\r\n *\r\n * Does NOT follow `extends` \u2014 only the root config's own `paths`, same \"minimal, not exhaustive\"\r\n * boundary this file already draws elsewhere (see the module docblock).\r\n */\r\nexport function resolveAliasPrefixes(\r\n results: CodegenFileResult[],\r\n workspaceRoot: string | null,\r\n): string[] {\r\n const root = resolve(workspaceRoot ?? \".\");\r\n\r\n for (const filename of [\"tsconfig.json\", \"jsconfig.json\"]) {\r\n const configPath = join(root, filename);\r\n const generated = results.find((r) => resolve(r.targetPath) === configPath);\r\n\r\n let raw: string | null;\r\n if (generated) {\r\n raw = generated.newContent;\r\n } else {\r\n try {\r\n raw = readFileSync(configPath, \"utf8\");\r\n } catch {\r\n raw = null;\r\n }\r\n }\r\n if (raw === null) continue;\r\n\r\n try {\r\n const parsed = JSON.parse(stripJsonComments(raw)) as TsOrJsConfig;\r\n const paths = parsed.compilerOptions?.paths;\r\n const fromConfig =\r\n paths && typeof paths === \"object\"\r\n ? Object.keys(paths).map((k) => (k.endsWith(\"*\") ? k.slice(0, -1) : k))\r\n : [];\r\n return [...new Set([...DEFAULT_ALIAS_PREFIXES, ...fromConfig])];\r\n } catch {\r\n continue; // malformed \u2014 try the next config file, or fall through to the floor\r\n }\r\n }\r\n\r\n return DEFAULT_ALIAS_PREFIXES;\r\n}\r\n\r\n/** Regressions and new failures named separately elsewhere in this package for the same reason\r\n * this exists at all: conflating diagnoses wastes someone's morning. */\r\nexport function describeDependencyViolations(check: DependencyCheck): string {\r\n return check.violations\r\n .map((v) => `${v.file} imports ${v.packages.join(\", \")}, not a dependency of this repository`)\r\n .join(\"; \");\r\n}\r\n", "import { addAll, diffCachedNamesMatching } from \"./git\";\r\n\r\n/** Stages everything, then refuses to proceed if any staged file matches a denied-path glob.\r\n * Public and inspectable on purpose (Suyash, 2026-09-10): moving this into a published package\r\n * doesn't hide the enforcement \u2014 it's the same check, just no longer duplicated per customer repo. */\r\nexport function checkGuardrail(deniedPaths: string[]): void {\r\n addAll();\r\n const violations = deniedPaths.flatMap((pattern) => diffCachedNamesMatching(pattern));\r\n if (violations.length > 0) {\r\n throw new Error(`QuikPilot touched denied paths:\\n${violations.join(\"\\n\")}`);\r\n }\r\n}\r\n", "import { describeQuikTrackFailure } from \"./quiktrackError\";\r\n\r\ninterface InstallationTokenResponse {\r\n success: boolean;\r\n data: { token: string; expiresAt: string };\r\n}\r\n\r\n/** Exchange the QuikPilot run token for a repo-scoped GitHub installation token (QUIKTR-804) \u2014\r\n * mirrors `tokenExchange.ts`'s `exchangeForRunToken` shape: bearer auth, `{success,data}`\r\n * envelope, same error-message style. */\r\nexport async function exchangeForInstallationToken(\r\n installationTokenUrl: string,\r\n runToken: string,\r\n): Promise<string> {\r\n const res = await fetch(installationTokenUrl, {\r\n method: \"POST\",\r\n headers: { Authorization: `Bearer ${runToken}` },\r\n });\r\n if (!res.ok) {\r\n throw new Error(`Exchange installation token failed: ${await describeQuikTrackFailure(res)}`);\r\n }\r\n const body = (await res.json()) as InstallationTokenResponse;\r\n if (body.success !== true) {\r\n throw new Error(\"Exchange installation token failed: response did not carry success:true\");\r\n }\r\n return body.data.token;\r\n}\r\n", "import { required } from \"./env\";\r\n\r\n/** Must equal `apps/quiktrack/lib/services/github/oidc.ts`'s own copy of this literal \u2014 that app\r\n * verifies the token this package requests. Duplicated because this package is published outside\r\n * the monorepo and cannot import from the app; same reasoning `packet.ts`'s header gives for\r\n * duplicating `PilotPacket`'s shape. */\r\nconst QUIKPILOT_OIDC_AUDIENCE = \"quiktrack-quikpilot\";\r\n\r\ninterface OidcTokenResponse {\r\n value: string;\r\n}\r\n\r\n/** Request a GitHub Actions OIDC ID token \u2014 the runner's proof of identity, exchanged at\r\n * `TOKEN_URL` for a QuikPilot run token (QUIKTR-805). `ACTIONS_ID_TOKEN_REQUEST_URL` and\r\n * `ACTIONS_ID_TOKEN_REQUEST_TOKEN` are ambient GitHub Actions env vars, present only because the\r\n * generated workflow declares `permissions: id-token: write` \u2014 no dispatch input carries them. */\r\nexport async function fetchGithubOidcToken(\r\n env: NodeJS.ProcessEnv = process.env,\r\n): Promise<string> {\r\n const requestUrl = required(\r\n \"ACTIONS_ID_TOKEN_REQUEST_URL\",\r\n env.ACTIONS_ID_TOKEN_REQUEST_URL,\r\n );\r\n const requestToken = required(\r\n \"ACTIONS_ID_TOKEN_REQUEST_TOKEN\",\r\n env.ACTIONS_ID_TOKEN_REQUEST_TOKEN,\r\n );\r\n const separator = requestUrl.includes(\"?\") ? \"&\" : \"?\";\r\n const url = `${requestUrl}${separator}audience=${encodeURIComponent(QUIKPILOT_OIDC_AUDIENCE)}`;\r\n const res = await fetch(url, {\r\n headers: { Authorization: `Bearer ${requestToken}` },\r\n });\r\n if (!res.ok) {\r\n throw new Error(`Fetch GitHub OIDC token failed: ${res.status} ${res.statusText}`);\r\n }\r\n const body = (await res.json()) as OidcTokenResponse;\r\n if (!body.value) {\r\n throw new Error(\"GitHub OIDC token response carried no value\");\r\n }\r\n return body.value;\r\n}\r\n", "import { describeQuikTrackFailure } from \"./quiktrackError\";\r\n\r\n/** Mirrors `apps/quiktrack/lib/services/pilot/packet.ts`'s `PilotPacket` shape. Duplicated rather\r\n * than imported \u2014 this package is published outside the monorepo and cannot depend on the app. */\r\nexport interface PilotPacket {\r\n runId: string;\r\n issueKey: string | null;\r\n /** QUIKTR-1067 \u2014 same nullability as issueKey, for the same reason: the commit message needs\r\n * both to say what actually changed instead of the hardcoded \"Phase 0 skeleton\" placeholder. */\r\n issueTitle: string | null;\r\n branch: string | null;\r\n targetBranch: string | null;\r\n /** QUIKTR-1033 \u2014 the subtree targeting (QUIKTR-1035) lists files under. Null means the\r\n * repository root, as null \u2014 never normalised to \".\". */\r\n workspaceRoot: string | null;\r\n commands: {\r\n setup: string | null;\r\n test: string | null;\r\n e2e: string | null;\r\n lint: string | null;\r\n /** QUIKTR-1045 \u2014 run after codegen flushes, before lint. Soft failure. */\r\n format: string | null;\r\n /** QUIKTR-1402 \u2014 runs ONE test file (path appended, or substituted for `{file}`) against the untouched\r\n * code, for the baseline check. Optional: an older QuikTrack omits it. Null/absent turns the check off. */\r\n testFile?: string | null;\r\n };\r\n guardrails: {\r\n deniedPaths: string[];\r\n maxHealIterations: number;\r\n maxWallClockMinutes: number;\r\n // No maxRunUsd \u2014 it travels as a claim on gateway.token instead (QUIKTR-823).\r\n };\r\n /** Where to call for AI codegen, and the credential that authorizes it. */\r\n gateway: {\r\n baseUrl: string;\r\n token: string;\r\n };\r\n /** The pilot.design technical design, as context for codegen. No file paths \u2014 see the app's\r\n * spec-contract.ts. Null only in theory (dispatch requires a design to already exist). */\r\n design: {\r\n rootCause: string;\r\n approach: string;\r\n /** Mirrors `apps/quiktrack/lib/services/pilot/spec-contract.ts`'s `PilotApiChange`. */\r\n apiChanges: { surface: string; change: string; reason: string }[];\r\n riskLevel: \"LOW\" | \"MEDIUM\" | \"HIGH\";\r\n riskRationale: string;\r\n } | null;\r\n quikTest: { testRunId: string; resultsUrl: string } | null;\r\n /** QUIKTR-1065 \u2014 the approved test cases codegen still owes real test code for. Sent to\r\n * pilot.targeting so it can propose a test-file target naming which cases it covers; today\r\n * nothing reads this field yet (the AI Runtime side isn't built), so it always arrives as `[]`\r\n * or is silently unused once wired up here. */\r\n requiredTests: {\r\n automationId: string;\r\n title: string;\r\n covers: string[];\r\n given: string | null;\r\n when: string | null;\r\n then: string | null;\r\n }[];\r\n /** QUIKTR-1402 \u2014 automationId -> the case's current type (FUNCTIONAL, NEGATIVE, REGRESSION, \u2026), only for\r\n * cases whose AI-assigned label QuikTrack recorded. Optional: an older QuikTrack omits it. A case that is\r\n * absent here is UNKNOWN and is never checked; REGRESSION is exempt. DELIBERATELY not a field of\r\n * `requiredTests`: those objects are forwarded to the AI Runtime as-is, and an unknown key on the\r\n * versioned path is refused CONTRACT_REJECTED. Nothing in this map may ever be sent to the runtime. */\r\n requiredTestTypes?: Record<string, string>;\r\n /** QUIKTR-1401 \u2014 the reviewer's approved \"things QuikPilot must not change\" list. Optional: a\r\n * QuikTrack that predates the field omits it. Forwarded to pilot.targeting and pilot.codegen (\u00A720,\r\n * deployed by the AI Runtime 2026-10-01) when non-empty, never to pilot.design. Free text, so unlike\r\n * `deniedPaths` it can only be told to the model, not checked. */\r\n outOfScope?: string[];\r\n /** QUIKTR-1315, \u00A719 of the AI Runtime contract (AGREED, final tagged shape) \u2014 the repo-relative\r\n * files the last DONE run's own ingested JUnit report named, sourced from stored QuikTest data,\r\n * not a live baseline capture here. Always present (never undefined) \u2014 \u00A719.12: a project with no\r\n * prior DONE run's report is `{ report: \"ABSENT\" }`, not an omitted field. `{ report: \"PRESENT\" }`\r\n * with an empty `discoveredTestFiles` is a different, real fact: a report was ingested but\r\n * nothing in it was path-shaped. See targeting.ts for how this is forwarded. */\r\n testDiscovery:\r\n | { report: \"PRESENT\"; discoveredTestFiles: string[]; unmappedEntries: number }\r\n | { report: \"ABSENT\" };\r\n}\r\n\r\ninterface PacketResponse {\r\n success: boolean;\r\n data: PilotPacket;\r\n}\r\n\r\n/** GET the run's work packet. Bearer auth via the run token, matching the header curl sent on\r\n * stdin (`--config -`) so it never showed up in `ps` \u2014 an HTTP client's header option is already\r\n * invisible to `ps`, so no equivalent trick is needed here. */\r\nexport async function fetchPacket(\r\n packetUrl: string,\r\n runToken: string,\r\n githubRunId: string,\r\n): Promise<PilotPacket> {\r\n const url = `${packetUrl}?githubRunId=${encodeURIComponent(githubRunId)}`;\r\n const res = await fetch(url, {\r\n headers: { Authorization: `Bearer ${runToken}` },\r\n });\r\n if (!res.ok) {\r\n throw new Error(`Fetch work packet failed: ${await describeQuikTrackFailure(res)}`);\r\n }\r\n const body = (await res.json()) as PacketResponse;\r\n if (body.success !== true) {\r\n throw new Error(\"Fetch work packet failed: response did not carry success:true\");\r\n }\r\n return body.data;\r\n}\r\n", "import { appendFileSync, mkdirSync } from \"node:fs\";\r\n\r\n/** Phase 0 has no agent. This proves the loop end to end without touching real source, which would\r\n * risk breaking the build for a reason nobody would connect back to QuikPilot. Verbatim carry-over\r\n * from the inlined workflow \u2014 real codegen is separate, not-yet-built work. */\r\nexport function writePhase0Marker(runId: string): void {\r\n mkdirSync(\".quikpilot\", { recursive: true });\r\n appendFileSync(\".quikpilot/phase0-marker.txt\", `QuikPilot Phase 0 skeleton marker for run ${runId}\\n`);\r\n}\r\n", "import { readFileSync, readdirSync, rmSync, statSync } from \"node:fs\";\r\nimport { join } from \"node:path\";\r\n\r\nconst SKIP_DIRS = new Set([\"node_modules\", \".git\"]);\r\n\r\nfunction walkForJUnitByName(dir: string): string | null {\r\n let entries: string[];\r\n try {\r\n entries = readdirSync(dir);\r\n } catch {\r\n return null;\r\n }\r\n for (const entry of entries) {\r\n if (SKIP_DIRS.has(entry)) continue;\r\n const full = join(dir, entry);\r\n let stat;\r\n try {\r\n stat = statSync(full);\r\n } catch {\r\n continue;\r\n }\r\n if (stat.isDirectory()) {\r\n const found = walkForJUnitByName(full);\r\n if (found) return found;\r\n } else if (/^junit.*\\.xml$/.test(entry)) {\r\n return full;\r\n }\r\n }\r\n return null;\r\n}\r\n\r\nfunction firstXmlIn(dir: string, namePattern: RegExp): string | null {\r\n let entries: string[];\r\n try {\r\n entries = readdirSync(dir);\r\n } catch {\r\n return null;\r\n }\r\n const match = entries.find((e) => namePattern.test(e));\r\n return match ? join(dir, match) : null;\r\n}\r\n\r\n/** The test report as bytes, or null when there is none or it cannot be read. QUIKTR-1447 takes a copy for a failed\r\n * run BEFORE `reportToQuikTest` sends and deletes it. */\r\nexport function readTestReportBytes(cwd = process.cwd()): Buffer | null {\r\n try {\r\n const report = findJUnitReport(cwd);\r\n return report ? readFileSync(report) : null;\r\n } catch {\r\n return null;\r\n }\r\n}\r\n\r\n/** QtPilotConfig has no column for the report path, so this is a convention over a short list of\r\n * common locations rather than a configurable setting. A project that writes its report elsewhere\r\n * reports nothing and finds out from the log \u2014 a missing artefact must not fail the run. Checked\r\n * in the same priority the original `find` clause listed them, though exact traversal order was\r\n * never guaranteed there either. */\r\nexport function findJUnitReport(cwd = process.cwd()): string | null {\r\n return (\r\n walkForJUnitByName(cwd) ??\r\n firstXmlIn(join(cwd, \"test-results\"), /\\.xml$/) ??\r\n firstXmlIn(join(cwd, \"reports\"), /^junit.*\\.xml$/) ??\r\n firstXmlIn(join(cwd, \"target\", \"surefire-reports\"), /\\.xml$/)\r\n );\r\n}\r\n\r\nfunction buildCiUrl(serverUrl: string, repository: string, githubRunId: string): string {\r\n return `${serverUrl}/${repository}/actions/runs/${githubRunId}`;\r\n}\r\n\r\n/** The ingest route's summary of automationIds present in the JUnit report that matched no\r\n * `QtTestCase` \u2014 computed and returned by QuikTrack's own ingest today (`IngestSummary.unmatched`\r\n * in `apps/quiktrack/lib/services/testIngest.ts`), but silently discarded here until QUIKTR-1374:\r\n * a bracket/format mismatch (or any other ingest failure) produced zero matches on every run with\r\n * nothing on screen to say why. */\r\nexport interface ReportToQuikTestResult {\r\n unmatched: Array<{ automationId: string; count: number }>;\r\n}\r\n\r\n/** One warning naming every unmatched id and its count \u2014 `null` when there's nothing to report,\r\n * so the caller can push straight into `warnings` without an extra length check. */\r\nexport function describeUnmatchedAutomationIds(unmatched: ReportToQuikTestResult[\"unmatched\"]): string | null {\r\n if (unmatched.length === 0) return null;\r\n const named = unmatched.map((u) => `${u.automationId} (\u00D7${u.count})`).join(\", \");\r\n return `${unmatched.length} generated test result(s) did not match any test case: ${named} \u2014 check the automationId format.`;\r\n}\r\n\r\n/** Best-effort \u2014 every branch here is designed to never throw, matching the bash step's own\r\n * `if: always()` + internally tolerant logic (null resultsUrl and \"no report found\" are both the\r\n * common path in Phase 0, not edge cases \u2014 D19). Deletes the report after a successful POST so the\r\n * guardrail's `git add -A` never commits a CI artefact into the customer's pull request. Returns\r\n * `null` whenever nothing was actually reported (no results URL, no report found, or the POST\r\n * itself failed) \u2014 the caller folds a non-null `unmatched` array into the run's warnings. */\r\nexport async function reportToQuikTest(params: {\r\n resultsUrl: string | null | undefined;\r\n runToken: string;\r\n githubServerUrl: string;\r\n githubRepository: string;\r\n githubRunId: string;\r\n /** QUIKTR-1333 \u2014 the files QuikPilot actually generated or edited this run. Scopes QuikTrack's\r\n * unmatched-automationId warning to just these, so a repository's own pre-existing tests (which\r\n * can never carry a QuikPilot id) stop being reported as unmatched on every single run.\r\n * `undefined` = no scoping information (the server keeps its unfiltered behavior). An EMPTY\r\n * array is a real answer \u2014 codegen produced nothing (it failed, or there was no target) \u2014 and is\r\n * sent as an empty parameter so the server scopes to nothing instead of falling back. */\r\n generatedFiles?: string[];\r\n cwd?: string;\r\n}): Promise<ReportToQuikTestResult | null> {\r\n const { resultsUrl, runToken, githubServerUrl, githubRepository, githubRunId, generatedFiles, cwd } = params;\r\n if (!resultsUrl) {\r\n console.log(\"packet.quikTest is null \u2014 this run has no QuikTest run to report into.\");\r\n return null;\r\n }\r\n const report = findJUnitReport(cwd);\r\n if (!report) {\r\n console.warn(\"::warning::QuikPilot found no JUnit report \u2014 no results reported to QuikTest.\");\r\n return null;\r\n }\r\n try {\r\n console.log(`reporting ${report}`);\r\n const ciUrl = buildCiUrl(githubServerUrl, githubRepository, githubRunId);\r\n const { readFileSync } = await import(\"node:fs\");\r\n const body = readFileSync(report);\r\n // QUIKTR-1082 \u2014 this runner is the only caller QuikPilot controls; requesting \"bracket\"\r\n // explicitly here changes nothing for any other QuikTest customer's own ingestion.\r\n let url = `${resultsUrl}?ciUrl=${encodeURIComponent(ciUrl)}&automationIdFormat=bracket`;\r\n // QUIKTR-1333 \u2014 optional: an old runner or a human's manual upload (the sibling route) never\r\n // sends this, and the server falls back to today's unfiltered behavior either way. Sent even\r\n // when empty: \"generated nothing\" must not be mistaken for \"no information\".\r\n if (generatedFiles) {\r\n url += `&generatedFiles=${encodeURIComponent(generatedFiles.join(\",\"))}`;\r\n }\r\n const res = await fetch(url, {\r\n method: \"POST\",\r\n headers: { Authorization: `Bearer ${runToken}`, \"Content-Type\": \"text/xml\" },\r\n body,\r\n });\r\n if (!res.ok) {\r\n throw new Error(`QuikTest report POST failed: ${res.status} ${res.statusText}`);\r\n }\r\n rmSync(report, { force: true });\r\n // QUIKTR-1374 \u2014 read the ingest summary instead of discarding it. Best-effort: the POST\r\n // itself already succeeded (res.ok), so a body that isn't the expected JSON shape must never\r\n // turn a working report into a failure \u2014 it just means no warning can be derived from it.\r\n let unmatched: ReportToQuikTestResult[\"unmatched\"] = [];\r\n try {\r\n const json = (await res.json()) as { data?: { unmatched?: ReportToQuikTestResult[\"unmatched\"] } };\r\n unmatched = json.data?.unmatched ?? [];\r\n } catch {\r\n // Not JSON, or not the expected shape \u2014 leave unmatched empty.\r\n }\r\n return { unmatched };\r\n } catch (err) {\r\n console.warn(`::warning::QuikPilot failed to report results to QuikTest: ${err instanceof Error ? err.message : String(err)}`);\r\n return null;\r\n }\r\n}\r\n", "import { execFileSync } from \"node:child_process\";\r\nimport { existsSync, mkdirSync, readFileSync, rmSync, rmdirSync, statSync, writeFileSync } from \"node:fs\";\r\nimport { dirname, isAbsolute, relative, resolve } from \"node:path\";\r\nimport type { CodegenFileResult } from \"./codegen\";\r\nimport { runCommandWithTimeout, type TimedRunOutcome } from \"./commands\";\r\nimport { findJUnitReport } from \"./quiktest\";\r\nimport { readAutomationIdResults } from \"./regressionCheck\";\r\nimport type { PilotTarget } from \"./targeting\";\r\n\r\n/**\r\n * QUIKTR-1402 \u2014 the baseline check.\r\n *\r\n * A spec can contain a case that asserts something ALREADY TRUE before any change (\"the server route\r\n * remains unchanged\"); no test can satisfy it, and a phrase list cannot catch the next phrasing. What every\r\n * such case shares is not wording but behaviour: its generated test PASSES on the unmodified code. So,\r\n * after codegen and before anything is written for real, this writes ONLY the generated test files, runs\r\n * each one alone against the untouched code, flags a non-Regression case whose test passed, and puts\r\n * everything back. A Regression case is meant to pass there, so it is exempt.\r\n *\r\n * It FLAGS and never blocks: a no-op change is legitimate, and an unsatisfiable case is a spec problem a\r\n * person should see rather than a run that dies. Every uncertain outcome therefore means \"no flag\", and\r\n * every one of them is said out loud (a silent timeout would look exactly like a check that found nothing).\r\n *\r\n * Unknown is never flagged: only a case whose label QuikTrack recorded (`requiredTestTypes`) is checked,\r\n * so anything approved before the label was kept, and any label we did not recognise, is left alone.\r\n */\r\n\r\n/**\r\n * How long one single-file run may take before it is stopped. A constant, not a setting (Suyash): one more\r\n * knob is one more thing to get wrong, and nobody has the information to tune it. Measured on QuikTrack and\r\n * QuikChat, one file takes 2 to 5 seconds warm and up to ~14 seconds on a cold start; two minutes is far\r\n * outside that and only ever reached by a command that hangs, which produces no error and would otherwise\r\n * hold the run until the job's own limit while looking like QuikPilot being slow.\r\n */\r\nexport const BASELINE_CHECK_TIMEOUT_MS = 120_000;\r\n\r\nexport interface BaselineFindings {\r\n /** ALREADY_TRUE: the change altered the code but the case still passed before it. NO_OP: every file the\r\n * change edited came out unchanged. The check cannot tell the two apart for certain; the wording hedges. */\r\n cause: \"ALREADY_TRUE\" | \"NO_OP\";\r\n /** Case ids only \u2014 QuikTrack looks the titles up itself, so case text never travels. */\r\n automationIds: string[];\r\n}\r\n\r\nexport interface BaselineCheckResult {\r\n findings: BaselineFindings | null;\r\n /** Run-record sentences: a finding, or a reason the check could not give an answer. */\r\n warnings: string[];\r\n}\r\n\r\nexport interface BaselineCheckParams {\r\n targets: PilotTarget[];\r\n results: CodegenFileResult[];\r\n testFileCmd: string | null | undefined;\r\n /** automationId -> the case's current type, only for cases whose label is known. */\r\n requiredTestTypes: Record<string, string> | undefined;\r\n cwd?: string;\r\n /** Test seam: the real one spawns bash with a hard time limit. */\r\n runFile?: (command: string, timeoutMs: number) => Promise<TimedRunOutcome>;\r\n}\r\n\r\n/** POSIX single-quoting: the path is chosen by the model, so it must never be able to inject a command. */\r\nexport function shellQuote(value: string): string {\r\n return `'${value.split(\"'\").join(\"'\\\\''\")}'`;\r\n}\r\n\r\n/** `{file}` is replaced wherever it appears; with no placeholder the path is appended as the last argument. */\r\nexport function buildSingleFileCommand(command: string, path: string): string {\r\n const quoted = shellQuote(path);\r\n return command.includes(\"{file}\") ? command.split(\"{file}\").join(quoted) : `${command} ${quoted}`;\r\n}\r\n\r\nconst isTestTarget = (t: PilotTarget): boolean => (t.automationIds?.length ?? 0) > 0;\r\n\r\n/** A case is checked only if its label is KNOWN and is not Regression (which is supposed to pass). */\r\nfunction checkableIds(ids: string[], types: Record<string, string> | undefined): string[] {\r\n if (!types) return [];\r\n return ids.filter((id) => {\r\n if (!Object.prototype.hasOwnProperty.call(types, id)) return false;\r\n const type = types[id];\r\n return typeof type === \"string\" && type.trim() !== \"\" && type.trim().toUpperCase() !== \"REGRESSION\";\r\n });\r\n}\r\n\r\n/** Absolute path inside the checkout, or null when the target would land outside it. */\r\nfunction insideCheckout(cwd: string, path: string): string | null {\r\n const abs = resolve(cwd, path);\r\n const rel = relative(cwd, abs);\r\n return rel === \"\" || rel.startsWith(\"..\") || isAbsolute(rel) ? null : abs;\r\n}\r\n\r\ninterface WrittenFile {\r\n abs: string;\r\n /** null when the file did not exist before. */\r\n original: Buffer | null;\r\n /** Directories this check had to create, outermost first. */\r\n createdDirs: string[];\r\n}\r\n\r\nfunction writeForCheck(abs: string, content: string): WrittenFile {\r\n const original = existsSync(abs) ? readFileSync(abs) : null;\r\n const createdDirs: string[] = [];\r\n if (original === null) {\r\n const missing: string[] = [];\r\n for (let d = dirname(abs); !existsSync(d); d = dirname(d)) missing.push(d);\r\n for (const d of missing.reverse()) {\r\n mkdirSync(d);\r\n createdDirs.push(d);\r\n }\r\n }\r\n writeFileSync(abs, content);\r\n return { abs, original, createdDirs };\r\n}\r\n\r\nfunction restore(written: WrittenFile[]): void {\r\n for (const file of [...written].reverse()) {\r\n try {\r\n if (file.original !== null) writeFileSync(file.abs, file.original);\r\n else rmSync(file.abs, { force: true });\r\n for (const d of [...file.createdDirs].reverse()) {\r\n try {\r\n rmdirSync(d);\r\n } catch {\r\n // not empty or already gone \u2014 leave it\r\n }\r\n }\r\n } catch (err) {\r\n console.error(`Baseline check could not restore ${file.abs}: ${err instanceof Error ? err.message : String(err)}`);\r\n }\r\n }\r\n}\r\n\r\n/** Untracked, non-ignored files \u2014 exactly what the guardrail's `git add -A` would commit. `null` when git\r\n * cannot say, in which case nothing is cleaned up rather than guessing. */\r\nfunction untrackedFiles(cwd: string): Set<string> | null {\r\n try {\r\n const out = execFileSync(\"git\", [\"ls-files\", \"--others\", \"--exclude-standard\", \"-z\"], {\r\n cwd,\r\n encoding: \"utf8\",\r\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\r\n maxBuffer: 64 * 1024 * 1024,\r\n });\r\n return new Set(out.split(\"\\0\").filter(Boolean));\r\n } catch {\r\n return null;\r\n }\r\n}\r\n\r\nconst mtimeOf = (path: string): number | null => {\r\n try {\r\n return statSync(path).mtimeMs;\r\n } catch {\r\n return null;\r\n }\r\n};\r\n\r\n/** NO_OP only when there is code to compare and every file the change edits came out exactly as it was. */\r\nfunction decideCause(targets: PilotTarget[], results: Map<string, string>, cwd: string): BaselineFindings[\"cause\"] {\r\n const codeTargets = targets.filter((t) => !isTestTarget(t));\r\n if (codeTargets.length === 0) return \"ALREADY_TRUE\";\r\n for (const t of codeTargets) {\r\n if (t.kind === \"NEW_FILE\") return \"ALREADY_TRUE\";\r\n const next = results.get(t.path);\r\n const abs = insideCheckout(cwd, t.path);\r\n if (next === undefined || abs === null) return \"ALREADY_TRUE\";\r\n try {\r\n if (readFileSync(abs, \"utf8\") !== next) return \"ALREADY_TRUE\";\r\n } catch {\r\n return \"ALREADY_TRUE\";\r\n }\r\n }\r\n return \"NO_OP\";\r\n}\r\n\r\nexport async function runBaselineCheck(params: BaselineCheckParams): Promise<BaselineCheckResult> {\r\n const { targets, results, testFileCmd, requiredTestTypes } = params;\r\n const cwd = params.cwd ?? process.cwd();\r\n const runFile = params.runFile ?? runCommandWithTimeout;\r\n const nothing: BaselineCheckResult = { findings: null, warnings: [] };\r\n\r\n if (!testFileCmd || testFileCmd.trim() === \"\") return nothing;\r\n const testTargets = targets.filter(isTestTarget);\r\n const toCheck = testTargets\r\n .map((target) => ({ target, ids: checkableIds(target.automationIds ?? [], requiredTestTypes) }))\r\n .filter((entry) => entry.ids.length > 0);\r\n if (toCheck.length === 0) {\r\n console.log(\"Baseline check: no case with a known, non-Regression label \u2014 nothing to check.\");\r\n return nothing;\r\n }\r\n\r\n const warnings: string[] = [];\r\n const flagged: string[] = [];\r\n const written: WrittenFile[] = [];\r\n const unsafe = new Set<string>();\r\n const skip = (path: string, why: string) => {\r\n const message = `Baseline check skipped for ${path}: ${why}`;\r\n console.warn(`::warning::${message}`);\r\n warnings.push(message);\r\n };\r\n\r\n try {\r\n const contentByPath = new Map(results.map((r) => [r.targetPath, r.newContent]));\r\n const cause = decideCause(targets, contentByPath, cwd);\r\n\r\n // Only the generated TEST files are written; the code under test stays exactly as it is.\r\n for (const target of testTargets) {\r\n const content = contentByPath.get(target.path);\r\n if (content === undefined) continue;\r\n const abs = insideCheckout(cwd, target.path);\r\n if (abs === null) {\r\n unsafe.add(target.path);\r\n continue;\r\n }\r\n written.push(writeForCheck(abs, content));\r\n }\r\n\r\n for (const { target, ids } of toCheck) {\r\n if (unsafe.has(target.path)) {\r\n skip(target.path, \"the path is outside the checkout, so the file was not written or run.\");\r\n continue;\r\n }\r\n if (!contentByPath.has(target.path)) continue;\r\n\r\n const reportBefore = findJUnitReport(cwd);\r\n const mtimeBefore = reportBefore ? mtimeOf(reportBefore) : null;\r\n const untrackedBefore = untrackedFiles(cwd);\r\n\r\n const outcome = await runFile(buildSingleFileCommand(testFileCmd, target.path), BASELINE_CHECK_TIMEOUT_MS);\r\n\r\n if (outcome === \"timeout\") {\r\n skip(\r\n target.path,\r\n `the single-file command did not finish within ${BASELINE_CHECK_TIMEOUT_MS / 1000} seconds and was stopped. ` +\r\n \"No test case from this file was flagged.\",\r\n );\r\n } else if (outcome === \"error\") {\r\n skip(target.path, \"the single-file command could not be started. No test case from this file was flagged.\");\r\n } else {\r\n const reportAfter = findJUnitReport(cwd);\r\n const fresh = reportAfter !== null && (reportAfter !== reportBefore || mtimeOf(reportAfter) !== mtimeBefore);\r\n if (!fresh) {\r\n skip(\r\n target.path,\r\n \"the single-file command wrote no new JUnit report (it must write the same JUnit report as the test \" +\r\n \"command), so nothing could be checked.\",\r\n );\r\n } else {\r\n const byId = readAutomationIdResults(cwd);\r\n for (const id of ids) if (byId?.get(id) === \"pass\") flagged.push(id);\r\n }\r\n }\r\n\r\n // The report has been read; now remove whatever this run left behind that the guardrail would commit\r\n // (a snapshot file written against the OLD behaviour would make the real run fail). Never anything\r\n // that existed before this run.\r\n const untrackedAfter = untrackedFiles(cwd);\r\n if (untrackedBefore && untrackedAfter) {\r\n for (const file of untrackedAfter) {\r\n if (untrackedBefore.has(file)) continue;\r\n const abs = insideCheckout(cwd, file);\r\n if (abs) rmSync(abs, { force: true });\r\n }\r\n }\r\n }\r\n\r\n if (flagged.length === 0) return { findings: null, warnings };\r\n\r\n const automationIds = [...new Set(flagged)].slice(0, 200);\r\n const list = automationIds.join(\", \");\r\n warnings.push(\r\n cause === \"NO_OP\"\r\n ? `Baseline check: ${automationIds.length} test case(s) passed against the unmodified code, and every file the ` +\r\n `generated change edited came out unchanged, so the change itself may have been a no-op: ${list}.`\r\n : `Baseline check: ${automationIds.length} test case(s) passed against the unmodified code, so they may assert ` +\r\n `something already true: ${list}. This check cannot tell that from a change that did nothing.`,\r\n );\r\n return { findings: { cause, automationIds }, warnings };\r\n } catch (err) {\r\n const message = `Baseline check could not run: ${err instanceof Error ? err.message : String(err)}`;\r\n console.warn(`::warning::${message}`);\r\n return { findings: null, warnings: [...warnings, message] };\r\n } finally {\r\n restore(written);\r\n }\r\n}\r\n", "import { readFileSync } from \"node:fs\";\r\nimport { runTestCommand, runTestCommandAsync, type TestOutcome } from \"./commands\";\r\nimport { findJUnitReport } from \"./quiktest\";\r\n\r\n/**\r\n * QUIKTR-1036 \u2014 once codegen writes real code, a failing test after it probably means the\r\n * generated code (or a generated test) is wrong. Blocking unconditionally would break any repo\r\n * with pre-existing failures, so a run captures a \"before\" snapshot (the baseline, run against the\r\n * untouched tree) and an \"after\" snapshot (post-codegen), and diffs them per test:\r\n * passed before, fails now -> regression, block\r\n * absent before, fails now -> new failure, block (codegen writing test files makes this the\r\n * common case, not an edge case \u2014 a different diagnosis from a\r\n * regression, so it's reported separately)\r\n * failed before, fails now -> not ours, stays soft (the case the soft-fail existed for)\r\n *\r\n * Only a minimal <testcase> scanner \u2014 not a full XML parser like\r\n * apps/quiktrack/lib/test/resultParser.ts, which extracts failure messages/stack traces across\r\n * multiple formats for QuikTest's ingest API and can't be imported here anyway (this package is\r\n * published outside the monorepo \u2014 same reason packet.ts duplicates its types instead of sharing\r\n * them). classname::name (or bare name with no classname) is an internal-only identity, used only\r\n * to match a test between two local runs \u2014 it never needs to match QuikTest's own configurable\r\n * automationIdFormat.\r\n */\r\nexport interface TestSnapshot {\r\n outcome: TestOutcome;\r\n /** testId -> passed. null when no JUnit report was found or it couldn't be parsed \u2014 the\r\n * fallback used when either snapshot lacks this is to stay soft, same as today, since blocking\r\n * with no way to name what broke would contradict the whole point of the classification. */\r\n results: Map<string, boolean> | null;\r\n /**\r\n * QUIKTR-1029 self-heal prerequisite 1 (Suyash, 2026-09-22 \u2014 \"buildable now and useful on its\r\n * own: today a regression blocks the push without saying why the test failed\"). testId -> a\r\n * bounded failure message, only for tests that failed IN THIS SNAPSHOT. Deliberately a second,\r\n * optional map rather than widening `results`'s value type: `checkForRegressions`'s diffing\r\n * logic (and every existing test constructing a `TestSnapshot` fixture directly) stays untouched\r\n * \u2014 this is additive context, not a new signal the diff itself reasons about.\r\n */\r\n failureText?: Map<string, string>;\r\n /**\r\n * QUIKTR-1315 \u2014 the file paths the test runner itself discovered, read from each `<testsuite>`'s\r\n * `file` attribute and each `<testcase>`'s `file`/`classname` attributes, verbatim (backslashes\r\n * normalised to forward slashes only). `null` when no report was found \u2014 same \"can't tell, don't\r\n * block\" posture as `results`. An empty (non-null) set means a report existed but carried no\r\n * file-shaped attribution at all \u2014 also treated as \"can't tell\" by `testPlacementCheck.ts`, not as\r\n * \"nothing was discovered.\" Best-effort only: `classname` is a real file path for Vitest and\r\n * derivable for pytest, but not guaranteed for Jest (depends on `jest-junit` config) or Go\r\n * (typically package-, not file-, scoped) \u2014 see `testPlacementCheck.ts`'s own docblock for how\r\n * this is matched loosely rather than exactly for that reason.\r\n */\r\n discoveredFiles?: Set<string> | null;\r\n /**\r\n * QUIKTR-1315 \u2014 every `[<automationId>]` leading-bracket token found in a `<testcase>` name,\r\n * duplicating `apps/quiktrack/lib/test/resultParser.ts`'s `LEADING_BRACKET_RE` convention (this\r\n * package can't import that file \u2014 published outside the monorepo). `null` when no report was\r\n * found, same as `discoveredFiles`.\r\n */\r\n discoveredAutomationIds?: Set<string> | null;\r\n}\r\n\r\nconst TESTCASE_RE = /<testcase\\b([^>]*?)(?:\\/>|>([\\s\\S]*?)<\\/testcase>)/g;\r\nconst NAME_ATTR_RE = /\\bname=\"([^\"]*)\"/;\r\nconst CLASSNAME_ATTR_RE = /\\bclassname=\"([^\"]*)\"/;\r\nconst FAILURE_CHILD_RE = /<failure\\b|<error\\b/;\r\nconst SKIPPED_CHILD_RE = /<skipped\\b/;\r\n\r\n// QUIKTR-1315 \u2014 `<testsuite>` open tags only (not self-closed the way an empty `<testcase/>` can\r\n// be): a suite always wraps at least its own attributes even with zero testcases inside.\r\nconst TESTSUITE_OPEN_RE = /<testsuite\\b([^>]*?)>/g;\r\nconst FILE_ATTR_RE = /\\bfile=\"([^\"]*)\"/;\r\n// QUIKTR-1082/1374's convention, duplicated \u2014 see this file's module docblock and\r\n// `TestSnapshot`'s `discoveredAutomationIds` field for why this can't just import\r\n// resultParser.ts instead. Matches QuikPilot's own token shape (QP-<PROJECT-KEY>-<issue>-<n>)\r\n// anywhere in the name rather than requiring it at the start \u2014 a bare \"[Smoke]\"-style tag can\r\n// never satisfy this shape, so QUIKTR-1082's \"don't match an unrelated bracketed tag\" safety\r\n// property holds without depending on position, which Vitest's JUnit reporter doesn't preserve.\r\nconst QP_TOKEN_BRACKET_RE = /\\[(QP-[A-Z][A-Z0-9]*-\\d+-\\d+)\\]/;\r\n\r\nfunction normalizeSlashes(path: string): string {\r\n return path.replace(/\\\\/g, \"/\");\r\n}\r\n\r\n/** The `<failure>`/`<error>` child itself, within one `<testcase>`'s already-isolated body. */\r\nconst FAILURE_TAG_RE = /<(?:failure|error)\\b([^>]*?)(?:\\/>|>([\\s\\S]*?)<\\/(?:failure|error)>)/;\r\nconst FAILURE_MESSAGE_ATTR_RE = /\\bmessage=\"([^\"]*)\"/;\r\n\r\n/** Console/PR-message budget, not a data-integrity bound \u2014 this is display text, never re-parsed. */\r\nconst MAX_FAILURE_TEXT = 500;\r\n\r\n/** The five entities the JUnit writers in real use (Vitest, Jest, pytest, go-junit-report) all\r\n * produce \u2014 not a general XML-unescape, same \"minimal scanner, not a parser\" posture as the rest\r\n * of this file. Literal `"`/`&` reaching a console log or a PR body reads as broken. */\r\nfunction unescapeXmlEntities(s: string): string {\r\n return s.replace(/</g, \"<\").replace(/>/g, \">\").replace(/"/g, '\"').replace(/'/g, \"'\").replace(/&/g, \"&\");\r\n}\r\n\r\n/** A file Vite cannot parse is reported with one generic message whatever the file or the syntax error;\r\n * only a `File: <path>:<line>[:<col>]` line in the body says which file and where (Vitest 4.1.11). */\r\nconst FAILURE_FILE_LINE_RE = /^[ \\t]*File:[ \\t]*(\\S[^\\r\\n]*?:\\d+(?::\\d+)?)[ \\t]*$/m;\r\nconst MAX_FAILURE_LOCATION = 300;\r\n\r\nfunction parseFailureLocation(body: string): string | null {\r\n const found = FAILURE_FILE_LINE_RE.exec(unescapeXmlEntities(body));\r\n if (!found) return null;\r\n const path = normalizeSlashes(found[1]);\r\n const root = `${normalizeSlashes(process.cwd()).replace(/\\/+$/, \"\")}/`;\r\n const shown = path.startsWith(root) ? path.slice(root.length) : path;\r\n return shown.length > MAX_FAILURE_LOCATION ? `${shown.slice(0, MAX_FAILURE_LOCATION)}\u2026` : shown;\r\n}\r\n\r\n/** `message=\"...\"` when present (short, what every framework puts the assertion diff in);\r\n * otherwise the tag's own body text (stack trace), truncated \u2014 never both, never neither if\r\n * either exists. `null` when the testcase body has no `<failure>`/`<error>` at all, or the tag\r\n * carries no text either way (both attrs and body empty \u2014 seen from at least one Go harness).\r\n *\r\n * Exception: when the message attribute is used and the body names a file and position (a file that\r\n * failed to parse), that location is appended, because the message alone cannot say which file. */\r\nfunction extractFailureText(testcaseBody: string): string | null {\r\n const tag = FAILURE_TAG_RE.exec(testcaseBody);\r\n if (!tag) return null;\r\n const [, attrs = \"\", inner = \"\"] = tag;\r\n const messageAttr = FAILURE_MESSAGE_ATTR_RE.exec(attrs)?.[1];\r\n const raw = (messageAttr ?? inner).trim();\r\n if (!raw) return null;\r\n const text = unescapeXmlEntities(raw);\r\n const shortened = text.length > MAX_FAILURE_TEXT ? `${text.slice(0, MAX_FAILURE_TEXT)}\u2026` : text;\r\n const location = messageAttr === undefined ? null : parseFailureLocation(inner);\r\n return location ? `${shortened} [at ${location}]` : shortened;\r\n}\r\n\r\n/** QUIKTR-1402 \u2014 one QuikPilot case's result in a report. `skipped` is its own answer, NOT a pass: a test\r\n * that did not run shows nothing about the case, and the baseline check must never read it as \"passed\". */\r\nexport type AutomationIdResult = \"pass\" | \"fail\" | \"skipped\";\r\n\r\n/** When several tests carry one case's id, the worst answer wins: fail > skipped > pass. */\r\nconst RESULT_RANK: Record<AutomationIdResult, number> = { pass: 0, skipped: 1, fail: 2 };\r\n\r\ninterface JUnitParseResult {\r\n outcomes: Map<string, boolean>;\r\n automationIdResults: Map<string, AutomationIdResult>;\r\n failureText: Map<string, string>;\r\n discoveredFiles: Set<string>;\r\n discoveredAutomationIds: Set<string>;\r\n}\r\n\r\nfunction parseJUnitOutcomes(xml: string): JUnitParseResult {\r\n const outcomes = new Map<string, boolean>();\r\n const automationIdResults = new Map<string, AutomationIdResult>();\r\n const failureText = new Map<string, string>();\r\n const discoveredFiles = new Set<string>();\r\n const discoveredAutomationIds = new Set<string>();\r\n\r\n TESTSUITE_OPEN_RE.lastIndex = 0;\r\n let suiteMatch: RegExpExecArray | null;\r\n while ((suiteMatch = TESTSUITE_OPEN_RE.exec(xml))) {\r\n const file = FILE_ATTR_RE.exec(suiteMatch[1])?.[1];\r\n if (file) discoveredFiles.add(normalizeSlashes(file));\r\n }\r\n\r\n let match: RegExpExecArray | null;\r\n TESTCASE_RE.lastIndex = 0;\r\n while ((match = TESTCASE_RE.exec(xml))) {\r\n const [, attrs, body = \"\"] = match;\r\n // A test's identity is its title as a person reads it. JUnit writers escape it (\"describe > test\" arrives as\r\n // \"describe > test\"), and the identity is what a failed run's reason names, so it is unescaped here once.\r\n const rawName = NAME_ATTR_RE.exec(attrs)?.[1];\r\n if (!rawName) continue;\r\n const name = unescapeXmlEntities(rawName);\r\n const rawClassname = CLASSNAME_ATTR_RE.exec(attrs)?.[1];\r\n const classname = rawClassname === undefined ? undefined : unescapeXmlEntities(rawClassname);\r\n const id = classname ? `${classname}::${name}` : name;\r\n const failed = FAILURE_CHILD_RE.test(body);\r\n outcomes.set(id, !failed);\r\n if (failed) {\r\n const text = extractFailureText(body);\r\n if (text) failureText.set(id, text);\r\n }\r\n const file = FILE_ATTR_RE.exec(attrs)?.[1];\r\n if (file) discoveredFiles.add(normalizeSlashes(file));\r\n if (classname) discoveredFiles.add(normalizeSlashes(classname));\r\n const bracket = QP_TOKEN_BRACKET_RE.exec(name)?.[1];\r\n if (bracket) {\r\n discoveredAutomationIds.add(bracket);\r\n const result: AutomationIdResult = failed ? \"fail\" : SKIPPED_CHILD_RE.test(body) ? \"skipped\" : \"pass\";\r\n const seen = automationIdResults.get(bracket);\r\n if (!seen || RESULT_RANK[result] > RESULT_RANK[seen]) automationIdResults.set(bracket, result);\r\n }\r\n }\r\n return { outcomes, automationIdResults, failureText, discoveredFiles, discoveredAutomationIds };\r\n}\r\n\r\nfunction readJUnitOutcomes(cwd: string): JUnitParseResult | null {\r\n const report = findJUnitReport(cwd);\r\n if (!report) return null;\r\n try {\r\n return parseJUnitOutcomes(readFileSync(report, \"utf8\"));\r\n } catch {\r\n return null;\r\n }\r\n}\r\n\r\n/** QUIKTR-1402 \u2014 per-case results from whatever JUnit report is on disk now; `null` when none is found or\r\n * it cannot be parsed (\"could not tell\", which the baseline check must treat differently from \"nothing\r\n * passed\"). Deliberately not part of TestSnapshot: only the baseline check reads it. */\r\nexport function readAutomationIdResults(cwd = process.cwd()): Map<string, AutomationIdResult> | null {\r\n return readJUnitOutcomes(cwd)?.automationIdResults ?? null;\r\n}\r\n\r\nexport function captureTestSnapshot(command: string | null, cwd = process.cwd()): TestSnapshot {\r\n const outcome = runTestCommand(command);\r\n const parsed = readJUnitOutcomes(cwd);\r\n return {\r\n outcome,\r\n results: parsed?.outcomes ?? null,\r\n failureText: parsed?.failureText,\r\n discoveredFiles: parsed?.discoveredFiles ?? null,\r\n discoveredAutomationIds: parsed?.discoveredAutomationIds ?? null,\r\n };\r\n}\r\n\r\nexport async function captureBaselineSnapshot(\r\n command: string | null,\r\n cwd = process.cwd(),\r\n): Promise<TestSnapshot> {\r\n const outcome = await runTestCommandAsync(command);\r\n const parsed = readJUnitOutcomes(cwd);\r\n return {\r\n outcome,\r\n results: parsed?.outcomes ?? null,\r\n failureText: parsed?.failureText,\r\n discoveredFiles: parsed?.discoveredFiles ?? null,\r\n discoveredAutomationIds: parsed?.discoveredAutomationIds ?? null,\r\n };\r\n}\r\n\r\nexport interface RegressionCheck {\r\n blocked: boolean;\r\n regressions: string[];\r\n newFailures: string[];\r\n preExisting: string[];\r\n /** testId -> bounded failure text, for whichever `regressions`/`newFailures` entries had one in\r\n * the AFTER snapshot (the failure that actually blocks the push \u2014 the baseline's own failure\r\n * text, if any, is irrelevant here). Always present, possibly empty \u2014 never omitted, so a\r\n * caller never has to guard its absence the way `results` itself still requires. */\r\n failureText: Map<string, string>;\r\n}\r\n\r\nexport function checkForRegressions(baseline: TestSnapshot, after: TestSnapshot): RegressionCheck {\r\n if (!baseline.results || !after.results) {\r\n return { blocked: false, regressions: [], newFailures: [], preExisting: [], failureText: new Map() };\r\n }\r\n\r\n const regressions: string[] = [];\r\n const newFailures: string[] = [];\r\n const preExisting: string[] = [];\r\n const failureText = new Map<string, string>();\r\n const afterFailureText = after.failureText;\r\n\r\n for (const [testId, passed] of after.results) {\r\n if (passed) continue;\r\n const before = baseline.results.get(testId);\r\n if (before === true) {\r\n regressions.push(testId);\r\n const text = afterFailureText?.get(testId);\r\n if (text) failureText.set(testId, text);\r\n } else if (before === false) {\r\n preExisting.push(testId);\r\n } else {\r\n newFailures.push(testId);\r\n const text = afterFailureText?.get(testId);\r\n if (text) failureText.set(testId, text);\r\n }\r\n }\r\n\r\n return { blocked: regressions.length > 0 || newFailures.length > 0, regressions, newFailures, preExisting, failureText };\r\n}\r\n\r\n/** Regressions and new failures named separately \u2014 conflating them is the thing that wastes\r\n * someone's morning (they're different diagnoses: one means the generated code broke something\r\n * that worked, the other means a generated test doesn't pass yet). Pre-existing failures are\r\n * noted, not hidden, so the message doesn't read as if they were silently dropped.\r\n *\r\n * QUIKTR-1029 self-heal prerequisite 1 \u2014 each named test now carries its failure text inline\r\n * when one was captured, so a run that blocks says WHY, not only WHAT. */\r\nexport function describeRegressions(check: RegressionCheck): string {\r\n const withText = (id: string) => {\r\n const text = check.failureText.get(id);\r\n return text ? `${id} (${text})` : id;\r\n };\r\n const parts: string[] = [];\r\n if (check.regressions.length > 0) {\r\n parts.push(\r\n `${check.regressions.length} regression(s) (passed before, now fail): ${check.regressions.map(withText).join(\", \")}`,\r\n );\r\n }\r\n if (check.newFailures.length > 0) {\r\n parts.push(\r\n `${check.newFailures.length} new failure(s) (did not exist before): ${check.newFailures.map(withText).join(\", \")}`,\r\n );\r\n }\r\n if (check.preExisting.length > 0) {\r\n parts.push(`${check.preExisting.length} pre-existing failure(s), unrelated to this change, not blocking`);\r\n }\r\n return parts.join(\"; \");\r\n}\r\n", "import { existsSync, mkdirSync, rmSync, writeFileSync } from \"node:fs\";\r\nimport { dirname, isAbsolute, join, relative, resolve } from \"node:path\";\r\nimport { scrubSecrets } from \"./failureReason\";\r\n\r\n/**\r\n * QUIKTR-1447 \u2014 what a failed run leaves behind for a person: the files QuikPilot wrote, the last test report and a short\r\n * manifest, in a folder the workflow uploads as an Actions artifact (kept 7 days, readable by whoever can see the repo's\r\n * Actions). Nothing goes to a branch or a pull request, and QuikTrack stores none of it.\r\n *\r\n * Written only after code generation finished, and never able to change how the run ends: the caller wraps it, and it\r\n * reports `written: false` instead of throwing.\r\n */\r\n\r\n/** Relative to the checkout root, which is where the workflow's upload step looks. */\r\nexport const FAILURE_ARTIFACT_DIR = \"quikpilot-failure\";\r\n\r\n/** Not named `junit*.xml`: the runner's own report finder walks the checkout for that pattern and would pick the copy up. */\r\nconst REPORT_COPY = \"final-test-report.xml\";\r\nconst MAX_REPORT_BYTES = 5 * 1024 * 1024;\r\nconst MAX_FILES = 200;\r\n\r\n// Replaced at build time (build.mjs); absent under vitest.\r\ndeclare const __RUNNER_VERSION__: string | undefined;\r\nconst RUNNER_VERSION = typeof __RUNNER_VERSION__ === \"string\" ? __RUNNER_VERSION__ : \"dev\";\r\n\r\nexport interface FailureArtifactInput {\r\n cwd: string;\r\n runId: string;\r\n issueKey: string | null;\r\n targets: ReadonlyArray<{ path: string; kind: string; automationIds?: string[] }>;\r\n results: ReadonlyArray<{ targetPath: string; newContent: string }>;\r\n /** The test report from the run after code generation, or null if no such run happened. A report from before\r\n * generation (the baseline) must never be passed. */\r\n testReport: Buffer | null;\r\n /** Already scrubbed and cut by the caller; scrubbed again here as the manifest is written. */\r\n failureReasons: readonly string[];\r\n /** Values that must not appear anywhere in the manifest, such as the run token. */\r\n secrets: readonly string[];\r\n}\r\n\r\n/** A path from the model must resolve inside the folder: absolute and parent-directory paths are refused. */\r\nfunction safeDestination(base: string, repoPath: string): string | null {\r\n if (!repoPath || isAbsolute(repoPath)) return null;\r\n const destination = resolve(base, repoPath);\r\n const rel = relative(base, destination);\r\n if (!rel || rel.startsWith(\"..\") || isAbsolute(rel)) return null;\r\n return destination;\r\n}\r\n\r\nexport function writeFailureArtifact(input: FailureArtifactInput): { written: boolean } {\r\n if (input.results.length === 0) return { written: false };\r\n try {\r\n const base = resolve(input.cwd, FAILURE_ARTIFACT_DIR);\r\n // A folder from an earlier call must not mix with this one.\r\n rmSync(base, { recursive: true, force: true });\r\n mkdirSync(base, { recursive: true });\r\n\r\n const files: Array<{ path: string; bytes: number }> = [];\r\n const skipped: string[] = [];\r\n for (const result of input.results) {\r\n const destination = files.length < MAX_FILES ? safeDestination(base, result.targetPath) : null;\r\n if (!destination) {\r\n skipped.push(result.targetPath);\r\n continue;\r\n }\r\n mkdirSync(dirname(destination), { recursive: true });\r\n writeFileSync(destination, result.newContent);\r\n files.push({ path: result.targetPath, bytes: Buffer.byteLength(result.newContent) });\r\n }\r\n\r\n let testReport: \"included\" | \"none\" | \"too-large\" = \"none\";\r\n if (input.testReport) {\r\n if (input.testReport.byteLength > MAX_REPORT_BYTES) {\r\n testReport = \"too-large\";\r\n } else {\r\n writeFileSync(join(base, REPORT_COPY), input.testReport);\r\n testReport = \"included\";\r\n }\r\n }\r\n\r\n const manifest = {\r\n runId: input.runId,\r\n issueKey: input.issueKey,\r\n runnerVersion: RUNNER_VERSION,\r\n generatedAt: new Date().toISOString(),\r\n targets: input.targets.map((t) => ({\r\n path: t.path,\r\n kind: t.kind,\r\n ...(t.automationIds && t.automationIds.length > 0 ? { automationIds: t.automationIds } : {}),\r\n })),\r\n files,\r\n skipped,\r\n testReport,\r\n failureReasons: input.failureReasons,\r\n };\r\n // Every string is scrubbed as the manifest is written, so a token that reached any field is taken out.\r\n const text = JSON.stringify(manifest, (_key, value) => (typeof value === \"string\" ? scrubSecrets(value, input.secrets) : value), 2);\r\n writeFileSync(join(base, \"manifest.json\"), text);\r\n return { written: existsSync(join(base, \"manifest.json\")) };\r\n } catch (err: unknown) {\r\n console.warn(`::warning::Could not keep the failed run's files: ${err instanceof Error ? err.message : String(err)}`);\r\n return { written: false };\r\n }\r\n}\r\n", "import { RuntimeReplyError } from \"./runtimeReplyError\";\r\n\r\n/** What a failed run tells QuikTrack about why. The message a hard failure threw used to go to the CI job log and\r\n * nowhere else; it is now sent, so it is written on one line, cut to a safe length, and has anything that looks like\r\n * a credential taken out first (an error from a failed push or request can carry one). */\r\nexport const MAX_FAILURE_REASON = 1000;\r\n\r\n/** Anything shorter than this is not treated as a secret to search for: replacing a three-letter \"token\" would wreck\r\n * every word that contains it. */\r\nconst MIN_SECRET_LENGTH = 8;\r\n\r\nconst CREDENTIAL_PATTERNS: RegExp[] = [\r\n /\\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}/g,\r\n /\\bgithub_pat_[A-Za-z0-9_]{20,}/g,\r\n /x-access-token:[^@\\s'\"]+/gi,\r\n // Only the header form (\"Authorization: basic <token>\"), or a bearer value that contains a digit: a bare\r\n // \"basic authentication\" or \"bearer of the news\" is prose, not a credential.\r\n /\\bauthorization:\\s*(?:basic|bearer|token)\\s+[^\\s'\"]{8,}/gi,\r\n /\\bbearer\\s+(?=[A-Za-z0-9._~+/=-]*\\d)[A-Za-z0-9._~+/=-]{12,}/gi,\r\n // A signed JWT is three dot-separated segments; QuikPilot's own run token is an encrypted JWT (alg dir) of five, the\r\n // second one empty. The run token is also matched by exact value, but one that has expired or rotated is not the\r\n // current value, so its shape has to catch it.\r\n /\\beyJ[A-Za-z0-9_-]{8,}(?:\\.[A-Za-z0-9_-]*){2,4}/g,\r\n];\r\n\r\n/** What may leave the job for a thrown error: the summary when the error quotes the AI Runtime's reply, otherwise its\r\n * message. The full message is still printed to the job log by the caller. */\r\nexport function failureSummary(err: unknown): string {\r\n if (err instanceof RuntimeReplyError) return err.summary;\r\n return err instanceof Error ? err.message : String(err);\r\n}\r\n\r\n/** Takes known secrets (by value) and anything shaped like a credential out of a piece of text. Does not change the\r\n * text otherwise: no line folding, no cutting. */\r\nexport function scrubSecrets(message: string, secrets: readonly string[] = []): string {\r\n let text = message;\r\n for (const secret of secrets) {\r\n if (secret.length >= MIN_SECRET_LENGTH) text = text.split(secret).join(\"***\");\r\n }\r\n for (const pattern of CREDENTIAL_PATTERNS) text = text.replace(pattern, \"***\");\r\n return text;\r\n}\r\n\r\nexport function describeFailureReason(message: string, secrets: readonly string[] = []): string {\r\n let text = scrubSecrets(message, secrets);\r\n text = text.replace(/\\s*\\n\\s*/g, \" | \").trim();\r\n return text.length > MAX_FAILURE_REASON ? `${text.slice(0, MAX_FAILURE_REASON)}\u2026` : text;\r\n}\r\n", "import { readFileSync } from \"node:fs\";\r\nimport type { CodegenFileResult } from \"./codegen\";\r\nimport type { PilotTarget } from \"./targeting\";\r\n\r\n/**\r\n * QUIKTR-1081 \u2014 QUIKSPL-5's PR #22 fixed the reported bug in src/validation.js and also silently\r\n * added an undeclared PUT endpoint to src/server.js that returned success while updating nothing.\r\n * Tests passed, the dependency check passed, and nothing compared what codegen actually added\r\n * against the design's own declared `apiChanges` \u2014 because nothing did.\r\n *\r\n * Same \"minimal, not exhaustive\" standard as dependencyCheck.ts's import scanner and\r\n * regressionCheck.ts's JUnit scanner, for the same reason: this package is dependency-free,\r\n * bundled into a single CLI file with no externals, published outside the monorepo, and the\r\n * target repository is arbitrary \u2014 no real per-framework route parser is on the table. This is a\r\n * same-line METHOD+PATH text heuristic, a tripwire against the ticket's own incident (method and\r\n * path both named on the documenting comment's line), not a route parser for every framework a\r\n * customer repo might use. It will not catch a Next.js-style `export function PUT(...)` whose path\r\n * comes from file location rather than an in-file string \u2014 ROUTE_EXPORT_RE below covers that one\r\n * export shape specifically, matched by method presence alone since it has no in-file path to\r\n * compare.\r\n *\r\n * \"Exported symbols\" (the ticket's own words) is deliberately narrowed to route-handler-shaped\r\n * exports here, not any new exported symbol: an arbitrary new exported helper is routine,\r\n * legitimate refactoring, and checking every export against free-text `apiChanges` would produce\r\n * exactly the kind of false-positive noise this package's checks otherwise avoid.\r\n */\r\nexport interface ScopeViolation {\r\n file: string;\r\n method: string;\r\n path: string;\r\n}\r\n\r\nexport interface ScopeCheck {\r\n blocked: boolean;\r\n violations: ScopeViolation[];\r\n}\r\n\r\ninterface RouteMention {\r\n method: string;\r\n path: string;\r\n}\r\n\r\nconst ROUTE_METHOD_RE = /\\b(GET|POST|PUT|PATCH|DELETE)\\b/i;\r\nconst ROUTE_PATH_RE = /\\/[A-Za-z0-9_\\-{}[\\]]+(?:\\/[A-Za-z0-9_\\-:{}[\\]]+)+/;\r\nconst ROUTE_EXPORT_RE = /\\bexport\\s+(?:async\\s+)?function\\s+(GET|POST|PUT|PATCH|DELETE)\\s*\\(/;\r\n\r\n/** No in-file path \u2014 a Next.js-style route handler's path comes from where the file lives, not a\r\n * string in it. Matched against `apiChanges` by method presence alone (see `surfaceCovers`). */\r\nconst NO_PATH = \"(this file's route)\";\r\n\r\nfunction detectMentions(text: string): RouteMention[] {\r\n const found: RouteMention[] = [];\r\n for (const line of text.split(\"\\n\")) {\r\n const methodMatch = ROUTE_METHOD_RE.exec(line);\r\n const pathMatch = ROUTE_PATH_RE.exec(line);\r\n if (methodMatch && pathMatch) {\r\n found.push({ method: methodMatch[1].toUpperCase(), path: pathMatch[0] });\r\n }\r\n const exportMatch = ROUTE_EXPORT_RE.exec(line);\r\n if (exportMatch) {\r\n found.push({ method: exportMatch[1].toUpperCase(), path: NO_PATH });\r\n }\r\n }\r\n return found;\r\n}\r\n\r\n/** `:id`, `{id}`, `[id]` all become `*` so a declared surface and a detected mention compare equal\r\n * regardless of the exact param name either side happens to use. */\r\nfunction normalizePath(path: string): string {\r\n return path.replace(/:[A-Za-z0-9_]+|\\{[^}]+\\}|\\[[^\\]]+\\]/g, \"*\");\r\n}\r\n\r\nfunction surfaceCovers(surface: string, mention: RouteMention): boolean {\r\n if (!new RegExp(`\\\\b${mention.method}\\\\b`, \"i\").test(surface)) return false;\r\n if (mention.path === NO_PATH) return true; // method presence is all a route-export mention has\r\n const declaredPath = normalizePath(surface);\r\n const mentionPath = normalizePath(mention.path);\r\n return declaredPath.includes(mentionPath) || mentionPath.includes(declaredPath);\r\n}\r\n\r\n/** Lines present in `after` but not in `before` \u2014 a set difference, not a positional diff (code\r\n * can shift line numbers around an addition). Good enough to separate \"genuinely new this run\"\r\n * from \"was already there\" without a real diff algorithm, same spirit as this package's other\r\n * scanners. */\r\nfunction addedLines(before: string, after: string): string {\r\n const beforeLines = new Set(before.split(\"\\n\"));\r\n return after\r\n .split(\"\\n\")\r\n .filter((line) => !beforeLines.has(line))\r\n .join(\"\\n\");\r\n}\r\n\r\n/** A test names and calls routes constantly (`describe(\"POST /api/x\", \u2026)`) but cannot define one,\r\n * so scanning it can only produce false positives. Common conventions only, in the same spirit as\r\n * the rest of this file \u2014 not an exhaustive per-framework list. */\r\nconst TEST_FILE_RES = [\r\n /(^|\\/)(__tests__|__mocks__|tests?|specs?)\\//i,\r\n /\\.(test|spec)\\.[^/.]+$/i,\r\n /(^|\\/)test_[^/]+\\.py$/i,\r\n /_test\\.(py|go)$/i,\r\n /Tests?\\.(java|kt|cs)$/,\r\n];\r\n\r\nfunction isTestFile(path: string): boolean {\r\n return TEST_FILE_RES.some((re) => re.test(path));\r\n}\r\n\r\nexport function checkApiScope(\r\n results: CodegenFileResult[],\r\n targets: PilotTarget[],\r\n apiChanges: { surface: string; change: string; reason: string }[],\r\n): ScopeCheck {\r\n const targetsByPath = new Map(targets.map((t) => [t.path, t]));\r\n const violations: ScopeViolation[] = [];\r\n\r\n for (const { targetPath, newContent } of results) {\r\n if (isTestFile(targetPath)) continue;\r\n const target = targetsByPath.get(targetPath);\r\n const isNewFile = target?.kind === \"NEW_FILE\";\r\n\r\n let scanned: string;\r\n if (isNewFile) {\r\n scanned = newContent;\r\n } else {\r\n let currentContent: string;\r\n try {\r\n currentContent = readFileSync(targetPath, \"utf8\");\r\n } catch {\r\n currentContent = \"\";\r\n }\r\n scanned = addedLines(currentContent, newContent);\r\n }\r\n\r\n for (const mention of detectMentions(scanned)) {\r\n if (!apiChanges.some((c) => surfaceCovers(c.surface, mention))) {\r\n violations.push({ file: targetPath, method: mention.method, path: mention.path });\r\n }\r\n }\r\n }\r\n\r\n return { blocked: violations.length > 0, violations };\r\n}\r\n\r\nexport function describeScopeViolations(check: ScopeCheck): string {\r\n return check.violations\r\n .map((v) => `${v.file} adds ${v.method} ${v.path}, not declared in the design's API changes`)\r\n .join(\"; \");\r\n}\r\n", "import { resolve, relative, isAbsolute } from \"node:path\";\r\nimport { findDeniedContextPath, matchesDeniedPath } from \"./deniedPaths\";\r\nimport { listFiles } from \"./git\";\r\nimport { checkHardFailure, unwrapExecute } from \"./envelope\";\r\nimport { RuntimeReplyError } from \"./runtimeReplyError\";\r\nimport type { PilotPacket } from \"./packet\";\r\nimport { fetchWithRetry } from \"./retryFetch\";\r\nimport { DeniedPathError, TargetingHttpError } from \"./targetingErrors\";\r\nimport { resolveTargetingMode, type TargetingMode } from \"./targetingMode\";\r\nimport {\r\n LoopFailure,\r\n SafetyRefusalError,\r\n runTargetingLoop,\r\n type FallbackReason,\r\n type LoopDeps,\r\n type LoopSummary,\r\n} from \"./targetingLoop\";\r\n\r\nexport { DeniedPathError, TargetingHttpError };\r\n\r\n/**\r\n * QUIKTR-1035 \u2014 `pilot.targeting`: turns the design plus a file listing into real per-file\r\n * instructions, replacing codegen.ts's old planStepsFromDesign entirely. Proven live by the AI\r\n * Runtime against a real 624-file QuikChat listing before this was wired in.\r\n *\r\n * QUIKTR-1083 (\u00A715) \u2014 the versioned test-target contract. `contractVersion: \"test-targets-1\"` is\r\n * sent unconditionally: per \u00A715.6 the unversioned path is only \"exactly today's behaviour\" for a\r\n * caller that never asks for the new shape, and this runner always wants it once it ships.\r\n */\r\nconst CONTRACT_VERSION = \"test-targets-1\";\r\n\r\nexport type TargetKind = \"EXISTING\" | \"NEW_FILE\";\r\n\r\nexport interface PilotTarget {\r\n path: string;\r\n kind: TargetKind;\r\n planStepsImplemented: string[];\r\n // Context contract change \u2014 pilot.targeting now names, per target, which other files\r\n // pilot.codegen should read before writing this one (\"to write this file, read these\").\r\n // codegen.ts validates and reads these; absent/empty means no context, no fallback.\r\n contextPaths?: string[];\r\n /** \u00A715.3 \u2014 present only on a test target: the automation IDs (not database ids \u2014 see\r\n * \u00A715.3's own naming rationale) this target's generated file must cover. codegen.ts forwards\r\n * only the matching `requiredTests` subset for a target carrying this. */\r\n automationIds?: string[];\r\n}\r\n\r\n/** \u00A715.3 amendment 1 \u2014 a case with no behaviour (given/when/then all null) is named here instead\r\n * of silently dropped; the model has no discretion over which cases land here vs. in a target's\r\n * `automationIds` (completeness is enforced on the runtime side). Informational on this side \u2014\r\n * folded into `run.ts`'s `warnings`, never blocking. */\r\nexport interface SkippedCase {\r\n automationId: string;\r\n reason: \"NO_BEHAVIOUR\";\r\n}\r\n\r\nexport type TargetingResult = (\r\n | {\r\n outcome: \"TARGETED\";\r\n targets: PilotTarget[];\r\n skippedCases: SkippedCase[];\r\n /** Paths targeting called NEW_FILE although they are already in the checkout; they come back as EXISTING. */\r\n correctedKinds?: string[];\r\n }\r\n | { outcome: \"NO_TARGET\"; reason: string | null }\r\n) & {\r\n /** QUIKTR-1458 \u2014 present only when the read-only loop ran (or was tried): what it did. */\r\n loop?: LoopSummary;\r\n /** Non-blocking notes for the run's warnings list (today: only \"the loop fell back\"). */\r\n warnings?: string[];\r\n};\r\n\r\nexport interface TargetingResponse {\r\n outcome?: \"TARGETED\" | \"NO_TARGET\";\r\n targets?: {\r\n path: string;\r\n kind: string;\r\n planStepsImplemented: string[];\r\n contextPaths?: string[];\r\n automationIds?: string[];\r\n }[];\r\n skippedCases?: SkippedCase[];\r\n noTargetReason?: string;\r\n}\r\n\r\n/**\r\n * Tracked files under the packet's workspace root, or the whole checkout when it's null\r\n * (QUIKTR-1033) \u2014 never normalised to \".\" at the packet layer itself, only here where a concrete\r\n * pathspec is actually needed. An unscoped listing on a large monorepo is ~210k tokens, which fits\r\n * one provider and breaks the fallback chain \u2014 see workspaceRoot's own doc comment on PilotPacket.\r\n */\r\nexport function listWorkspaceFiles(workspaceRoot: string | null): string[] {\r\n return listFiles(workspaceRoot ?? \".\");\r\n}\r\n\r\n/**\r\n * VALIDATION IS OURS \u2014 the AI Runtime's schema doesn't guarantee a path is actually safe to write.\r\n * An EXISTING target must already be in the checkout; a NEW_FILE target must resolve inside the\r\n * workspace root. Either failure throws \u2014 a dropped target is a plan half-executed, and run.ts's\r\n * existing top-level try/catch already turns this into the same hard failure any other pre-setup\r\n * step gets.\r\n */\r\nfunction validateTarget(\r\n target: { path: string; kind: string; contextPaths?: string[] },\r\n workspaceRoot: string | null,\r\n workspaceListing: Set<string>,\r\n deniedPaths: string[],\r\n): void {\r\n // QUIKTR-1083 (\u00A715.3) \u2014 layer 2 of three: checked here, before any codegen spend, regardless of\r\n // kind. Layer 1 (the runtime's own targeting validator) should already exclude a denied path;\r\n // this does not trust that and re-checks independently.\r\n const denied = matchesDeniedPath(target.path, deniedPaths);\r\n if (denied) {\r\n throw new DeniedPathError(\r\n `pilot.targeting proposed a target matching a denied path (${denied}): ${target.path}`,\r\n );\r\n }\r\n // QUIKTR-1420 \u2014 the same list applies to what the target cites as CONTEXT, which the runner reads and\r\n // sends to the model provider. Checked before anything else, and before any codegen spend.\r\n const deniedContext = findDeniedContextPath(target.contextPaths ?? [], deniedPaths);\r\n if (deniedContext) {\r\n throw new DeniedPathError(\r\n `pilot.targeting cited a denied path as context (${deniedContext.pattern}): ${deniedContext.path} (target ${target.path})`,\r\n );\r\n }\r\n if (target.kind !== \"EXISTING\" && target.kind !== \"NEW_FILE\") {\r\n throw new Error(`pilot.targeting returned an unknown kind \"${target.kind}\" for ${target.path}`);\r\n }\r\n if (target.kind === \"EXISTING\") {\r\n if (!workspaceListing.has(target.path)) {\r\n throw new Error(\r\n `pilot.targeting named an EXISTING file not found in the checkout: ${target.path}`,\r\n );\r\n }\r\n return;\r\n }\r\n const root = resolve(workspaceRoot ?? \".\");\r\n const rel = relative(root, resolve(target.path));\r\n if (rel.startsWith(\"..\") || isAbsolute(rel)) {\r\n throw new Error(\r\n `pilot.targeting named a NEW_FILE path that escapes the workspace root: ${target.path}`,\r\n );\r\n }\r\n}\r\n\r\n/**\r\n * The request body for the single-call `pilot.targeting`. Key ORDER is part of the contract with the\r\n * AI Runtime's versioned path and is pinned by targeting.characterisation.test.ts.\r\n */\r\nexport function buildContextData(\r\n design: PilotPacket[\"design\"],\r\n workspaceListing: string[],\r\n requiredTests: PilotPacket[\"requiredTests\"],\r\n deniedPaths: string[],\r\n testDiscovery: PilotPacket[\"testDiscovery\"],\r\n outOfScope: string[],\r\n): Record<string, unknown> {\r\n const contextData: Record<string, unknown> = {\r\n // NESTED, NOT FLATTENED \u2014 a second vocabulary for the design shape is exactly what\r\n // QUIKTR-1034 cost.\r\n workspaceListing,\r\n design,\r\n // QUIKTR-1065/1083 \u2014 requiredTests carried through so targeting can propose a test-file\r\n // target naming which cases it covers (\u00A715.1's Case shape, unchanged).\r\n requiredTests,\r\n // QUIKTR-1083 (\u00A715.6) \u2014 required on the versioned path.\r\n contractVersion: CONTRACT_VERSION,\r\n };\r\n // QUIKTR-1083 (\u00A715.3) \u2014 optional on the wire; omitted rather than sent empty, matching\r\n // codegen.ts's identical treatment.\r\n if (deniedPaths.length > 0) {\r\n contextData.deniedPaths = deniedPaths;\r\n }\r\n // QUIKTR-1401, \u00A720 of the AI Runtime contract (deployed and confirmed 2026-10-01) \u2014 an optional declared key\r\n // under the versioned contract, sent only when non-empty: an empty list would make the prompt mention\r\n // constraints that are not there. Free text, so unlike deniedPaths it can only be TOLD to the model, never\r\n // checked. Never sent to pilot.design.\r\n if (outOfScope.length > 0) {\r\n contextData.outOfScope = outOfScope;\r\n }\r\n // QUIKTR-1315, \u00A719 of the AI Runtime contract \u2014 AGREED (2026-09-28), confirmed deployed and\r\n // live (2026-09-29). ALWAYS sent, never omitted \u2014 \u00A719's whole point is the tagged\r\n // `{ report: \"PRESENT\" | \"ABSENT\" }` shape replacing an absent-vs-empty key distinction, so this\r\n // must not fall back to \"omit when nothing to say\" the way `deniedPaths` does above. The packet\r\n // already resolves this to a real value in every case (never undefined) \u2014 see packet.ts.\r\n contextData.testDiscovery = testDiscovery;\r\n return contextData;\r\n}\r\n\r\n/**\r\n * One POST of `pilot.targeting`, returning the RAW `/ai/execute` envelope. Shared by the single call\r\n * and by every turn of the read-only loop. QUIKTR-1069 \u2014 retryFetch retries a transport-level failure\r\n * only (502/503/504, a dropped connection); a real refusal always arrives as a 200 with the refusal\r\n * inside the envelope. `signal` is for loop turns only; the single call never had a timeout and\r\n * keeps behaving exactly as before.\r\n */\r\nexport async function postTargeting(\r\n gateway: PilotPacket[\"gateway\"],\r\n contextData: Record<string, unknown>,\r\n signal?: AbortSignal,\r\n): Promise<unknown> {\r\n const res = await fetchWithRetry(`${gateway.baseUrl}/ai/execute`, {\r\n method: \"POST\",\r\n headers: { \"content-type\": \"application/json\", \"x-run-token\": gateway.token },\r\n body: JSON.stringify({\r\n appId: \"quiktrack\",\r\n useCase: \"pilot.targeting\",\r\n expectedOutputType: \"json\",\r\n userPrompt: \"\",\r\n contextData,\r\n }),\r\n ...(signal ? { signal } : {}),\r\n });\r\n\r\n if (!res.ok) {\r\n throw new TargetingHttpError(res.status, res.statusText);\r\n }\r\n return res.json();\r\n}\r\n\r\n/**\r\n * Everything that happens to a targeting ANSWER, whichever way it was obtained: the shape check, our\r\n * own validation of every target, and the NEW_FILE correction. The single call and the read-only loop\r\n * both end here, so a target is judged by exactly the same rules either way.\r\n */\r\nexport function finalizeTargeting(\r\n body: TargetingResponse,\r\n workspaceRoot: string | null,\r\n workspaceListing: string[],\r\n deniedPaths: string[],\r\n): TargetingResult {\r\n if (body.outcome === \"NO_TARGET\") {\r\n return { outcome: \"NO_TARGET\", reason: body.noTargetReason ?? null };\r\n }\r\n if (body.outcome !== \"TARGETED\" || !Array.isArray(body.targets)) {\r\n throw new RuntimeReplyError(\r\n `pilot.targeting returned an unexpected shape: ${JSON.stringify(body)}`,\r\n \"pilot.targeting returned an unexpected shape\",\r\n );\r\n }\r\n\r\n const listing = new Set(workspaceListing);\r\n for (const target of body.targets) {\r\n validateTarget(target, workspaceRoot, listing, deniedPaths);\r\n }\r\n\r\n // A NEW_FILE target is sent to codegen with no current content, so a file that already exists would be\r\n // overwritten blind (QUIKTR-1448). The checkout listing says which it is, so the label is corrected here\r\n // rather than failing a run over a mistake with an obvious answer.\r\n const correctedKinds: string[] = [];\r\n const targets = (body.targets as PilotTarget[]).map((target) => {\r\n if (target.kind === \"NEW_FILE\" && listing.has(target.path)) {\r\n correctedKinds.push(target.path);\r\n return { ...target, kind: \"EXISTING\" as const };\r\n }\r\n return target;\r\n });\r\n\r\n return {\r\n outcome: \"TARGETED\",\r\n targets,\r\n skippedCases: body.skippedCases ?? [],\r\n ...(correctedKinds.length > 0 ? { correctedKinds } : {}),\r\n };\r\n}\r\n\r\n/** Today's behaviour: one call, answered from the file listing alone. */\r\nexport async function runSingleShot(\r\n gateway: PilotPacket[\"gateway\"],\r\n design: PilotPacket[\"design\"],\r\n workspaceRoot: string | null,\r\n workspaceListing: string[],\r\n requiredTests: PilotPacket[\"requiredTests\"],\r\n deniedPaths: string[],\r\n testDiscovery: PilotPacket[\"testDiscovery\"],\r\n outOfScope: string[] = [],\r\n): Promise<TargetingResult> {\r\n const contextData = buildContextData(design, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope);\r\n // /ai/execute wraps every result in an envelope \u2014 the use-case result lives at\r\n // structuredJson, and a failure can arrive as success:false in an HTTP 200 (see envelope.ts).\r\n // QUIKTR-1083 \u2014 SEMANTIC_MISMATCH/CONTRACT_REJECTED are checked on the raw envelope, before\r\n // unwrapping, same reason codegen.ts's pre-existing CODEGEN_* checks do: unwrapping first would\r\n // throw unwrapExecute's generic success:false error and lose the distinction.\r\n const envelope = await postTargeting(gateway, contextData);\r\n checkHardFailure(envelope, \"pilot.targeting\");\r\n const body = unwrapExecute<TargetingResponse>(envelope, \"pilot.targeting\");\r\n return finalizeTargeting(body, workspaceRoot, workspaceListing, deniedPaths);\r\n}\r\n\r\nexport interface RunTargetingOptions {\r\n /** Overrides the environment switch. Tests, and (one day) a QuikTrack setting, pass this. */\r\n mode?: TargetingMode;\r\n /** Test seam: a fake filesystem, tighter limits, a fake clock or log for the loop. */\r\n loopDeps?: Partial<Omit<LoopDeps, \"post\">>;\r\n}\r\n\r\nconst CODE_LIKE = /^[A-Z0-9_]{1,40}$/;\r\n\r\n/**\r\n * `pilot.targeting`: which files to change. By default one call answered from the file listing alone.\r\n * With the read-only loop switched on (QUIKTR-1458: `QUIKPILOT_TARGETING_MODE=loop`) the AI may look\r\n * at the code first; if the loop cannot finish for an ordinary reason, the run falls back to the\r\n * single call and says so. A refusal never falls back (see targetingLoop.ts).\r\n */\r\nexport async function runTargeting(\r\n gateway: PilotPacket[\"gateway\"],\r\n design: PilotPacket[\"design\"],\r\n workspaceRoot: string | null,\r\n workspaceListing: string[],\r\n requiredTests: PilotPacket[\"requiredTests\"],\r\n deniedPaths: string[],\r\n testDiscovery: PilotPacket[\"testDiscovery\"],\r\n /** QUIKTR-1401 (\u00A720) \u2014 what the reviewer approved the change must NOT touch. Optional and last: every\r\n * existing caller is unchanged. */\r\n outOfScope: string[] = [],\r\n options: RunTargetingOptions = {},\r\n): Promise<TargetingResult> {\r\n const mode = options.mode ?? resolveTargetingMode();\r\n if (mode !== \"loop\") {\r\n return runSingleShot(gateway, design, workspaceRoot, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope);\r\n }\r\n\r\n const baseContext = buildContextData(design, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope);\r\n let summary: LoopSummary | undefined;\r\n let runtimeCode: string | undefined;\r\n let reason: FallbackReason;\r\n try {\r\n const looped = await runTargetingLoop(\r\n { baseContext, listing: workspaceListing, deniedPaths },\r\n { ...options.loopDeps, post: (contextData, signal) => postTargeting(gateway, contextData, signal) },\r\n );\r\n summary = looped.summary;\r\n const result = finalizeTargeting(looped.body as TargetingResponse, workspaceRoot, workspaceListing, deniedPaths);\r\n return { ...result, loop: summary };\r\n } catch (err) {\r\n // A refusal is never answered by trying again another way.\r\n if (err instanceof DeniedPathError || err instanceof SafetyRefusalError) throw err;\r\n if (err instanceof LoopFailure) {\r\n reason = err.reason;\r\n runtimeCode = err.runtimeCode;\r\n summary = err.summary ?? summary;\r\n } else {\r\n // Only finalizeTargeting can end up here: the loop got an answer, but it is not usable.\r\n reason = \"final_invalid\";\r\n }\r\n }\r\n\r\n const fellBack: LoopSummary = {\r\n turns: summary?.turns ?? 0,\r\n toolCalls: summary?.toolCalls ?? 0,\r\n readChars: summary?.readChars ?? 0,\r\n refused: summary?.refused ?? 0,\r\n reads: summary?.reads ?? [],\r\n stopReason: \"fallback\",\r\n fellBack: true,\r\n fallbackReason: reason,\r\n };\r\n const log = options.loopDeps?.log ?? ((e: Record<string, unknown>) => console.log(JSON.stringify(e)));\r\n log({\r\n event: \"targeting.loop_fallback\",\r\n reason,\r\n turn: fellBack.turns,\r\n toolCalls: fellBack.toolCalls,\r\n ...(runtimeCode && CODE_LIKE.test(runtimeCode) ? { runtimeCode } : {}),\r\n });\r\n\r\n // If this fails too, it fails the run exactly as it would have without the loop.\r\n const single = await runSingleShot(gateway, design, workspaceRoot, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope);\r\n return {\r\n ...single,\r\n loop: fellBack,\r\n warnings: [`QuikPilot's read-only targeting could not complete (${reason}); standard targeting was used instead.`],\r\n };\r\n}\r\n", "/**\r\n * QUIKTR-1458 \u2014 which way `pilot.targeting` runs.\r\n *\r\n * `single` is today's behaviour: one call, the model answers from the file listing alone. `loop` lets\r\n * the model look at the code first, through read-only tools (targetingLoop.ts). It is OFF unless\r\n * asked for, and only the exact word `loop` asks.\r\n *\r\n * Today the switch is an environment variable in the workflow file, set by hand. The long-term home\r\n * is a per-project QuikTrack setting carried in the run packet; `packetSetting` is that seam, so the\r\n * day it exists it is one argument at one call site and this precedence (setting, then environment,\r\n * then off) is already settled and tested. Nothing passes it yet.\r\n */\r\nexport type TargetingMode = \"single\" | \"loop\";\r\n\r\nexport const TARGETING_MODE_ENV = \"QUIKPILOT_TARGETING_MODE\";\r\n\r\nfunction parse(value: string | null | undefined): TargetingMode | null {\r\n if (typeof value !== \"string\") return null;\r\n const v = value.trim().toLowerCase();\r\n if (v === \"loop\") return \"loop\";\r\n if (v === \"single\") return \"single\";\r\n return null;\r\n}\r\n\r\nexport function resolveTargetingMode(\r\n env: NodeJS.ProcessEnv = process.env,\r\n packetSetting?: string | null,\r\n): TargetingMode {\r\n const fromSetting = parse(packetSetting);\r\n if (fromSetting) return fromSetting;\r\n return parse(env[TARGETING_MODE_ENV]) ?? \"single\";\r\n}\r\n", "import type { TargetKind, TargetingResult } from \"./targeting\";\r\nimport type { LoopStopReason, LoopSummary } from \"./targetingLoop\";\r\n\r\n/**\r\n * QUIKTR-1421 \u2014 a record of what pilot.targeting decided, reported to QuikTrack in the run's final callback so\r\n * \"which contextPaths did targeting list for the test?\" can be answered after the fact. Twice it could not\r\n * (QUIKSPL-16, then run 25): the AI Runtime's logs carry counts only, deliberately, and QuikTrack's run trail\r\n * stores a payload hash, so neither side kept what was actually DECIDED.\r\n *\r\n * PATHS AND CASE IDS ONLY (Suyash). Never case text, never `planStepsImplemented` (model-written prose about\r\n * the customer's code), never file content. The one free-text field is the NO_TARGET reason, cut to 300\r\n * characters with a flag saying so.\r\n *\r\n * Every cap below matches QuikTrack's `targetingRecordSchema`. That is not tidiness: a record QuikTrack finds\r\n * invalid is dropped, so a record over the caps is a record lost. Anything cut sets `truncated`.\r\n */\r\nconst MAX_TARGETS = 25;\r\nconst MAX_IDS_PER_TARGET = 50;\r\nconst MAX_CONTEXT_PATHS = 20;\r\nconst MAX_ADDED_PATHS = 20;\r\nconst MAX_SKIPPED_CONTEXT = 20;\r\nconst MAX_SKIPPED_CASES = 200;\r\nconst MAX_CONTEXT_RECORDS = 25;\r\nconst MAX_PATH_CHARS = 300;\r\nconst MAX_ID_CHARS = 100;\r\nconst MAX_REASON_CHARS = 300;\r\n// QUIKTR-1458 \u2014 the read-only loop's part of the record. These must match QuikTrack's schema when it adds the field.\r\nconst MAX_LOOP_READS = 50;\r\nconst MAX_FALLBACK_REASON_CHARS = 40;\r\n\r\n/** One `runCodegen` call: what targeting named as context, what the runner ADDED (QUIKTR-1419), and what it\r\n * skipped. `runCodegen` fills a caller-owned array of these, so the entries survive a later throw. */\r\nexport interface CodegenContextRecord {\r\n targetPath: string;\r\n contextPaths: string[];\r\n addedPaths: string[];\r\n skipped: { path: string; reason: string }[];\r\n /** QUIKTR-1454 \u2014 the part of `addedPaths` that came from the target's own imports. Log line only: QuikTrack's\r\n * record keeps `addedPaths` (which includes them) and strips fields it does not know. Omitted when empty. */\r\n importedPaths?: string[];\r\n /** QUIKTR-1454 \u2014 path-alias imports (`@/x`) seen and not followed. Counted, not listed. Omitted when zero. */\r\n aliasImports?: number;\r\n /** The runtime refused the context as too large and the call was retried WITHOUT the added files, so\r\n * `addedPaths` is empty even though files were offered first. */\r\n retriedWithoutAdded?: true;\r\n}\r\n\r\n/**\r\n * QUIKTR-1458 \u2014 what the read-only targeting loop looked at. PATHS AND COUNTS ONLY: never file content, a\r\n * search text or the AI's reasoning. Present only when the loop ran (or was tried and fell back); an older\r\n * QuikTrack strips the key it does not know. It is how a reviewer can see what the AI read, which is why\r\n * refused reads are listed too.\r\n */\r\nexport interface LoopRecord {\r\n turns: number;\r\n toolCalls: number;\r\n refused: number;\r\n stopReason: LoopStopReason;\r\n fellBack?: true;\r\n fallbackReason?: string;\r\n reads: { path: string; startLine?: number; endLine?: number; chars: number; refused?: true }[];\r\n truncated?: true;\r\n}\r\n\r\nexport interface TargetingRecord {\r\n outcome: \"TARGETED\" | \"NO_TARGET\";\r\n noTargetReason?: string;\r\n noTargetReasonTruncated?: true;\r\n targets: { path: string; kind: TargetKind; contextPaths: string[]; automationIds: string[] }[];\r\n skippedCaseIds: string[];\r\n codegenContext: CodegenContextRecord[];\r\n truncated?: true;\r\n /** QUIKTR-1458 \u2014 see LoopRecord. */\r\n loop?: LoopRecord;\r\n}\r\n\r\n/** Keeps at most `max` non-empty entries no longer than `maxChars`, telling the caller if anything was cut. A\r\n * too-long value is DROPPED, not shortened: a cut-off path is a wrong path. */\r\nfunction clampList(values: string[] | undefined, max: number, maxChars: number): { kept: string[]; cut: boolean } {\r\n let cut = false;\r\n const kept: string[] = [];\r\n for (const raw of values ?? []) {\r\n const v = typeof raw === \"string\" ? raw.trim() : \"\";\r\n if (v.length === 0) continue;\r\n if (v.length > maxChars || kept.length >= max) {\r\n cut = true;\r\n continue;\r\n }\r\n kept.push(v);\r\n }\r\n return { kept, cut };\r\n}\r\n\r\nfunction wholeNumber(n: unknown): number {\r\n return typeof n === \"number\" && Number.isInteger(n) && n >= 0 ? n : 0;\r\n}\r\n\r\n/** A too-long path is DROPPED, not shortened (a cut-off path is a wrong path), and the cut is flagged. */\r\nfunction clampLoop(loop: LoopSummary): LoopRecord {\r\n let cut = false;\r\n const reads: LoopRecord[\"reads\"] = [];\r\n for (const r of loop.reads ?? []) {\r\n if (reads.length >= MAX_LOOP_READS) {\r\n cut = true;\r\n break;\r\n }\r\n const path = typeof r.path === \"string\" ? r.path.trim() : \"\";\r\n if (path.length === 0 || path.length > MAX_PATH_CHARS) {\r\n cut = true;\r\n continue;\r\n }\r\n reads.push({\r\n path,\r\n ...(Number.isInteger(r.startLine) ? { startLine: r.startLine } : {}),\r\n ...(Number.isInteger(r.endLine) ? { endLine: r.endLine } : {}),\r\n chars: wholeNumber(r.chars),\r\n ...(r.refused ? { refused: true as const } : {}),\r\n });\r\n }\r\n return {\r\n turns: wholeNumber(loop.turns),\r\n toolCalls: wholeNumber(loop.toolCalls),\r\n refused: wholeNumber(loop.refused),\r\n stopReason: loop.stopReason,\r\n ...(loop.fellBack ? { fellBack: true as const } : {}),\r\n ...(loop.fallbackReason ? { fallbackReason: String(loop.fallbackReason).slice(0, MAX_FALLBACK_REASON_CHARS) } : {}),\r\n reads,\r\n ...(cut ? { truncated: true as const } : {}),\r\n };\r\n}\r\n\r\nexport function buildTargetingRecord(targeting: TargetingResult, contextLog: CodegenContextRecord[]): TargetingRecord {\r\n let truncated = false;\r\n const note = (cut: boolean) => {\r\n if (cut) truncated = true;\r\n };\r\n\r\n if (targeting.outcome === \"NO_TARGET\") {\r\n const record: TargetingRecord = { outcome: \"NO_TARGET\", targets: [], skippedCaseIds: [], codegenContext: [] };\r\n const reason = (targeting.reason ?? \"\").trim();\r\n if (reason.length > 0) {\r\n record.noTargetReason = reason.slice(0, MAX_REASON_CHARS);\r\n if (reason.length > MAX_REASON_CHARS) record.noTargetReasonTruncated = true;\r\n }\r\n if (targeting.loop) record.loop = clampLoop(targeting.loop);\r\n return record;\r\n }\r\n\r\n const targets: TargetingRecord[\"targets\"] = [];\r\n for (const t of targeting.targets) {\r\n if (targets.length >= MAX_TARGETS) {\r\n truncated = true;\r\n break;\r\n }\r\n const path = typeof t.path === \"string\" ? t.path.trim() : \"\";\r\n if (path.length === 0 || path.length > MAX_PATH_CHARS) {\r\n truncated = true;\r\n continue;\r\n }\r\n const contextPaths = clampList(t.contextPaths, MAX_CONTEXT_PATHS, MAX_PATH_CHARS);\r\n const automationIds = clampList(t.automationIds, MAX_IDS_PER_TARGET, MAX_ID_CHARS);\r\n note(contextPaths.cut);\r\n note(automationIds.cut);\r\n targets.push({ path, kind: t.kind, contextPaths: contextPaths.kept, automationIds: automationIds.kept });\r\n }\r\n\r\n const skipped = clampList(\r\n (targeting.skippedCases ?? []).map((c) => c.automationId),\r\n MAX_SKIPPED_CASES,\r\n MAX_ID_CHARS,\r\n );\r\n note(skipped.cut);\r\n\r\n const codegenContext: CodegenContextRecord[] = [];\r\n for (const entry of contextLog) {\r\n if (codegenContext.length >= MAX_CONTEXT_RECORDS) {\r\n truncated = true;\r\n break;\r\n }\r\n const targetPath = typeof entry.targetPath === \"string\" ? entry.targetPath.trim() : \"\";\r\n if (targetPath.length === 0 || targetPath.length > MAX_PATH_CHARS) {\r\n truncated = true;\r\n continue;\r\n }\r\n const contextPaths = clampList(entry.contextPaths, MAX_CONTEXT_PATHS, MAX_PATH_CHARS);\r\n const addedPaths = clampList(entry.addedPaths, MAX_ADDED_PATHS, MAX_PATH_CHARS);\r\n const skippedPaths = clampList(\r\n (entry.skipped ?? []).map((s) => s.path),\r\n MAX_SKIPPED_CONTEXT,\r\n MAX_PATH_CHARS,\r\n );\r\n note(contextPaths.cut);\r\n note(addedPaths.cut);\r\n note(skippedPaths.cut);\r\n const reasonByPath = new Map((entry.skipped ?? []).map((s) => [s.path.trim(), s.reason]));\r\n codegenContext.push({\r\n targetPath,\r\n contextPaths: contextPaths.kept,\r\n addedPaths: addedPaths.kept,\r\n skipped: skippedPaths.kept.map((path) => ({ path, reason: String(reasonByPath.get(path) ?? \"skipped\").slice(0, 40) })),\r\n ...(entry.retriedWithoutAdded ? { retriedWithoutAdded: true as const } : {}),\r\n });\r\n }\r\n\r\n const record: TargetingRecord = {\r\n outcome: \"TARGETED\",\r\n targets,\r\n skippedCaseIds: skipped.kept,\r\n codegenContext,\r\n };\r\n if (truncated) record.truncated = true;\r\n if (targeting.loop) record.loop = clampLoop(targeting.loop);\r\n return record;\r\n}\r\n", "import type { PilotTarget } from \"./targeting\";\r\n\r\n/**\r\n * QUIKTR-1315 \u2014 targeting can claim a test case's `automationId` against a SOURCE-file target while\r\n * proposing a separate, empty test-file target alongside it (no plan steps, no automationIds).\r\n * Verified against a real captured AI Runtime sample (`targeting-versioned.json`): the model wrote\r\n * `tests/auth/login.test.ts` with `automationIds: []` and claimed all three cases on\r\n * `src/auth/middleware.ts`/`src/auth/login.ts` instead. When that happens, the generated test lands\r\n * inside a source file the repository's test runner never discovers \u2014 the case has zero real\r\n * coverage even though its id is present in the generated text, and \u00A715's own completeness rule\r\n * (every case appears exactly once) is satisfied regardless.\r\n *\r\n * Two detectors, both using the repository's OWN JUnit report as ground truth for \"which files the\r\n * test runner actually looks at\" \u2014 no naming convention, derived by running the repo's own tooling,\r\n * language-neutral by construction:\r\n *\r\n * `checkTestPlacement` \u2014 BEFORE the write, against the BASELINE report (pre-codegen).\r\n * Scoped to EXISTING targets only: a NEW_FILE test target is never\r\n * in the baseline set because it does not exist yet, so this check\r\n * must never run on one \u2014 a legitimate first test file would be\r\n * indistinguishable from the suspicious case.\r\n * `checkAutomationIdCoverage` \u2014 AFTER the change, against the AFTER report (post-codegen). The\r\n * stronger of the two: catches inverted placement regardless of\r\n * why it happened, including whatever the first check's loose\r\n * file-matching missed.\r\n *\r\n * Both are TRIPWIRES, not proofs \u2014 same posture as this package's other `*Check.ts` scanners\r\n * (`dependencyCheck.ts`, `scopeCheck.ts`): a minimal heuristic against an arbitrary target repo,\r\n * deliberately erring toward under-flagging (fewer false positives blocking a real run) rather than\r\n * over-flagging, since both are hard-failing checks.\r\n */\r\nexport interface TestPlacementViolation {\r\n file: string;\r\n automationIds: string[];\r\n}\r\n\r\nexport interface TestPlacementCheck {\r\n blocked: boolean;\r\n violations: TestPlacementViolation[];\r\n}\r\n\r\n/** A target's path counts as \"discovered\" if it exactly equals, is a suffix of, or has as a suffix,\r\n * any candidate string the JUnit report produced. Loose on purpose: `classname` is a real file path\r\n * for Vitest and derivable for pytest, but not guaranteed for Jest or Go \u2014 see this file's module\r\n * docblock. A tighter, exact-only match would false-positive on every repo where the report's path\r\n * is relative to a different root than the target's own path. */\r\nfunction isDiscovered(targetPath: string, discoveredFiles: Set<string>): boolean {\r\n const normalized = targetPath.replace(/\\\\/g, \"/\");\r\n for (const candidate of discoveredFiles) {\r\n if (candidate === normalized) return true;\r\n if (candidate.endsWith(normalized) || normalized.endsWith(candidate)) return true;\r\n }\r\n return false;\r\n}\r\n\r\n/**\r\n * `discoveredFiles` is the BASELINE run's `TestSnapshot.discoveredFiles` \u2014 `undefined`/`null`/empty\r\n * all mean \"can't tell,\" and the check no-ops rather than blocking on a question it can't answer\r\n * (no baseline report at all, or one with no file-shaped attribution). A repository producing no\r\n * JUnit report gets no detector \u2014 not a gap here, `readiness-panel`'s existing dry-run warning\r\n * (QUIKTR-1084) is what tells the user to fix that.\r\n */\r\nexport function checkTestPlacement(\r\n targets: PilotTarget[],\r\n discoveredFiles: Set<string> | null | undefined,\r\n): TestPlacementCheck {\r\n if (!discoveredFiles || discoveredFiles.size === 0) return { blocked: false, violations: [] };\r\n\r\n const violations: TestPlacementViolation[] = [];\r\n for (const target of targets) {\r\n if (target.kind !== \"EXISTING\") continue;\r\n if (!target.automationIds || target.automationIds.length === 0) continue;\r\n if (!isDiscovered(target.path, discoveredFiles)) {\r\n violations.push({ file: target.path, automationIds: target.automationIds });\r\n }\r\n }\r\n return { blocked: violations.length > 0, violations };\r\n}\r\n\r\nexport function describeTestPlacementViolations(check: TestPlacementCheck): string {\r\n return check.violations\r\n .map(\r\n (v) =>\r\n `${v.file} claims test case(s) ${v.automationIds.join(\", \")} but the repository's own test runner never discovered this file`,\r\n )\r\n .join(\"; \");\r\n}\r\n\r\nexport interface AutomationCoverageCheck {\r\n blocked: boolean;\r\n missing: string[];\r\n}\r\n\r\n/**\r\n * `discoveredAutomationIds` is the AFTER run's `TestSnapshot.discoveredAutomationIds` \u2014\r\n * `undefined`/`null` means \"can't tell\" (no post-codegen report at all), same no-op posture as\r\n * `checkTestPlacement`. An EMPTY (present) set is different and deliberate: it means a report\r\n * existed but nothing in it carried a bracketed id at all, which \u2014 if this run claimed any\r\n * `automationIds` \u2014 is exactly the failure this check exists to catch, so it blocks.\r\n */\r\nexport function checkAutomationIdCoverage(\r\n targets: PilotTarget[],\r\n discoveredAutomationIds: Set<string> | null | undefined,\r\n): AutomationCoverageCheck {\r\n if (discoveredAutomationIds === null || discoveredAutomationIds === undefined) {\r\n return { blocked: false, missing: [] };\r\n }\r\n\r\n const claimed = new Set<string>();\r\n for (const target of targets) {\r\n for (const id of target.automationIds ?? []) claimed.add(id);\r\n }\r\n const missing = [...claimed].filter((id) => !discoveredAutomationIds.has(id));\r\n return { blocked: missing.length > 0, missing };\r\n}\r\n\r\nexport function describeAutomationCoverageViolations(check: AutomationCoverageCheck): string {\r\n return `test case(s) ${check.missing.join(\", \")} have no matching test discovered in the test run \u2014 generated, but never executed`;\r\n}\r\n", "import { describeQuikTrackFailure } from \"./quiktrackError\";\r\n\r\ninterface TokenExchangeResponse {\r\n success: boolean;\r\n data: { runToken: string; expiresAt: string };\r\n}\r\n\r\n/** Exchange a GitHub OIDC ID token for a QuikPilot run token (QUIKTR-805) \u2014 mirrors `packet.ts`'s\r\n * `fetchPacket` shape: bearer auth, `{success,data}` envelope, same error-message style. */\r\nexport async function exchangeForRunToken(tokenUrl: string, oidcToken: string): Promise<string> {\r\n const res = await fetch(tokenUrl, {\r\n method: \"POST\",\r\n headers: { Authorization: `Bearer ${oidcToken}` },\r\n });\r\n if (!res.ok) {\r\n throw new Error(`Exchange run token failed: ${await describeQuikTrackFailure(res)}`);\r\n }\r\n const body = (await res.json()) as TokenExchangeResponse;\r\n if (body.success !== true) {\r\n throw new Error(\"Exchange run token failed: response did not carry success:true\");\r\n }\r\n return body.data.runToken;\r\n}\r\n", "import type { TestSnapshot } from \"./regressionCheck\";\r\n\r\n/**\r\n * QUIKTR-1448 \u2014 a test that ran before the change and is missing from the final report. The regression gate\r\n * only looks at tests present AFTER, so a rewritten test file that drops tests passes it (QuikSplit PR #4\r\n * lost 9 tests this way). Warn-only: the fix may mean to remove or rename a test, and a user has no way yet\r\n * to approve that, so nothing here blocks a run.\r\n */\r\nexport interface VanishedTests {\r\n /** Test ids (`classname::name`), at most MAX_VANISHED_NAMES. */\r\n names: string[];\r\n /** How many went missing, including any names cut by the cap. */\r\n total: number;\r\n}\r\n\r\n/** Bounds the callback body and the pull request description. */\r\nexport const MAX_VANISHED_NAMES = 50;\r\n\r\n/** Null when nothing is missing, or when either run produced no report (cannot tell \u2014 same posture as\r\n * `checkForRegressions`, which also stays quiet then). A test that still exists and now fails is a\r\n * regression, not a missing test, so it is not named here. */\r\nexport function findVanishedTests(baseline: TestSnapshot, after: TestSnapshot): VanishedTests | null {\r\n if (!baseline.results || !after.results) return null;\r\n const missing = [...baseline.results.keys()].filter((id) => !after.results!.has(id));\r\n if (missing.length === 0) return null;\r\n return { names: missing.slice(0, MAX_VANISHED_NAMES), total: missing.length };\r\n}\r\n\r\n/** The run-event warning. A COUNT only: test titles are the customer's text and the event reason is stored by\r\n * QuikTrack; the titles go to the pull request description instead. */\r\nexport function describeVanishedTests(vanished: VanishedTests): string {\r\n const noun = vanished.total === 1 ? \"1 test\" : `${vanished.total} tests`;\r\n return `${noun} that ran before this change ${vanished.total === 1 ? \"is\" : \"are\"} missing from the final test report; the pull request lists ${vanished.total === 1 ? \"it\" : \"them\"}.`;\r\n}\r\n", "import { reportBack } from \"./callback\";\r\nimport { runCommand, runTestCommand } from \"./commands\";\r\nimport { commitAndPush } from \"./commit\";\r\nimport { buildJudgedByPool, flushCodegenResults, type CodegenFileResult } from \"./codegen\";\r\nimport { resolveCodegenMode } from \"./codegenMode\";\r\nimport type { CodegenLoopRecord } from \"./codegenLoopRecord\";\r\nimport { runCodegenStep } from \"./codegenStep\";\r\nimport {\r\n checkImportDependencies,\r\n describeDependencyViolations,\r\n readDeclaredDependencies,\r\n resolveAliasPrefixes,\r\n} from \"./dependencyCheck\";\r\nimport type { PilotRunEnv } from \"./env\";\r\nimport { checkGuardrail } from \"./guardrail\";\r\nimport { checkoutTargetBranch } from \"./git\";\r\nimport { exchangeForInstallationToken } from \"./installationToken\";\r\nimport { fetchGithubOidcToken } from \"./oidc\";\r\nimport { describeOverlapWarnings, findOverlappingSteps } from \"./overlapCheck\";\r\nimport { fetchPacket, type PilotPacket } from \"./packet\";\r\nimport { writePhase0Marker } from \"./phase0\";\r\nimport { describeUnmatchedAutomationIds, readTestReportBytes, reportToQuikTest } from \"./quiktest\";\r\nimport { runBaselineCheck, type BaselineFindings } from \"./baselineCheck\";\r\nimport { writeFailureArtifact } from \"./failureArtifact\";\r\nimport { describeFailureReason, failureSummary } from \"./failureReason\";\r\nimport { captureBaselineSnapshot, captureTestSnapshot, checkForRegressions, describeRegressions } from \"./regressionCheck\";\r\nimport { checkApiScope, describeScopeViolations } from \"./scopeCheck\";\r\nimport { listWorkspaceFiles, runTargeting, type TargetingResult } from \"./targeting\";\r\nimport { buildTargetingRecord, type CodegenContextRecord } from \"./targetingRecord\";\r\nimport {\r\n checkAutomationIdCoverage,\r\n checkTestPlacement,\r\n describeAutomationCoverageViolations,\r\n describeTestPlacementViolations,\r\n} from \"./testPlacementCheck\";\r\nimport { exchangeForRunToken } from \"./tokenExchange\";\r\nimport { describeVanishedTests, findVanishedTests, type VanishedTests } from \"./vanishedTests\";\r\n\r\n/**\r\n * QUIKTR-572 \u2014 the run sequence, preserving the original inlined workflow's error semantics exactly:\r\n * Fetch packet / Checkout branch / Setup / Lint / Guardrail are hard failures that skip everything\r\n * remaining except the QuikTest report and the final callback (both ran under `if: always()`\r\n * before). Test alone is soft \u2014 its failure never blocks Guardrail/Commit/Push and never flips the\r\n * final callback to `failed` (QuikTest owns per-test outcomes; captured here only for the log).\r\n *\r\n * QUIKTR-1045 \u2014 Format is soft, same reasoning as Test: a formatting hiccup must not block a\r\n * correct fix. Caught locally at its own call site (not a new commands.ts function) and logged;\r\n * never sets hardFailure, never blocks the Lint/regression-check/Guardrail/Commit/Push that follow.\r\n *\r\n * QUIKTR-805 \u2014 the very first thing the run does is exchange a GitHub OIDC ID token for a run\r\n * token (no QuikPilot credential exists before this). It is folded into the same top-level try as\r\n * every other hard failure, with one deliberate exception: if THIS step fails, there is no run\r\n * token to report failure with either, so reportToQuikTest/reportBack are skipped rather than\r\n * called with nothing to authenticate \u2014 the job's own log is the only record, and the run's\r\n * existing DISPATCHING-expiry sweep is what notices it (same accepted fallback dispatch.ts's own\r\n * docblock documents for its \"RESIDUAL WINDOW\" crash case).\r\n *\r\n * QUIKTR-804 \u2014 immediately before pushing, the run token (already in hand by this point) is\r\n * exchanged for a repo-scoped GitHub installation token, which authenticates the push itself\r\n * instead of the ambient `github.token`. Folded into the EXISTING Guardrail/Commit/Push try block\r\n * below rather than given its own \u2014 a failure here is just another commit/push hard failure, with\r\n * no new edge case: unlike the OIDC exchange above, the run token already exists, so\r\n * reportToQuikTest/reportBack fire normally either way.\r\n */\r\n/** Caller narrows `RunnerEnv` to `PilotRunEnv` first \u2014 `index.ts` branches on `mode` before either\r\n * this or `readinessCheck.ts`'s `runReadinessCheck` is invoked. No default parameter: the old\r\n * `readRunnerEnv()` default returned this shape unconditionally, which is no longer true now\r\n * that `RunnerEnv` is a union (QUIKTR-1084). */\r\nexport async function run(env: PilotRunEnv): Promise<{ hardFailure: boolean }> {\r\n let hardFailure = false;\r\n let packet: PilotPacket | undefined;\r\n let branch: string | undefined;\r\n let runToken: string | undefined;\r\n const warnings: string[] = [];\r\n // Why the run failed, for the final callback. The message used to be printed to the job log and lost to\r\n // QuikTrack, which then knew only \"failed\". Scrubbed of credentials and cut before it is kept.\r\n const failureReasons: string[] = [];\r\n const recordFailure = (err: unknown) => {\r\n const message = err instanceof Error ? err.message : String(err);\r\n console.error(message);\r\n // The job log gets the full message; what is reported is the summary when the error quotes the AI Runtime's reply.\r\n const reason = describeFailureReason(failureSummary(err), runToken ? [runToken] : []);\r\n if (reason) failureReasons.push(reason);\r\n };\r\n // QUIKTR-1067 \u2014 hoisted out of the try block's TARGETED branch: commitAndPush\r\n // needs it later, outside that scope, to build a real commit message instead\r\n // of the \"Phase 0 skeleton\" placeholder. Defaults false \u2014 correct for\r\n // NO_TARGET and for any early hard failure, both of which skip commitAndPush\r\n // or must fall back to the marker message anyway.\r\n let targeted = false;\r\n // QUIKTR-1333 \u2014 same hoisting reason as `targeted` above: reportToQuikTest is\r\n // called later, outside the TARGETED branch's scope where `results` lives.\r\n // Empty for NO_TARGET and any early failure \u2014 correct, since nothing was\r\n // written either way.\r\n let generatedFilePaths: string[] = [];\r\n // QUIKTR-1447 \u2014 hoisted for the same reason, so a run that fails AFTER code generation can keep what was generated.\r\n // Held in memory because the dependency, scope and placement checks fail before the files are flushed. The final\r\n // test report is read right after the post-generation test run and nowhere else: a report on disk before that is\r\n // the baseline's, and reportToQuikTest deletes it once sent.\r\n let generatedResults: CodegenFileResult[] = [];\r\n let finalTestReport: Buffer | null = null;\r\n // QUIKTR-1421 \u2014 hoisted for the same reason: the record is built at the end, outside the try, so a run that\r\n // dies in codegen still reports what targeting decided and which context codegen had already assembled.\r\n let targetingResult: TargetingResult | undefined;\r\n // QUIKTR-1402 \u2014 hoisted for the same reason: reported at the end, outside the try. Undefined when the check\r\n // did not run or flagged nothing.\r\n let baselineFindings: BaselineFindings | undefined;\r\n // QUIKTR-1448 \u2014 hoisted for the same reason: reported at the end, and it must survive a run that then fails on a\r\n // regression. Undefined when no test went missing or a report was not available.\r\n let vanishedTests: VanishedTests | undefined;\r\n const contextLog: CodegenContextRecord[] = [];\r\n // QUIKTR-1458 \u00A724 \u2014 what the code-writing loop did, when it ran or was tried. Hoisted so it is reported even when the run then fails.\r\n const codegenOut: { loop?: CodegenLoopRecord } = {};\r\n\r\n try {\r\n runToken = await exchangeForRunToken(env.tokenUrl, await fetchGithubOidcToken());\r\n packet = await fetchPacket(env.packetUrl, runToken, env.githubRunId);\r\n checkoutTargetBranch(packet.targetBranch);\r\n\r\n const workspaceListing = listWorkspaceFiles(packet.workspaceRoot);\r\n // QUIKTR-1401 (\u00A720) \u2014 the reviewer's approved \"must not change\" list, with blank entries dropped. A QuikTrack\r\n // that predates the field sends none, which is the same as an empty list.\r\n const outOfScope = (packet.outOfScope ?? []).map((entry) => entry.trim()).filter((entry) => entry.length > 0);\r\n const targeting = await runTargeting(\r\n packet.gateway,\r\n packet.design,\r\n packet.workspaceRoot,\r\n workspaceListing,\r\n packet.requiredTests,\r\n packet.guardrails.deniedPaths,\r\n packet.testDiscovery,\r\n outOfScope,\r\n );\r\n targetingResult = targeting;\r\n // QUIKTR-1458 \u2014 the read-only loop could not finish and the single call was used instead. Not blocking, but\r\n // said out loud: it changes what the AI was shown, and a run that quietly stopped using the loop would make\r\n // every comparison between the two modes meaningless.\r\n for (const w of targeting.warnings ?? []) {\r\n warnings.push(w);\r\n console.warn(`QuikPilot targeting warning (not blocking): ${w}`);\r\n }\r\n // QUIKTR-1448 \u2014 targeting called an existing file a new one; runTargeting already treated it as existing, so the\r\n // model saw its content. Said out loud because it is a mistake in the plan, not something to hide.\r\n if (targeting.outcome === \"TARGETED\") {\r\n for (const path of targeting.correctedKinds ?? []) {\r\n const w = `QuikPilot named ${path} as a new file, but it already exists in the repository. It was treated as an existing file so its current content was kept in view.`;\r\n warnings.push(w);\r\n console.warn(`QuikPilot targeting warning (not blocking): ${w}`);\r\n console.log(JSON.stringify({ event: \"targeting.kind_corrected\", path }));\r\n }\r\n }\r\n if (targeting.outcome === \"NO_TARGET\") {\r\n // Nothing to write \u2014 a marker commit is more honest than an empty one. Nothing was\r\n // generated, so there's nothing to regress against \u2014 Test stays soft, unchanged.\r\n writePhase0Marker(env.runId);\r\n runCommand(packet.commands.setup, \"Setup\");\r\n runCommand(packet.commands.lint, \"Lint\");\r\n runTestCommand(packet.commands.test);\r\n } else {\r\n targeted = true;\r\n // QUIKTR-1083 (\u00A715.3) \u2014 informational, never blocking: a case with no given/when/then has\r\n // nothing to test, and the runtime already enforces every requiredTests case lands in\r\n // exactly one of a target's automationIds or here, never both, never neither. Folded into\r\n // the same warnings array the overlap-check below already populates and reportBack sends.\r\n if (targeting.skippedCases?.length) {\r\n for (const skipped of targeting.skippedCases) {\r\n const w = `Test case ${skipped.automationId} has no given/when/then \u2014 skipped, no test was written for it.`;\r\n warnings.push(w);\r\n console.warn(`QuikPilot targeting warning (not blocking): ${w}`);\r\n }\r\n }\r\n // QUIKTR-1064 \u2014 cheap: two targets whose planStepsImplemented describe the same rule (the\r\n // real fix is pilot.targeting's prompt, an AI Runtime change, not this package's \u2014 see\r\n // overlapCheck.ts). QUIKTR-1081 \u2014 a literal identical instruction now blocks outright: two\r\n // legitimate halves of one change never share the exact same instruction, and PR #23 merged\r\n // 28 seconds after opening on exactly this signal. A near-identical, reworded pair stays a\r\n // non-blocking warning, logged and reported back, same as before.\r\n const overlaps = findOverlappingSteps(targeting.targets);\r\n const blockingOverlaps = overlaps.filter((o) => o.severity === \"identical\");\r\n const softOverlaps = overlaps.filter((o) => o.severity === \"similar\");\r\n if (softOverlaps.length > 0) {\r\n const overlapWarnings = describeOverlapWarnings(softOverlaps);\r\n warnings.push(...overlapWarnings);\r\n for (const w of overlapWarnings) {\r\n console.warn(`QuikPilot targeting warning (not blocking): ${w}`);\r\n }\r\n }\r\n if (blockingOverlaps.length > 0) {\r\n throw new Error(\r\n `QuikPilot's generated plan gives two files identical instructions \u2014 ${describeOverlapWarnings(blockingOverlaps).join(\"; \")}`,\r\n );\r\n }\r\n\r\n // QUIKTR-1036 \u2014 Setup moves here (was after codegen/flush): the baseline test needs\r\n // dependencies installed, but has to run against the PRE-codegen tree. Installing\r\n // dependencies doesn't depend on which application source files exist, so this is safe, and\r\n // running Setup a second time later would undercut \"the baseline costs almost no wall-clock.\"\r\n runCommand(packet.commands.setup, \"Setup\");\r\n\r\n // \u00A718 \u2014 built once, from every case claimed by any target in the run, minus the\r\n // NO_BEHAVIOUR skips above. Sent only to code targets (codegen.ts's own else-branch);\r\n // targeting.skippedCases is the same list already folded into warnings just above.\r\n const judgedByPool = buildJudgedByPool(\r\n packet.requiredTests,\r\n targeting.targets,\r\n targeting.skippedCases ?? [],\r\n );\r\n\r\n // Baseline runs concurrently with codegen's network-bound calls \u2014 codegen writes nothing\r\n // until flushCodegenResults, so there's nothing for the baseline to race against.\r\n const [baseline, results] = await Promise.all([\r\n captureBaselineSnapshot(packet.commands.test),\r\n runCodegenStep({\r\n mode: resolveCodegenMode(),\r\n gateway: packet.gateway,\r\n targets: targeting.targets,\r\n workspaceListing,\r\n requiredTests: packet.requiredTests,\r\n deniedPaths: packet.guardrails.deniedPaths,\r\n judgedByPool,\r\n warnings,\r\n contextLog,\r\n outOfScope,\r\n testDiscovery: packet.testDiscovery,\r\n skippedCases: targeting.skippedCases ?? [],\r\n out: codegenOut,\r\n }),\r\n ]);\r\n\r\n generatedResults = results;\r\n\r\n // QUIKTR-1045 \u2014 checked on the in-memory results, BEFORE anything is\r\n // written: an invented import is never written to disk at all, matching\r\n // the same all-or-nothing treatment every other codegen failure already\r\n // gets here. Hard failure \u2014 a generation that imports a package this\r\n // repository doesn't have can't be trusted.\r\n const depCheck = checkImportDependencies(\r\n results,\r\n readDeclaredDependencies(results, packet.workspaceRoot),\r\n resolveAliasPrefixes(results, packet.workspaceRoot),\r\n );\r\n if (depCheck.blocked) {\r\n throw new Error(\r\n `QuikPilot's generated code imports packages this repository doesn't have \u2014 ${describeDependencyViolations(depCheck)}`,\r\n );\r\n }\r\n\r\n // QUIKTR-1081 \u2014 QUIKSPL-5's PR #22: codegen added an undeclared PUT endpoint alongside the\r\n // fix nobody asked for. Checked here for the same reason as the dependency check above \u2014\r\n // in-memory, before anything is written \u2014 against the design's own declared apiChanges.\r\n const scopeCheck = checkApiScope(results, targeting.targets, packet.design?.apiChanges ?? []);\r\n if (scopeCheck.blocked) {\r\n throw new Error(\r\n `QuikPilot's generated code exceeds the approved design \u2014 ${describeScopeViolations(scopeCheck)}`,\r\n );\r\n }\r\n\r\n // QUIKTR-1315 \u2014 same \"in-memory results, before anything is written\" point as the two checks\r\n // above: a test case claimed against a source-file target instead of the real test file has\r\n // zero coverage even though its id is present, and nothing else here catches that. Uses the\r\n // BASELINE run's JUnit report (already captured above) as the ground truth for which files\r\n // the test runner actually discovers \u2014 never the workspace listing, which includes files the\r\n // runner never looks at.\r\n const placementCheck = checkTestPlacement(targeting.targets, baseline.discoveredFiles);\r\n if (placementCheck.blocked) {\r\n throw new Error(\r\n `QuikPilot's generated tests are not where the test runner will find them \u2014 ${describeTestPlacementViolations(placementCheck)}`,\r\n );\r\n }\r\n\r\n // QUIKTR-1402 \u2014 run the generated tests alone on the still-untouched tree and flag a non-Regression\r\n // case that already passes there. After the in-memory checks above (no point spending the time on a\r\n // run that is about to fail) and before the flush (the code files are still the originals). Flag-only:\r\n // it never throws out of here, and a surprise from it must not cost the run.\r\n try {\r\n const baselineCheck = await runBaselineCheck({\r\n targets: targeting.targets,\r\n results,\r\n testFileCmd: packet.commands.testFile,\r\n requiredTestTypes: packet.requiredTestTypes,\r\n });\r\n warnings.push(...baselineCheck.warnings);\r\n baselineFindings = baselineCheck.findings ?? undefined;\r\n } catch (err) {\r\n const message = `Baseline check could not run: ${err instanceof Error ? err.message : String(err)}`;\r\n console.error(message);\r\n warnings.push(message);\r\n }\r\n\r\n // QUIKTR-1333 \u2014 the files QuikPilot actually generated or edited this run, exactly what\r\n // reportToQuikTest's generatedFiles param needs to scope the unmatched-id warning. runCodegen\r\n // is all-or-nothing, so by this point `results` is the complete, successful set \u2014 nothing\r\n // extra needed from targeting.targets.\r\n generatedFilePaths = results.map((r) => r.targetPath);\r\n\r\n flushCodegenResults(results);\r\n try {\r\n runCommand(packet.commands.format, \"Format\");\r\n } catch (err) {\r\n // QUIKTR-1045 \u2014 soft, like Test: see the file docblock.\r\n console.error(`Format failed (not blocking): ${err instanceof Error ? err.message : String(err)}`);\r\n }\r\n runCommand(packet.commands.lint, \"Lint\");\r\n\r\n const after = captureTestSnapshot(packet.commands.test);\r\n finalTestReport = readTestReportBytes();\r\n // QUIKTR-1448 \u2014 before the regression throw below, so a run that then fails still reports it. Warn-only.\r\n vanishedTests = findVanishedTests(baseline, after) ?? undefined;\r\n if (vanishedTests) {\r\n const w = describeVanishedTests(vanishedTests);\r\n warnings.push(w);\r\n console.warn(`QuikPilot test warning (not blocking): ${w}`);\r\n }\r\n const check = checkForRegressions(baseline, after);\r\n if (check.blocked) {\r\n throw new Error(\r\n `QuikPilot's generated code introduced test failures \u2014 ${describeRegressions(check)}`,\r\n );\r\n }\r\n\r\n // QUIKTR-1315 \u2014 the stronger of the two placement checks: run against the REAL, post-codegen\r\n // JUnit report, so it catches inverted placement regardless of why it happened, including\r\n // whatever checkTestPlacement's baseline-only, loose file-matching missed above.\r\n const coverageCheck = checkAutomationIdCoverage(targeting.targets, after.discoveredAutomationIds);\r\n if (coverageCheck.blocked) {\r\n throw new Error(\r\n `QuikPilot's generated tests were not executed \u2014 ${describeAutomationCoverageViolations(coverageCheck)}`,\r\n );\r\n }\r\n }\r\n } catch (err) {\r\n hardFailure = true;\r\n recordFailure(err);\r\n }\r\n\r\n if (!runToken) {\r\n console.error(\"No run token \u2014 the OIDC exchange failed before QuikTrack could be reached.\");\r\n return { hardFailure: true };\r\n }\r\n\r\n const quikTestReport = await reportToQuikTest({\r\n resultsUrl: packet?.quikTest?.resultsUrl,\r\n runToken,\r\n githubServerUrl: env.githubServerUrl,\r\n githubRepository: env.githubRepository,\r\n githubRunId: env.githubRunId,\r\n generatedFiles: generatedFilePaths,\r\n });\r\n // QUIKTR-1374 \u2014 the ingest response already knows which generated automationIds matched no\r\n // test case; read it and surface it here instead of letting it disappear once reportToQuikTest\r\n // returns. Reuses the same warnings -> reportBack path QUIKTR-1064's overlap detection already\r\n // uses, which QuikTrack folds into the run's own event timeline \u2014 no new plumbing.\r\n const unmatchedWarning = quikTestReport ? describeUnmatchedAutomationIds(quikTestReport.unmatched) : null;\r\n if (unmatchedWarning) {\r\n warnings.push(unmatchedWarning);\r\n console.warn(`QuikPilot ingest warning (not blocking): ${unmatchedWarning}`);\r\n }\r\n\r\n if (!hardFailure && packet) {\r\n try {\r\n checkGuardrail(packet.guardrails.deniedPaths);\r\n const installationToken = await exchangeForInstallationToken(\r\n env.installationTokenUrl,\r\n runToken,\r\n );\r\n const result = commitAndPush(\r\n packet.branch,\r\n env.runId,\r\n installationToken,\r\n targeted,\r\n packet.issueKey,\r\n packet.issueTitle,\r\n );\r\n branch = result.branch;\r\n } catch (err) {\r\n hardFailure = true;\r\n recordFailure(err);\r\n }\r\n }\r\n\r\n // QUIKTR-1447 \u2014 before the callback, so it exists whether or not the callback succeeds. Only for a run that got as far\r\n // as generating files, and never allowed to change how the run ends.\r\n if (hardFailure && generatedResults.length > 0) {\r\n try {\r\n writeFailureArtifact({\r\n cwd: process.cwd(),\r\n runId: env.runId,\r\n issueKey: packet?.issueKey ?? null,\r\n targets: targetingResult?.outcome === \"TARGETED\" ? targetingResult.targets : [],\r\n results: generatedResults,\r\n testReport: finalTestReport,\r\n failureReasons,\r\n secrets: runToken ? [runToken] : [],\r\n });\r\n } catch (err: unknown) {\r\n console.warn(`::warning::Could not keep the failed run's files: ${err instanceof Error ? err.message : String(err)}`);\r\n }\r\n }\r\n\r\n await reportBack({\r\n callbackUrl: env.callbackUrl,\r\n runToken,\r\n status: hardFailure ? \"failed\" : \"completed\",\r\n branch,\r\n warnings,\r\n // Omitted when targeting itself never produced a result (nothing exists to record).\r\n targeting: targetingResult ? buildTargetingRecord(targetingResult, contextLog) : undefined,\r\n baselineFindings,\r\n vanishedTests,\r\n codegenLoop: codegenOut.loop,\r\n unresolved: failureReasons.length > 0 ? failureReasons : undefined,\r\n });\r\n\r\n return { hardFailure };\r\n}\r\n", "import type { ReadinessCheckEnv } from \"./env\";\r\nimport { runCommand, runTestCommand } from \"./commands\";\r\nimport { findJUnitReport } from \"./quiktest\";\r\nimport { describeQuikTrackFailure } from \"./quiktrackError\";\r\n\r\n/**\r\n * QUIKTR-1084 \u2014 readiness's \"later session\": actually run the customer's `setupCmd`/`testCmd` and\r\n * report whether the run produced a JUnit report the pilot-run path (`quiktest.ts`) will ever\r\n * find. Checked out onto the default branch already by the workflow's own `actions/checkout` step\r\n * \u2014 no packet, no design, no codegen, no commit, no push.\r\n *\r\n * Both command failures are soft here, deliberately unlike `run.ts`'s hard-fails-on-Setup: a\r\n * repo's setup or test suite failing is not what this check is FOR \u2014 it exists purely to answer\r\n * \"if a real run happened, would QuikTest hear about it,\" which only needs the report to exist,\r\n * not the tests to pass.\r\n */\r\nexport interface ReadinessCheckResult {\r\n setupOk: boolean;\r\n testOk: boolean;\r\n junitFound: boolean;\r\n junitPath: string | null;\r\n}\r\n\r\nexport async function runReadinessCheck(env: ReadinessCheckEnv): Promise<void> {\r\n let setupOk = true;\r\n try {\r\n runCommand(env.setupCmd || null, \"Setup\");\r\n } catch (err) {\r\n setupOk = false;\r\n console.error(err instanceof Error ? err.message : String(err));\r\n }\r\n\r\n const testOutcome = runTestCommand(env.testCmd);\r\n const testOk = testOutcome === \"success\";\r\n\r\n const junitPath = findJUnitReport();\r\n const result: ReadinessCheckResult = {\r\n setupOk,\r\n testOk,\r\n junitFound: junitPath !== null,\r\n junitPath,\r\n };\r\n\r\n try {\r\n const res = await fetch(env.readinessCallbackUrl, {\r\n method: \"POST\",\r\n headers: { Authorization: `Bearer ${env.readinessToken}`, \"Content-Type\": \"application/json\" },\r\n body: JSON.stringify(result),\r\n });\r\n if (!res.ok) {\r\n throw new Error(`Readiness callback POST failed: ${await describeQuikTrackFailure(res)}`);\r\n }\r\n } catch (err) {\r\n // Same \"never throws\" posture as reportToQuikTest/reportBack \u2014 the job's own log is the\r\n // fallback record if even this fails. The expiry sweep readiness.ts will need (mirroring\r\n // dispatch.ts's DISPATCHING-expiry sweep) is what notices a dry run stuck in RUNNING.\r\n console.warn(\r\n `::warning::QuikPilot readiness check failed to report its result: ${err instanceof Error ? err.message : String(err)}`,\r\n );\r\n }\r\n}\r\n", "import { readRunnerEnv } from \"./env\";\r\nimport { run } from \"./run\";\r\nimport { runReadinessCheck } from \"./readinessCheck\";\r\n\r\nconst env = readRunnerEnv();\r\n\r\n// QUIKTR-1084 \u2014 narrows the RunnerEnv union before either branch runs; run()/runReadinessCheck()\r\n// each take only their own variant, not the union, so this `if` is what makes that safe.\r\nconst task =\r\n env.mode === \"readiness_check\"\r\n ? runReadinessCheck(env).then(() => ({ hardFailure: false }))\r\n : run(env);\r\n\r\ntask\r\n .then(({ hardFailure }) => {\r\n process.exitCode = hardFailure ? 1 : 0;\r\n })\r\n .catch((err) => {\r\n // reportBack/the readiness callback itself throwing is the one failure mode neither branch can\r\n // recover from internally \u2014 still exit non-zero so the raw Actions UI shows the run as failed.\r\n console.error(err instanceof Error ? err.message : String(err));\r\n process.exitCode = 1;\r\n });\r\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;AA+CO,SAAS,SAAS,MAAc,OAAmC;AACxE,MAAI,CAAC,OAAO;AACV,UAAM,IAAI,MAAM,0CAA0C,IAAI,EAAE;AAAA,EAClE;AACA,SAAO;AACT;AAEO,SAAS,cAAcA,OAAyB,QAAQ,KAAgB;AAC7E,QAAM,cAAc,SAAS,iBAAiBA,KAAI,aAAa;AAC/D,QAAM,kBAAkBA,KAAI,qBAAqB;AACjD,QAAM,mBAAmB,SAAS,qBAAqBA,KAAI,iBAAiB;AAE5E,MAAIA,KAAI,SAAS,mBAAmB;AAClC,WAAO;AAAA,MACL,MAAM;AAAA,MACN,gBAAgB,SAAS,mBAAmBA,KAAI,eAAe;AAAA,MAC/D,sBAAsB,SAAS,0BAA0BA,KAAI,sBAAsB;AAAA,MACnF,UAAUA,KAAI,aAAa;AAAA,MAC3B,SAAS,SAAS,YAAYA,KAAI,QAAQ;AAAA,MAC1C;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AAAA,IACL,MAAM;AAAA,IACN,OAAO,SAAS,UAAUA,KAAI,M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,CAAC;AAC9D,UAAQ,WAAW;AACrB,CAAC;",
|
|
6
|
-
"names": ["env", "resolve", "import_node_child_process", "import_node_path", "relative", "path", "path", "whole", "env", "import_node_fs", "join", "import_node_path", "import_node_fs", "import_node_path", "env", "import_node_fs", "import_node_path", "hasNul", "bad", "env", "isPlainObject", "env", "MAX_ID_CHARS", "MAX_CALLS_IN_A_REPLY", "TOOL_NAMES", "isPlainObject", "classifyTransport", "env", "import_node_fs", "import_node_path", "env", "import_node_fs", "import_node_fs", "import_node_path", "readFileSync", "import_node_child_process", "import_node_fs", "import_node_path", "import_node_fs", "isTestTarget", "import_node_fs", "import_node_path", "import_node_fs", "import_node_path", "parse", "env", "CONTRACT_VERSION", "MAX_PATH_CHARS", "MAX_ID_CHARS", "record", "env", "env"]
|
|
3
|
+
"sources": ["../../../node_modules/estraverse/estraverse.js", "../../../node_modules/esrecurse/package.json", "../../../node_modules/esrecurse/esrecurse.js", "../src/env.ts", "../src/quiktrackError.ts", "../src/callback.ts", "../src/commands.ts", "../src/commandEnv.ts", "../src/git.ts", "../src/commit.ts", "../src/codegen.ts", "../src/deniedPaths.ts", "../src/editsApply.ts", "../src/runtimeReplyError.ts", "../src/envelope.ts", "../src/importContext.ts", "../src/retryFetch.ts", "../src/codegenMode.ts", "../src/codegenLoopRecord.ts", "../src/codegenLoopContext.ts", "../src/overlapCheck.ts", "../src/addOnly.ts", "../../../node_modules/acorn/dist/acorn.mjs", "../src/jsParse.ts", "../../../node_modules/eslint-scope/lib/index.js", "../../../node_modules/eslint-scope/lib/scope.js", "../../../node_modules/eslint-scope/lib/reference.js", "../../../node_modules/eslint-scope/lib/variable.js", "../../../node_modules/eslint-scope/lib/definition.js", "../../../node_modules/eslint-scope/lib/scope-manager.js", "../../../node_modules/eslint-scope/lib/referencer.js", "../../../node_modules/eslint-scope/lib/pattern-visitor.js", "../src/nameScope.ts", "../src/knownGlobals.ts", "../src/syntaxCheck.ts", "../src/targetingPaths.ts", "../src/targetingTools.ts", "../src/workspaceOverlay.ts", "../src/codegenTools.ts", "../src/targetingErrors.ts", "../src/tokenEstimate.ts", "../src/targetingLoop.ts", "../src/codegenLoop.ts", "../src/codegenStep.ts", "../src/dependencyCheck.ts", "../src/guardrail.ts", "../src/installationToken.ts", "../src/oidc.ts", "../src/packet.ts", "../src/phase0.ts", "../src/quiktest.ts", "../src/baselineCheck.ts", "../src/regressionCheck.ts", "../src/failureArtifact.ts", "../src/failureReason.ts", "../src/scopeCheck.ts", "../src/targeting.ts", "../src/targetingMode.ts", "../src/targetingRecord.ts", "../src/testPlacementCheck.ts", "../src/tokenExchange.ts", "../src/vanishedTests.ts", "../src/run.ts", "../src/readinessCheck.ts", "../src/index.ts"],
|
|
4
|
+
"sourcesContent": ["/*\n Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>\n Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\n DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/*jslint vars:false, bitwise:true*/\n/*jshint indent:4*/\n/*global exports:true*/\n(function clone(exports) {\n 'use strict';\n\n var Syntax,\n VisitorOption,\n VisitorKeys,\n BREAK,\n SKIP,\n REMOVE;\n\n function deepCopy(obj) {\n var ret = {}, key, val;\n for (key in obj) {\n if (obj.hasOwnProperty(key)) {\n val = obj[key];\n if (typeof val === 'object' && val !== null) {\n ret[key] = deepCopy(val);\n } else {\n ret[key] = val;\n }\n }\n }\n return ret;\n }\n\n // based on LLVM libc++ upper_bound / lower_bound\n // MIT License\n\n function upperBound(array, func) {\n var diff, len, i, current;\n\n len = array.length;\n i = 0;\n\n while (len) {\n diff = len >>> 1;\n current = i + diff;\n if (func(array[current])) {\n len = diff;\n } else {\n i = current + 1;\n len -= diff + 1;\n }\n }\n return i;\n }\n\n Syntax = {\n AssignmentExpression: 'AssignmentExpression',\n AssignmentPattern: 'AssignmentPattern',\n ArrayExpression: 'ArrayExpression',\n ArrayPattern: 'ArrayPattern',\n ArrowFunctionExpression: 'ArrowFunctionExpression',\n AwaitExpression: 'AwaitExpression', // CAUTION: It's deferred to ES7.\n BlockStatement: 'BlockStatement',\n BinaryExpression: 'BinaryExpression',\n BreakStatement: 'BreakStatement',\n CallExpression: 'CallExpression',\n CatchClause: 'CatchClause',\n ChainExpression: 'ChainExpression',\n ClassBody: 'ClassBody',\n ClassDeclaration: 'ClassDeclaration',\n ClassExpression: 'ClassExpression',\n ComprehensionBlock: 'ComprehensionBlock', // CAUTION: It's deferred to ES7.\n ComprehensionExpression: 'ComprehensionExpression', // CAUTION: It's deferred to ES7.\n ConditionalExpression: 'ConditionalExpression',\n ContinueStatement: 'ContinueStatement',\n DebuggerStatement: 'DebuggerStatement',\n DirectiveStatement: 'DirectiveStatement',\n DoWhileStatement: 'DoWhileStatement',\n EmptyStatement: 'EmptyStatement',\n ExportAllDeclaration: 'ExportAllDeclaration',\n ExportDefaultDeclaration: 'ExportDefaultDeclaration',\n ExportNamedDeclaration: 'ExportNamedDeclaration',\n ExportSpecifier: 'ExportSpecifier',\n ExpressionStatement: 'ExpressionStatement',\n ForStatement: 'ForStatement',\n ForInStatement: 'ForInStatement',\n ForOfStatement: 'ForOfStatement',\n FunctionDeclaration: 'FunctionDeclaration',\n FunctionExpression: 'FunctionExpression',\n GeneratorExpression: 'GeneratorExpression', // CAUTION: It's deferred to ES7.\n Identifier: 'Identifier',\n IfStatement: 'IfStatement',\n ImportExpression: 'ImportExpression',\n ImportDeclaration: 'ImportDeclaration',\n ImportDefaultSpecifier: 'ImportDefaultSpecifier',\n ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',\n ImportSpecifier: 'ImportSpecifier',\n Literal: 'Literal',\n LabeledStatement: 'LabeledStatement',\n LogicalExpression: 'LogicalExpression',\n MemberExpression: 'MemberExpression',\n MetaProperty: 'MetaProperty',\n MethodDefinition: 'MethodDefinition',\n ModuleSpecifier: 'ModuleSpecifier',\n NewExpression: 'NewExpression',\n ObjectExpression: 'ObjectExpression',\n ObjectPattern: 'ObjectPattern',\n PrivateIdentifier: 'PrivateIdentifier',\n Program: 'Program',\n Property: 'Property',\n PropertyDefinition: 'PropertyDefinition',\n RestElement: 'RestElement',\n ReturnStatement: 'ReturnStatement',\n SequenceExpression: 'SequenceExpression',\n SpreadElement: 'SpreadElement',\n Super: 'Super',\n SwitchStatement: 'SwitchStatement',\n SwitchCase: 'SwitchCase',\n TaggedTemplateExpression: 'TaggedTemplateExpression',\n TemplateElement: 'TemplateElement',\n TemplateLiteral: 'TemplateLiteral',\n ThisExpression: 'ThisExpression',\n ThrowStatement: 'ThrowStatement',\n TryStatement: 'TryStatement',\n UnaryExpression: 'UnaryExpression',\n UpdateExpression: 'UpdateExpression',\n VariableDeclaration: 'VariableDeclaration',\n VariableDeclarator: 'VariableDeclarator',\n WhileStatement: 'WhileStatement',\n WithStatement: 'WithStatement',\n YieldExpression: 'YieldExpression'\n };\n\n VisitorKeys = {\n AssignmentExpression: ['left', 'right'],\n AssignmentPattern: ['left', 'right'],\n ArrayExpression: ['elements'],\n ArrayPattern: ['elements'],\n ArrowFunctionExpression: ['params', 'body'],\n AwaitExpression: ['argument'], // CAUTION: It's deferred to ES7.\n BlockStatement: ['body'],\n BinaryExpression: ['left', 'right'],\n BreakStatement: ['label'],\n CallExpression: ['callee', 'arguments'],\n CatchClause: ['param', 'body'],\n ChainExpression: ['expression'],\n ClassBody: ['body'],\n ClassDeclaration: ['id', 'superClass', 'body'],\n ClassExpression: ['id', 'superClass', 'body'],\n ComprehensionBlock: ['left', 'right'], // CAUTION: It's deferred to ES7.\n ComprehensionExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7.\n ConditionalExpression: ['test', 'consequent', 'alternate'],\n ContinueStatement: ['label'],\n DebuggerStatement: [],\n DirectiveStatement: [],\n DoWhileStatement: ['body', 'test'],\n EmptyStatement: [],\n ExportAllDeclaration: ['source'],\n ExportDefaultDeclaration: ['declaration'],\n ExportNamedDeclaration: ['declaration', 'specifiers', 'source'],\n ExportSpecifier: ['exported', 'local'],\n ExpressionStatement: ['expression'],\n ForStatement: ['init', 'test', 'update', 'body'],\n ForInStatement: ['left', 'right', 'body'],\n ForOfStatement: ['left', 'right', 'body'],\n FunctionDeclaration: ['id', 'params', 'body'],\n FunctionExpression: ['id', 'params', 'body'],\n GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7.\n Identifier: [],\n IfStatement: ['test', 'consequent', 'alternate'],\n ImportExpression: ['source'],\n ImportDeclaration: ['specifiers', 'source'],\n ImportDefaultSpecifier: ['local'],\n ImportNamespaceSpecifier: ['local'],\n ImportSpecifier: ['imported', 'local'],\n Literal: [],\n LabeledStatement: ['label', 'body'],\n LogicalExpression: ['left', 'right'],\n MemberExpression: ['object', 'property'],\n MetaProperty: ['meta', 'property'],\n MethodDefinition: ['key', 'value'],\n ModuleSpecifier: [],\n NewExpression: ['callee', 'arguments'],\n ObjectExpression: ['properties'],\n ObjectPattern: ['properties'],\n PrivateIdentifier: [],\n Program: ['body'],\n Property: ['key', 'value'],\n PropertyDefinition: ['key', 'value'],\n RestElement: [ 'argument' ],\n ReturnStatement: ['argument'],\n SequenceExpression: ['expressions'],\n SpreadElement: ['argument'],\n Super: [],\n SwitchStatement: ['discriminant', 'cases'],\n SwitchCase: ['test', 'consequent'],\n TaggedTemplateExpression: ['tag', 'quasi'],\n TemplateElement: [],\n TemplateLiteral: ['quasis', 'expressions'],\n ThisExpression: [],\n ThrowStatement: ['argument'],\n TryStatement: ['block', 'handler', 'finalizer'],\n UnaryExpression: ['argument'],\n UpdateExpression: ['argument'],\n VariableDeclaration: ['declarations'],\n VariableDeclarator: ['id', 'init'],\n WhileStatement: ['test', 'body'],\n WithStatement: ['object', 'body'],\n YieldExpression: ['argument']\n };\n\n // unique id\n BREAK = {};\n SKIP = {};\n REMOVE = {};\n\n VisitorOption = {\n Break: BREAK,\n Skip: SKIP,\n Remove: REMOVE\n };\n\n function Reference(parent, key) {\n this.parent = parent;\n this.key = key;\n }\n\n Reference.prototype.replace = function replace(node) {\n this.parent[this.key] = node;\n };\n\n Reference.prototype.remove = function remove() {\n if (Array.isArray(this.parent)) {\n this.parent.splice(this.key, 1);\n return true;\n } else {\n this.replace(null);\n return false;\n }\n };\n\n function Element(node, path, wrap, ref) {\n this.node = node;\n this.path = path;\n this.wrap = wrap;\n this.ref = ref;\n }\n\n function Controller() { }\n\n // API:\n // return property path array from root to current node\n Controller.prototype.path = function path() {\n var i, iz, j, jz, result, element;\n\n function addToPath(result, path) {\n if (Array.isArray(path)) {\n for (j = 0, jz = path.length; j < jz; ++j) {\n result.push(path[j]);\n }\n } else {\n result.push(path);\n }\n }\n\n // root node\n if (!this.__current.path) {\n return null;\n }\n\n // first node is sentinel, second node is root element\n result = [];\n for (i = 2, iz = this.__leavelist.length; i < iz; ++i) {\n element = this.__leavelist[i];\n addToPath(result, element.path);\n }\n addToPath(result, this.__current.path);\n return result;\n };\n\n // API:\n // return type of current node\n Controller.prototype.type = function () {\n var node = this.current();\n return node.type || this.__current.wrap;\n };\n\n // API:\n // return array of parent elements\n Controller.prototype.parents = function parents() {\n var i, iz, result;\n\n // first node is sentinel\n result = [];\n for (i = 1, iz = this.__leavelist.length; i < iz; ++i) {\n result.push(this.__leavelist[i].node);\n }\n\n return result;\n };\n\n // API:\n // return current node\n Controller.prototype.current = function current() {\n return this.__current.node;\n };\n\n Controller.prototype.__execute = function __execute(callback, element) {\n var previous, result;\n\n result = undefined;\n\n previous = this.__current;\n this.__current = element;\n this.__state = null;\n if (callback) {\n result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node);\n }\n this.__current = previous;\n\n return result;\n };\n\n // API:\n // notify control skip / break\n Controller.prototype.notify = function notify(flag) {\n this.__state = flag;\n };\n\n // API:\n // skip child nodes of current node\n Controller.prototype.skip = function () {\n this.notify(SKIP);\n };\n\n // API:\n // break traversals\n Controller.prototype['break'] = function () {\n this.notify(BREAK);\n };\n\n // API:\n // remove node\n Controller.prototype.remove = function () {\n this.notify(REMOVE);\n };\n\n Controller.prototype.__initialize = function(root, visitor) {\n this.visitor = visitor;\n this.root = root;\n this.__worklist = [];\n this.__leavelist = [];\n this.__current = null;\n this.__state = null;\n this.__fallback = null;\n if (visitor.fallback === 'iteration') {\n this.__fallback = Object.keys;\n } else if (typeof visitor.fallback === 'function') {\n this.__fallback = visitor.fallback;\n }\n\n this.__keys = VisitorKeys;\n if (visitor.keys) {\n this.__keys = Object.assign(Object.create(this.__keys), visitor.keys);\n }\n };\n\n function isNode(node) {\n if (node == null) {\n return false;\n }\n return typeof node === 'object' && typeof node.type === 'string';\n }\n\n function isProperty(nodeType, key) {\n return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key;\n }\n \n function candidateExistsInLeaveList(leavelist, candidate) {\n for (var i = leavelist.length - 1; i >= 0; --i) {\n if (leavelist[i].node === candidate) {\n return true;\n }\n }\n return false;\n }\n\n Controller.prototype.traverse = function traverse(root, visitor) {\n var worklist,\n leavelist,\n element,\n node,\n nodeType,\n ret,\n key,\n current,\n current2,\n candidates,\n candidate,\n sentinel;\n\n this.__initialize(root, visitor);\n\n sentinel = {};\n\n // reference\n worklist = this.__worklist;\n leavelist = this.__leavelist;\n\n // initialize\n worklist.push(new Element(root, null, null, null));\n leavelist.push(new Element(null, null, null, null));\n\n while (worklist.length) {\n element = worklist.pop();\n\n if (element === sentinel) {\n element = leavelist.pop();\n\n ret = this.__execute(visitor.leave, element);\n\n if (this.__state === BREAK || ret === BREAK) {\n return;\n }\n continue;\n }\n\n if (element.node) {\n\n ret = this.__execute(visitor.enter, element);\n\n if (this.__state === BREAK || ret === BREAK) {\n return;\n }\n\n worklist.push(sentinel);\n leavelist.push(element);\n\n if (this.__state === SKIP || ret === SKIP) {\n continue;\n }\n\n node = element.node;\n nodeType = node.type || element.wrap;\n candidates = this.__keys[nodeType];\n if (!candidates) {\n if (this.__fallback) {\n candidates = this.__fallback(node);\n } else {\n throw new Error('Unknown node type ' + nodeType + '.');\n }\n }\n\n current = candidates.length;\n while ((current -= 1) >= 0) {\n key = candidates[current];\n candidate = node[key];\n if (!candidate) {\n continue;\n }\n\n if (Array.isArray(candidate)) {\n current2 = candidate.length;\n while ((current2 -= 1) >= 0) {\n if (!candidate[current2]) {\n continue;\n }\n\n if (candidateExistsInLeaveList(leavelist, candidate[current2])) {\n continue;\n }\n\n if (isProperty(nodeType, candidates[current])) {\n element = new Element(candidate[current2], [key, current2], 'Property', null);\n } else if (isNode(candidate[current2])) {\n element = new Element(candidate[current2], [key, current2], null, null);\n } else {\n continue;\n }\n worklist.push(element);\n }\n } else if (isNode(candidate)) {\n if (candidateExistsInLeaveList(leavelist, candidate)) {\n continue;\n }\n\n worklist.push(new Element(candidate, key, null, null));\n }\n }\n }\n }\n };\n\n Controller.prototype.replace = function replace(root, visitor) {\n var worklist,\n leavelist,\n node,\n nodeType,\n target,\n element,\n current,\n current2,\n candidates,\n candidate,\n sentinel,\n outer,\n key;\n\n function removeElem(element) {\n var i,\n key,\n nextElem,\n parent;\n\n if (element.ref.remove()) {\n // When the reference is an element of an array.\n key = element.ref.key;\n parent = element.ref.parent;\n\n // If removed from array, then decrease following items' keys.\n i = worklist.length;\n while (i--) {\n nextElem = worklist[i];\n if (nextElem.ref && nextElem.ref.parent === parent) {\n if (nextElem.ref.key < key) {\n break;\n }\n --nextElem.ref.key;\n }\n }\n }\n }\n\n this.__initialize(root, visitor);\n\n sentinel = {};\n\n // reference\n worklist = this.__worklist;\n leavelist = this.__leavelist;\n\n // initialize\n outer = {\n root: root\n };\n element = new Element(root, null, null, new Reference(outer, 'root'));\n worklist.push(element);\n leavelist.push(element);\n\n while (worklist.length) {\n element = worklist.pop();\n\n if (element === sentinel) {\n element = leavelist.pop();\n\n target = this.__execute(visitor.leave, element);\n\n // node may be replaced with null,\n // so distinguish between undefined and null in this place\n if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {\n // replace\n element.ref.replace(target);\n }\n\n if (this.__state === REMOVE || target === REMOVE) {\n removeElem(element);\n }\n\n if (this.__state === BREAK || target === BREAK) {\n return outer.root;\n }\n continue;\n }\n\n target = this.__execute(visitor.enter, element);\n\n // node may be replaced with null,\n // so distinguish between undefined and null in this place\n if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {\n // replace\n element.ref.replace(target);\n element.node = target;\n }\n\n if (this.__state === REMOVE || target === REMOVE) {\n removeElem(element);\n element.node = null;\n }\n\n if (this.__state === BREAK || target === BREAK) {\n return outer.root;\n }\n\n // node may be null\n node = element.node;\n if (!node) {\n continue;\n }\n\n worklist.push(sentinel);\n leavelist.push(element);\n\n if (this.__state === SKIP || target === SKIP) {\n continue;\n }\n\n nodeType = node.type || element.wrap;\n candidates = this.__keys[nodeType];\n if (!candidates) {\n if (this.__fallback) {\n candidates = this.__fallback(node);\n } else {\n throw new Error('Unknown node type ' + nodeType + '.');\n }\n }\n\n current = candidates.length;\n while ((current -= 1) >= 0) {\n key = candidates[current];\n candidate = node[key];\n if (!candidate) {\n continue;\n }\n\n if (Array.isArray(candidate)) {\n current2 = candidate.length;\n while ((current2 -= 1) >= 0) {\n if (!candidate[current2]) {\n continue;\n }\n if (isProperty(nodeType, candidates[current])) {\n element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2));\n } else if (isNode(candidate[current2])) {\n element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2));\n } else {\n continue;\n }\n worklist.push(element);\n }\n } else if (isNode(candidate)) {\n worklist.push(new Element(candidate, key, null, new Reference(node, key)));\n }\n }\n }\n\n return outer.root;\n };\n\n function traverse(root, visitor) {\n var controller = new Controller();\n return controller.traverse(root, visitor);\n }\n\n function replace(root, visitor) {\n var controller = new Controller();\n return controller.replace(root, visitor);\n }\n\n function extendCommentRange(comment, tokens) {\n var target;\n\n target = upperBound(tokens, function search(token) {\n return token.range[0] > comment.range[0];\n });\n\n comment.extendedRange = [comment.range[0], comment.range[1]];\n\n if (target !== tokens.length) {\n comment.extendedRange[1] = tokens[target].range[0];\n }\n\n target -= 1;\n if (target >= 0) {\n comment.extendedRange[0] = tokens[target].range[1];\n }\n\n return comment;\n }\n\n function attachComments(tree, providedComments, tokens) {\n // At first, we should calculate extended comment ranges.\n var comments = [], comment, len, i, cursor;\n\n if (!tree.range) {\n throw new Error('attachComments needs range information');\n }\n\n // tokens array is empty, we attach comments to tree as 'leadingComments'\n if (!tokens.length) {\n if (providedComments.length) {\n for (i = 0, len = providedComments.length; i < len; i += 1) {\n comment = deepCopy(providedComments[i]);\n comment.extendedRange = [0, tree.range[0]];\n comments.push(comment);\n }\n tree.leadingComments = comments;\n }\n return tree;\n }\n\n for (i = 0, len = providedComments.length; i < len; i += 1) {\n comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens));\n }\n\n // This is based on John Freeman's implementation.\n cursor = 0;\n traverse(tree, {\n enter: function (node) {\n var comment;\n\n while (cursor < comments.length) {\n comment = comments[cursor];\n if (comment.extendedRange[1] > node.range[0]) {\n break;\n }\n\n if (comment.extendedRange[1] === node.range[0]) {\n if (!node.leadingComments) {\n node.leadingComments = [];\n }\n node.leadingComments.push(comment);\n comments.splice(cursor, 1);\n } else {\n cursor += 1;\n }\n }\n\n // already out of owned node\n if (cursor === comments.length) {\n return VisitorOption.Break;\n }\n\n if (comments[cursor].extendedRange[0] > node.range[1]) {\n return VisitorOption.Skip;\n }\n }\n });\n\n cursor = 0;\n traverse(tree, {\n leave: function (node) {\n var comment;\n\n while (cursor < comments.length) {\n comment = comments[cursor];\n if (node.range[1] < comment.extendedRange[0]) {\n break;\n }\n\n if (node.range[1] === comment.extendedRange[0]) {\n if (!node.trailingComments) {\n node.trailingComments = [];\n }\n node.trailingComments.push(comment);\n comments.splice(cursor, 1);\n } else {\n cursor += 1;\n }\n }\n\n // already out of owned node\n if (cursor === comments.length) {\n return VisitorOption.Break;\n }\n\n if (comments[cursor].extendedRange[0] > node.range[1]) {\n return VisitorOption.Skip;\n }\n }\n });\n\n return tree;\n }\n\n exports.Syntax = Syntax;\n exports.traverse = traverse;\n exports.replace = replace;\n exports.attachComments = attachComments;\n exports.VisitorKeys = VisitorKeys;\n exports.VisitorOption = VisitorOption;\n exports.Controller = Controller;\n exports.cloneEnvironment = function () { return clone({}); };\n\n return exports;\n}(exports));\n/* vim: set sw=4 ts=4 et tw=80 : */\n", "{\n \"name\": \"esrecurse\",\n \"description\": \"ECMAScript AST recursive visitor\",\n \"homepage\": \"https://github.com/estools/esrecurse\",\n \"main\": \"esrecurse.js\",\n \"version\": \"4.3.0\",\n \"engines\": {\n \"node\": \">=4.0\"\n },\n \"maintainers\": [\n {\n \"name\": \"Yusuke Suzuki\",\n \"email\": \"utatane.tea@gmail.com\",\n \"web\": \"https://github.com/Constellation\"\n }\n ],\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/estools/esrecurse.git\"\n },\n \"dependencies\": {\n \"estraverse\": \"^5.2.0\"\n },\n \"devDependencies\": {\n \"babel-cli\": \"^6.24.1\",\n \"babel-eslint\": \"^7.2.3\",\n \"babel-preset-es2015\": \"^6.24.1\",\n \"babel-register\": \"^6.24.1\",\n \"chai\": \"^4.0.2\",\n \"esprima\": \"^4.0.0\",\n \"gulp\": \"^3.9.0\",\n \"gulp-bump\": \"^2.7.0\",\n \"gulp-eslint\": \"^4.0.0\",\n \"gulp-filter\": \"^5.0.0\",\n \"gulp-git\": \"^2.4.1\",\n \"gulp-mocha\": \"^4.3.1\",\n \"gulp-tag-version\": \"^1.2.1\",\n \"jsdoc\": \"^3.3.0-alpha10\",\n \"minimist\": \"^1.1.0\"\n },\n \"license\": \"BSD-2-Clause\",\n \"scripts\": {\n \"test\": \"gulp travis\",\n \"unit-test\": \"gulp test\",\n \"lint\": \"gulp lint\"\n },\n \"babel\": {\n \"presets\": [\n \"es2015\"\n ]\n }\n}\n", "/*\n Copyright (C) 2014 Yusuke Suzuki <utatane.tea@gmail.com>\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\n DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n(function () {\n 'use strict';\n\n var estraverse = require('estraverse');\n\n function isNode(node) {\n if (node == null) {\n return false;\n }\n return typeof node === 'object' && typeof node.type === 'string';\n }\n\n function isProperty(nodeType, key) {\n return (nodeType === estraverse.Syntax.ObjectExpression || nodeType === estraverse.Syntax.ObjectPattern) && key === 'properties';\n }\n\n function Visitor(visitor, options) {\n options = options || {};\n\n this.__visitor = visitor || this;\n this.__childVisitorKeys = options.childVisitorKeys\n ? Object.assign({}, estraverse.VisitorKeys, options.childVisitorKeys)\n : estraverse.VisitorKeys;\n if (options.fallback === 'iteration') {\n this.__fallback = Object.keys;\n } else if (typeof options.fallback === 'function') {\n this.__fallback = options.fallback;\n }\n }\n\n /* Default method for visiting children.\n * When you need to call default visiting operation inside custom visiting\n * operation, you can use it with `this.visitChildren(node)`.\n */\n Visitor.prototype.visitChildren = function (node) {\n var type, children, i, iz, j, jz, child;\n\n if (node == null) {\n return;\n }\n\n type = node.type || estraverse.Syntax.Property;\n\n children = this.__childVisitorKeys[type];\n if (!children) {\n if (this.__fallback) {\n children = this.__fallback(node);\n } else {\n throw new Error('Unknown node type ' + type + '.');\n }\n }\n\n for (i = 0, iz = children.length; i < iz; ++i) {\n child = node[children[i]];\n if (child) {\n if (Array.isArray(child)) {\n for (j = 0, jz = child.length; j < jz; ++j) {\n if (child[j]) {\n if (isNode(child[j]) || isProperty(type, children[i])) {\n this.visit(child[j]);\n }\n }\n }\n } else if (isNode(child)) {\n this.visit(child);\n }\n }\n }\n };\n\n /* Dispatching node. */\n Visitor.prototype.visit = function (node) {\n var type;\n\n if (node == null) {\n return;\n }\n\n type = node.type || estraverse.Syntax.Property;\n if (this.__visitor[type]) {\n this.__visitor[type].call(this, node);\n return;\n }\n this.visitChildren(node);\n };\n\n exports.version = require('./package.json').version;\n exports.Visitor = Visitor;\n exports.visit = function (node, visitor, options) {\n var v = new Visitor(visitor, options);\n v.visit(node);\n };\n}());\n/* vim: set sw=4 ts=4 et tw=80 : */\n", "/** The `workflow_dispatch` inputs QuikTrack's `dispatch.ts` sends, unchanged by QUIKTR-572 \u2014 the\r\n * generated workflow file still passes them through as job-level env vars under these exact\r\n * names. QUIKTR-805: `runToken`/`RUN_TOKEN` (a bearer, visible in the Actions UI as a dispatch\r\n * input) was replaced with `tokenUrl`/`TOKEN_URL` \u2014 the runner now exchanges a GitHub OIDC ID\r\n * token there for a run token at runtime; see `oidc.ts` and `tokenExchange.ts`. QUIKTR-804 adds\r\n * `installationTokenUrl`/`INSTALLATION_TOKEN_URL` \u2014 the run token is exchanged there for a\r\n * repo-scoped GitHub push credential; see `installationToken.ts`. */\r\nexport interface PilotRunEnv {\r\n mode: \"run\";\r\n runId: string;\r\n callbackUrl: string;\r\n packetUrl: string;\r\n tokenUrl: string;\r\n installationTokenUrl: string;\r\n /** GitHub Actions built-ins, read directly from `process.env` rather than threaded through here\r\n * individually. */\r\n githubRunId: string;\r\n githubServerUrl: string;\r\n githubRepository: string;\r\n}\r\n\r\n/**\r\n * QUIKTR-1084 \u2014 the readiness dry-run branch. Deliberately carries none of `PilotRunEnv`'s\r\n * fields: no packet fetch, no OIDC/run-token exchange, no design/codegen/commit/push. It only\r\n * needs the two commands to run and where to report the result.\r\n *\r\n * `readinessToken`/`READINESS_TOKEN` travels as a plain dispatch input, unlike the pilot-run\r\n * token \u2014 deliberately. QUIKTR-805 stopped doing that for the run token because a leaked one\r\n * could spend money through the LLM gateway; this token can only POST a\r\n * `{ junitFound, junitPath }` result for the one `QtPilotConfig` it was minted for (see\r\n * `readiness-dispatch.ts`), which is the same blast radius the pre-805 run token had. Splitting\r\n * out a second OIDC-exchange endpoint to protect a credential this narrow isn't worth the new\r\n * surface.\r\n */\r\nexport interface ReadinessCheckEnv {\r\n mode: \"readiness_check\";\r\n readinessToken: string;\r\n readinessCallbackUrl: string;\r\n setupCmd: string;\r\n testCmd: string;\r\n githubRunId: string;\r\n githubServerUrl: string;\r\n githubRepository: string;\r\n}\r\n\r\nexport type RunnerEnv = PilotRunEnv | ReadinessCheckEnv;\r\n\r\nexport function required(name: string, value: string | undefined): string {\r\n if (!value) {\r\n throw new Error(`Missing required environment variable: ${name}`);\r\n }\r\n return value;\r\n}\r\n\r\nexport function readRunnerEnv(env: NodeJS.ProcessEnv = process.env): RunnerEnv {\r\n const githubRunId = required(\"GITHUB_RUN_ID\", env.GITHUB_RUN_ID);\r\n const githubServerUrl = env.GITHUB_SERVER_URL ?? \"https://github.com\";\r\n const githubRepository = required(\"GITHUB_REPOSITORY\", env.GITHUB_REPOSITORY);\r\n\r\n if (env.MODE === \"readiness_check\") {\r\n return {\r\n mode: \"readiness_check\",\r\n readinessToken: required(\"READINESS_TOKEN\", env.READINESS_TOKEN),\r\n readinessCallbackUrl: required(\"READINESS_CALLBACK_URL\", env.READINESS_CALLBACK_URL),\r\n setupCmd: env.SETUP_CMD ?? \"\",\r\n testCmd: required(\"TEST_CMD\", env.TEST_CMD),\r\n githubRunId,\r\n githubServerUrl,\r\n githubRepository,\r\n };\r\n }\r\n\r\n return {\r\n mode: \"run\",\r\n runId: required(\"RUN_ID\", env.RUN_ID),\r\n callbackUrl: required(\"CALLBACK_URL\", env.CALLBACK_URL),\r\n packetUrl: required(\"PACKET_URL\", env.PACKET_URL),\r\n tokenUrl: required(\"TOKEN_URL\", env.TOKEN_URL),\r\n installationTokenUrl: required(\"INSTALLATION_TOKEN_URL\", env.INSTALLATION_TOKEN_URL),\r\n githubRunId,\r\n githubServerUrl,\r\n githubRepository,\r\n };\r\n}\r\n", "/**\r\n * QUIKTR-1080 \u2014 QuikTrack's internal pilot routes return a stable `reason_code` in the body on\r\n * every `pilotError()`-shaped failure (401/403/409/429); the generic 500 catch-all has none, and a\r\n * non-2xx response isn't guaranteed to be JSON at all (a proxy/gateway error can produce a\r\n * non-JSON body). Best effort: falls back to bare status/statusText when `reason_code` is absent\r\n * or the body doesn't parse \u2014 never throws itself.\r\n *\r\n * Unrelated to envelope.ts's `errorCode` \u2014 that's the AI Runtime's own, separate `/ai/execute`\r\n * contract. Two different services, two different field names; not to be conflated.\r\n */\r\nexport async function describeQuikTrackFailure(res: Response): Promise<string> {\r\n try {\r\n const body = await res.json();\r\n if (body && typeof body === \"object\" && typeof (body as Record<string, unknown>).reason_code === \"string\") {\r\n return `${res.status} ${res.statusText} (${(body as Record<string, unknown>).reason_code})`;\r\n }\r\n } catch {\r\n // not JSON, no json() method at all, or already consumed \u2014 fall back below\r\n }\r\n return `${res.status} ${res.statusText}`;\r\n}\r\n", "import { describeQuikTrackFailure } from \"./quiktrackError\";\r\nimport type { BaselineFindings } from \"./baselineCheck\";\r\nimport type { CodegenLoopRecord } from \"./codegenLoopRecord\";\r\nimport type { TargetingRecord } from \"./targetingRecord\";\r\nimport type { VanishedTests } from \"./vanishedTests\";\r\n\r\nexport type RunStatus = \"completed\" | \"failed\";\r\n\r\n/** Always fires, regardless of what failed upstream \u2014 a run that fails silently is worse than one\r\n * that fails loudly. `branch` is omitted entirely (not sent as null/empty) when no push happened,\r\n * matching the original `jq ... | with_entries(select(.value != null and .value != \"\"))`. Same\r\n * treatment for `warnings` (QUIKTR-1064) \u2014 non-fatal findings like a targeting overlap, omitted\r\n * when there are none rather than sent as an empty array. */\r\nexport async function reportBack(params: {\r\n callbackUrl: string;\r\n runToken: string;\r\n status: RunStatus;\r\n branch?: string;\r\n warnings?: string[];\r\n /** QUIKTR-1421 \u2014 what pilot.targeting decided (paths and case ids only). Omitted when targeting never\r\n * produced a result; an older QuikTrack strips the unknown key silently. */\r\n targeting?: TargetingRecord;\r\n /** QUIKTR-1402 \u2014 test cases that passed against the unmodified code (ids only). Omitted when the check\r\n * flagged nothing or did not run; QuikTrack validates it separately and drops a bad one. */\r\n baselineFindings?: BaselineFindings;\r\n /** QUIKTR-1448 \u2014 tests that ran before the change and are missing from the final report. Test titles are the\r\n * customer's own text, so QuikTrack puts them in the pull request description only and stores none. Omitted when\r\n * nothing is missing; an older QuikTrack ignores the unknown key. */\r\n vanishedTests?: VanishedTests;\r\n /** QUIKTR-1458 \u00A724 \u2014 what the code-writing loop did (paths, counts and the AI's short reasoning), when it ran or was tried. Omitted\r\n * otherwise; an older QuikTrack ignores the unknown key. */\r\n codegenLoop?: CodegenLoopRecord;\r\n /** Why a failed run stopped (already written on one line, cut and scrubbed of credentials). Omitted when there is\r\n * nothing to say; an older QuikTrack accepts it and ignores it for a failed run. */\r\n unresolved?: string[];\r\n}): Promise<void> {\r\n const { callbackUrl, runToken, status, branch, warnings, targeting, baselineFindings, vanishedTests, codegenLoop, unresolved } = params;\r\n const body: Record<string, unknown> = { status };\r\n if (branch) body.branch = branch;\r\n if (warnings && warnings.length > 0) body.warnings = warnings;\r\n if (unresolved && unresolved.length > 0) body.unresolved = unresolved;\r\n if (targeting) body.targeting = targeting;\r\n if (baselineFindings) body.baselineFindings = baselineFindings;\r\n if (vanishedTests) body.vanishedTests = vanishedTests;\r\n if (codegenLoop) body.codegenLoop = codegenLoop;\r\n const res = await fetch(callbackUrl, {\r\n method: \"POST\",\r\n headers: { Authorization: `Bearer ${runToken}`, \"Content-Type\": \"application/json\" },\r\n body: JSON.stringify(body),\r\n });\r\n if (!res.ok) {\r\n throw new Error(`Report back to QuikTrack failed: ${await describeQuikTrackFailure(res)}`);\r\n }\r\n}\r\n", "import { execSync, spawn } from \"node:child_process\";\r\nimport { commandEnv, withheldNames } from \"./commandEnv\";\r\n\r\n/** QUIKTR-1502 \u2014 every repository command runs with this, never with the runner's own environment.\r\n * The names withheld are logged once per process (names only), so a command that needed something\r\n * is diagnosable from the job log. */\r\nlet withheldLogged = false;\r\nfunction repositoryCommandEnv(): NodeJS.ProcessEnv {\r\n if (!withheldLogged) {\r\n withheldLogged = true;\r\n const names = withheldNames();\r\n if (names.length > 0) {\r\n console.log(`Repository commands run without ${names.length} environment variable(s): ${names.join(\", \")}`);\r\n }\r\n }\r\n return commandEnv();\r\n}\r\n\r\n/** Runs a packet-supplied command through bash \u2014 same interpreter GitHub's own `run:` steps used,\r\n * so a command written against that shell (e.g. `set -o pipefail`-reliant) behaves the same way.\r\n * A null/empty command is a no-op, matching the original `[ -n \"$CMD\" ]` guard. */\r\nexport function runCommand(command: string | null, label: string): void {\r\n if (!command) return;\r\n try {\r\n execSync(command, { shell: \"/bin/bash\", stdio: \"inherit\", env: repositoryCommandEnv() });\r\n } catch (err) {\r\n throw new Error(`${label} failed: ${err instanceof Error ? err.message : String(err)}`);\r\n }\r\n}\r\n\r\nexport type TestOutcome = \"success\" | \"failure\";\r\n\r\n/** The Test step alone is soft \u2014 a failing suite must not hide the rest of the run (guardrail,\r\n * commit, push) from happening, and must not flip the final callback to `failed`. QuikTest owns\r\n * per-test outcomes; this is only ever logged, never reported. QUIKTR-1036: this is still correct\r\n * for a NO_TARGET run (nothing was generated, so there's nothing to regress against) \u2014 a\r\n * codegen'd run's Test step is decided by regressionCheck.ts instead, using the async twin below. */\r\nexport function runTestCommand(command: string | null): TestOutcome {\r\n if (!command) return \"success\";\r\n try {\r\n execSync(command, { shell: \"/bin/bash\", stdio: \"inherit\", env: repositoryCommandEnv() });\r\n return \"success\";\r\n } catch {\r\n return \"failure\";\r\n }\r\n}\r\n\r\n/** Same contract as `runTestCommand`, but non-blocking: `execSync` blocks the event loop, which\r\n * would serialize the baseline test run behind (or in front of) codegen's network-bound calls\r\n * instead of letting them overlap. QUIKTR-1036 \u2014 the baseline run is the only caller today. */\r\nexport function runTestCommandAsync(command: string | null): Promise<TestOutcome> {\r\n if (!command) return Promise.resolve(\"success\");\r\n return new Promise((resolve) => {\r\n const child = spawn(command, { shell: \"/bin/bash\", stdio: \"inherit\", env: repositoryCommandEnv() });\r\n child.on(\"exit\", (code) => resolve(code === 0 ? \"success\" : \"failure\"));\r\n child.on(\"error\", () => resolve(\"failure\"));\r\n });\r\n}\r\n\r\nexport type TimedRunOutcome = \"exited\" | \"timeout\" | \"error\";\r\n\r\n/**\r\n * QUIKTR-1402 \u2014 runs a command through bash with a hard time limit, for the baseline check's single-file\r\n * run. A command that HANGS produces no error, so \"any failure means no flag\" cannot cover it: without a\r\n * limit it would hold the run until the job's own limit and look like QuikPilot being slow. The exit code\r\n * is deliberately not reported \u2014 a failing test is the normal outcome of running a generated test against\r\n * code that does not have the change yet; only \"finished\", \"timed out\" and \"could not start\" matter.\r\n *\r\n * The command runs in its own process group (`detached`) so a timeout can kill the test runner AND\r\n * whatever it started; killing only the shell would leave the runner holding the job open.\r\n */\r\nexport function runCommandWithTimeout(command: string, timeoutMs: number): Promise<TimedRunOutcome> {\r\n return new Promise((resolve) => {\r\n let settled = false;\r\n const finish = (outcome: TimedRunOutcome) => {\r\n if (settled) return;\r\n settled = true;\r\n clearTimeout(timer);\r\n resolve(outcome);\r\n };\r\n const child = spawn(command, {\r\n shell: \"/bin/bash\",\r\n stdio: \"inherit\",\r\n detached: true,\r\n env: repositoryCommandEnv(),\r\n });\r\n const timer = setTimeout(() => {\r\n try {\r\n if (child.pid !== undefined) process.kill(-child.pid, \"SIGKILL\");\r\n else child.kill(\"SIGKILL\");\r\n } catch {\r\n try {\r\n child.kill(\"SIGKILL\");\r\n } catch {\r\n // already gone\r\n }\r\n }\r\n finish(\"timeout\");\r\n }, timeoutMs);\r\n child.on(\"exit\", () => finish(\"exited\"));\r\n child.on(\"error\", () => finish(\"error\"));\r\n });\r\n}\r\n", "/**\r\n * QUIKTR-1502 \u2014 the environment a repository command runs with.\r\n *\r\n * Setup, Test, Lint, Format and the baseline checks run code nobody has reviewed yet: AI-written\r\n * tests, and whatever a dependency's install script does. Handing them the runner's own environment\r\n * hands them `ACTIONS_ID_TOKEN_REQUEST_URL` and `_TOKEN` (GitHub adds both to every step of a job\r\n * with `id-token: write`), which request an OIDC token that QuikProjects exchanges for a run token.\r\n * The server now refuses a second exchange per dispatch, which is what actually closes that path;\r\n * this is the second layer, and it also keeps the artifact/cache service credentials, the ambient\r\n * job token and the runner's own addresses out of reach.\r\n *\r\n * An allow-list, not a block-list: a variable GitHub or the runner image adds next year is withheld\r\n * until someone decides it is needed. What it cannot do is hide the runner's own environment from a\r\n * child that reads `/proc/<parent>/environ` (same user, same job); that is why the server-side\r\n * rule exists.\r\n *\r\n * What is withheld is reported by NAME (never value) so a command that needed something is\r\n * diagnosable; see `commands.ts`.\r\n */\r\n\r\n/** Names kept exactly. */\r\nconst ALLOWED_NAMES = new Set([\r\n // Identity, locale and scratch space.\r\n \"PATH\", \"Path\", \"HOME\", \"USER\", \"USERNAME\", \"LOGNAME\", \"SHELL\", \"HOSTNAME\",\r\n \"TMPDIR\", \"TMP\", \"TEMP\", \"TZ\", \"LANG\", \"LANGUAGE\", \"TERM\", \"COLORTERM\", \"NO_COLOR\", \"FORCE_COLOR\",\r\n \"DISPLAY\", \"CI\",\r\n // Windows system variables, for the developer machine.\r\n \"SystemRoot\", \"SYSTEMROOT\", \"windir\", \"COMSPEC\", \"PATHEXT\", \"USERPROFILE\", \"APPDATA\", \"LOCALAPPDATA\",\r\n // Network settings a hosted or self-hosted runner may rely on.\r\n \"HTTP_PROXY\", \"HTTPS_PROXY\", \"NO_PROXY\", \"ALL_PROXY\",\r\n \"http_proxy\", \"https_proxy\", \"no_proxy\", \"all_proxy\",\r\n \"SSL_CERT_FILE\", \"SSL_CERT_DIR\", \"NODE_EXTRA_CA_CERTS\", \"REQUESTS_CA_BUNDLE\", \"CURL_CA_BUNDLE\",\r\n // Toolchain locations the setup-* actions and the runner image export.\r\n \"NODE_OPTIONS\", \"NODE_PATH\", \"NVM_DIR\", \"ImageOS\", \"ImageVersion\", \"AGENT_TOOLSDIRECTORY\",\r\n \"CONDA\", \"pythonLocation\", \"PKG_CONFIG_PATH\", \"LD_LIBRARY_PATH\",\r\n \"CARGO_HOME\", \"RUSTUP_HOME\", \"GOPATH\", \"GOMODCACHE\", \"GOCACHE\", \"GOFLAGS\",\r\n \"JAVA_HOME\", \"GRADLE_HOME\", \"GRADLE_USER_HOME\", \"MAVEN_HOME\", \"M2_HOME\",\r\n \"ANDROID_HOME\", \"ANDROID_SDK_ROOT\",\r\n \"GEM_HOME\", \"GEM_PATH\", \"BUNDLE_PATH\", \"PIPX_HOME\", \"PIPX_BIN_DIR\", \"POETRY_HOME\",\r\n \"PNPM_HOME\", \"BUN_INSTALL\", \"DENO_INSTALL\", \"DENO_DIR\", \"VOLTA_HOME\", \"COREPACK_HOME\", \"PYENV_ROOT\", \"RBENV_ROOT\",\r\n]);\r\n\r\n/** Families kept by prefix. Case matters: toolchains export these exact spellings. */\r\nconst ALLOWED_PREFIXES = [\r\n \"LC_\",\r\n \"RUNNER_\",\r\n \"GITHUB_\",\r\n \"JAVA_HOME_\",\r\n \"GOROOT\",\r\n \"ANDROID_NDK\",\r\n \"Python\", // Python_ROOT_DIR, Python2_ROOT_DIR, Python3_ROOT_DIR\r\n \"XDG_\",\r\n \"DOTNET_\",\r\n \"VCPKG_\",\r\n \"npm_config_\",\r\n \"NPM_CONFIG_\",\r\n];\r\n\r\n/** Dropped even though a family above would keep them: the ambient job token, and the files a\r\n * command could append to in order to steer the job's LATER steps (the upload-artifact step runs\r\n * after the runner). */\r\nconst ALWAYS_WITHHELD = new Set([\r\n \"GITHUB_TOKEN\", \"GITHUB_ENV\", \"GITHUB_PATH\", \"GITHUB_OUTPUT\", \"GITHUB_STATE\", \"GITHUB_STEP_SUMMARY\",\r\n]);\r\n\r\n/** A name that reads like a credential is dropped even inside an allowed family or under an\r\n * allowed name. */\r\nconst CREDENTIAL_NAME = /(token|secret|password|passwd|credential|private_?key|api_?key)/i;\r\n\r\nfunction isAllowed(name: string): boolean {\r\n if (ALWAYS_WITHHELD.has(name) || CREDENTIAL_NAME.test(name)) return false;\r\n if (ALLOWED_NAMES.has(name)) return true;\r\n return ALLOWED_PREFIXES.some((prefix) => name.startsWith(prefix));\r\n}\r\n\r\n/** A fresh environment for a repository command: the allow-listed variables of `source` and nothing else. */\r\nexport function commandEnv(source: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {\r\n const out: NodeJS.ProcessEnv = {};\r\n for (const [name, value] of Object.entries(source)) {\r\n if (value === undefined) continue;\r\n if (isAllowed(name)) out[name] = value;\r\n }\r\n return out;\r\n}\r\n\r\n/** The names `commandEnv` drops, sorted. Names only: a value never leaves this module. */\r\nexport function withheldNames(source: NodeJS.ProcessEnv = process.env): string[] {\r\n return Object.entries(source)\r\n .filter(([name, value]) => value !== undefined && !isAllowed(name))\r\n .map(([name]) => name)\r\n .sort();\r\n}\r\n", "import { execFileSync } from \"node:child_process\";\r\n\r\n/** Thin wrapper around `execFileSync` \u2014 args passed as an array, never through a shell, so a\r\n * branch name or guardrail pattern can never be interpreted as shell syntax. `extraEnv` layers\r\n * on top of the inherited environment; every existing call site is unaffected since it defaults\r\n * to empty. */\r\nfunction git(args: string[], extraEnv: NodeJS.ProcessEnv = {}): string {\r\n return execFileSync(\"git\", args, {\r\n encoding: \"utf8\",\r\n env: { ...process.env, ...extraEnv },\r\n }).trim();\r\n}\r\n\r\nexport function currentBranch(): string {\r\n return git([\"rev-parse\", \"--abbrev-ref\", \"HEAD\"]);\r\n}\r\n\r\n/** Only fetches + checks out when the packet names a target branch different from the one the\r\n * workflow_dispatch already put us on \u2014 dispatch always runs against the default branch (the\r\n * only place `workflow_dispatch` can find the file), but the PR base may differ. */\r\nexport function checkoutTargetBranch(targetBranch: string | null): void {\r\n if (!targetBranch || targetBranch === currentBranch()) return;\r\n git([\"fetch\", \"origin\", targetBranch]);\r\n git([\"checkout\", targetBranch]);\r\n}\r\n\r\nexport function addAll(): void {\r\n git([\"add\", \"-A\"]);\r\n}\r\n\r\n/** `:(glob)` pathspec \u2014 same semantics `**` needs that a hand-rolled glob-to-regex would risk\r\n * getting wrong. */\r\nexport function diffCachedNamesMatching(pattern: string): string[] {\r\n const out = git([\"diff\", \"--cached\", \"--name-only\", \"--\", `:(glob)${pattern}`]);\r\n return out ? out.split(\"\\n\").filter(Boolean) : [];\r\n}\r\n\r\n/** Tracked files under `pathspec`, relative to cwd \u2014 same cwd every other export here already\r\n * assumes is the checkout root, so a caller can feed these straight to readFileSync/writeFileSync\r\n * with no translation. QUIKTR-1035 \u2014 `pathspec` is always concrete; \"null means repo root\" is\r\n * targeting.ts's workspaceRoot concept, not a generic git one. */\r\nexport function listFiles(pathspec: string): string[] {\r\n const out = git([\"ls-files\", \"--\", pathspec]);\r\n return out ? out.split(\"\\n\").filter(Boolean) : [];\r\n}\r\n\r\nexport function hasStagedChanges(): boolean {\r\n try {\r\n execFileSync(\"git\", [\"diff\", \"--cached\", \"--quiet\"]);\r\n return false;\r\n } catch {\r\n return true;\r\n }\r\n}\r\n\r\nexport function configureCommitIdentity(): void {\r\n git([\"config\", \"user.name\", \"quikpilot[bot]\"]);\r\n git([\"config\", \"user.email\", \"quikpilot@users.noreply.github.com\"]);\r\n}\r\n\r\nexport function checkoutNewBranch(branch: string): void {\r\n git([\"checkout\", \"-b\", branch]);\r\n}\r\n\r\nexport function commit(message: string): void {\r\n git([\"commit\", \"-m\", message]);\r\n}\r\n\r\n/**\r\n * Push, authenticated with a repo-scoped GitHub installation token (QUIKTR-804, D16) rather than\r\n * whatever ambient credential checkout configured. `x-access-token:<token>` Basic-auth, GitHub's\r\n * documented scheme for installation tokens over HTTPS git.\r\n *\r\n * Carried via `GIT_CONFIG_COUNT`/`GIT_CONFIG_KEY_0`/`GIT_CONFIG_VALUE_0` env vars rather than a\r\n * `-c http.extraheader=...` argv flag or a `.git/config` write: env vars are not visible to `ps`,\r\n * argv is \u2014 the same class of exposure `packet.ts`'s own header comment already avoids for this\r\n * runner's other credential. Scoped to this one invocation only; never persisted.\r\n *\r\n * QUIKTR-943 rehearsal, 7.0.1 \u2014 the key MUST be `http.https://github.com/.extraheader`\r\n * (URL-scoped), not the unscoped `http.extraheader`. `actions/checkout` persists its own\r\n * credential under the URL-scoped key, pointing at the job's ambient token (contents: read since\r\n * QUIKTR-804 dropped it). Git prefers the more specific URL-scoped key, so an unscoped header here\r\n * silently loses to checkout's read-only one \u2014 the push then fails with \"denied to\r\n * github-actions[bot]\" even though this token itself has write access and the exchange succeeded.\r\n *\r\n * QUIKTR-943 rehearsal, 7.0.2 \u2014 url-scoping alone re-broke the push a second way:\r\n * `http.<url>.extraheader` is multi-valued (git appends, it doesn't replace), so checkout's\r\n * `.git/config` entry and this call's env-var entry are BOTH sent, and GitHub 400s with\r\n * `Duplicate header: \"Authorization\"`. `--unset-all` clears checkout's entry from `.git/config`\r\n * first, so our env-var header (scoped to this one invocation, never written to disk) is the only\r\n * one on the wire. Tolerates the key already being absent (exit 5) \u2014 nothing to clear is not a\r\n * failure, and a workflow that ever runs with `persist-credentials: false` shouldn't crash here.\r\n */\r\nfunction clearCheckoutExtraHeader(): void {\r\n try {\r\n git([\"config\", \"--unset-all\", \"http.https://github.com/.extraheader\"]);\r\n } catch (err: unknown) {\r\n const status = (err as { status?: number }).status;\r\n if (status !== 5) throw err;\r\n }\r\n}\r\n\r\nexport function push(branch: string, installationToken: string): void {\r\n clearCheckoutExtraHeader();\r\n const basicAuth = Buffer.from(`x-access-token:${installationToken}`).toString(\"base64\");\r\n git([\"push\", \"--set-upstream\", \"origin\", branch], {\r\n GIT_CONFIG_COUNT: \"1\",\r\n GIT_CONFIG_KEY_0: \"http.https://github.com/.extraheader\",\r\n GIT_CONFIG_VALUE_0: `AUTHORIZATION: basic ${basicAuth}`,\r\n });\r\n}\r\n", "import {\r\n checkoutNewBranch,\r\n commit,\r\n configureCommitIdentity,\r\n hasStagedChanges,\r\n push,\r\n} from \"./git\";\r\n\r\nexport interface CommitResult {\r\n changed: boolean;\r\n branch?: string;\r\n}\r\n\r\n/**\r\n * QUIKTR-1067 \u2014 \"QuikPilot Phase 0 skeleton\" used to be hardcoded for every commit, including one\r\n * carrying a real generated fix (PR #19) \u2014 indistinguishable from the genuinely-empty NO_TARGET\r\n * marker commit without opening the diff, and git history is permanent. `targeted: false` is the\r\n * one case that message is still accurate for. `issueKey`/`issueTitle` null with `targeted: true`\r\n * is defensive only \u2014 dispatch never reaches commit before Gate 1, which always attaches an issue.\r\n */\r\nexport function buildCommitMessage(\r\n runId: string,\r\n targeted: boolean,\r\n issueKey: string | null,\r\n issueTitle: string | null,\r\n): string {\r\n if (!targeted) return `QuikPilot Phase 0 skeleton (run ${runId})`;\r\n if (issueKey && issueTitle) return `${issueKey}: ${issueTitle}\\n\\nQuikPilot run ${runId}`;\r\n return `QuikPilot generated changes (run ${runId})`;\r\n}\r\n\r\n/** Runs regardless of the Test step's outcome \u2014 a failing suite must not hide the generated diff\r\n * from a reviewer (the whole reason Test alone is a soft failure). Only reached when Setup, Lint,\r\n * and the guardrail check all passed. The branch name comes from the packet, not `runId`: QuikTrack\r\n * already computed and stored it, and two sources for one value will eventually disagree.\r\n * `installationToken` (QUIKTR-804) is the repo-scoped GitHub credential the push authenticates\r\n * with \u2014 see git.ts's `push` for why. */\r\nexport function commitAndPush(\r\n branch: string | null,\r\n runId: string,\r\n installationToken: string,\r\n targeted: boolean,\r\n issueKey: string | null,\r\n issueTitle: string | null,\r\n): CommitResult {\r\n if (!hasStagedChanges()) return { changed: false };\r\n if (!branch) {\r\n throw new Error(\"packet carried no branch name\");\r\n }\r\n configureCommitIdentity();\r\n checkoutNewBranch(branch);\r\n commit(buildCommitMessage(runId, targeted, issueKey, issueTitle));\r\n push(branch, installationToken);\r\n return { changed: true, branch };\r\n}\r\n", "import { readFileSync, writeFileSync, mkdirSync } from \"node:fs\";\r\nimport { dirname } from \"node:path\";\r\nimport { findDeniedContextPath, matchesDeniedPath } from \"./deniedPaths\";\r\nimport { applyEdits, detectLineEnding, fromLf, toLf, type AnchorRefusal, type LineEnding } from \"./editsApply\";\r\nimport { checkHardFailure, unwrapExecute } from \"./envelope\";\r\nimport { ACTIONABLE_IMPORT_SKIPS, collectImportContext } from \"./importContext\";\r\nimport { RuntimeReplyError } from \"./runtimeReplyError\";\r\nimport type { PilotPacket } from \"./packet\";\r\nimport { fetchWithRetry } from \"./retryFetch\";\r\nimport type { CodegenContextRecord } from \"./targetingRecord\";\r\nimport type { PilotTarget, SkippedCase } from \"./targeting\";\r\n\r\n/**\r\n * QUIKTR-823 \u2014 one `/ai/execute` call per file, proven working against a real request this\r\n * morning (Suyash): `x-run-token` header carrying the packet's `gateway.token`, full file content\r\n * in and out. Never a patch \u2014 a failed apply would cost a whole extra call against a tight budget,\r\n * and a patch that can't apply is exactly the kind of failure this loop can't safely paper over.\r\n *\r\n * QUIKTR-1035 \u2014 `targets` (with per-target `planStepsImplemented`) replaces the old\r\n * `targetPaths: string[]` plus a single `design`-derived `planSteps` shared across every file.\r\n * Merging targeting's per-target steps back into one shared list would destroy the reason they're\r\n * per-target: the route file and the service file need different instructions.\r\n *\r\n * \u2500\u2500 ALL-OR-NOTHING \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n *\r\n * The first failed or REFUSED file throws, and `run.ts`'s existing hard-failure handling takes it\r\n * from there: no branch, no pull request. A pull request is a claim the work is done; a\r\n * partially-applied change compiles sometimes, passes tests sometimes, and looks complete either\r\n * way. Already decided twice elsewhere for the same reason \u2014 Gate 1's spec commit is one\r\n * transaction, and `create_issue` with `testCases` is explicitly all-or-nothing. Retrying the\r\n * failed file instead of discarding the rest is the better long-run answer and belongs with\r\n * self-heal (Phase 3, unscoped) \u2014 not silently attempted here.\r\n *\r\n * `CODEGEN_FILE_TOO_LARGE` and `CODEGEN_CONTEXT_TOO_LARGE` are the AI Runtime's own distinct error\r\n * codes, checked on their side before dispatch \u2014 retrying hits the identical wall every time, so\r\n * both are deliberately not retried, same as every other failure here.\r\n *\r\n * \u2500\u2500 CONTEXT CONTRACT (contextPaths \u2192 contextContents) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n *\r\n * pilot.targeting now names, per target, which other files pilot.codegen should read\r\n * (`target.contextPaths`) \u2014 replacing the old `siblingContent` guess (nearest file by directory),\r\n * which only ever ran for NEW_FILE targets and was never more than a stated assumption about this\r\n * repo's own layout. `contextContents: [{ path, content }]` is now sent for EXISTING targets too,\r\n * not just NEW_FILE. Empty/absent contextPaths means empty contextContents \u2014 no fallback.\r\n * `workspaceListing` still goes out for NEW_FILE only, unchanged.\r\n *\r\n * \u2500\u2500 BUFFERED WRITES (QUIKTR-1035) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n *\r\n * `runCodegen` no longer writes anything \u2014 it collects `{targetPath, newContent}` in memory and\r\n * `flushCodegenResults` writes them all, only once every call has succeeded. Two independent\r\n * reasons: it makes all-or-nothing literally true for the working tree, not just the pull request\r\n * (today a failure on file 3 leaves files 1-2 already written even though the throw stops the\r\n * commit); and it lets the test baseline run against an untouched tree while codegen's network-\r\n * bound calls are still in flight (QUIKTR-1036 is what actually wires that concurrency up \u2014 this\r\n * only makes it possible).\r\n */\r\nconst FILE_TOO_LARGE_CODE = \"CODEGEN_FILE_TOO_LARGE\";\r\nconst CONTEXT_TOO_LARGE_CODE = \"CODEGEN_CONTEXT_TOO_LARGE\";\r\n/** \u00A716.7 \u2014 the AI Runtime's OWN output-cap guard telling us directly, distinct from\r\n * `looksLikeTruncatedRewrite` below (this file's interim heuristic guess at the same problem). */\r\nconst OUTPUT_TOO_LARGE_CODE = \"CODEGEN_OUTPUT_TOO_LARGE\";\r\nconst NOT_RETRIED_CODES = new Set([FILE_TOO_LARGE_CODE, CONTEXT_TOO_LARGE_CODE, OUTPUT_TOO_LARGE_CODE]);\r\n/** \u00A718.8.1 \u2014 the ONE retried refusal in this file, deliberately not in `NOT_RETRIED_CODES` above:\r\n * unlike the three sibling TOO_LARGE codes (which hit the identical wall on any retry), this one\r\n * is retried exactly once, with `judgedBy` narrowed to only the cases a test target's own\r\n * `contextPaths` ties to this code target \u2014 see `narrowJudgedByForTarget` below. */\r\nconst JUDGED_BY_TOO_LARGE_CODE = \"CODEGEN_JUDGED_BY_TOO_LARGE\";\r\n\r\n/**\r\n * QUIKTR-1419 \u2014 a test target is written against whatever files pilot.targeting listed for it (model\r\n * output), so it can be handed nothing of the code the run is changing. The runner therefore also gives it\r\n * the run's OTHER existing code targets. Bounded on purpose (Suyash): files changed in this run only, never\r\n * the files THEY import.\r\n *\r\n * QUIKTR-1454 \u2014 separately, EVERY existing target is also shown the files IT imports, one hop (importContext.ts).\r\n * That is a different rule from the one above, not an exception to it: an import is a fact the file states,\r\n * so it is parsed rather than left to targeting's judgement (the first real 9.0.0 run failed twice on a file\r\n * targeting never listed). Suyash, 5 Oct: one hop, what was added and skipped is logged with the reason, and\r\n * targeting's own list is never replaced. The run files above still never bring THEIR imports with them.\r\n *\r\n * The contract states no numeric limit for CODEGEN_CONTEXT_TOO_LARGE (only 200,000 chars for\r\n * `currentContent`), and that budget is shared with `currentContent` and `workspaceListing`. These are our\r\n * own conservative numbers, in characters like every other runner number (real targets seen: ~38.5k and\r\n * ~39.5k). Going over skips a file; it never fails the run.\r\n */\r\nexport const MAX_ADDED_FILE_CHARS = 40_000;\r\nexport const MAX_ADDED_CONTEXT_CHARS = 60_000;\r\n\r\nexport interface AddedContext {\r\n entries: { path: string; content: string }[];\r\n skipped: { path: string; reason: \"too large\" | \"over budget\" | \"unreadable\" }[];\r\n}\r\n\r\n/**\r\n * The extra `contextContents` entries for one target. Empty unless it is a TEST target (one with\r\n * `automationIds`); a code target's context stays exactly what targeting asked for. Candidates are the run's\r\n * other EXISTING targets that are not tests: a NEW_FILE has nothing on disk yet, and another test file adds\r\n * size for no help. `alreadyNamed` are the paths targeting already listed, so nothing is sent twice.\r\n *\r\n * Content is what is on disk NOW, i.e. before this run's edit \u2014 writes are buffered until every call has\r\n * succeeded. A route the change is adding is therefore visible to the test only through the plan steps.\r\n */\r\nexport function collectRunContext(\r\n target: PilotTarget,\r\n targets: PilotTarget[],\r\n alreadyNamed: Set<string>,\r\n deniedPaths: string[],\r\n readFile: (path: string) => string = (p) => readFileSync(p, \"utf8\"),\r\n): AddedContext {\r\n const added: AddedContext = { entries: [], skipped: [] };\r\n if (!target.automationIds?.length) return added;\r\n\r\n const seen = new Set(alreadyNamed);\r\n seen.add(target.path);\r\n let total = 0;\r\n for (const candidate of targets) {\r\n if (candidate.kind !== \"EXISTING\" || candidate.automationIds?.length) continue;\r\n if (seen.has(candidate.path)) continue;\r\n seen.add(candidate.path);\r\n // validateTarget already rejects a denied target, so this is defence in depth: a path in context is\r\n // read and sent to the LLM provider.\r\n if (matchesDeniedPath(candidate.path, deniedPaths)) continue;\r\n\r\n let content: string;\r\n try {\r\n content = readFile(candidate.path);\r\n } catch {\r\n added.skipped.push({ path: candidate.path, reason: \"unreadable\" });\r\n continue;\r\n }\r\n if (content.length > MAX_ADDED_FILE_CHARS) {\r\n added.skipped.push({ path: candidate.path, reason: \"too large\" });\r\n } else if (total + content.length > MAX_ADDED_CONTEXT_CHARS) {\r\n added.skipped.push({ path: candidate.path, reason: \"over budget\" });\r\n } else {\r\n total += content.length;\r\n added.entries.push({ path: candidate.path, content });\r\n }\r\n }\r\n return added;\r\n}\r\n\r\n/**\r\n * \u00A716.7 \u2014 interim runner-side guard, live under \u00A715 today (not gated on self-heal or on the AI\r\n * Runtime's own `CODEGEN_OUTPUT_TOO_LARGE` check, which isn't deployed yet). Codegen's output is\r\n * capped around 8,192 tokens; `CODEGEN_FILE_TOO_LARGE` only checks the ~200k-char *input*, so a\r\n * rewrite of a file well under that can still get truncated on the way out. The dangerous case is\r\n * a retry that comes back as valid, `success: true` JSON with the file quietly abbreviated \u2014\r\n * codegen's contract is that anything missing from `newContent` is deleted, so that reads as a\r\n * clean success while silently destroying code. \u00A716.7 names this exact heuristic as QuikTrack's\r\n * own stopgap until the real guard (a pre-dispatch prediction plus a finish-reason check) ships on\r\n * the runtime side.\r\n */\r\nconst SUSPECT_PLACEHOLDER_RE =\r\n /rest(?: of the)? (?:file|code) unchanged|remainder unchanged|\\/\\/\\s*\\.\\.\\.\\s*(?:rest|remaining)/i;\r\n/** Below 60% of its original length, an EXISTING rewrite is suspect rather than a real edit \u2014 a\r\n * targeted fix (planStepsImplemented) trims, it doesn't gut a file to a stub. Raised from 0.5 to\r\n * 0.6 after the AI Runtime's 2026-09-24 incident: a real pilot-chat.ts rewrite came back 38,500 ->\r\n * 22,585 chars (58.67% remaining) with success: true and no placeholder text \u2014 the old 0.5 ratio\r\n * only fires below 50% remaining, so that exact silent deletion sailed through undetected. */\r\nconst SUSPECT_LENGTH_DROP_RATIO = 0.6;\r\n/** A drop in character count can hide behind reformatting (fewer, longer lines) \u2014 this catches\r\n * the opposite failure: a rewrite that removes a large share of *lines* without a matching drop\r\n * in characters. 30% is a deliberately conservative starting point, not a calibrated number \u2014 no\r\n * incident has been observed on this signal alone yet. Tighten once real call metrics exist. */\r\nconst SUSPECT_REMOVED_LINE_RATIO = 0.3;\r\n/** Below this many lines, the multiset diff's \"changed line looks like removed+added\" blind spot\r\n * makes the ratio check unreliable \u2014 skip it rather than false-positive on small/single-line files. */\r\nconst MIN_LINES_FOR_REMOVED_LINE_CHECK = 10;\r\n/** Exported symbols removed silently are exactly the \"code vanishes, response still looks valid\"\r\n * failure mode \u2014 TS/JS only, since this parses no grammar beyond an `export` declaration. */\r\nconst JS_TS_EXTENSION_RE = /\\.(?:ts|tsx|js|jsx|mjs|cjs)$/;\r\nconst EXPORTED_SYMBOL_RE =\r\n /^export\\s+(?:default\\s+)?(?:async\\s+)?(?:function\\*?|class|const|let|var|interface|type|enum)\\s+([A-Za-z_$][\\w$]*)/gm;\r\n\r\n/** Language-neutral, line-based multiset diff \u2014 not an LCS/AST diff. Counts lines present in\r\n * `currentContent` with no matching occurrence left in `newContent`; good enough to flag \"lines\r\n * vanished\" without claiming to be a minimal diff. */\r\nfunction countRemovedLines(currentContent: string, newContent: string): number {\r\n const remaining = new Map<string, number>();\r\n for (const line of newContent.split(\"\\n\")) {\r\n remaining.set(line, (remaining.get(line) ?? 0) + 1);\r\n }\r\n let removed = 0;\r\n for (const line of currentContent.split(\"\\n\")) {\r\n const count = remaining.get(line) ?? 0;\r\n if (count > 0) {\r\n remaining.set(line, count - 1);\r\n } else {\r\n removed++;\r\n }\r\n }\r\n return removed;\r\n}\r\n\r\nfunction extractExportedSymbols(content: string): Set<string> {\r\n const symbols = new Set<string>();\r\n for (const match of content.matchAll(EXPORTED_SYMBOL_RE)) {\r\n symbols.add(match[1]);\r\n }\r\n return symbols;\r\n}\r\n\r\n/** Symbols removed by the rewrite that the plan text never names \u2014 a naive substring check, not a\r\n * reference-tracking one: it undercounts (a symbol renamed to match a plan word would slip past)\r\n * rather than overcounts, which is the right side to err on for a hard-failing guard. */\r\nfunction removedUnexplainedSymbols(targetPath: string, planText: string, currentContent: string, newContent: string): string[] {\r\n if (!JS_TS_EXTENSION_RE.test(targetPath)) return [];\r\n const before = extractExportedSymbols(currentContent);\r\n const after = extractExportedSymbols(newContent);\r\n const lowerPlan = planText.toLowerCase();\r\n return [...before].filter((symbol) => !after.has(symbol) && !lowerPlan.includes(symbol.toLowerCase()));\r\n}\r\n\r\nexport function looksLikeTruncatedRewrite(target: PilotTarget, currentContent: string, newContent: string): string | null {\r\n if (SUSPECT_PLACEHOLDER_RE.test(newContent)) {\r\n return \"contains placeholder text suggesting an abbreviated rewrite\";\r\n }\r\n if (currentContent.length > 0 && newContent.length < currentContent.length * SUSPECT_LENGTH_DROP_RATIO) {\r\n return `sharp length drop (${currentContent.length} -> ${newContent.length} chars)`;\r\n }\r\n\r\n // A multiset line diff can't tell \"line changed\" from \"line removed\" \u2014 on a short/single-line\r\n // file, one edited line reads as 100% removed. Require a real line count before trusting it.\r\n const currentLineCount = currentContent.length > 0 ? currentContent.split(\"\\n\").length : 0;\r\n if (currentLineCount >= MIN_LINES_FOR_REMOVED_LINE_CHECK) {\r\n const removedLines = countRemovedLines(currentContent, newContent);\r\n if (removedLines > currentLineCount * SUSPECT_REMOVED_LINE_RATIO) {\r\n const pct = ((removedLines / currentLineCount) * 100).toFixed(0);\r\n return `removed ${removedLines} of ${currentLineCount} lines (${pct}%) without a matching drop in character count`;\r\n }\r\n }\r\n\r\n const planText = target.planStepsImplemented.join(\" \");\r\n const unexplainedSymbols = removedUnexplainedSymbols(target.path, planText, currentContent, newContent);\r\n if (unexplainedSymbols.length > 0) {\r\n return `removed exported symbol(s) the plan steps don't mention: ${unexplainedSymbols.join(\", \")}`;\r\n }\r\n\r\n return null;\r\n}\r\n\r\n/** QUIKTR-1083 (\u00A715.6) \u2014 sent on every codegen call, same reasoning as targeting.ts's own constant. */\r\nconst CONTRACT_VERSION = \"test-targets-1\";\r\n/** 9.0.0, Doc 62 \u00A72 \u2014 cumulative over test-targets-1. For an EXISTING target the reply is anchored `edits` the runner\r\n * applies, not a whole file. A NEW_FILE target has nothing to anchor against and never asks for it. */\r\nconst CONTRACT_VERSION_EDITS = \"edits-1\";\r\n/** The runtime's code for anchors the ONE regeneration still could not place (Doc 62 \u00A72.1). Our remedy is our own:\r\n * re-request the whole file without edits-1. The fallback is the runner's, so it shows in the run trail. */\r\nconst ANCHOR_REFUSED_CODE = \"CODEGEN_ANCHOR_REFUSED\";\r\n\r\n/** The shape at `envelope.structuredJson` for `pilot.codegen` \u2014 NOT the envelope itself. A\r\n * refusal's reason is `refusalReason`; the envelope has no `code`/`message` fields (those were\r\n * never real \u2014 see envelope.ts). Under edits-1 an EXISTING target's GENERATED reply carries `edits`, not `newContent`. */\r\ninterface CodegenResult {\r\n outcome?: \"GENERATED\" | \"REFUSED\";\r\n newContent?: string;\r\n edits?: unknown;\r\n summary?: string;\r\n refusalReason?: string;\r\n}\r\n\r\n/** Which way a call went, for the one log line per call. `edits`: anchored edits applied. `fallback`: edits were\r\n * refused or did not place, so the whole file was requested. `whole_file`: no edits were asked for, or the reply was\r\n * a whole file anyway. */\r\ntype EditsPath = \"edits\" | \"fallback\" | \"whole_file\";\r\n\r\n/** What a refusal may say about itself: counts and kinds, never the text of an anchor. These strings end up in the\r\n * run's warnings, which reach QuikTrack. */\r\ninterface RefusalSummary {\r\n text: string;\r\n matchCounts: number[];\r\n}\r\n\r\nfunction summariseLocalRefusals(refusals: AnchorRefusal[]): RefusalSummary {\r\n const parts: string[] = [];\r\n const matchCounts: number[] = [];\r\n for (const r of refusals) {\r\n if (r.kind === \"ambiguous\") {\r\n parts.push(`an anchor matched ${r.matchCount} times`);\r\n if (r.matchCount !== null) matchCounts.push(r.matchCount);\r\n } else if (r.kind === \"no_match\") {\r\n parts.push(\"an anchor matched nothing\");\r\n } else if (r.kind === \"overlap\") {\r\n parts.push(`edits ${r.edits.join(\" and \")} overlap`);\r\n } else if (r.kind === \"no_edits\") {\r\n parts.push(\"the reply had no edits\");\r\n } else {\r\n parts.push(\"an edit was missing its anchor or replacement\");\r\n }\r\n }\r\n return { text: [...new Set(parts)].join(\"; \"), matchCounts };\r\n}\r\n\r\n/** The runtime's own refusal text quotes the anchor (\"The anchor was: \u2026\"), so it is read for its counts and never passed on. */\r\nfunction summariseRuntimeRefusal(error: unknown): RefusalSummary {\r\n const text = typeof error === \"string\" ? error : \"\";\r\n const matchCounts = [...text.matchAll(/anchor matched (\\d+) times/g)].map((m) => Number(m[1]));\r\n const parts: string[] = matchCounts.map((n) => `an anchor matched ${n} times`);\r\n if (/no match/i.test(text)) parts.push(\"an anchor matched nothing\");\r\n if (/overlap/i.test(text)) parts.push(\"edits overlapped\");\r\n if (/empty anchor|missing a string/i.test(text)) parts.push(\"an edit was missing its anchor or replacement\");\r\n return { text: parts.length > 0 ? [...new Set(parts)].join(\"; \") : \"the runtime could not place the edits\", matchCounts };\r\n}\r\n\r\n/** The two hard stops a reply can carry after any retry: a code that is never retried, and a judgedBy overflow that is\r\n * still too large after narrowing. One place so the whole-file fallback holds the same line as the first call. */\r\nfunction throwOnTerminalRefusal(envelope: any, targetPath: string): void {\r\n if (typeof envelope?.errorCode === \"string\" && NOT_RETRIED_CODES.has(envelope.errorCode)) {\r\n const detail = envelope.error ? `: ${envelope.error}` : \"\";\r\n throw new RuntimeReplyError(\r\n `Codegen refused ${targetPath}: ${envelope.errorCode} (not retried)${detail}`,\r\n `Codegen refused ${targetPath}: ${envelope.errorCode} (not retried)`,\r\n );\r\n }\r\n if (envelope?.errorCode === JUDGED_BY_TOO_LARGE_CODE) {\r\n // Still too large after narrowing (or the retry hit some other JUDGED_BY_TOO_LARGE cause) \u2014\r\n // no further retry, same all-or-nothing posture as every other codegen failure here.\r\n const detail = envelope.error ? `: ${envelope.error}` : \"\";\r\n throw new RuntimeReplyError(\r\n `Codegen refused ${targetPath}: ${envelope.errorCode} (after narrowing)${detail}`,\r\n `Codegen refused ${targetPath}: ${envelope.errorCode} (after narrowing)`,\r\n );\r\n }\r\n}\r\n\r\nfunction codegenRefusedError(targetPath: string, body: CodegenResult): RuntimeReplyError {\r\n return new RuntimeReplyError(\r\n `Codegen refused ${targetPath}${body.refusalReason ? `: ${body.refusalReason}` : \"\"}`,\r\n `Codegen refused ${targetPath}`,\r\n );\r\n}\r\n\r\nexport interface CodegenFileResult {\r\n targetPath: string;\r\n newContent: string;\r\n}\r\n\r\n/** \u00A718 `judgedBy` \u2014 the internal (runner-only) shape, keeping `automationId` for the\r\n * overflow-narrowing filter below; stripped down to `{title, given, when, then}` only when\r\n * actually serialized onto the wire (\u00A718.9 refuses any other key on an entry). */\r\nexport interface JudgedByCase {\r\n automationId: string;\r\n title: string;\r\n given: string;\r\n when: string;\r\n then: string;\r\n}\r\n\r\n/**\r\n * \u00A718 \u2014 every case claimed by SOME target in this run (not scoped to `contextPaths` matches \u2014\r\n * that's `narrowJudgedByForTarget`'s overflow-fallback job only, not the primary rule), minus\r\n * targeting's own `skippedCases` (\u00A715.3's `NO_BEHAVIOUR` skip), minus any entry still missing\r\n * given/when/then \u2014 defensive: a non-skipped case should already have all three by construction,\r\n * but \u00A718.9 refuses `CONTRACT_REJECTED` on any entry outside the declared shape, so this never\r\n * trusts that invariant blindly. Built once per run, in `run.ts`, and passed into `runCodegen`.\r\n */\r\nexport function buildJudgedByPool(\r\n requiredTests: PilotPacket[\"requiredTests\"],\r\n targets: PilotTarget[],\r\n skippedCases: SkippedCase[],\r\n): JudgedByCase[] {\r\n const claimedIds = new Set<string>();\r\n for (const t of targets) {\r\n for (const id of t.automationIds ?? []) claimedIds.add(id);\r\n }\r\n const skippedIds = new Set(skippedCases.map((s) => s.automationId));\r\n\r\n const pool: JudgedByCase[] = [];\r\n for (const tc of requiredTests) {\r\n if (!claimedIds.has(tc.automationId) || skippedIds.has(tc.automationId)) continue;\r\n if (!tc.given || !tc.when || !tc.then) continue;\r\n pool.push({ automationId: tc.automationId, title: tc.title, given: tc.given, when: tc.when, then: tc.then });\r\n }\r\n return pool;\r\n}\r\n\r\n/** \u00A718.8.1's overflow fallback \u2014 narrow the full pool down to only cases claimed by a test target\r\n * whose own `contextPaths` names this code target's path. Not the primary rule (a claiming test\r\n * target's `contextPaths` is model output and can be missing/wrong), only the retry narrowing. */\r\nfunction narrowJudgedByForTarget(pool: JudgedByCase[], targets: PilotTarget[], codeTargetPath: string): JudgedByCase[] {\r\n const narrowedIds = new Set<string>();\r\n for (const t of targets) {\r\n if (!t.automationIds?.length || !t.contextPaths?.includes(codeTargetPath)) continue;\r\n for (const id of t.automationIds) narrowedIds.add(id);\r\n }\r\n return pool.filter((c) => narrowedIds.has(c.automationId));\r\n}\r\n\r\n/** Strips `automationId` for the wire \u2014 \u00A718.9 refuses any key outside `{title, given, when, then}`. */\r\nfunction toWireJudgedBy(pool: JudgedByCase[]): { title: string; given: string; when: string; then: string }[] {\r\n return pool.map(({ automationId: _automationId, ...rest }) => rest);\r\n}\r\n\r\n/**\r\n * Run codegen for exactly the targets named, in order, stopping at the first failure. Throws\r\n * rather than returning a partial result \u2014 see the ALL-OR-NOTHING note above; a caller that wants\r\n * to know how far it got before failing should catch and inspect the message, not branch on a\r\n * return value that implies partial success is a valid state. Writes nothing \u2014 call\r\n * `flushCodegenResults` with the return value once this resolves.\r\n *\r\n * `warnings` is a shared, mutable array \u2014 same convention `run.ts` already uses for\r\n * QUIKTR-1064/1374's non-blocking findings \u2014 pushed into directly rather than returned, so this\r\n * function's return type stays `CodegenFileResult[]`.\r\n */\r\nexport async function runCodegen(\r\n gateway: PilotPacket[\"gateway\"],\r\n targets: PilotTarget[],\r\n workspaceListing: string[],\r\n requiredTests: PilotPacket[\"requiredTests\"],\r\n deniedPaths: string[],\r\n judgedByPool: JudgedByCase[],\r\n warnings: string[],\r\n /** QUIKTR-1421 \u2014 a caller-owned array this fills with one entry per call (what targeting named, what the\r\n * runner added, what it skipped), so run.ts can report it to QuikTrack. Optional and last: every existing\r\n * caller is unchanged. Entries are pushed BEFORE the call, so they survive a later throw. */\r\n contextLog?: CodegenContextRecord[],\r\n /** QUIKTR-1401 (\u00A720) \u2014 what the reviewer approved the change must NOT touch, sent on every call (code and test\r\n * targets alike) when non-empty. Optional and last: every existing caller is unchanged. */\r\n outOfScope: string[] = [],\r\n): Promise<CodegenFileResult[]> {\r\n const results: CodegenFileResult[] = [];\r\n const listing = new Set(workspaceListing);\r\n\r\n for (const target of targets) {\r\n const isNewFile = target.kind === \"NEW_FILE\";\r\n const currentContent = isNewFile ? \"\" : readFileSync(target.path, \"utf8\");\r\n // 9.0.0, Doc 62 \u00A72 \u2014 an EXISTING file asks for anchored edits against its LF form, and gets its own convention back\r\n // when written. A file with BOTH conventions cannot be restored faithfully, so it keeps the whole-file path.\r\n const lineEnding: LineEnding = isNewFile ? \"LF\" : detectLineEnding(currentContent);\r\n const wantsEdits = !isNewFile && lineEnding !== \"mixed\";\r\n\r\n // targeting names its own context needs per target \u2014 an invented contextPath is the same\r\n // class of bug as an invented EXISTING target (targeting.ts's validateTarget): fail loudly\r\n // rather than silently sending less context than the model asked for.\r\n const contextPaths = target.contextPaths ?? [];\r\n // QUIKTR-1420 \u2014 the egress point: this is where a context file is READ and put in the request.\r\n // runTargeting re-checks too; this holds even for a target that did not come through it, and it runs\r\n // before the not-found check so a denied path is never reported as merely missing.\r\n const deniedContext = findDeniedContextPath(contextPaths, deniedPaths);\r\n if (deniedContext) {\r\n throw new Error(\r\n `pilot.codegen contextPaths cited a denied path (${deniedContext.pattern}): ${deniedContext.path} (target ${target.path})`,\r\n );\r\n }\r\n for (const contextPath of contextPaths) {\r\n if (!listing.has(contextPath)) {\r\n throw new Error(\r\n `pilot.codegen contextPaths named a file not found in the checkout: ${contextPath} (target ${target.path})`,\r\n );\r\n }\r\n }\r\n const namedContents = contextPaths.map((path) => ({ path, content: readFileSync(path, \"utf8\") }));\r\n\r\n // QUIKTR-1419 \u2014 for a test target, also the run's other existing code files (see collectRunContext).\r\n const runFiles = collectRunContext(target, targets, new Set(contextPaths), deniedPaths);\r\n for (const s of runFiles.skipped) {\r\n warnings.push(`not shown to the test for ${target.path}: ${s.path} (${s.reason})`);\r\n }\r\n // QUIKTR-1454 \u2014 and the files this target itself imports, one hop. Added AFTER what targeting named and what the\r\n // run's files brought, never instead of them. A NEW_FILE has no content to read imports from.\r\n const imports = isNewFile\r\n ? { entries: [], skipped: [], importedPaths: [], aliasImports: 0 }\r\n : collectImportContext({\r\n targetPath: target.path,\r\n source: currentContent,\r\n alreadyNamed: new Set([...contextPaths, ...runFiles.entries.map((e) => e.path)]),\r\n deniedPaths,\r\n listing,\r\n readFile: (p) => readFileSync(p, \"utf8\"),\r\n maxFileChars: MAX_ADDED_FILE_CHARS,\r\n maxTotalChars: MAX_ADDED_CONTEXT_CHARS,\r\n spentChars: runFiles.entries.reduce((n, e) => n + e.content.length, 0),\r\n });\r\n for (const s of imports.skipped) {\r\n if (ACTIONABLE_IMPORT_SKIPS.has(s.reason)) {\r\n warnings.push(`not shown with ${target.path}: ${s.path} (imported by it; ${s.reason.replace(/^import: /, \"\")})`);\r\n }\r\n }\r\n const added: Pick<AddedContext, \"entries\"> & { skipped: { path: string; reason: string }[] } = {\r\n entries: [...runFiles.entries, ...imports.entries],\r\n skipped: [...runFiles.skipped, ...imports.skipped],\r\n };\r\n const contextContents = [...namedContents, ...added.entries];\r\n // One line per call: which files targeting named and which the runner added. Without it, \"was the\r\n // file even in front of the model?\" cannot be answered from this runner's own log (run 25). QUIKTR-1454: and\r\n // which of those came from imports, what was skipped and why, and how many path aliases were not followed.\r\n const contextRecord: CodegenContextRecord = {\r\n targetPath: target.path,\r\n contextPaths,\r\n addedPaths: added.entries.map((e) => e.path),\r\n skipped: added.skipped,\r\n ...(imports.importedPaths.length > 0 ? { importedPaths: imports.importedPaths } : {}),\r\n ...(imports.aliasImports > 0 ? { aliasImports: imports.aliasImports } : {}),\r\n };\r\n console.log(JSON.stringify({ event: \"codegen.context\", ...contextRecord }));\r\n // QUIKTR-1421 \u2014 the same facts, handed back so they reach QuikTrack's run trail, not just this job's log.\r\n contextLog?.push(contextRecord);\r\n\r\n const contextData: Record<string, unknown> = {\r\n targetPath: target.path,\r\n // Every anchor and replacement is LF, always (Doc 62 \u00A72), so the file is sent as LF.\r\n currentContent: wantsEdits ? toLf(currentContent) : currentContent,\r\n planSteps: target.planStepsImplemented,\r\n kind: target.kind,\r\n contextContents,\r\n // QUIKTR-1083 (\u00A715.6) \u2014 required on every call on the versioned path.\r\n contractVersion: wantsEdits ? CONTRACT_VERSION_EDITS : CONTRACT_VERSION,\r\n };\r\n if (isNewFile) {\r\n // Bounds WHAT EXISTS \u2014 stops an invented import like hooks/useGroups \u2014 only meaningful for\r\n // a file that doesn't exist yet to compare against.\r\n contextData.workspaceListing = workspaceListing;\r\n }\r\n if (deniedPaths.length > 0) {\r\n contextData.deniedPaths = deniedPaths;\r\n }\r\n // QUIKTR-1401, \u00A720 \u2014 omitted rather than sent empty, same as deniedPaths. Free text: told, never checked.\r\n if (outOfScope.length > 0) {\r\n contextData.outOfScope = outOfScope;\r\n }\r\n // QUIKTR-1083 (\u00A715.4) \u2014 only for a test target (one targeting named automationIds for), and\r\n // only that target's own subset \u2014 never the full list, and never for a code target at all.\r\n if (target.automationIds && target.automationIds.length > 0) {\r\n const wanted = new Set(target.automationIds);\r\n contextData.requiredTests = requiredTests.filter((tc) => wanted.has(tc.automationId));\r\n } else if (judgedByPool.length > 0) {\r\n // \u00A718 \u2014 a code target (no automationIds of its own) gets the run's claimed cases as\r\n // judging context instead. Mutually exclusive with requiredTests per call, by construction:\r\n // this is the else branch of the exact same condition. Omitted entirely when the pool is\r\n // empty, never sent as `[]`.\r\n contextData.judgedBy = toWireJudgedBy(judgedByPool);\r\n }\r\n\r\n // QUIKTR-1069 \u2014 retries a transport-level failure only (502/503/504, a dropped connection);\r\n // a real refusal always arrives as a 200 with the refusal inside the envelope, below.\r\n const callCodegen = () =>\r\n fetchWithRetry(`${gateway.baseUrl}/ai/execute`, {\r\n method: \"POST\",\r\n headers: { \"content-type\": \"application/json\", \"x-run-token\": gateway.token },\r\n body: JSON.stringify({\r\n appId: \"quiktrack\",\r\n useCase: \"pilot.codegen\",\r\n expectedOutputType: \"json\",\r\n userPrompt: \"\",\r\n contextData,\r\n }),\r\n });\r\n\r\n let res = await callCodegen();\r\n if (!res.ok) {\r\n throw new Error(`Codegen call failed for ${target.path}: ${res.status} ${res.statusText}`);\r\n }\r\n\r\n // /ai/execute wraps every result in an envelope \u2014 the use-case result lives at\r\n // structuredJson, and a failure can arrive as success:false in an HTTP 200 (see envelope.ts).\r\n // CODEGEN_FILE_TOO_LARGE / CODEGEN_CONTEXT_TOO_LARGE are checked on the RAW envelope, before\r\n // unwrapping: they arrive as a failure (success:false), so unwrapping first would throw the\r\n // generic envelope error and lose the not-retried distinction this check exists to preserve.\r\n let envelope: any = await res.json();\r\n // QUIKTR-1083 \u2014 SEMANTIC_MISMATCH/CONTRACT_REJECTED, same \"raw envelope, before unwrap\" point\r\n // as the CODEGEN_* check right below.\r\n checkHardFailure(envelope, \"pilot.codegen\", target.path);\r\n\r\n // \u00A718.8.1 \u2014 the one retried refusal here: narrow judgedBy to only the cases a test target's\r\n // own contextPaths ties to this file, then retry ONCE. Recorded on the run's trail either way\r\n // (even if the retry still fails) so the trail shows what was attempted.\r\n if (envelope?.errorCode === JUDGED_BY_TOO_LARGE_CODE && contextData.judgedBy) {\r\n const before = (contextData.judgedBy as unknown[]).length;\r\n const narrowed = narrowJudgedByForTarget(judgedByPool, targets, target.path);\r\n if (narrowed.length > 0) {\r\n contextData.judgedBy = toWireJudgedBy(narrowed);\r\n } else {\r\n delete contextData.judgedBy;\r\n }\r\n warnings.push(`judgedBy narrowed for ${target.path}: ${before} \u2192 ${narrowed.length} cases`);\r\n\r\n res = await callCodegen();\r\n if (!res.ok) {\r\n throw new Error(`Codegen call failed for ${target.path}: ${res.status} ${res.statusText}`);\r\n }\r\n envelope = await res.json();\r\n checkHardFailure(envelope, \"pilot.codegen\", target.path);\r\n }\r\n\r\n // QUIKTR-1419 \u2014 the runner's own additions must never turn a run that would have passed into a\r\n // failure. If the runtime refuses the context as too large AND we added files, retry ONCE with only\r\n // what targeting named; if it still refuses, that overflow is real and falls through to the throw below.\r\n if (envelope?.errorCode === CONTEXT_TOO_LARGE_CODE && added.entries.length > 0) {\r\n contextData.contextContents = namedContents;\r\n warnings.push(`context for ${target.path} was too large with the run's other files; retried without them`);\r\n // QUIKTR-1421 \u2014 the record must not claim files were shown that the retry dropped. The same object is\r\n // already in `contextLog`, so mutating it updates what gets reported.\r\n contextRecord.addedPaths = [];\r\n delete contextRecord.importedPaths;\r\n contextRecord.retriedWithoutAdded = true;\r\n\r\n res = await callCodegen();\r\n if (!res.ok) {\r\n throw new Error(`Codegen call failed for ${target.path}: ${res.status} ${res.statusText}`);\r\n }\r\n envelope = await res.json();\r\n checkHardFailure(envelope, \"pilot.codegen\", target.path);\r\n }\r\n\r\n throwOnTerminalRefusal(envelope, target.path);\r\n\r\n // 9.0.0, Doc 62 \u00A72/\u00A72.1 \u2014 what became of the edits. `newContent` is the file to write; `failedEdits` is set when the\r\n // edits could not be used, and there is exactly ONE answer to that: ask again for the whole file, without edits-1.\r\n let newContent: string | null = null;\r\n let failedEdits: { reason: \"anchor_refused\" | \"local_refusal\"; summary: RefusalSummary } | null = null;\r\n let editCount: number | undefined;\r\n let path: EditsPath = \"whole_file\";\r\n let reason: string | undefined = isNewFile ? \"new_file\" : wantsEdits ? undefined : \"mixed_line_endings\";\r\n\r\n if (wantsEdits && envelope?.errorCode === ANCHOR_REFUSED_CODE) {\r\n // Arrives only after the runtime's own ONE regeneration, so \"this was already retried\" is unambiguous.\r\n failedEdits = { reason: \"anchor_refused\", summary: summariseRuntimeRefusal(envelope.error) };\r\n } else {\r\n const body = unwrapExecute<CodegenResult>(envelope, \"pilot.codegen\");\r\n if (wantsEdits) {\r\n // A genuine refusal is the runtime's answer, not a malformed one: it ends the run exactly as it always has.\r\n if (body.outcome === \"REFUSED\") throw codegenRefusedError(target.path, body);\r\n // We asked for edits-1, so check we GOT edits-1 before using anything (Suyash, 5 Oct). `newContent` is valid under\r\n // test-targets-1, which is exactly why it must not be applied here: the call would succeed having asked for edits\r\n // and silently got something else. The runtime turns a malformed reply into SCHEMA_MISMATCH, so this should never\r\n // arrive; if it does it is a failure, not a candidate for the fallback, which is for anchors only (Suyash).\r\n if (body.outcome !== \"GENERATED\" || typeof body.newContent === \"string\") {\r\n throw new RuntimeReplyError(\r\n `Codegen reply for ${target.path} was not in the edits-1 shape and was not applied`,\r\n `Codegen reply for ${target.path} was not in the edits-1 shape`,\r\n );\r\n }\r\n // Every anchor is resolved against the content we sent, by the same rules the runtime held: exactly once, no\r\n // overlap. The runner writes the file, so it does not take the runtime's word for it.\r\n const applied = applyEdits(toLf(currentContent), body.edits);\r\n if (applied.ok) {\r\n newContent = fromLf(applied.content, lineEnding);\r\n path = \"edits\";\r\n editCount = applied.editCount;\r\n } else if (applied.refusals.some((r) => r.kind === \"no_edits\")) {\r\n // GENERATED with nothing to apply: a model that changed nothing while saying it did. The runtime's own answer to\r\n // that is SEMANTIC_MISMATCH, which is never retried; asking again here would only spend a bigger call on it.\r\n throw new RuntimeReplyError(\r\n `Codegen reply for ${target.path} carried no edits (not retried)`,\r\n `Codegen reply for ${target.path} carried no edits`,\r\n );\r\n } else {\r\n // Anchors that could not be placed: the one thing the whole-file fallback is for.\r\n failedEdits = { reason: \"local_refusal\", summary: summariseLocalRefusals(applied.refusals) };\r\n }\r\n } else {\r\n if (body.outcome !== \"GENERATED\" || typeof body.newContent !== \"string\") {\r\n throw codegenRefusedError(target.path, body);\r\n }\r\n newContent = body.newContent;\r\n }\r\n }\r\n\r\n if (failedEdits) {\r\n // The saving is lost on this call; the run survives, so edits-1 is never a new way to fail. It is also VISIBLE: this\r\n // warning reaches QuikTrack's run trail, which a runtime-side fallback could not do. Counts only, never an anchor.\r\n warnings.push(\r\n `edits for ${target.path} could not be placed (${failedEdits.summary.text}); asked again for the whole file`,\r\n );\r\n contextData.currentContent = currentContent;\r\n contextData.contractVersion = CONTRACT_VERSION;\r\n try {\r\n res = await callCodegen();\r\n if (!res.ok) {\r\n throw new Error(`Codegen call failed for ${target.path}: ${res.status} ${res.statusText}`);\r\n }\r\n envelope = await res.json();\r\n checkHardFailure(envelope, \"pilot.codegen\", target.path);\r\n throwOnTerminalRefusal(envelope, target.path);\r\n const whole = unwrapExecute<CodegenResult>(envelope, \"pilot.codegen\");\r\n if (whole.outcome !== \"GENERATED\" || typeof whole.newContent !== \"string\") {\r\n throw codegenRefusedError(target.path, whole);\r\n }\r\n newContent = whole.newContent;\r\n } catch (error: unknown) {\r\n // Honest, not a retry: the whole file is a BIGGER request, so where the provider cannot serve a large one\r\n // (AI_UNAVAILABLE) this can only fail the same way, and that is not transient. Say what happened and in which\r\n // order, so the failure is not read as a plain provider hiccup. Names and codes only in the reported summary.\r\n if (error instanceof RuntimeReplyError) {\r\n throw new RuntimeReplyError(\r\n `${error.message} (this was the whole-file request made after the edits for ${target.path} were refused: ${failedEdits.summary.text})`,\r\n `${error.summary} (the whole-file request, made after the edits were refused)`,\r\n );\r\n }\r\n throw error;\r\n }\r\n path = \"fallback\";\r\n reason = failedEdits.reason;\r\n }\r\n\r\n if (newContent === null) throw new Error(`Codegen produced no content for ${target.path}`);\r\n\r\n if (!isNewFile) {\r\n // Which path each call took (Doc 62 \u00A72.1): without it nobody can tell whether the retry earns its place, and the\r\n // measurement is free if collected from the start. Counts and outcomes only: no anchor, no replacement.\r\n console.log(\r\n JSON.stringify({\r\n event: \"codegen.edits_path\",\r\n targetPath: target.path,\r\n path,\r\n ...(reason ? { reason } : {}),\r\n ...(editCount !== undefined ? { editCount } : {}),\r\n ...(failedEdits && failedEdits.summary.matchCounts.length > 0 ? { matchCounts: failedEdits.summary.matchCounts } : {}),\r\n lineEnding,\r\n }),\r\n );\r\n }\r\n\r\n if (!isNewFile) {\r\n const suspectReason = looksLikeTruncatedRewrite(target, currentContent, newContent);\r\n if (suspectReason) {\r\n throw new Error(\r\n `Codegen output for ${target.path} looks like a truncated/abbreviated rewrite (${suspectReason}) ` +\r\n `\u2014 refusing to apply it. Interim guard per \u00A716.7; the AI Runtime's own output-cap check is not live yet.`,\r\n );\r\n }\r\n }\r\n\r\n // AI Runtime, 2026-09-24 \u2014 one structured line per call, to build the input/output/removed-line\r\n // distribution SUSPECT_LENGTH_DROP_RATIO and SUSPECT_REMOVED_LINE_RATIO were guessed without.\r\n // Not itself a safety check \u2014 plain data collection for calibrating the two guards above.\r\n console.log(\r\n JSON.stringify({\r\n event: \"codegen.metrics\",\r\n targetPath: target.path,\r\n kind: target.kind,\r\n inputLength: currentContent.length,\r\n outputLength: newContent.length,\r\n removedLines: isNewFile ? null : countRemovedLines(currentContent, newContent),\r\n }),\r\n );\r\n\r\n results.push({ targetPath: target.path, newContent });\r\n }\r\n\r\n return results;\r\n}\r\n\r\n/** Writes every result to disk. Only ever call this after every `runCodegen` call succeeded \u2014\r\n * see the buffered-writes note above. Creates the parent directory first: a NEW_FILE target can\r\n * legitimately name a directory that doesn't exist yet (e.g. a repo's first hooks/ file). */\r\nexport function flushCodegenResults(results: CodegenFileResult[]): void {\r\n for (const { targetPath, newContent } of results) {\r\n mkdirSync(dirname(targetPath), { recursive: true });\r\n writeFileSync(targetPath, newContent);\r\n }\r\n}\r\n", "/**\r\n * QUIKTR-1083 (\u00A715.3) \u2014 layer 2 of the three denied-path layers the contract describes: after\r\n * `pilot.targeting` responds, every proposed target's path is checked against `deniedPaths` here,\r\n * before any codegen spend. (Layer 1 is the AI Runtime's own targeting validator; layer 3 is\r\n * `guardrail.ts`'s post-commit check on the actually-staged diff.)\r\n *\r\n * Hand-rolled rather than a `minimatch`/`picomatch` dependency: this package is published\r\n * publicly and carries no secrets or heavy deps on purpose (see workflow-template.ts's own\r\n * docblock), and the denied-path patterns in real use (a dotfile glob under a double-star prefix,\r\n * a workflows directory suffixed with a double star, a bare lockfile name under a double-star\r\n * prefix) never need brace expansion, character classes, or `?` \u2014 only a double star (any depth,\r\n * including none) and a single star (anything but a path separator). A dependency for two glob\r\n * tokens is not worth the weight.\r\n */\r\nfunction globToRegExp(pattern: string): RegExp {\r\n const escaped = pattern\r\n .split(\"\")\r\n .map((c) => (/[.+^${}()|[\\]\\\\]/.test(c) ? `\\\\${c}` : c))\r\n .join(\"\");\r\n // Order matters: the more specific `**/` token first, so the generic `**`/`*` passes below\r\n // don't consume it first and lose the \"zero directories is also a match\" behaviour every\r\n // default pattern (`**/*.env*`, `**/package-lock.json`, ...) actually depends on \u2014 a repo-root\r\n // `.env` must match `**/*.env*` exactly as a nested one does, the same way `.gitignore`'s own\r\n // `**/` prefix works.\r\n const withGlobs = escaped\r\n .replace(/\\*\\*\\//g, \" SLASH \")\r\n .replace(/\\*\\*/g, \" STAR \")\r\n .replace(/\\*/g, \"[^/]*\")\r\n .replace(/ SLASH /g, \"(?:.*/)?\")\r\n .replace(/ STAR /g, \".*\");\r\n return new RegExp(`^${withGlobs}$`);\r\n}\r\n\r\n/** The first pattern `path` matches, or `null`. `path` is repo-relative, matching how every\r\n * `deniedPaths` entry and every target's `path` are already written elsewhere in this package. */\r\nexport function matchesDeniedPath(path: string, patterns: string[]): string | null {\r\n for (const pattern of patterns) {\r\n if (globToRegExp(pattern).test(path)) return pattern;\r\n }\r\n return null;\r\n}\r\n\r\n/**\r\n * QUIKTR-1420 \u2014 the first path in a list that matches a denied pattern, with the pattern it matched, or\r\n * `null`. For `contextPaths`: the runner reads each one and puts its content in the request to the model\r\n * provider, so a protected file cited as context is the same egress as one named as a target. The AI Runtime\r\n * refuses these itself (pilot_targeting.py:374, per Suyash), but for targets this package deliberately\r\n * re-checks rather than trusting that, and context was the one gap.\r\n */\r\nexport function findDeniedContextPath(\r\n contextPaths: string[],\r\n patterns: string[],\r\n): { path: string; pattern: string } | null {\r\n for (const path of contextPaths) {\r\n const pattern = matchesDeniedPath(path, patterns);\r\n if (pattern) return { path, pattern };\r\n }\r\n return null;\r\n}\r\n", "/**\r\n * Doc 62 \u00A72 / \u00A72.1 (\"edits-1\") \u2014 applying the AI Runtime's anchored edits to a file the runner is about to write.\r\n *\r\n * The runtime validates anchors against the content it was sent and splices only to measure the result; the RUNNER\r\n * writes the real file, so it applies the edits itself and holds the same rules rather than trusting the reply:\r\n * - every `find` matches the ORIGINAL content exactly once. Zero or several is a refusal, never a guess;\r\n * - every range is resolved before anything is applied, so a whole response is validated or refused;\r\n * - overlapping ranges refuse the WHOLE response; adjacent ranges do not overlap;\r\n * - application is order-independent, because ranges are spliced by position, not applied in sequence.\r\n *\r\n * Line endings: the content handed to `applyEdits` is LF. `toLf` / `detectLineEnding` / `fromLf` normalise a file before it\r\n * is sent and restore its own convention when it is written. Nothing else is normalised: in Python and YAML whitespace is\r\n * semantics, not formatting.\r\n *\r\n * Refusal messages carry counts and edit numbers only, never the text of an anchor or a replacement: they end up in the\r\n * run's warnings, which reach QuikTrack, and customer code does not.\r\n */\r\n\r\nexport type LineEnding = \"LF\" | \"CRLF\" | \"mixed\";\r\n\r\n/** The convention of `text` as read from disk. A lone CR is not a line ending, so it is counted neither way. */\r\nexport function detectLineEnding(text: string): LineEnding {\r\n const crlf = text.split(\"\\r\\n\").length - 1;\r\n const bareLf = text.split(\"\\n\").length - 1 - crlf;\r\n if (crlf > 0 && bareLf > 0) return \"mixed\";\r\n return crlf > 0 ? \"CRLF\" : \"LF\";\r\n}\r\n\r\nexport function toLf(text: string): string {\r\n return text.replace(/\\r\\n/g, \"\\n\");\r\n}\r\n\r\n/** Restores a convention on LF text. `mixed` cannot be restored faithfully, so callers never ask for it. */\r\nexport function fromLf(text: string, ending: LineEnding): string {\r\n return ending === \"CRLF\" ? text.replace(/\\n/g, \"\\r\\n\") : text;\r\n}\r\n\r\nexport type AnchorRefusalKind = \"ambiguous\" | \"no_match\" | \"empty\" | \"overlap\" | \"no_edits\";\r\n\r\nexport interface AnchorRefusal {\r\n kind: AnchorRefusalKind;\r\n /** 1-based numbers of the edits involved: one, or two for an overlap; empty for `no_edits`. */\r\n edits: number[];\r\n /** How many times the anchor matched; null when that does not apply. */\r\n matchCount: number | null;\r\n message: string;\r\n}\r\n\r\nexport type EditsOutcome =\r\n | { ok: true; content: string; editCount: number }\r\n | { ok: false; refusals: AnchorRefusal[]; editCount: number };\r\n\r\n/** Every start index of `needle` in `haystack`, overlapping occurrences included: \"aa\" occurs twice in \"aaa\", and an\r\n * anchor that can be placed two ways identifies no place. */\r\nfunction occurrences(haystack: string, needle: string): number[] {\r\n const found: number[] = [];\r\n let index = haystack.indexOf(needle);\r\n while (index !== -1) {\r\n found.push(index);\r\n index = haystack.indexOf(needle, index + 1);\r\n }\r\n return found;\r\n}\r\n\r\ninterface PlacedRange {\r\n start: number;\r\n end: number;\r\n number: number;\r\n replace: string;\r\n}\r\n\r\n/** Resolve every edit against `originalLf`, then either refuse the whole response or splice. Pure. */\r\nexport function applyEdits(originalLf: string, edits: unknown): EditsOutcome {\r\n if (!Array.isArray(edits) || edits.length === 0) {\r\n return {\r\n ok: false,\r\n editCount: 0,\r\n refusals: [{ kind: \"no_edits\", edits: [], matchCount: null, message: \"the response carried no edits\" }],\r\n };\r\n }\r\n\r\n const refusals: AnchorRefusal[] = [];\r\n const ranges: PlacedRange[] = [];\r\n\r\n edits.forEach((edit: unknown, index: number) => {\r\n const number = index + 1;\r\n const record = edit !== null && typeof edit === \"object\" ? (edit as Record<string, unknown>) : null;\r\n const find = record?.find;\r\n const replace = record?.replace;\r\n if (typeof find !== \"string\" || typeof replace !== \"string\") {\r\n refusals.push({\r\n kind: \"empty\",\r\n edits: [number],\r\n matchCount: null,\r\n message: `edit ${number} is missing a string find or replace`,\r\n });\r\n return;\r\n }\r\n if (find === \"\") {\r\n refusals.push({ kind: \"empty\", edits: [number], matchCount: null, message: `edit ${number} has an empty anchor` });\r\n return;\r\n }\r\n const starts = occurrences(originalLf, find);\r\n if (starts.length === 0) {\r\n refusals.push({ kind: \"no_match\", edits: [number], matchCount: 0, message: `edit ${number}: the anchor matched nothing` });\r\n } else if (starts.length > 1) {\r\n refusals.push({\r\n kind: \"ambiguous\",\r\n edits: [number],\r\n matchCount: starts.length,\r\n message: `edit ${number}: the anchor matched ${starts.length} times`,\r\n });\r\n } else {\r\n ranges.push({ start: starts[0]!, end: starts[0]! + find.length, number, replace });\r\n }\r\n });\r\n\r\n // Every overlapping pair, among the anchors that did place. Adjacent ranges (one ends where the next starts) are fine.\r\n for (let i = 0; i < ranges.length; i++) {\r\n for (let j = i + 1; j < ranges.length; j++) {\r\n const a = ranges[i]!;\r\n const b = ranges[j]!;\r\n if (a.start < b.end && b.start < a.end) {\r\n const [first, second] = a.number < b.number ? [a.number, b.number] : [b.number, a.number];\r\n refusals.push({\r\n kind: \"overlap\",\r\n edits: [first, second],\r\n matchCount: null,\r\n message: `edits ${first} and ${second} overlap`,\r\n });\r\n }\r\n }\r\n }\r\n\r\n if (refusals.length > 0) return { ok: false, refusals, editCount: edits.length };\r\n\r\n const pieces: string[] = [];\r\n let cursor = 0;\r\n for (const range of [...ranges].sort((x, y) => x.start - y.start)) {\r\n pieces.push(originalLf.slice(cursor, range.start), range.replace);\r\n cursor = range.end;\r\n }\r\n pieces.push(originalLf.slice(cursor));\r\n return { ok: true, content: pieces.join(\"\"), editCount: edits.length };\r\n}\r\n", "/** An error whose message quotes something the AI Runtime sent back: its explanation, a refusal reason, or the reply\r\n * itself. That text can carry case text or generated code, so the full `message` stays in the job log (where it has\r\n * always gone) and only `summary` \u2014 the error's name and code \u2014 may leave the job in the failed callback. Truncating\r\n * the message would bound its size, not its kind. */\r\nexport class RuntimeReplyError extends Error {\r\n readonly summary: string;\r\n\r\n constructor(message: string, summary: string) {\r\n super(message);\r\n this.name = \"RuntimeReplyError\";\r\n this.summary = summary;\r\n }\r\n}\r\n", "import { RuntimeReplyError } from \"./runtimeReplyError\";\r\n\r\n/**\r\n * QUIKTR-1046 \u2014 `/ai/execute` wraps every use-case result in an envelope; the use-case's own result\r\n * lives at `envelope.structuredJson`, not at the top level. Both `targeting.ts` and `codegen.ts`\r\n * read the raw response directly and have never worked against a real reply \u2014 this is the one\r\n * place that unwraps it, so there is exactly one place to get it right.\r\n *\r\n * A failed call can arrive as `success: false` in an HTTP 200 body \u2014 `res.ok` alone is not enough.\r\n * Observed live 2026-09-18/19/21, including a real RUN_CREDENTIAL_SCOPE refusal shaped exactly\r\n * like this.\r\n */\r\n/**\r\n * QUIKTR-1083 (\u00A715 of the spec-phase contract) \u2014 two hard-failure codes the AI Runtime raises on\r\n * the versioned `pilot.targeting`/`pilot.codegen` path, neither ever retried: `SEMANTIC_MISMATCH`\r\n * (the JSON shape was valid, a rule failed \u2014 e.g. a generated test file missing its\r\n * `[<automationId>]` marker) and `CONTRACT_REJECTED` (the request itself was refused \u2014 an unknown\r\n * or removed `contextData` key, or an unrecognised `contractVersion`). Both carry the explanation\r\n * in `envelope.error`.\r\n *\r\n * Checked on the RAW envelope, before `unwrapExecute` \u2014 same reason codegen.ts's existing\r\n * `CODEGEN_FILE_TOO_LARGE`/`CODEGEN_CONTEXT_TOO_LARGE` check already runs there: unwrapping first\r\n * would throw `unwrapExecute`'s generic `success:false` error and lose the distinction. No custom\r\n * error class \u2014 `run.ts`'s top-level catch already prints any thrown error's message, and\r\n * `fetchWithRetry` never retries a 200 response regardless of body, so \"print the violation list\"\r\n * and \"never retried\" both already hold once this throws a message that names the code and detail.\r\n */\r\nconst HARD_FAILURE_CODES = new Set([\"SEMANTIC_MISMATCH\", \"CONTRACT_REJECTED\"]);\r\n\r\n/** `target`, when the call is scoped to one file (codegen), is named in the message: the AI\r\n * Runtime's explanation says what broke but not in which file. */\r\nexport function checkHardFailure(envelope: any, useCase: string, target?: string): void {\r\n const code = envelope?.errorCode;\r\n if (typeof code === \"string\" && HARD_FAILURE_CODES.has(code)) {\r\n const detail = envelope.error ?? envelope.normalizedText ?? \"no detail\";\r\n const where = target ? ` for ${target}` : \"\";\r\n throw new RuntimeReplyError(\r\n `${useCase} failed${where} (${code}, not retried): ${detail}`,\r\n `${useCase} failed${where} (${code}, not retried)`,\r\n );\r\n }\r\n}\r\n\r\n/** Every error below quotes the AI Runtime's reply in its message (the job log keeps it); `RuntimeReplyError.summary`\r\n * is the name and code only, which is all that may be reported to QuikTrack. */\r\nexport function unwrapExecute<T>(envelope: any, useCase: string): T {\r\n if (envelope?.success === false) {\r\n const code = envelope.errorCode ?? \"UNKNOWN\";\r\n throw new RuntimeReplyError(\r\n `${useCase} failed: ${code} \u2014 ${envelope.error ?? envelope.normalizedText ?? \"no message\"}`,\r\n `${useCase} failed: ${code}`,\r\n );\r\n }\r\n if (!envelope?.structuredJson || typeof envelope.structuredJson !== \"object\") {\r\n throw new RuntimeReplyError(\r\n `${useCase} returned no structuredJson: ${JSON.stringify(envelope)}`,\r\n `${useCase} returned no structuredJson`,\r\n );\r\n }\r\n return envelope.structuredJson as T;\r\n}\r\n", "import { posix } from \"node:path\";\r\nimport { matchesDeniedPath } from \"./deniedPaths\";\r\n\r\n/**\r\n * QUIKTR-1454 \u2014 the files a changed file imports, shown to the code-writing step alongside the ones targeting\r\n * named. First real 9.0.0 run (QUIKSPL-35): `validation.js` imports from `exchange.js`, targeting did not list\r\n * it, and the model invented a name that file does not export. An import is a fact the file states, so it is\r\n * parsed here rather than asked of a model (Suyash, 5 Oct). Three rules from him: ONE hop (never what an\r\n * imported file imports), what was added and skipped is logged with the reason, and targeting's own list is\r\n * never replaced \u2014 this only adds to it.\r\n *\r\n * Pure: the caller hands over the repo listing and a reader. JavaScript/TypeScript only for now; any other kind\r\n * of file simply yields nothing.\r\n */\r\n\r\n// \u2500\u2500 reading imports out of source \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\ntype Token = { k: \"id\" | \"str\" | \"num\" | \"p\" | \"tpl\"; v: string };\r\n\r\nconst REGEX_PRECEDING_KEYWORDS = new Set([\r\n \"return\", \"typeof\", \"instanceof\", \"in\", \"of\", \"new\", \"delete\", \"void\", \"throw\", \"case\", \"do\", \"else\", \"yield\", \"await\",\r\n]);\r\n\r\n/** ASCII space characters plus the Unicode ones editors leave in files: byte-order mark, no-break space, line and\r\n * paragraph separators. A leading BOM read as part of the word \"import\" hid the first import of 72 repository files. */\r\nconst SPACE_CODES = new Set([0x20, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0xa0, 0x1680, 0x2028, 0x2029, 0x202f, 0x205f, 0x3000, 0xfeff]);\r\nconst isSpace = (c: string) => {\r\n const code = c.charCodeAt(0);\r\n return SPACE_CODES.has(code) || (code >= 0x2000 && code <= 0x200a);\r\n};\r\nconst isIdStart = (c: string) => !isSpace(c) && (/[A-Za-z_$]/.test(c) || c.charCodeAt(0) > 0x7f);\r\nconst isIdPart = (c: string) => !isSpace(c) && (/[A-Za-z0-9_$]/.test(c) || c.charCodeAt(0) > 0x7f);\r\n\r\n/**\r\n * Splits source into the tokens that matter and drops what must not be mistaken for code: comments, string\r\n * contents, template text and regular-expression literals. A quote that never closes on its line ends at the\r\n * line break, as a real scanner reports it \u2014 a JSX apostrophe (\"Don't\") must not swallow the rest of the file.\r\n * `${ \u2026 }` inside a template is code and is scanned (an `import()` can sit there).\r\n */\r\nfunction tokenize(src: string): Token[] {\r\n const out: Token[] = [];\r\n const n = src.length;\r\n\r\n function regexAllowed(): boolean {\r\n const prev = out[out.length - 1];\r\n if (!prev) return true;\r\n if (prev.k === \"p\") return prev.v !== \")\" && prev.v !== \"]\" && prev.v !== \"}\";\r\n if (prev.k === \"id\") return REGEX_PRECEDING_KEYWORDS.has(prev.v);\r\n return false;\r\n }\r\n\r\n /** Scans code from `i`; when `inSubstitution`, stops after the `}` that closes the `${`. Returns the next index. */\r\n function scan(start: number, inSubstitution: boolean): number {\r\n let i = start;\r\n let depth = 0;\r\n while (i < n) {\r\n const c = src[i]!;\r\n if (isSpace(c)) {\r\n i++;\r\n continue;\r\n }\r\n if (c === \"/\" && src[i + 1] === \"/\") {\r\n while (i < n && src[i] !== \"\\n\") i++;\r\n continue;\r\n }\r\n if (c === \"/\" && src[i + 1] === \"*\") {\r\n const end = src.indexOf(\"*/\", i + 2);\r\n i = end === -1 ? n : end + 2;\r\n continue;\r\n }\r\n if (c === \"'\" || c === '\"') {\r\n let j = i + 1;\r\n let closed = false;\r\n while (j < n) {\r\n const d = src[j]!;\r\n if (d === \"\\\\\") {\r\n j += 2;\r\n continue;\r\n }\r\n if (d === c) {\r\n closed = true;\r\n break;\r\n }\r\n if (d === \"\\n\" || d === \"\\r\") break;\r\n j++;\r\n }\r\n if (closed) out.push({ k: \"str\", v: src.slice(i + 1, j) });\r\n i = closed ? j + 1 : j;\r\n continue;\r\n }\r\n if (c === \"`\") {\r\n let j = i + 1;\r\n let hasSubstitution = false;\r\n let closed = false;\r\n const textStart = j;\r\n let textEnd = j;\r\n while (j < n) {\r\n const d = src[j]!;\r\n if (d === \"\\\\\") {\r\n j += 2;\r\n continue;\r\n }\r\n if (d === \"`\") {\r\n closed = true;\r\n textEnd = hasSubstitution ? textEnd : j;\r\n break;\r\n }\r\n if (d === \"$\" && src[j + 1] === \"{\") {\r\n hasSubstitution = true;\r\n j = scan(j + 2, true);\r\n continue;\r\n }\r\n j++;\r\n }\r\n if (closed) out.push(hasSubstitution ? { k: \"tpl\", v: \"\" } : { k: \"str\", v: src.slice(textStart, textEnd) });\r\n i = closed ? j + 1 : n;\r\n continue;\r\n }\r\n if (c === \"/\" && regexAllowed()) {\r\n let j = i + 1;\r\n let inClass = false;\r\n let closed = false;\r\n while (j < n) {\r\n const d = src[j]!;\r\n if (d === \"\\\\\") {\r\n j += 2;\r\n continue;\r\n }\r\n if (d === \"\\n\" || d === \"\\r\") break;\r\n if (d === \"[\") inClass = true;\r\n else if (d === \"]\") inClass = false;\r\n else if (d === \"/\" && !inClass) {\r\n closed = true;\r\n break;\r\n }\r\n j++;\r\n }\r\n if (closed) {\r\n j++;\r\n while (j < n && /[a-z]/i.test(src[j]!)) j++;\r\n out.push({ k: \"num\", v: \"/re/\" });\r\n i = j;\r\n continue;\r\n }\r\n out.push({ k: \"p\", v: \"/\" });\r\n i++;\r\n continue;\r\n }\r\n if (/[0-9]/.test(c)) {\r\n let j = i + 1;\r\n while (j < n && /[0-9A-Za-z_.]/.test(src[j]!)) j++;\r\n out.push({ k: \"num\", v: src.slice(i, j) });\r\n i = j;\r\n continue;\r\n }\r\n if (isIdStart(c)) {\r\n let j = i + 1;\r\n while (j < n && isIdPart(src[j]!)) j++;\r\n out.push({ k: \"id\", v: src.slice(i, j) });\r\n i = j;\r\n continue;\r\n }\r\n if (inSubstitution) {\r\n if (c === \"{\") depth++;\r\n else if (c === \"}\") {\r\n if (depth === 0) return i + 1;\r\n depth--;\r\n }\r\n }\r\n out.push({ k: \"p\", v: c });\r\n i++;\r\n }\r\n return n;\r\n }\r\n\r\n scan(0, false);\r\n return out;\r\n}\r\n\r\n/**\r\n * The module specifiers a JavaScript/TypeScript file names, in order of first appearance, each once: static\r\n * `import \u2026 from`, side-effect `import \"x\"`, `export \u2026 from`, `import(\"x\")`, `require(\"x\")` and\r\n * `import x = require(\"x\")`. Only string literals (or a template with no substitution) count; an expression is\r\n * ignored, as are comments, text inside strings and a method that merely happens to be called `require`.\r\n */\r\nexport function extractImportSpecifiers(source: string): string[] {\r\n const t = tokenize(source);\r\n const found: string[] = [];\r\n const seen = new Set<string>();\r\n const add = (s: string) => {\r\n if (!seen.has(s)) {\r\n seen.add(s);\r\n found.push(s);\r\n }\r\n };\r\n const isP = (tok: Token | undefined, v: string) => tok?.k === \"p\" && tok.v === v;\r\n\r\n for (let i = 0; i < t.length; i++) {\r\n const tok = t[i]!;\r\n if (tok.k !== \"id\") continue;\r\n if (isP(t[i - 1], \".\")) continue; // obj.import / obj.require \u2014 a property, not the keyword\r\n\r\n if (tok.v === \"require\") {\r\n if (isP(t[i + 1], \"(\") && t[i + 2]?.k === \"str\" && isP(t[i + 3], \")\")) add(t[i + 2]!.v);\r\n continue;\r\n }\r\n if (tok.v !== \"import\" && tok.v !== \"export\") continue;\r\n\r\n const next = t[i + 1];\r\n if (tok.v === \"import\") {\r\n if (next?.k === \"str\") {\r\n add(next.v);\r\n continue;\r\n }\r\n if (isP(next, \"(\")) {\r\n if (t[i + 2]?.k === \"str\" && (isP(t[i + 3], \")\") || isP(t[i + 3], \",\"))) add(t[i + 2]!.v);\r\n continue;\r\n }\r\n }\r\n // import <clause> from \"x\" / export <clause> from \"x\". The scan ends at the next import or export, so a long\r\n // chain of back-to-back statements (`export{a}export{b}\u2026`, no semicolons) is read once, not once per statement.\r\n for (let j = i + 1; j < t.length; j++) {\r\n const c = t[j]!;\r\n if (c.k === \"id\") {\r\n if (c.v === \"import\" || c.v === \"export\") break;\r\n if (c.v === \"from\" && t[j + 1]?.k === \"str\") {\r\n add(t[j + 1]!.v);\r\n break;\r\n }\r\n continue;\r\n }\r\n if (c.k === \"p\" && (c.v === \"{\" || c.v === \"}\" || c.v === \",\" || c.v === \"*\")) continue;\r\n break;\r\n }\r\n }\r\n return found;\r\n}\r\n\r\n/** Files the scanner understands. */\r\nexport function supportsImportScan(path: string): boolean {\r\n return /\\.(?:[cm]?[jt]sx?)$/i.test(path);\r\n}\r\n\r\n// \u2500\u2500 turning a specifier into a file in the repository \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\nexport type ResolvedImport =\r\n | { kind: \"repo\"; path: string }\r\n | { kind: \"external\" }\r\n | { kind: \"unresolved\"; reason: \"alias\" | \"not found\" | \"asset\"; attempted?: string };\r\n\r\nconst CODE_EXTS = [\".ts\", \".tsx\", \".js\", \".jsx\", \".mjs\", \".cjs\", \".mts\", \".cts\", \".json\"];\r\nconst ASSET_EXTS = new Set([\r\n \".css\", \".scss\", \".sass\", \".less\", \".svg\", \".png\", \".jpg\", \".jpeg\", \".gif\", \".webp\", \".avif\", \".ico\", \".bmp\",\r\n \".woff\", \".woff2\", \".ttf\", \".otf\", \".eot\", \".mp3\", \".mp4\", \".webm\", \".wav\", \".pdf\", \".zip\", \".wasm\",\r\n]);\r\n/** TypeScript's ESM habit: `./x.js` written in source, `x.ts` on disk. */\r\nconst TS_SIBLINGS: Record<string, string[]> = { \".js\": [\".ts\", \".tsx\"], \".jsx\": [\".tsx\"], \".mjs\": [\".mts\"], \".cjs\": [\".cts\"] };\r\n\r\n/**\r\n * Where a specifier points. `listing` is the repository's file list (the same notion of \"what exists\" targeting's\r\n * context paths are checked against), so nothing is probed on disk and nothing outside it is ever followed.\r\n */\r\nexport function resolveImport(fromPath: string, specifier: string, listing: ReadonlySet<string>): ResolvedImport {\r\n if (/^(?:@\\/|~\\/|#|\\$|\\/)/.test(specifier)) return { kind: \"unresolved\", reason: \"alias\" };\r\n const clean = specifier.replace(/[?#].*$/, \"\");\r\n const relative = clean === \".\" || clean === \"..\" || clean.startsWith(\"./\") || clean.startsWith(\"../\");\r\n if (!relative) return { kind: \"external\" };\r\n\r\n const base = posix.normalize(posix.join(posix.dirname(fromPath), clean));\r\n if (base === \"..\" || base.startsWith(\"../\") || posix.isAbsolute(base)) return { kind: \"unresolved\", reason: \"not found\" };\r\n\r\n const ext = posix.extname(base);\r\n if (ASSET_EXTS.has(ext.toLowerCase())) return { kind: \"unresolved\", reason: \"asset\" };\r\n\r\n const candidates: string[] = [];\r\n if (CODE_EXTS.includes(ext)) {\r\n candidates.push(base);\r\n for (const sibling of TS_SIBLINGS[ext] ?? []) candidates.push(base.slice(0, -ext.length) + sibling);\r\n }\r\n for (const e of CODE_EXTS) candidates.push(base + e);\r\n candidates.push(base + \".d.ts\");\r\n for (const e of CODE_EXTS) candidates.push(`${base}/index${e}`);\r\n\r\n for (const candidate of candidates) {\r\n if (listing.has(candidate)) return { kind: \"repo\", path: candidate };\r\n }\r\n return { kind: \"unresolved\", reason: \"not found\", attempted: base };\r\n}\r\n\r\n// \u2500\u2500 what gets added \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\nexport interface ImportContextParams {\r\n targetPath: string;\r\n /** The target's content on disk now. */\r\n source: string;\r\n /** Paths already in front of the model for this call (targeting's list and the run's other files). */\r\n alreadyNamed: ReadonlySet<string>;\r\n deniedPaths: string[];\r\n listing: ReadonlySet<string>;\r\n readFile: (path: string) => string;\r\n maxFileChars: number;\r\n maxTotalChars: number;\r\n /** Characters the run's other added files already spent against `maxTotalChars`. */\r\n spentChars: number;\r\n}\r\n\r\nexport interface ImportContext {\r\n entries: { path: string; content: string }[];\r\n skipped: { path: string; reason: string }[];\r\n /** The paths of `entries`, for the context log. */\r\n importedPaths: string[];\r\n /** Path-alias imports (`@/x`) seen and not followed. Counted, not listed: they can be many. */\r\n aliasImports: number;\r\n}\r\n\r\n/** Skips worth a line in the run's notes: the file mattered and could not be shown. The rest stay in the log. */\r\nexport const ACTIONABLE_IMPORT_SKIPS = new Set([\"import: too large\", \"import: over budget\", \"import: unreadable\"]);\r\n\r\n/**\r\n * The direct imports of one target, read and sized like the run's other added files (same per-file and total\r\n * limits, shared). Order is first appearance in the file. A path already named, already added, or the target\r\n * itself is never repeated; a denied path is never read.\r\n */\r\nexport function collectImportContext(p: ImportContextParams): ImportContext {\r\n const out: ImportContext = { entries: [], skipped: [], importedPaths: [], aliasImports: 0 };\r\n if (!supportsImportScan(p.targetPath)) return out;\r\n\r\n const seen = new Set<string>(p.alreadyNamed);\r\n seen.add(p.targetPath);\r\n let total = p.spentChars;\r\n\r\n for (const specifier of extractImportSpecifiers(p.source)) {\r\n const resolved = resolveImport(p.targetPath, specifier, p.listing);\r\n if (resolved.kind === \"external\") continue;\r\n if (resolved.kind === \"unresolved\") {\r\n if (resolved.reason === \"alias\") out.aliasImports++;\r\n else if (resolved.reason === \"not found\") {\r\n const path = resolved.attempted ?? specifier;\r\n if (!seen.has(path)) {\r\n seen.add(path);\r\n out.skipped.push({ path, reason: \"import: not in workspace\" });\r\n }\r\n }\r\n continue;\r\n }\r\n\r\n const path = resolved.path;\r\n if (seen.has(path)) continue;\r\n seen.add(path);\r\n // Defence in depth, like the run-file collector: a path in context is read and sent to the model provider.\r\n if (matchesDeniedPath(path, p.deniedPaths)) {\r\n out.skipped.push({ path, reason: \"import: denied\" });\r\n continue;\r\n }\r\n let content: string;\r\n try {\r\n content = p.readFile(path);\r\n } catch {\r\n out.skipped.push({ path, reason: \"import: unreadable\" });\r\n continue;\r\n }\r\n if (content.length > p.maxFileChars) {\r\n out.skipped.push({ path, reason: \"import: too large\" });\r\n } else if (total + content.length > p.maxTotalChars) {\r\n out.skipped.push({ path, reason: \"import: over budget\" });\r\n } else {\r\n total += content.length;\r\n out.entries.push({ path, content });\r\n out.importedPaths.push(path);\r\n }\r\n }\r\n return out;\r\n}\r\n", "/**\r\n * QUIKTR-1069 \u2014 a gateway timeout in front of the AI Runtime is not a refusal: the demo rehearsal\r\n * hit a 504 from a devtunnel/load balancer, not the runtime, and the same call succeeded on retry.\r\n * Retries ONLY transport-level signals \u2014 HTTP 502/503/504, or a thrown network error\r\n * (ECONNRESET/ETIMEDOUT) \u2014 twice, with a short fixed backoff. Every other failure (a real refusal,\r\n * CODEGEN_FILE_TOO_LARGE, success:false+errorCode, any 4xx) arrives as a normal HTTP 200 with the\r\n * refusal inside the envelope body, or a genuine non-transient 4xx \u2014 neither ever matches this\r\n * function's retry condition, so nothing here needs to special-case them.\r\n *\r\n * Spend: a retried call the runtime actually completed has been paid for twice. maxRunUsd already\r\n * caps the run (enforced at the gateway, per packet.ts's own comment), so this fails safe \u2014 the\r\n * worst case is hitting the budget wall slightly sooner, never an uncapped spend.\r\n */\r\nconst RETRYABLE_STATUS_CODES = new Set([502, 503, 504]);\r\nconst RETRYABLE_NETWORK_ERROR_CODES = new Set([\"ECONNRESET\", \"ETIMEDOUT\"]);\r\n\r\nfunction isRetryableNetworkError(err: unknown): boolean {\r\n const code =\r\n (err as { cause?: { code?: string } } | undefined)?.cause?.code ??\r\n (err as { code?: string } | undefined)?.code;\r\n return typeof code === \"string\" && RETRYABLE_NETWORK_ERROR_CODES.has(code);\r\n}\r\n\r\nexport async function fetchWithRetry(\r\n url: string,\r\n init: RequestInit,\r\n { retries = 2, backoffMs = 250 }: { retries?: number; backoffMs?: number } = {},\r\n): Promise<Response> {\r\n for (let attempt = 0; ; attempt++) {\r\n try {\r\n const res = await fetch(url, init);\r\n if (RETRYABLE_STATUS_CODES.has(res.status) && attempt < retries) {\r\n await new Promise((r) => setTimeout(r, backoffMs));\r\n continue;\r\n }\r\n return res;\r\n } catch (err) {\r\n if (isRetryableNetworkError(err) && attempt < retries) {\r\n await new Promise((r) => setTimeout(r, backoffMs));\r\n continue;\r\n }\r\n throw err;\r\n }\r\n }\r\n}\r\n", "/**\r\n * QUIKTR-1458 \u00A724 \u2014 which way the code is written.\r\n *\r\n * `single` is today's behaviour: one AI call per target file. `loop` lets the AI look, edit and write through tools over several\r\n * turns (codegenLoop.ts), and falls back to `single` if it cannot finish. It is OFF unless asked for, and only the exact word\r\n * `loop` asks. Like the targeting mode, today the switch is an environment variable in the workflow; `packetSetting` is the\r\n * seam for a per-project setting later, with the precedence (setting, then environment, then off) already settled.\r\n */\r\nexport type CodegenMode = \"single\" | \"loop\";\r\n\r\nexport const CODEGEN_MODE_ENV = \"QUIKPILOT_CODEGEN_MODE\";\r\n\r\nfunction parse(value: string | null | undefined): CodegenMode | null {\r\n if (typeof value !== \"string\") return null;\r\n const v = value.trim().toLowerCase();\r\n if (v === \"loop\") return \"loop\";\r\n if (v === \"single\") return \"single\";\r\n return null;\r\n}\r\n\r\nexport function resolveCodegenMode(env: NodeJS.ProcessEnv = process.env, packetSetting?: string | null): CodegenMode {\r\n return parse(packetSetting) ?? parse(env[CODEGEN_MODE_ENV]) ?? \"single\";\r\n}\r\n", "import type { CodegenLoopSummary } from \"./codegenLoop\";\r\n\r\n/**\r\n * QUIKTR-1458 \u00A724 \u2014 what the code-writing loop did, for the run's audit record that goes to QuikProjects.\r\n *\r\n * PATHS, COUNTS, A CLOSED VOCABULARY OF STATUSES, AND THE AI'S OWN SHORT REASONING \u2014 never file content, an anchor, a\r\n * replacement or a search text. The reasoning is model-written text about the customer's code (like `noTargetReason`), cut to a\r\n * short length and flagged when cut, so a reviewer can see why the AI went where it went without anything from a file.\r\n *\r\n * These caps must match QuikProjects' schema. A path longer than the cap is DROPPED, not shortened (a cut-off path is a wrong\r\n * path), and the cut is flagged.\r\n */\r\nexport const MAX_RECORD_PATHS = 50;\r\nexport const MAX_RECORD_PATH_CHARS = 300;\r\nexport const MAX_RECORD_REASONING_TURNS = 30;\r\nexport const MAX_RECORD_REASONING_CHARS = 500;\r\nexport const MAX_RECORD_FALLBACK_REASON_CHARS = 40;\r\nconst MAX_STATUS_KEYS = 20;\r\nconst MAX_STATUS_KEY_CHARS = 40;\r\n\r\nexport interface CodegenLoopRecord {\r\n turns: number;\r\n toolCalls: number;\r\n refused: number;\r\n stopReason: string;\r\n fellBack?: true;\r\n fallbackReason?: string;\r\n reads: { path: string; startLine?: number; endLine?: number; chars: number; refused?: true }[];\r\n edits: { path: string; count: number }[];\r\n created: { path: string; chars: number }[];\r\n statusCounts: Record<string, number>;\r\n /** Write results that told the AI a file no longer parses (only present when there were any). */\r\n syntaxWarnings?: number;\r\n reasoning: { turn: number; text: string; truncated?: true }[];\r\n /** Something was left out to fit the caps above. */\r\n truncated?: true;\r\n}\r\n\r\nfunction whole(n: unknown): number {\r\n return typeof n === \"number\" && Number.isInteger(n) && n >= 0 ? n : 0;\r\n}\r\n\r\nfunction pathOk(p: unknown): p is string {\r\n return typeof p === \"string\" && p.length > 0 && p.length <= MAX_RECORD_PATH_CHARS;\r\n}\r\n\r\nexport function buildCodegenLoopRecord(loop: CodegenLoopSummary): CodegenLoopRecord {\r\n let cut = false;\r\n const room = <T extends { path: string }>(rows: T[]): T[] => {\r\n const kept: T[] = [];\r\n for (const r of rows) {\r\n if (kept.length >= MAX_RECORD_PATHS) {\r\n cut = true;\r\n break;\r\n }\r\n if (!pathOk(r.path)) {\r\n cut = true;\r\n continue;\r\n }\r\n kept.push(r);\r\n }\r\n return kept;\r\n };\r\n\r\n const reads = room(loop.reads).map((r) => ({\r\n path: r.path.trim(),\r\n ...(Number.isInteger(r.startLine) ? { startLine: r.startLine } : {}),\r\n ...(Number.isInteger(r.endLine) ? { endLine: r.endLine } : {}),\r\n chars: whole(r.chars),\r\n ...(r.refused ? { refused: true as const } : {}),\r\n }));\r\n const edits = room(loop.edits).map((e) => ({ path: e.path, count: whole(e.count) }));\r\n const created = room(loop.created).map((c) => ({ path: c.path, chars: whole(c.chars) }));\r\n\r\n const statusCounts: Record<string, number> = {};\r\n for (const [k, v] of Object.entries(loop.statusCounts).slice(0, MAX_STATUS_KEYS)) {\r\n if (k.length > 0 && k.length <= MAX_STATUS_KEY_CHARS) statusCounts[k] = whole(v);\r\n else cut = true;\r\n }\r\n if (Object.keys(loop.statusCounts).length > MAX_STATUS_KEYS) cut = true;\r\n\r\n const reasoning: CodegenLoopRecord[\"reasoning\"] = [];\r\n for (const r of loop.reasoning) {\r\n if (reasoning.length >= MAX_RECORD_REASONING_TURNS) {\r\n cut = true;\r\n break;\r\n }\r\n const text = typeof r.text === \"string\" ? r.text.trim() : \"\";\r\n if (text.length === 0) continue;\r\n const over = text.length > MAX_RECORD_REASONING_CHARS;\r\n reasoning.push({ turn: whole(r.turn), text: over ? text.slice(0, MAX_RECORD_REASONING_CHARS) : text, ...(over ? { truncated: true as const } : {}) });\r\n }\r\n\r\n return {\r\n turns: whole(loop.turns),\r\n toolCalls: whole(loop.toolCalls),\r\n refused: whole(loop.refused),\r\n stopReason: loop.stopReason,\r\n ...(loop.fellBack ? { fellBack: true as const } : {}),\r\n ...(loop.fallbackReason ? { fallbackReason: String(loop.fallbackReason).slice(0, MAX_RECORD_FALLBACK_REASON_CHARS) } : {}),\r\n reads,\r\n edits,\r\n created,\r\n statusCounts,\r\n ...(whole(loop.syntaxWarnings) > 0 ? { syntaxWarnings: whole(loop.syntaxWarnings) } : {}),\r\n reasoning,\r\n ...(cut ? { truncated: true as const } : {}),\r\n };\r\n}\r\n", "import { readFileSync } from \"node:fs\";\r\nimport { MAX_ADDED_CONTEXT_CHARS, MAX_ADDED_FILE_CHARS } from \"./codegen\";\r\nimport { matchesDeniedPath } from \"./deniedPaths\";\r\nimport { toLf } from \"./editsApply\";\r\nimport { collectImportContext } from \"./importContext\";\r\nimport { isTestTarget } from \"./overlapCheck\";\r\nimport type { PilotTarget } from \"./targeting\";\r\nimport type { CodegenContextRecord } from \"./targetingRecord\";\r\n\r\n/**\r\n * QUIKTR-1458 \u00A724 \u2014 the files the code-writing loop is SHOWN before its first turn.\r\n *\r\n * Without this the loop starts blind and has to decide for itself to read the file that defines a value. In three smoke runs on\r\n * 7 Oct it read that file once: the other two times it wrote its own list of supported currencies (QUIKSPL-47) or its own\r\n * expected amounts (QUIKSPL-49) from a guess. A prompt line asking it to look helped once and not twice, so the same facts the\r\n * one-file-at-a-time path has always shown are now put in front of it, by the runner, every time:\r\n *\r\n * - the files targeting named for each target (`contextPaths`), then\r\n * - the files each EXISTING target itself imports, one hop (`importContext.ts`, QUIKTR-1454).\r\n *\r\n * and, FIRST after what targeting named, the EXISTING TESTS of the code being changed (below). Never the other targets: the AI reads\r\n * those with its own tools, and showing them again would count twice against the turn ceiling.\r\n *\r\n * Why the tests come first: in the ten runs of 8 Oct, every run that broke an existing test read that test file AFTER it had edited\r\n * the code, and every run that read it first passed. The existing tests are the executable statement of what the code does today (the\r\n * default for a missing currency, the message for a code that is not three letters), and they are the one thing the AI could not\r\n * have read in the one-file-at-a-time path at all. They are shown as LF text, because that is the form an edit has to match. A denied path is never read. The limits are the one-file path's (40,000 characters a file, 60,000 in all), shared\r\n * across the whole run, and the per-turn token ceiling still applies on top.\r\n */\r\n\r\nexport interface LoopContext {\r\n entries: { path: string; content: string }[];\r\n /** The part of `entries` that are existing tests (they also appear in `entries`). Log line only. */\r\n testPaths: string[];\r\n /** One record per target, in the shape the run's `codegenContext` record already uses, so QuikProjects shows it unchanged. */\r\n records: CodegenContextRecord[];\r\n}\r\n\r\nexport interface LoopContextParams {\r\n targets: PilotTarget[];\r\n listing: string[];\r\n deniedPaths: string[];\r\n readFile?: (path: string) => string;\r\n}\r\n\r\nconst TEST_NAME_RE = /^(.+)\\.(?:test|spec)\\.[cm]?[jt]sx?$/i;\r\nconst CODE_NAME_RE = /^(.+)\\.[cm]?[jt]sx?$/i;\r\n\r\nfunction dirOf(path: string): string {\r\n const i = path.lastIndexOf(\"/\");\r\n return i === -1 ? \"\" : path.slice(0, i);\r\n}\r\n\r\nfunction baseOf(path: string): string {\r\n return path.slice(path.lastIndexOf(\"/\") + 1);\r\n}\r\n\r\nfunction parentOf(dir: string): string {\r\n return dir === \"\" ? \"\" : dirOf(dir);\r\n}\r\n\r\n/**\r\n * The existing test files of a code file, by the usual naming (`name.test.ext`, `name.spec.ext`) and the usual places: beside it, in\r\n * a `__tests__` folder beside it, or in the `__tests__`, `tests` or `test` folder of its parent. Only files in the listing, sorted.\r\n * A same-named test elsewhere in a monorepo is not this file's.\r\n */\r\nexport function pairedTestPaths(codePath: string, listing: ReadonlySet<string>): string[] {\r\n if (isTestTarget(codePath)) return [];\r\n const m = CODE_NAME_RE.exec(baseOf(codePath));\r\n if (!m) return [];\r\n const stem = m[1]!.toLowerCase();\r\n const dir = dirOf(codePath);\r\n const parent = parentOf(dir);\r\n const join = (d: string, leaf: string) => (d === \"\" ? leaf : `${d}/${leaf}`);\r\n const homes = new Set<string>([dir, join(dir, \"__tests__\"), join(parent, \"__tests__\"), join(parent, \"tests\"), join(parent, \"test\")]);\r\n const found: string[] = [];\r\n for (const path of listing) {\r\n if (!homes.has(dirOf(path))) continue;\r\n const t = TEST_NAME_RE.exec(baseOf(path));\r\n if (t && t[1]!.toLowerCase() === stem) found.push(path);\r\n }\r\n return found.sort();\r\n}\r\n\r\nfunction asLf(text: string): string {\r\n return toLf(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);\r\n}\r\n\r\nexport function collectLoopContext(p: LoopContextParams): LoopContext {\r\n const readFile = p.readFile ?? ((path: string) => readFileSync(path, \"utf8\"));\r\n const listing = new Set(p.listing);\r\n // Every target is left to the AI's own tools, except an existing TEST target: its content is the thing to show first.\r\n const seen = new Set<string>(p.targets.filter((t) => !(t.kind === \"EXISTING\" && isTestTarget(t.path))).map((t) => t.path));\r\n const entries: LoopContext[\"entries\"] = [];\r\n const testPaths: string[] = [];\r\n const records: CodegenContextRecord[] = [];\r\n let total = 0;\r\n\r\n for (const target of p.targets) {\r\n const named = target.contextPaths ?? [];\r\n const added: string[] = [];\r\n const skipped: { path: string; reason: string }[] = [];\r\n\r\n for (const path of named) {\r\n if (seen.has(path)) continue;\r\n seen.add(path);\r\n if (matchesDeniedPath(path, p.deniedPaths)) {\r\n skipped.push({ path, reason: \"denied\" });\r\n continue;\r\n }\r\n if (!listing.has(path)) {\r\n skipped.push({ path, reason: \"not in workspace\" });\r\n continue;\r\n }\r\n let content: string;\r\n try {\r\n content = readFile(path);\r\n } catch {\r\n skipped.push({ path, reason: \"unreadable\" });\r\n continue;\r\n }\r\n if (content.length > MAX_ADDED_FILE_CHARS) skipped.push({ path, reason: \"too large\" });\r\n else if (total + content.length > MAX_ADDED_CONTEXT_CHARS) skipped.push({ path, reason: \"over budget\" });\r\n else {\r\n entries.push({ path, content });\r\n added.push(path);\r\n total += content.length;\r\n }\r\n }\r\n\r\n // The existing tests of this target: itself when it is an existing test file, or the tests that sit beside the code it changes.\r\n const wantedTests = target.kind !== \"EXISTING\" ? [] : isTestTarget(target.path) ? [target.path] : pairedTestPaths(target.path, listing);\r\n for (const path of wantedTests) {\r\n if (seen.has(path)) continue;\r\n seen.add(path);\r\n if (matchesDeniedPath(path, p.deniedPaths)) {\r\n skipped.push({ path, reason: \"denied\" });\r\n continue;\r\n }\r\n let content: string;\r\n try {\r\n content = asLf(readFile(path));\r\n } catch {\r\n skipped.push({ path, reason: \"unreadable\" });\r\n continue;\r\n }\r\n if (content.length > MAX_ADDED_FILE_CHARS) skipped.push({ path, reason: \"too large\" });\r\n else if (total + content.length > MAX_ADDED_CONTEXT_CHARS) skipped.push({ path, reason: \"over budget\" });\r\n else {\r\n entries.push({ path, content });\r\n added.push(path);\r\n testPaths.push(path);\r\n total += content.length;\r\n }\r\n }\r\n\r\n let importedPaths: string[] = [];\r\n let aliasImports = 0;\r\n if (target.kind === \"EXISTING\") {\r\n let source: string | null = null;\r\n try {\r\n source = readFile(target.path);\r\n } catch {\r\n skipped.push({ path: target.path, reason: \"import: unreadable\" });\r\n }\r\n if (source !== null) {\r\n const imports = collectImportContext({\r\n targetPath: target.path,\r\n source,\r\n alreadyNamed: seen,\r\n deniedPaths: p.deniedPaths,\r\n listing,\r\n readFile,\r\n maxFileChars: MAX_ADDED_FILE_CHARS,\r\n maxTotalChars: MAX_ADDED_CONTEXT_CHARS,\r\n spentChars: total,\r\n });\r\n for (const e of imports.entries) {\r\n entries.push(e);\r\n added.push(e.path);\r\n seen.add(e.path);\r\n total += e.content.length;\r\n }\r\n skipped.push(...imports.skipped);\r\n importedPaths = imports.importedPaths;\r\n aliasImports = imports.aliasImports;\r\n }\r\n }\r\n\r\n records.push({\r\n targetPath: target.path,\r\n contextPaths: named,\r\n addedPaths: added,\r\n skipped,\r\n ...(importedPaths.length > 0 ? { importedPaths } : {}),\r\n ...(aliasImports > 0 ? { aliasImports } : {}),\r\n });\r\n }\r\n\r\n return { entries, testPaths, records };\r\n}\r\n", "import type { PilotTarget } from \"./targeting\";\r\n\r\n/**\r\n * QUIKTR-1064 \u2014 QUIKSP-3's first live run implemented \"reject negative amounts\" twice: once in\r\n * src/server.js against raw input, once in src/validation.js against parsed minor units. Targeting\r\n * split the work across two files and gave each its own planStepsImplemented describing the same\r\n * rule; codegen faithfully built both. Per-target steps are meant to be DISJOINT (QUIKTR-1035) \u2014\r\n * nothing checked that they are.\r\n *\r\n * The real fix is `pilot.targeting`'s prompt \u2014 an AI Runtime change, not this package's. This is\r\n * the cheap half the ticket assigns here: a non-blocking warning, not semantic analysis. A\r\n * significant-word overlap between two steps in DIFFERENT targets is treated as the same rule\r\n * described twice. Same-target steps are never compared \u2014 one file legitimately implementing\r\n * several related steps is normal and not what this looks for.\r\n */\r\nexport interface OverlapWarning {\r\n targetA: string;\r\n stepA: string;\r\n targetB: string;\r\n stepB: string;\r\n /** QUIKTR-1081 \u2014 \"identical\" (the exact same instruction, modulo case/whitespace) is blocking;\r\n * \"similar\" (the existing Jaccard-threshold match, reworded but not the same text) stays a\r\n * warning. Two legitimate halves of one change never share the literal same instruction. */\r\n severity: \"identical\" | \"similar\";\r\n}\r\n\r\n// QUIKTR-1081 \u2014 a path-convention heuristic, not a real \"is this a test\" signal: nothing in this\r\n// package (or apps/quiktrack/lib/services/pilot) tags a PilotTarget as covering a test today. A\r\n// behaviour appearing in both a file and its test is correct, so a pair is exempt from this check\r\n// entirely \u2014 not merely from blocking \u2014 whenever either side looks like a test file.\r\nconst TEST_PATH_RE = /(\\.(test|spec)\\.[jt]sx?$)|(^|\\/)(__tests__|tests?)\\//i;\r\n\r\nexport function isTestTarget(path: string): boolean {\r\n return TEST_PATH_RE.test(path);\r\n}\r\n\r\nconst STOPWORDS = new Set([\r\n \"a\", \"an\", \"the\", \"is\", \"are\", \"was\", \"were\", \"be\", \"been\", \"being\",\r\n \"of\", \"to\", \"in\", \"on\", \"for\", \"with\", \"at\", \"by\", \"from\", \"as\",\r\n \"and\", \"or\", \"not\", \"no\", \"nor\",\r\n \"this\", \"that\", \"these\", \"those\", \"it\", \"its\",\r\n \"cannot\", \"can't\", \"should\", \"must\", \"may\", \"will\", \"shall\",\r\n \"when\", \"if\", \"than\", \"then\", \"so\", \"do\", \"does\", \"did\",\r\n]);\r\n\r\n// Ignore words this short too \u2014 they add noise to the overlap without carrying meaning (\"id\",\r\n// \"an\", two-letter fragments from punctuation stripping).\r\nconst MIN_WORD_LENGTH = 3;\r\n\r\nfunction significantWords(step: string): Set<string> {\r\n return new Set(\r\n step\r\n .toLowerCase()\r\n .replace(/[^a-z0-9\\s]/g, \" \")\r\n .split(/\\s+/)\r\n .filter((w) => w.length >= MIN_WORD_LENGTH && !STOPWORDS.has(w)),\r\n );\r\n}\r\n\r\nfunction jaccard(a: Set<string>, b: Set<string>): number {\r\n if (a.size === 0 || b.size === 0) return 0;\r\n let intersection = 0;\r\n for (const w of a) if (b.has(w)) intersection++;\r\n const union = a.size + b.size - intersection;\r\n return intersection / union;\r\n}\r\n\r\n// QUIKTR-1081 \u2014 stricter than significantWords' normalization (which drops stopwords/short words\r\n// entirely): this only ignores case and incidental whitespace, so \"identical\" means the actual\r\n// same instruction, not merely \"shares enough meaningful words.\"\r\nfunction normalizedStep(step: string): string {\r\n return step.trim().toLowerCase().replace(/\\s+/g, \" \");\r\n}\r\n\r\n// Cheap and deliberately generous \u2014 a false positive here costs a reviewer one glance at a warning\r\n// line; a false negative is exactly the bug this exists to catch.\r\nconst OVERLAP_THRESHOLD = 0.5;\r\n\r\n/** Every cross-target pair of plan steps whose significant words overlap enough to plausibly be the\r\n * same rule described twice. Steps within the same target are never compared. */\r\nexport function findOverlappingSteps(targets: PilotTarget[]): OverlapWarning[] {\r\n const items = targets.flatMap((target) =>\r\n target.planStepsImplemented.map((step) => ({\r\n target: target.path,\r\n step,\r\n words: significantWords(step),\r\n })),\r\n );\r\n\r\n const warnings: OverlapWarning[] = [];\r\n for (let i = 0; i < items.length; i++) {\r\n for (let j = i + 1; j < items.length; j++) {\r\n if (items[i].target === items[j].target) continue;\r\n if (isTestTarget(items[i].target) || isTestTarget(items[j].target)) continue;\r\n if (jaccard(items[i].words, items[j].words) >= OVERLAP_THRESHOLD) {\r\n warnings.push({\r\n targetA: items[i].target,\r\n stepA: items[i].step,\r\n targetB: items[j].target,\r\n stepB: items[j].step,\r\n severity: normalizedStep(items[i].step) === normalizedStep(items[j].step) ? \"identical\" : \"similar\",\r\n });\r\n }\r\n }\r\n }\r\n return warnings;\r\n}\r\n\r\nexport function describeOverlapWarnings(warnings: OverlapWarning[]): string[] {\r\n return warnings.map(\r\n (w) =>\r\n `${w.targetA} and ${w.targetB} both implement what looks like the same rule \u2014 \"${w.stepA}\" / \"${w.stepB}\". Check these aren't two independent implementations of the same behavior.`,\r\n );\r\n}\r\n", "/**\r\n * QUIKTR-1458 \u00A724 \u2014 \"an existing test file may only be added to\".\r\n *\r\n * The code-writing loop edits by replacing one piece of text (`find`) with another (`replace`). For a test file that already\r\n * existed, the only change allowed is ADDING: every character of `find` has to stay in `replace`, in the same order, with ONE new\r\n * block of whole lines put somewhere in it. Anything else (changing a line, deleting one, commenting one out, wrapping the lot in\r\n * a comment) would let the AI make code pass by weakening the test that checks it, which is the one thing it must never do.\r\n *\r\n * The first version of this rule only allowed the new text at either END of `find`. That refused the natural way to add a test to\r\n * an existing `describe` block (match the end of the last test and the block's closing line, and put the new test between them),\r\n * and the refusal ended a whole run (QUIKSPL-48, 7 Oct). So the new text may also go BETWEEN two lines of `find`, with these\r\n * guards, because inside a test body a plain \"insert some lines\" is exactly how a test gets switched off (`return;`, `it.skip`):\r\n *\r\n * - the new text is whole lines: it ends with a newline, and it goes at a line boundary of `find` (at the very end, it has to\r\n * start a new line instead);\r\n * - the new text is new TEST code, not arbitrary code: it declares a test (`it(`, `test(` or `describe(` at the start of a line)\r\n * and its brackets balance, so it is a self-contained block; or it is nothing but `import` lines.\r\n *\r\n * Only JavaScript and TypeScript test files get the looser rule. For anything else the old rule stands, because the guards above\r\n * read the language.\r\n */\r\n\r\nconst JS_FAMILY = /\\.(?:[cm]?[jt]sx?)$/i;\r\nconst DECLARES_TEST = /^[ \\t]*(?:it|test|describe)\\b/m;\r\nconst IMPORT_LINE = /^\\s*import\\b/;\r\n\r\n/** True when `path` is a test file this module knows how to read. */\r\nexport function usesLooseRule(path: string): boolean {\r\n return JS_FAMILY.test(path);\r\n}\r\n\r\n/**\r\n * Whether every bracket opened in `text` is closed in it, ignoring brackets inside strings, template literals and comments. A new\r\n * test is self-contained; a fragment that opens or closes something that was already there is not.\r\n */\r\nexport function bracketsBalance(text: string): boolean {\r\n const stack: string[] = [];\r\n const pairs: Record<string, string> = { \")\": \"(\", \"]\": \"[\", \"}\": \"{\" };\r\n let i = 0;\r\n while (i < text.length) {\r\n const c = text[i]!;\r\n const next = text[i + 1];\r\n if (c === \"/\" && next === \"/\") {\r\n const nl = text.indexOf(\"\\n\", i);\r\n i = nl === -1 ? text.length : nl + 1;\r\n continue;\r\n }\r\n if (c === \"/\" && next === \"*\") {\r\n const end = text.indexOf(\"*/\", i + 2);\r\n if (end === -1) return false;\r\n i = end + 2;\r\n continue;\r\n }\r\n if (c === '\"' || c === \"'\" || c === \"`\") {\r\n let j = i + 1;\r\n while (j < text.length && text[j] !== c) {\r\n if (text[j] === \"\\\\\") j++;\r\n if (c !== \"`\" && text[j] === \"\\n\") return false;\r\n j++;\r\n }\r\n if (j >= text.length) return false;\r\n i = j + 1;\r\n continue;\r\n }\r\n if (c === \"(\" || c === \"[\" || c === \"{\") stack.push(c);\r\n else if (c === \")\" || c === \"]\" || c === \"}\") {\r\n if (stack.pop() !== pairs[c]) return false;\r\n }\r\n i++;\r\n }\r\n return stack.length === 0;\r\n}\r\n\r\nfunction onlyImports(text: string): boolean {\r\n const lines = text.split(\"\\n\").filter((l) => l.trim().length > 0);\r\n return lines.length > 0 && lines.every((l) => IMPORT_LINE.test(l));\r\n}\r\n\r\nfunction isNewTestCode(added: string): boolean {\r\n return (DECLARES_TEST.test(added) && bracketsBalance(added)) || onlyImports(added);\r\n}\r\n\r\n/** Where the new text sits is acceptable, and what it is is acceptable. */\r\nfunction placementOk(find: string, k: number, added: string): boolean {\r\n if (added === \"\") return true;\r\n const wholeLines =\r\n k === 0\r\n ? added.endsWith(\"\\n\") // before the matched text: whole lines\r\n : k === find.length\r\n ? find.endsWith(\"\\n\") || added.startsWith(\"\\n\") // after it: it has to start a new line\r\n : find[k - 1] === \"\\n\" && added.endsWith(\"\\n\"); // between two of its lines\r\n return wholeLines && isNewTestCode(added);\r\n}\r\n\r\n/**\r\n * The old rule, kept for languages this module cannot read: the new text goes before or after `find`, which stays intact at one end.\r\n * (It lets an arbitrary prefix through, which is the hole the JavaScript rule closes.)\r\n */\r\nfunction strictEndsRule(find: string, replace: string): boolean {\r\n return replace.startsWith(find) || replace.endsWith(find);\r\n}\r\n\r\n/** True when `replace` is `find` with one block of new lines added and nothing else changed. */\r\nexport function isAddOnly(path: string, find: string, replace: string): boolean {\r\n if (replace === find) return true;\r\n if (!usesLooseRule(path)) return strictEndsRule(find, replace);\r\n if (replace.length <= find.length) return false;\r\n const addedLength = replace.length - find.length;\r\n let common = 0;\r\n while (common < find.length && find.charCodeAt(common) === replace.charCodeAt(common)) common++;\r\n for (let k = common; k >= 0; k--) {\r\n if (!replace.endsWith(find.slice(k))) continue;\r\n if (placementOk(find, k, replace.slice(k, k + addedLength))) return true;\r\n }\r\n return false;\r\n}\r\n", "// This file was generated. Do not modify manually!\nvar astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 7, 9, 32, 4, 318, 1, 78, 5, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 68, 8, 2, 0, 3, 0, 2, 3, 2, 4, 2, 0, 15, 1, 83, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 7, 19, 58, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 199, 7, 137, 9, 54, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 55, 9, 266, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 10, 5350, 0, 7, 14, 11465, 27, 2343, 9, 87, 9, 39, 4, 60, 6, 26, 9, 535, 9, 470, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4178, 9, 519, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 245, 1, 2, 9, 233, 0, 3, 0, 8, 1, 6, 0, 475, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];\n\n// This file was generated. Do not modify manually!\nvar astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 4, 51, 13, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 7, 25, 39, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 39, 27, 10, 22, 251, 41, 7, 1, 17, 5, 57, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 31, 9, 2, 0, 3, 0, 2, 37, 2, 0, 26, 0, 2, 0, 45, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 200, 32, 32, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 24, 43, 261, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 26, 3994, 6, 582, 6842, 29, 1763, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 433, 44, 212, 63, 33, 24, 3, 24, 45, 74, 6, 0, 67, 12, 65, 1, 2, 0, 15, 4, 10, 7381, 42, 31, 98, 114, 8702, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 229, 29, 3, 0, 208, 30, 2, 2, 2, 1, 2, 6, 3, 4, 10, 1, 225, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4381, 3, 5773, 3, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 8489];\n\n// This file was generated. Do not modify manually!\nvar nonASCIIidentifierChars = \"\\u200c\\u200d\\xb7\\u0300-\\u036f\\u0387\\u0483-\\u0487\\u0591-\\u05bd\\u05bf\\u05c1\\u05c2\\u05c4\\u05c5\\u05c7\\u0610-\\u061a\\u064b-\\u0669\\u0670\\u06d6-\\u06dc\\u06df-\\u06e4\\u06e7\\u06e8\\u06ea-\\u06ed\\u06f0-\\u06f9\\u0711\\u0730-\\u074a\\u07a6-\\u07b0\\u07c0-\\u07c9\\u07eb-\\u07f3\\u07fd\\u0816-\\u0819\\u081b-\\u0823\\u0825-\\u0827\\u0829-\\u082d\\u0859-\\u085b\\u0897-\\u089f\\u08ca-\\u08e1\\u08e3-\\u0903\\u093a-\\u093c\\u093e-\\u094f\\u0951-\\u0957\\u0962\\u0963\\u0966-\\u096f\\u0981-\\u0983\\u09bc\\u09be-\\u09c4\\u09c7\\u09c8\\u09cb-\\u09cd\\u09d7\\u09e2\\u09e3\\u09e6-\\u09ef\\u09fe\\u0a01-\\u0a03\\u0a3c\\u0a3e-\\u0a42\\u0a47\\u0a48\\u0a4b-\\u0a4d\\u0a51\\u0a66-\\u0a71\\u0a75\\u0a81-\\u0a83\\u0abc\\u0abe-\\u0ac5\\u0ac7-\\u0ac9\\u0acb-\\u0acd\\u0ae2\\u0ae3\\u0ae6-\\u0aef\\u0afa-\\u0aff\\u0b01-\\u0b03\\u0b3c\\u0b3e-\\u0b44\\u0b47\\u0b48\\u0b4b-\\u0b4d\\u0b55-\\u0b57\\u0b62\\u0b63\\u0b66-\\u0b6f\\u0b82\\u0bbe-\\u0bc2\\u0bc6-\\u0bc8\\u0bca-\\u0bcd\\u0bd7\\u0be6-\\u0bef\\u0c00-\\u0c04\\u0c3c\\u0c3e-\\u0c44\\u0c46-\\u0c48\\u0c4a-\\u0c4d\\u0c55\\u0c56\\u0c62\\u0c63\\u0c66-\\u0c6f\\u0c81-\\u0c83\\u0cbc\\u0cbe-\\u0cc4\\u0cc6-\\u0cc8\\u0cca-\\u0ccd\\u0cd5\\u0cd6\\u0ce2\\u0ce3\\u0ce6-\\u0cef\\u0cf3\\u0d00-\\u0d03\\u0d3b\\u0d3c\\u0d3e-\\u0d44\\u0d46-\\u0d48\\u0d4a-\\u0d4d\\u0d57\\u0d62\\u0d63\\u0d66-\\u0d6f\\u0d81-\\u0d83\\u0dca\\u0dcf-\\u0dd4\\u0dd6\\u0dd8-\\u0ddf\\u0de6-\\u0def\\u0df2\\u0df3\\u0e31\\u0e34-\\u0e3a\\u0e47-\\u0e4e\\u0e50-\\u0e59\\u0eb1\\u0eb4-\\u0ebc\\u0ec8-\\u0ece\\u0ed0-\\u0ed9\\u0f18\\u0f19\\u0f20-\\u0f29\\u0f35\\u0f37\\u0f39\\u0f3e\\u0f3f\\u0f71-\\u0f84\\u0f86\\u0f87\\u0f8d-\\u0f97\\u0f99-\\u0fbc\\u0fc6\\u102b-\\u103e\\u1040-\\u1049\\u1056-\\u1059\\u105e-\\u1060\\u1062-\\u1064\\u1067-\\u106d\\u1071-\\u1074\\u1082-\\u108d\\u108f-\\u109d\\u135d-\\u135f\\u1369-\\u1371\\u1712-\\u1715\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17b4-\\u17d3\\u17dd\\u17e0-\\u17e9\\u180b-\\u180d\\u180f-\\u1819\\u18a9\\u1920-\\u192b\\u1930-\\u193b\\u1946-\\u194f\\u19d0-\\u19da\\u1a17-\\u1a1b\\u1a55-\\u1a5e\\u1a60-\\u1a7c\\u1a7f-\\u1a89\\u1a90-\\u1a99\\u1ab0-\\u1abd\\u1abf-\\u1add\\u1ae0-\\u1aeb\\u1b00-\\u1b04\\u1b34-\\u1b44\\u1b50-\\u1b59\\u1b6b-\\u1b73\\u1b80-\\u1b82\\u1ba1-\\u1bad\\u1bb0-\\u1bb9\\u1be6-\\u1bf3\\u1c24-\\u1c37\\u1c40-\\u1c49\\u1c50-\\u1c59\\u1cd0-\\u1cd2\\u1cd4-\\u1ce8\\u1ced\\u1cf4\\u1cf7-\\u1cf9\\u1dc0-\\u1dff\\u200c\\u200d\\u203f\\u2040\\u2054\\u20d0-\\u20dc\\u20e1\\u20e5-\\u20f0\\u2cef-\\u2cf1\\u2d7f\\u2de0-\\u2dff\\u302a-\\u302f\\u3099\\u309a\\u30fb\\ua620-\\ua629\\ua66f\\ua674-\\ua67d\\ua69e\\ua69f\\ua6f0\\ua6f1\\ua802\\ua806\\ua80b\\ua823-\\ua827\\ua82c\\ua880\\ua881\\ua8b4-\\ua8c5\\ua8d0-\\ua8d9\\ua8e0-\\ua8f1\\ua8ff-\\ua909\\ua926-\\ua92d\\ua947-\\ua953\\ua980-\\ua983\\ua9b3-\\ua9c0\\ua9d0-\\ua9d9\\ua9e5\\ua9f0-\\ua9f9\\uaa29-\\uaa36\\uaa43\\uaa4c\\uaa4d\\uaa50-\\uaa59\\uaa7b-\\uaa7d\\uaab0\\uaab2-\\uaab4\\uaab7\\uaab8\\uaabe\\uaabf\\uaac1\\uaaeb-\\uaaef\\uaaf5\\uaaf6\\uabe3-\\uabea\\uabec\\uabed\\uabf0-\\uabf9\\ufb1e\\ufe00-\\ufe0f\\ufe20-\\ufe2f\\ufe33\\ufe34\\ufe4d-\\ufe4f\\uff10-\\uff19\\uff3f\\uff65\";\n\n// This file was generated. Do not modify manually!\nvar nonASCIIidentifierStartChars = \"\\xaa\\xb5\\xba\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u02c1\\u02c6-\\u02d1\\u02e0-\\u02e4\\u02ec\\u02ee\\u0370-\\u0374\\u0376\\u0377\\u037a-\\u037d\\u037f\\u0386\\u0388-\\u038a\\u038c\\u038e-\\u03a1\\u03a3-\\u03f5\\u03f7-\\u0481\\u048a-\\u052f\\u0531-\\u0556\\u0559\\u0560-\\u0588\\u05d0-\\u05ea\\u05ef-\\u05f2\\u0620-\\u064a\\u066e\\u066f\\u0671-\\u06d3\\u06d5\\u06e5\\u06e6\\u06ee\\u06ef\\u06fa-\\u06fc\\u06ff\\u0710\\u0712-\\u072f\\u074d-\\u07a5\\u07b1\\u07ca-\\u07ea\\u07f4\\u07f5\\u07fa\\u0800-\\u0815\\u081a\\u0824\\u0828\\u0840-\\u0858\\u0860-\\u086a\\u0870-\\u0887\\u0889-\\u088f\\u08a0-\\u08c9\\u0904-\\u0939\\u093d\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098c\\u098f\\u0990\\u0993-\\u09a8\\u09aa-\\u09b0\\u09b2\\u09b6-\\u09b9\\u09bd\\u09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7-\\u0eb0\\u0eb2\\u0eb3\\u0ebd\\u0ec0-\\u0ec4\\u0ec6\\u0edc-\\u0edf\\u0f00\\u0f40-\\u0f47\\u0f49-\\u0f6c\\u0f88-\\u0f8c\\u1000-\\u102a\\u103f\\u1050-\\u1055\\u105a-\\u105d\\u1061\\u1065\\u1066\\u106e-\\u1070\\u1075-\\u1081\\u108e\\u10a0-\\u10c5\\u10c7\\u10cd\\u10d0-\\u10fa\\u10fc-\\u1248\\u124a-\\u124d\\u1250-\\u1256\\u1258\\u125a-\\u125d\\u1260-\\u1288\\u128a-\\u128d\\u1290-\\u12b0\\u12b2-\\u12b5\\u12b8-\\u12be\\u12c0\\u12c2-\\u12c5\\u12c8-\\u12d6\\u12d8-\\u1310\\u1312-\\u1315\\u1318-\\u135a\\u1380-\\u138f\\u13a0-\\u13f5\\u13f8-\\u13fd\\u1401-\\u166c\\u166f-\\u167f\\u1681-\\u169a\\u16a0-\\u16ea\\u16ee-\\u16f8\\u1700-\\u1711\\u171f-\\u1731\\u1740-\\u1751\\u1760-\\u176c\\u176e-\\u1770\\u1780-\\u17b3\\u17d7\\u17dc\\u1820-\\u1878\\u1880-\\u18a8\\u18aa\\u18b0-\\u18f5\\u1900-\\u191e\\u1950-\\u196d\\u1970-\\u1974\\u1980-\\u19ab\\u19b0-\\u19c9\\u1a00-\\u1a16\\u1a20-\\u1a54\\u1aa7\\u1b05-\\u1b33\\u1b45-\\u1b4c\\u1b83-\\u1ba0\\u1bae\\u1baf\\u1bba-\\u1be5\\u1c00-\\u1c23\\u1c4d-\\u1c4f\\u1c5a-\\u1c7d\\u1c80-\\u1c8a\\u1c90-\\u1cba\\u1cbd-\\u1cbf\\u1ce9-\\u1cec\\u1cee-\\u1cf3\\u1cf5\\u1cf6\\u1cfa\\u1d00-\\u1dbf\\u1e00-\\u1f15\\u1f18-\\u1f1d\\u1f20-\\u1f45\\u1f48-\\u1f4d\\u1f50-\\u1f57\\u1f59\\u1f5b\\u1f5d\\u1f5f-\\u1f7d\\u1f80-\\u1fb4\\u1fb6-\\u1fbc\\u1fbe\\u1fc2-\\u1fc4\\u1fc6-\\u1fcc\\u1fd0-\\u1fd3\\u1fd6-\\u1fdb\\u1fe0-\\u1fec\\u1ff2-\\u1ff4\\u1ff6-\\u1ffc\\u2071\\u207f\\u2090-\\u209c\\u2102\\u2107\\u210a-\\u2113\\u2115\\u2118-\\u211d\\u2124\\u2126\\u2128\\u212a-\\u2139\\u213c-\\u213f\\u2145-\\u2149\\u214e\\u2160-\\u2188\\u2c00-\\u2ce4\\u2ceb-\\u2cee\\u2cf2\\u2cf3\\u2d00-\\u2d25\\u2d27\\u2d2d\\u2d30-\\u2d67\\u2d6f\\u2d80-\\u2d96\\u2da0-\\u2da6\\u2da8-\\u2dae\\u2db0-\\u2db6\\u2db8-\\u2dbe\\u2dc0-\\u2dc6\\u2dc8-\\u2dce\\u2dd0-\\u2dd6\\u2dd8-\\u2dde\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303c\\u3041-\\u3096\\u309b-\\u309f\\u30a1-\\u30fa\\u30fc-\\u30ff\\u3105-\\u312f\\u3131-\\u318e\\u31a0-\\u31bf\\u31f0-\\u31ff\\u3400-\\u4dbf\\u4e00-\\ua48c\\ua4d0-\\ua4fd\\ua500-\\ua60c\\ua610-\\ua61f\\ua62a\\ua62b\\ua640-\\ua66e\\ua67f-\\ua69d\\ua6a0-\\ua6ef\\ua717-\\ua71f\\ua722-\\ua788\\ua78b-\\ua7dc\\ua7f1-\\ua801\\ua803-\\ua805\\ua807-\\ua80a\\ua80c-\\ua822\\ua840-\\ua873\\ua882-\\ua8b3\\ua8f2-\\ua8f7\\ua8fb\\ua8fd\\ua8fe\\ua90a-\\ua925\\ua930-\\ua946\\ua960-\\ua97c\\ua984-\\ua9b2\\ua9cf\\ua9e0-\\ua9e4\\ua9e6-\\ua9ef\\ua9fa-\\ua9fe\\uaa00-\\uaa28\\uaa40-\\uaa42\\uaa44-\\uaa4b\\uaa60-\\uaa76\\uaa7a\\uaa7e-\\uaaaf\\uaab1\\uaab5\\uaab6\\uaab9-\\uaabd\\uaac0\\uaac2\\uaadb-\\uaadd\\uaae0-\\uaaea\\uaaf2-\\uaaf4\\uab01-\\uab06\\uab09-\\uab0e\\uab11-\\uab16\\uab20-\\uab26\\uab28-\\uab2e\\uab30-\\uab5a\\uab5c-\\uab69\\uab70-\\uabe2\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufa6d\\ufa70-\\ufad9\\ufb00-\\ufb06\\ufb13-\\ufb17\\ufb1d\\ufb1f-\\ufb28\\ufb2a-\\ufb36\\ufb38-\\ufb3c\\ufb3e\\ufb40\\ufb41\\ufb43\\ufb44\\ufb46-\\ufbb1\\ufbd3-\\ufd3d\\ufd50-\\ufd8f\\ufd92-\\ufdc7\\ufdf0-\\ufdfb\\ufe70-\\ufe74\\ufe76-\\ufefc\\uff21-\\uff3a\\uff41-\\uff5a\\uff66-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc\";\n\n// These are a run-length and offset encoded representation of the\n// >0xffff code points that are a valid part of identifiers. The\n// offset starts at 0x10000, and each pair of numbers represents an\n// offset to the next range, and then a size of the range.\n\n// Reserved word lists for various dialects of the language\n\nvar reservedWords = {\n 3: \"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile\",\n 5: \"class enum extends super const export import\",\n 6: \"enum\",\n strict: \"implements interface let package private protected public static yield\",\n strictBind: \"eval arguments\"\n};\n\n// And the keywords\n\nvar ecma5AndLessKeywords = \"break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this\";\n\nvar keywords$1 = {\n 5: ecma5AndLessKeywords,\n \"5module\": ecma5AndLessKeywords + \" export import\",\n 6: ecma5AndLessKeywords + \" const class extends export import super\"\n};\n\nvar keywordRelationalOperator = /^in(stanceof)?$/;\n\n// ## Character categories\n\nvar nonASCIIidentifierStart = new RegExp(\"[\" + nonASCIIidentifierStartChars + \"]\");\nvar nonASCIIidentifier = new RegExp(\"[\" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + \"]\");\n\n// This has a complexity linear to the value of the code. The\n// assumption is that looking up astral identifier characters is\n// rare.\nfunction isInAstralSet(code, set) {\n var pos = 0x10000;\n for (var i = 0; i < set.length; i += 2) {\n pos += set[i];\n if (pos > code) { return false }\n pos += set[i + 1];\n if (pos >= code) { return true }\n }\n return false\n}\n\n// Test whether a given character code starts an identifier.\n\nfunction isIdentifierStart(code, astral) {\n if (code < 65) { return code === 36 }\n if (code < 91) { return true }\n if (code < 97) { return code === 95 }\n if (code < 123) { return true }\n if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }\n if (astral === false) { return false }\n return isInAstralSet(code, astralIdentifierStartCodes)\n}\n\n// Test whether a given character is part of an identifier.\n\nfunction isIdentifierChar(code, astral) {\n if (code < 48) { return code === 36 }\n if (code < 58) { return true }\n if (code < 65) { return false }\n if (code < 91) { return true }\n if (code < 97) { return code === 95 }\n if (code < 123) { return true }\n if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }\n if (astral === false) { return false }\n return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)\n}\n\n// ## Token types\n\n// The assignment of fine-grained, information-carrying type objects\n// allows the tokenizer to store the information it has about a\n// token in a way that is very cheap for the parser to look up.\n\n// All token type variables start with an underscore, to make them\n// easy to recognize.\n\n// The `beforeExpr` property is used to disambiguate between regular\n// expressions and divisions. It is set on all token types that can\n// be followed by an expression (thus, a slash after them would be a\n// regular expression).\n//\n// The `startsExpr` property is used to check if the token ends a\n// `yield` expression. It is set on all token types that either can\n// directly start an expression (like a quotation mark) or can\n// continue an expression (like the body of a string).\n//\n// `isLoop` marks a keyword as starting a loop, which is important\n// to know when parsing a label, in order to allow or disallow\n// continue jumps to that label.\n\nvar TokenType = function TokenType(label, conf) {\n if ( conf === void 0 ) conf = {};\n\n this.label = label;\n this.keyword = conf.keyword;\n this.beforeExpr = !!conf.beforeExpr;\n this.startsExpr = !!conf.startsExpr;\n this.isLoop = !!conf.isLoop;\n this.isAssign = !!conf.isAssign;\n this.prefix = !!conf.prefix;\n this.postfix = !!conf.postfix;\n this.binop = conf.binop || null;\n this.updateContext = null;\n};\n\nfunction binop(name, prec) {\n return new TokenType(name, {beforeExpr: true, binop: prec})\n}\nvar beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};\n\n// Map keyword names to token types.\n\nvar keywords = {};\n\n// Succinct definitions of keyword token types\nfunction kw(name, options) {\n if ( options === void 0 ) options = {};\n\n options.keyword = name;\n return keywords[name] = new TokenType(name, options)\n}\n\nvar types$1 = {\n num: new TokenType(\"num\", startsExpr),\n regexp: new TokenType(\"regexp\", startsExpr),\n string: new TokenType(\"string\", startsExpr),\n name: new TokenType(\"name\", startsExpr),\n privateId: new TokenType(\"privateId\", startsExpr),\n eof: new TokenType(\"eof\"),\n\n // Punctuation token types.\n bracketL: new TokenType(\"[\", {beforeExpr: true, startsExpr: true}),\n bracketR: new TokenType(\"]\"),\n braceL: new TokenType(\"{\", {beforeExpr: true, startsExpr: true}),\n braceR: new TokenType(\"}\"),\n parenL: new TokenType(\"(\", {beforeExpr: true, startsExpr: true}),\n parenR: new TokenType(\")\"),\n comma: new TokenType(\",\", beforeExpr),\n semi: new TokenType(\";\", beforeExpr),\n colon: new TokenType(\":\", beforeExpr),\n dot: new TokenType(\".\"),\n question: new TokenType(\"?\", beforeExpr),\n questionDot: new TokenType(\"?.\"),\n arrow: new TokenType(\"=>\", beforeExpr),\n template: new TokenType(\"template\"),\n invalidTemplate: new TokenType(\"invalidTemplate\"),\n ellipsis: new TokenType(\"...\", beforeExpr),\n backQuote: new TokenType(\"`\", startsExpr),\n dollarBraceL: new TokenType(\"${\", {beforeExpr: true, startsExpr: true}),\n\n // Operators. These carry several kinds of properties to help the\n // parser use them properly (the presence of these properties is\n // what categorizes them as operators).\n //\n // `binop`, when present, specifies that this operator is a binary\n // operator, and will refer to its precedence.\n //\n // `prefix` and `postfix` mark the operator as a prefix or postfix\n // unary operator.\n //\n // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as\n // binary operators with a very low precedence, that should result\n // in AssignmentExpression nodes.\n\n eq: new TokenType(\"=\", {beforeExpr: true, isAssign: true}),\n assign: new TokenType(\"_=\", {beforeExpr: true, isAssign: true}),\n incDec: new TokenType(\"++/--\", {prefix: true, postfix: true, startsExpr: true}),\n prefix: new TokenType(\"!/~\", {beforeExpr: true, prefix: true, startsExpr: true}),\n logicalOR: binop(\"||\", 1),\n logicalAND: binop(\"&&\", 2),\n bitwiseOR: binop(\"|\", 3),\n bitwiseXOR: binop(\"^\", 4),\n bitwiseAND: binop(\"&\", 5),\n equality: binop(\"==/!=/===/!==\", 6),\n relational: binop(\"</>/<=/>=\", 7),\n bitShift: binop(\"<</>>/>>>\", 8),\n plusMin: new TokenType(\"+/-\", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),\n modulo: binop(\"%\", 10),\n star: binop(\"*\", 10),\n slash: binop(\"/\", 10),\n starstar: new TokenType(\"**\", {beforeExpr: true}),\n coalesce: binop(\"??\", 1),\n\n // Keyword token types.\n _break: kw(\"break\"),\n _case: kw(\"case\", beforeExpr),\n _catch: kw(\"catch\"),\n _continue: kw(\"continue\"),\n _debugger: kw(\"debugger\"),\n _default: kw(\"default\", beforeExpr),\n _do: kw(\"do\", {isLoop: true, beforeExpr: true}),\n _else: kw(\"else\", beforeExpr),\n _finally: kw(\"finally\"),\n _for: kw(\"for\", {isLoop: true}),\n _function: kw(\"function\", startsExpr),\n _if: kw(\"if\"),\n _return: kw(\"return\", beforeExpr),\n _switch: kw(\"switch\"),\n _throw: kw(\"throw\", beforeExpr),\n _try: kw(\"try\"),\n _var: kw(\"var\"),\n _const: kw(\"const\"),\n _while: kw(\"while\", {isLoop: true}),\n _with: kw(\"with\"),\n _new: kw(\"new\", {beforeExpr: true, startsExpr: true}),\n _this: kw(\"this\", startsExpr),\n _super: kw(\"super\", startsExpr),\n _class: kw(\"class\", startsExpr),\n _extends: kw(\"extends\", beforeExpr),\n _export: kw(\"export\"),\n _import: kw(\"import\", startsExpr),\n _null: kw(\"null\", startsExpr),\n _true: kw(\"true\", startsExpr),\n _false: kw(\"false\", startsExpr),\n _in: kw(\"in\", {beforeExpr: true, binop: 7}),\n _instanceof: kw(\"instanceof\", {beforeExpr: true, binop: 7}),\n _typeof: kw(\"typeof\", {beforeExpr: true, prefix: true, startsExpr: true}),\n _void: kw(\"void\", {beforeExpr: true, prefix: true, startsExpr: true}),\n _delete: kw(\"delete\", {beforeExpr: true, prefix: true, startsExpr: true})\n};\n\n// Matches a whole line break (where CRLF is considered a single\n// line break). Used to count lines.\n\nvar lineBreak = /\\r\\n?|\\n|\\u2028|\\u2029/;\nvar lineBreakG = new RegExp(lineBreak.source, \"g\");\n\nfunction isNewLine(code) {\n return code === 10 || code === 13 || code === 0x2028 || code === 0x2029\n}\n\nfunction nextLineBreak(code, from, end) {\n if ( end === void 0 ) end = code.length;\n\n for (var i = from; i < end; i++) {\n var next = code.charCodeAt(i);\n if (isNewLine(next))\n { return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 }\n }\n return -1\n}\n\nvar nonASCIIwhitespace = /[\\u1680\\u2000-\\u200a\\u202f\\u205f\\u3000\\ufeff]/;\n\nvar skipWhiteSpace = /(?:\\s|\\/\\/.*|\\/\\*[^]*?\\*\\/)*/g;\n\nvar ref = Object.prototype;\nvar hasOwnProperty = ref.hasOwnProperty;\nvar toString = ref.toString;\n\nvar hasOwn = Object.hasOwn || (function (obj, propName) { return (\n hasOwnProperty.call(obj, propName)\n); });\n\nvar isArray = Array.isArray || (function (obj) { return (\n toString.call(obj) === \"[object Array]\"\n); });\n\nvar regexpCache = Object.create(null);\n\nfunction wordsRegexp(words) {\n return regexpCache[words] || (regexpCache[words] = new RegExp(\"^(?:\" + words.replace(/ /g, \"|\") + \")$\"))\n}\n\nfunction codePointToString(code) {\n // UTF-16 Decoding\n if (code <= 0xFFFF) { return String.fromCharCode(code) }\n code -= 0x10000;\n return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)\n}\n\nvar loneSurrogate = /(?:[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF])/;\n\n// These are used when `options.locations` is on, for the\n// `startLoc` and `endLoc` properties.\n\nvar Position = function Position(line, col) {\n this.line = line;\n this.column = col;\n};\n\nPosition.prototype.offset = function offset (n) {\n return new Position(this.line, this.column + n)\n};\n\nvar SourceLocation = function SourceLocation(p, start, end) {\n this.start = start;\n this.end = end;\n if (p.sourceFile !== null) { this.source = p.sourceFile; }\n};\n\n// The `getLineInfo` function is mostly useful when the\n// `locations` option is off (for performance reasons) and you\n// want to find the line/column position for a given character\n// offset. `input` should be the code string that the offset refers\n// into.\n\nfunction getLineInfo(input, offset) {\n for (var line = 1, cur = 0;;) {\n var nextBreak = nextLineBreak(input, cur, offset);\n if (nextBreak < 0) { return new Position(line, offset - cur) }\n ++line;\n cur = nextBreak;\n }\n}\n\n// A second argument must be given to configure the parser process.\n// These options are recognized (only `ecmaVersion` is required):\n\nvar defaultOptions = {\n // `ecmaVersion` indicates the ECMAScript version to parse. Must be\n // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10\n // (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `\"latest\"`\n // (the latest version the library supports). This influences\n // support for strict mode, the set of reserved words, and support\n // for new syntax features.\n ecmaVersion: null,\n // `sourceType` indicates the mode the code should be parsed in.\n // Can be either `\"script\"`, `\"module\"` or `\"commonjs\"`. This influences global\n // strict mode and parsing of `import` and `export` declarations.\n sourceType: \"script\",\n // When set to true, enable strict parsing mode even if `sourceType`\n // is `\"script\"`.\n strict: false,\n // `onInsertedSemicolon` can be a callback that will be called when\n // a semicolon is automatically inserted. It will be passed the\n // position of the inserted semicolon as an offset, and if\n // `locations` is enabled, it is given the location as a `{line,\n // column}` object as second argument.\n onInsertedSemicolon: null,\n // `onTrailingComma` is similar to `onInsertedSemicolon`, but for\n // trailing commas.\n onTrailingComma: null,\n // By default, reserved words are only enforced if ecmaVersion >= 5.\n // Set `allowReserved` to a boolean value to explicitly turn this on\n // an off. When this option has the value \"never\", reserved words\n // and keywords can also not be used as property names.\n allowReserved: null,\n // When enabled, a return at the top level is not considered an\n // error.\n allowReturnOutsideFunction: false,\n // When enabled, import/export statements are not constrained to\n // appearing at the top of the program, and an import.meta expression\n // in a script isn't considered an error.\n allowImportExportEverywhere: false,\n // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.\n // When enabled, await identifiers are allowed to appear at the top-level scope,\n // but they are still not allowed in non-async functions.\n allowAwaitOutsideFunction: null,\n // When enabled, super identifiers are not constrained to\n // appearing in methods and do not raise an error when they appear elsewhere.\n allowSuperOutsideMethod: null,\n // When enabled, hashbang directive in the beginning of file is\n // allowed and treated as a line comment. Enabled by default when\n // `ecmaVersion` >= 2023.\n allowHashBang: false,\n // By default, the parser will verify that private properties are\n // only used in places where they are valid and have been declared.\n // Set this to false to turn such checks off.\n checkPrivateFields: true,\n // When `locations` is on, `loc` properties holding objects with\n // `start` and `end` properties in `{line, column}` form (with\n // line being 1-based and column 0-based) will be attached to the\n // nodes.\n locations: false,\n // Pass an optional `{line, column}` object to use for the start of\n // the parse. This is mostly useful when using `parseExpressionAt`\n // with `locations: true`, to prevent the parser from having to\n // determine the line position at the start position.\n startLocation: null,\n // A function can be passed as `onToken` option, which will\n // cause Acorn to call that function with object in the same\n // format as tokens returned from `tokenizer().getToken()`. Note\n // that you are not allowed to call the parser from the\n // callback\u2014that will corrupt its internal state.\n onToken: null,\n // A function can be passed as `onComment` option, which will\n // cause Acorn to call that function with `(block, text, start,\n // end)` parameters whenever a comment is skipped. `block` is a\n // boolean indicating whether this is a block (`/* */`) comment,\n // `text` is the content of the comment, and `start` and `end` are\n // character offsets that denote the start and end of the comment.\n // When the `locations` option is on, two more parameters are\n // passed, the full `{line, column}` locations of the start and\n // end of the comments. Note that you are not allowed to call the\n // parser from the callback\u2014that will corrupt its internal state.\n // When this option has an array as value, objects representing the\n // comments are pushed to it.\n onComment: null,\n // Nodes have their start and end characters offsets recorded in\n // `start` and `end` properties (directly on the node, rather than\n // the `loc` object, which holds line/column data. To also add a\n // [semi-standardized][range] `range` property holding a `[start,\n // end]` array with the same numbers, set the `ranges` option to\n // `true`.\n //\n // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678\n ranges: false,\n // It is possible to parse multiple files into a single AST by\n // passing the tree produced by parsing the first file as\n // `program` option in subsequent parses. This will add the\n // toplevel forms of the parsed file to the `Program` (top) node\n // of an existing parse tree.\n program: null,\n // When `locations` is on, you can pass this to record the source\n // file in every node's `loc` object.\n sourceFile: null,\n // This value, if given, is stored in every node, whether\n // `locations` is on or off.\n directSourceFile: null,\n // When enabled, parenthesized expressions are represented by\n // (non-standard) ParenthesizedExpression nodes\n preserveParens: false\n};\n\n// Interpret and default an options object\n\nvar warnedAboutEcmaVersion = false;\n\nfunction getOptions(opts) {\n var options = {};\n\n for (var opt in defaultOptions)\n { options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]; }\n\n if (options.ecmaVersion === \"latest\") {\n options.ecmaVersion = 1e8;\n } else if (options.ecmaVersion == null) {\n if (!warnedAboutEcmaVersion && typeof console === \"object\" && console.warn) {\n warnedAboutEcmaVersion = true;\n console.warn(\"Since Acorn 8.0.0, options.ecmaVersion is required.\\nDefaulting to 2020, but this will stop working in the future.\");\n }\n options.ecmaVersion = 11;\n } else if (options.ecmaVersion >= 2015) {\n options.ecmaVersion -= 2009;\n }\n\n if (options.allowReserved == null)\n { options.allowReserved = options.ecmaVersion < 5; }\n\n if (!opts || opts.allowHashBang == null)\n { options.allowHashBang = options.ecmaVersion >= 14; }\n\n if (isArray(options.onToken)) {\n var tokens = options.onToken;\n options.onToken = function (token) { return tokens.push(token); };\n }\n if (isArray(options.onComment))\n { options.onComment = pushComment(options, options.onComment); }\n\n if (options.sourceType === \"commonjs\" && options.allowAwaitOutsideFunction)\n { throw new Error(\"Cannot use allowAwaitOutsideFunction with sourceType: commonjs\") }\n\n return options\n}\n\nfunction pushComment(options, array) {\n return function(block, text, start, end, startLoc, endLoc) {\n var comment = {\n type: block ? \"Block\" : \"Line\",\n value: text,\n start: start,\n end: end\n };\n if (options.locations)\n { comment.loc = new SourceLocation(this, startLoc, endLoc); }\n if (options.ranges)\n { comment.range = [start, end]; }\n array.push(comment);\n }\n}\n\n// Each scope gets a bitset that may contain these flags\nvar\n SCOPE_TOP = 1,\n SCOPE_FUNCTION = 2,\n SCOPE_ASYNC = 4,\n SCOPE_GENERATOR = 8,\n SCOPE_ARROW = 16,\n SCOPE_SIMPLE_CATCH = 32,\n SCOPE_SUPER = 64,\n SCOPE_DIRECT_SUPER = 128,\n SCOPE_CLASS_STATIC_BLOCK = 256,\n SCOPE_CLASS_FIELD_INIT = 512,\n SCOPE_SWITCH = 1024,\n SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK;\n\nfunction functionFlags(async, generator) {\n return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)\n}\n\n// Used in checkLVal* and declareName to determine the type of a binding\nvar\n BIND_NONE = 0, // Not a binding\n BIND_VAR = 1, // Var-style binding\n BIND_LEXICAL = 2, // Let- or const-style binding\n BIND_FUNCTION = 3, // Function declaration\n BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding\n BIND_OUTSIDE = 5; // Special case for function names as bound inside the function\n\nvar Parser = function Parser(options, input, startPos) {\n this.options = options = getOptions(options);\n this.sourceFile = options.sourceFile;\n this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === \"module\" ? \"5module\" : 5]);\n var reserved = \"\";\n if (options.allowReserved !== true) {\n reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];\n if (options.sourceType === \"module\") { reserved += \" await\"; }\n }\n this.reservedWords = wordsRegexp(reserved);\n var reservedStrict = (reserved ? reserved + \" \" : \"\") + reservedWords.strict;\n this.reservedWordsStrict = wordsRegexp(reservedStrict);\n this.reservedWordsStrictBind = wordsRegexp(reservedStrict + \" \" + reservedWords.strictBind);\n this.input = String(input);\n\n // Used to signal to callers of `readWord1` whether the word\n // contained any escape sequences. This is needed because words with\n // escape sequences must not be interpreted as keywords.\n this.containsEsc = false;\n\n // Set up token state\n\n // The current position of the tokenizer in the input.\n this.pos = startPos || 0;\n this.curLine = 1;\n if (options.startLocation) {\n this.lineStart = this.pos - options.startLocation.column;\n this.curLine = options.startLocation.line;\n } else if (startPos) {\n this.lineStart = this.input.lastIndexOf(\"\\n\", startPos - 1) + 1;\n if (this.options.locations)\n { this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length; }\n } else {\n this.lineStart = 0;\n }\n\n // Properties of the current token:\n // Its type\n this.type = types$1.eof;\n // For tokens that include more information than their type, the value\n this.value = null;\n // Its start and end offset\n this.start = this.end = this.pos;\n // And, if locations are used, the {line, column} object\n // corresponding to those offsets\n this.startLoc = this.endLoc = this.curPosition();\n\n // Position information for the previous token\n this.lastTokEndLoc = this.lastTokStartLoc = null;\n this.lastTokStart = this.lastTokEnd = this.pos;\n\n // The context stack is used to superficially track syntactic\n // context to predict whether a regular expression is allowed in a\n // given position.\n this.context = this.initialContext();\n this.exprAllowed = true;\n\n // Figure out if it's a module code.\n this.inModule = options.sourceType === \"module\";\n this.strict = this.inModule || options.strict === true || this.strictDirective(this.pos);\n\n // Used to signify the start of a potential arrow function\n this.potentialArrowAt = -1;\n this.potentialArrowInForAwait = false;\n\n // Positions to delayed-check that yield/await does not exist in default parameters.\n this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;\n // Labels in scope.\n this.labels = [];\n // Thus-far undefined exports.\n this.undefinedExports = Object.create(null);\n\n // If enabled, skip leading hashbang line.\n if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === \"#!\")\n { this.skipLineComment(2); }\n\n // Scope tracking for duplicate variable names (see scope.js)\n this.scopeStack = [];\n this.enterScope(\n this.options.sourceType === \"commonjs\"\n // In commonjs, the top-level scope behaves like a function scope\n ? SCOPE_FUNCTION\n : SCOPE_TOP\n );\n\n // For RegExp validation\n this.regexpState = null;\n\n // The stack of private names.\n // Each element has two properties: 'declared' and 'used'.\n // When it exited from the outermost class definition, all used private names must be declared.\n this.privateNameStack = [];\n};\n\nvar prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },canAwait: { configurable: true },allowReturn: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },allowNewDotTarget: { configurable: true },allowUsing: { configurable: true },inClassStaticBlock: { configurable: true } };\n\nParser.prototype.parse = function parse () {\n var this$1$1 = this;\n\n var node = this.options.program || this.startNode();\n this.nextToken();\n return this.catchStackOverflow(function () { return this$1$1.parseTopLevel(node); })\n};\n\nprototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };\n\nprototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 };\n\nprototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 };\n\nprototypeAccessors.canAwait.get = function () {\n for (var i = this.scopeStack.length - 1; i >= 0; i--) {\n var ref = this.scopeStack[i];\n var flags = ref.flags;\n if (flags & (SCOPE_CLASS_STATIC_BLOCK | SCOPE_CLASS_FIELD_INIT)) { return false }\n if (flags & SCOPE_FUNCTION) { return (flags & SCOPE_ASYNC) > 0 }\n }\n return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction\n};\n\nprototypeAccessors.allowReturn.get = function () {\n if (this.inFunction) { return true }\n if (this.options.allowReturnOutsideFunction && this.currentVarScope().flags & SCOPE_TOP) { return true }\n return false\n};\n\nprototypeAccessors.allowSuper.get = function () {\n var ref = this.currentThisScope();\n var flags = ref.flags;\n return (flags & SCOPE_SUPER) > 0 || this.options.allowSuperOutsideMethod\n};\n\nprototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };\n\nprototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };\n\nprototypeAccessors.allowNewDotTarget.get = function () {\n for (var i = this.scopeStack.length - 1; i >= 0; i--) {\n var ref = this.scopeStack[i];\n var flags = ref.flags;\n if (flags & (SCOPE_CLASS_STATIC_BLOCK | SCOPE_CLASS_FIELD_INIT) ||\n ((flags & SCOPE_FUNCTION) && !(flags & SCOPE_ARROW))) { return true }\n }\n return false\n};\n\nprototypeAccessors.allowUsing.get = function () {\n var ref = this.currentScope();\n var flags = ref.flags;\n if (flags & SCOPE_SWITCH) { return false }\n if (!this.inModule && flags & SCOPE_TOP) { return false }\n return true\n};\n\nprototypeAccessors.inClassStaticBlock.get = function () {\n return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0\n};\n\nParser.extend = function extend () {\n var plugins = [], len = arguments.length;\n while ( len-- ) plugins[ len ] = arguments[ len ];\n\n var cls = this;\n for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }\n return cls\n};\n\nParser.parse = function parse (input, options) {\n return new this(options, input).parse()\n};\n\nParser.parseExpressionAt = function parseExpressionAt (input, pos, options) {\n var parser = new this(options, input, pos);\n parser.nextToken();\n return parser.parseExpression()\n};\n\nParser.tokenizer = function tokenizer (input, options) {\n return new this(options, input)\n};\n\nObject.defineProperties( Parser.prototype, prototypeAccessors );\n\nvar pp$9 = Parser.prototype;\n\n// ## Parser utilities\n\nvar literal = /^(?:'((?:\\\\[^]|[^'\\\\])*?)'|\"((?:\\\\[^]|[^\"\\\\])*?)\")/;\npp$9.strictDirective = function(start) {\n if (this.options.ecmaVersion < 5) { return false }\n for (;;) {\n // Try to find string literal.\n skipWhiteSpace.lastIndex = start;\n start += skipWhiteSpace.exec(this.input)[0].length;\n var match = literal.exec(this.input.slice(start));\n if (!match) { return false }\n if ((match[1] || match[2]) === \"use strict\") {\n skipWhiteSpace.lastIndex = start + match[0].length;\n var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;\n var next = this.input.charAt(end);\n return next === \";\" || next === \"}\" ||\n (lineBreak.test(spaceAfter[0]) &&\n !(/[(`.[+\\-/*%<>=,?^&]/.test(next) || next === \"!\" && this.input.charAt(end + 1) === \"=\"))\n }\n start += match[0].length;\n\n // Skip semicolon, if any.\n skipWhiteSpace.lastIndex = start;\n start += skipWhiteSpace.exec(this.input)[0].length;\n if (this.input[start] === \";\")\n { start++; }\n }\n};\n\n// Predicate that tests whether the next token is of the given\n// type, and if yes, consumes it as a side effect.\n\npp$9.eat = function(type) {\n if (this.type === type) {\n this.next();\n return true\n } else {\n return false\n }\n};\n\n// Tests whether parsed token is a contextual keyword.\n\npp$9.isContextual = function(name) {\n return this.type === types$1.name && this.value === name && !this.containsEsc\n};\n\n// Consumes contextual keyword if possible.\n\npp$9.eatContextual = function(name) {\n if (!this.isContextual(name)) { return false }\n this.next();\n return true\n};\n\npp$9.catchStackOverflow = function(f) {\n try {\n return f()\n } catch (e) {\n if (e instanceof Error && (/\\bstack\\b.*\\b(exceeded|overflow)\\b/i.test(e.message) || /\\btoo much recursion\\b/i.test(e.message)))\n { this.raise(this.start, \"Not enough stack space to parse input\"); }\n else\n { throw e }\n }\n};\n\n// Asserts that following token is given contextual keyword.\n\npp$9.expectContextual = function(name) {\n if (!this.eatContextual(name)) { this.unexpected(); }\n};\n\n// Test whether a semicolon can be inserted at the current position.\n\npp$9.canInsertSemicolon = function() {\n return this.type === types$1.eof ||\n this.type === types$1.braceR ||\n lineBreak.test(this.input.slice(this.lastTokEnd, this.start))\n};\n\npp$9.insertSemicolon = function() {\n if (this.canInsertSemicolon()) {\n if (this.options.onInsertedSemicolon)\n { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }\n return true\n }\n};\n\n// Consume a semicolon, or, failing that, see if we are allowed to\n// pretend that there is a semicolon at this position.\n\npp$9.semicolon = function() {\n if (!this.eat(types$1.semi) && !this.insertSemicolon()) { this.unexpected(); }\n};\n\npp$9.afterTrailingComma = function(tokType, notNext) {\n if (this.type === tokType) {\n if (this.options.onTrailingComma)\n { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }\n if (!notNext)\n { this.next(); }\n return true\n }\n};\n\n// Expect a token of a given type. If found, consume it, otherwise,\n// raise an unexpected token error.\n\npp$9.expect = function(type) {\n this.eat(type) || this.unexpected();\n};\n\n// Raise an unexpected token error.\n\npp$9.unexpected = function(pos) {\n this.raise(pos != null ? pos : this.start, \"Unexpected token\");\n};\n\nvar DestructuringErrors = function DestructuringErrors() {\n this.shorthandAssign =\n this.trailingComma =\n this.parenthesizedAssign =\n this.parenthesizedBind =\n this.doubleProto =\n -1;\n};\n\npp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) {\n if (!refDestructuringErrors) { return }\n if (refDestructuringErrors.trailingComma > -1)\n { this.raiseRecoverable(refDestructuringErrors.trailingComma, \"Comma is not permitted after the rest element\"); }\n var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;\n if (parens > -1) { this.raiseRecoverable(parens, isAssign ? \"Assigning to rvalue\" : \"Parenthesized pattern\"); }\n};\n\npp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) {\n if (!refDestructuringErrors) { return false }\n var shorthandAssign = refDestructuringErrors.shorthandAssign;\n var doubleProto = refDestructuringErrors.doubleProto;\n if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }\n if (shorthandAssign >= 0)\n { this.raise(shorthandAssign, \"Shorthand property assignments are valid only in destructuring patterns\"); }\n if (doubleProto >= 0)\n { this.raiseRecoverable(doubleProto, \"Redefinition of __proto__ property\"); }\n};\n\npp$9.checkYieldAwaitInDefaultParams = function() {\n if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))\n { this.raise(this.yieldPos, \"Yield expression cannot be a default value\"); }\n if (this.awaitPos)\n { this.raise(this.awaitPos, \"Await expression cannot be a default value\"); }\n};\n\npp$9.isSimpleAssignTarget = function(expr) {\n if (expr.type === \"ParenthesizedExpression\")\n { return this.isSimpleAssignTarget(expr.expression) }\n return expr.type === \"Identifier\" || expr.type === \"MemberExpression\"\n};\n\nvar pp$8 = Parser.prototype;\n\n// ### Statement parsing\n\n// Parse a program. Initializes the parser, reads any number of\n// statements, and wraps them in a Program node. Optionally takes a\n// `program` argument. If present, the statements will be appended\n// to its body instead of creating a new node.\n\npp$8.parseTopLevel = function(node) {\n var exports$1 = Object.create(null);\n if (!node.body) { node.body = []; }\n while (this.type !== types$1.eof) {\n var stmt = this.parseStatement(null, true, exports$1);\n node.body.push(stmt);\n }\n if (this.inModule)\n { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)\n {\n var name = list[i];\n\n this.raiseRecoverable(this.undefinedExports[name].start, (\"Export '\" + name + \"' is not defined\"));\n } }\n this.adaptDirectivePrologue(node.body);\n this.next();\n node.sourceType = this.options.sourceType === \"commonjs\" ? \"script\" : this.options.sourceType;\n return this.finishNode(node, \"Program\")\n};\n\nvar loopLabel = {kind: \"loop\"}, switchLabel = {kind: \"switch\"};\n\npp$8.isLet = function(context) {\n if (this.options.ecmaVersion < 6 || !this.isContextual(\"let\")) { return false }\n skipWhiteSpace.lastIndex = this.pos;\n var skip = skipWhiteSpace.exec(this.input);\n var next = this.pos + skip[0].length, nextCh = this.fullCharCodeAt(next);\n // For ambiguous cases, determine if a LexicalDeclaration (or only a\n // Statement) is allowed here. If context is not empty then only a Statement\n // is allowed. However, `let [` is an explicit negative lookahead for\n // ExpressionStatement, so special-case it first.\n if (nextCh === 91 || nextCh === 92) { return true } // '[', '\\'\n if (context) { return false }\n\n if (nextCh === 123) { return true } // '{'\n if (isIdentifierStart(nextCh)) {\n var start = next;\n do { next += nextCh <= 0xffff ? 1 : 2; }\n while (isIdentifierChar(nextCh = this.fullCharCodeAt(next)))\n if (nextCh === 92) { return true }\n var ident = this.input.slice(start, next);\n if (!keywordRelationalOperator.test(ident)) { return true }\n }\n return false\n};\n\n// check 'async [no LineTerminator here] function'\n// - 'async /*foo*/ function' is OK.\n// - 'async /*\\n*/ function' is invalid.\npp$8.isAsyncFunction = function() {\n if (this.options.ecmaVersion < 8 || !this.isContextual(\"async\"))\n { return false }\n\n skipWhiteSpace.lastIndex = this.pos;\n var skip = skipWhiteSpace.exec(this.input);\n var next = this.pos + skip[0].length, after;\n return !lineBreak.test(this.input.slice(this.pos, next)) &&\n this.input.slice(next, next + 8) === \"function\" &&\n (next + 8 === this.input.length ||\n !(isIdentifierChar(after = this.fullCharCodeAt(next + 8)) || after === 92 /* '\\' */))\n};\n\npp$8.isUsingKeyword = function(isAwaitUsing, isFor) {\n if (this.options.ecmaVersion < 17 || !this.isContextual(isAwaitUsing ? \"await\" : \"using\"))\n { return false }\n\n skipWhiteSpace.lastIndex = this.pos;\n var skip = skipWhiteSpace.exec(this.input);\n var next = this.pos + skip[0].length;\n\n if (lineBreak.test(this.input.slice(this.pos, next))) { return false }\n\n if (isAwaitUsing) {\n var usingEndPos = next + 5 /* using */, after;\n if (this.input.slice(next, usingEndPos) !== \"using\" ||\n usingEndPos === this.input.length ||\n isIdentifierChar(after = this.fullCharCodeAt(usingEndPos)) ||\n after === 92 /* '\\' */\n ) { return false }\n\n skipWhiteSpace.lastIndex = usingEndPos;\n var skipAfterUsing = skipWhiteSpace.exec(this.input);\n next = usingEndPos + skipAfterUsing[0].length;\n if (skipAfterUsing && lineBreak.test(this.input.slice(usingEndPos, next))) { return false }\n }\n\n var ch = this.fullCharCodeAt(next);\n if (!isIdentifierStart(ch) && ch !== 92 /* '\\' */) { return false }\n var idStart = next;\n do { next += ch <= 0xffff ? 1 : 2; }\n while (isIdentifierChar(ch = this.fullCharCodeAt(next)))\n if (ch === 92) { return true }\n var id = this.input.slice(idStart, next);\n if (keywordRelationalOperator.test(id)) { return false }\n if (isFor && !isAwaitUsing && id === \"of\") {\n // Look ahead for using declaration with initializer, i.e., `for (using of = ...)`\n skipWhiteSpace.lastIndex = next;\n var skipAfterOf = skipWhiteSpace.exec(this.input);\n next = next + skipAfterOf[0].length;\n if (this.input.charCodeAt(next) !== 61 /* '=' */ ||\n // Check for ==, === and => operators\n (ch = this.input.charCodeAt(next + 1)) === 61 /* '=' */ || ch === 62 /* '>' */) {\n return false\n }\n }\n return true\n};\n\npp$8.isAwaitUsing = function(isFor) {\n return this.isUsingKeyword(true, isFor)\n};\n\npp$8.isUsing = function(isFor) {\n return this.isUsingKeyword(false, isFor)\n};\n\n// Parse a single statement.\n//\n// If expecting a statement and finding a slash operator, parse a\n// regular expression literal. This is to handle cases like\n// `if (foo) /blah/.exec(foo)`, where looking at the previous token\n// does not help.\n\npp$8.parseStatement = function(context, topLevel, exports$1) {\n var starttype = this.type, node = this.startNode(), kind;\n\n if (this.isLet(context)) {\n starttype = types$1._var;\n kind = \"let\";\n }\n\n // Most types of statements are recognized by the keyword they\n // start with. Many are trivial to parse, some require a bit of\n // complexity.\n\n switch (starttype) {\n case types$1._break: case types$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword)\n case types$1._debugger: return this.parseDebuggerStatement(node)\n case types$1._do: return this.parseDoStatement(node)\n case types$1._for: return this.parseForStatement(node)\n case types$1._function:\n // Function as sole body of either an if statement or a labeled statement\n // works, but not when it is part of a labeled statement that is the sole\n // body of an if statement.\n if ((context && (this.strict || context !== \"if\" && context !== \"label\")) && this.options.ecmaVersion >= 6) { this.unexpected(); }\n return this.parseFunctionStatement(node, false, !context)\n case types$1._class:\n if (context) { this.unexpected(); }\n return this.parseClass(node, true)\n case types$1._if: return this.parseIfStatement(node)\n case types$1._return: return this.parseReturnStatement(node)\n case types$1._switch: return this.parseSwitchStatement(node)\n case types$1._throw: return this.parseThrowStatement(node)\n case types$1._try: return this.parseTryStatement(node)\n case types$1._const: case types$1._var:\n kind = kind || this.value;\n if (context && kind !== \"var\") { this.unexpected(); }\n return this.parseVarStatement(node, kind)\n case types$1._while: return this.parseWhileStatement(node)\n case types$1._with: return this.parseWithStatement(node)\n case types$1.braceL: return this.parseBlock(true, node)\n case types$1.semi: return this.parseEmptyStatement(node)\n case types$1._export:\n case types$1._import:\n if (this.options.ecmaVersion > 10 && starttype === types$1._import) {\n skipWhiteSpace.lastIndex = this.pos;\n var skip = skipWhiteSpace.exec(this.input);\n var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);\n if (nextCh === 40 || nextCh === 46) // '(' or '.'\n { return this.parseExpressionStatement(node, this.parseExpression()) }\n }\n\n if (!this.options.allowImportExportEverywhere) {\n if (!topLevel)\n { this.raise(this.start, \"'import' and 'export' may only appear at the top level\"); }\n if (!this.inModule)\n { this.raise(this.start, \"'import' and 'export' may appear only with 'sourceType: module'\"); }\n }\n return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports$1)\n\n // If the statement does not start with a statement keyword or a\n // brace, it's an ExpressionStatement or LabeledStatement. We\n // simply start parsing an expression, and afterwards, if the\n // next token is a colon and the expression was a simple\n // Identifier node, we switch to interpreting it as a label.\n default:\n if (this.isAsyncFunction()) {\n if (context) { this.unexpected(); }\n this.next();\n return this.parseFunctionStatement(node, true, !context)\n }\n\n var usingKind = this.isAwaitUsing(false) ? \"await using\" : this.isUsing(false) ? \"using\" : null;\n if (usingKind) {\n if (!this.allowUsing) {\n this.raise(this.start, \"Using declaration cannot appear in the top level when source type is `script` or in the bare case statement\");\n }\n if (context) {\n // Cases like `for (;;) using x = ...;`, `if (true) await using x = ...;`, etc. are not allowed.\n this.raise(this.start, \"Using declaration is not allowed in single-statement positions\");\n }\n if (usingKind === \"await using\") {\n if (!this.canAwait) {\n this.raise(this.start, \"Await using cannot appear outside of async function\");\n }\n this.next();\n }\n this.next();\n this.parseVar(node, false, usingKind);\n this.semicolon();\n return this.finishNode(node, \"VariableDeclaration\")\n }\n\n var maybeName = this.value, expr = this.parseExpression();\n if (starttype === types$1.name && expr.type === \"Identifier\" && this.eat(types$1.colon))\n { return this.parseLabeledStatement(node, maybeName, expr, context) }\n else { return this.parseExpressionStatement(node, expr) }\n }\n};\n\npp$8.parseBreakContinueStatement = function(node, keyword) {\n var isBreak = keyword === \"break\";\n this.next();\n if (this.eat(types$1.semi) || this.insertSemicolon()) { node.label = null; }\n else if (this.type !== types$1.name) { this.unexpected(); }\n else {\n node.label = this.parseIdent();\n this.semicolon();\n }\n\n // Verify that there is an actual destination to break or\n // continue to.\n var i = 0;\n for (; i < this.labels.length; ++i) {\n var lab = this.labels[i];\n if (node.label == null || lab.name === node.label.name) {\n if (lab.kind != null && (isBreak || lab.kind === \"loop\")) { break }\n if (node.label && isBreak) { break }\n }\n }\n if (i === this.labels.length) { this.raise(node.start, \"Unsyntactic \" + keyword); }\n return this.finishNode(node, isBreak ? \"BreakStatement\" : \"ContinueStatement\")\n};\n\npp$8.parseDebuggerStatement = function(node) {\n this.next();\n this.semicolon();\n return this.finishNode(node, \"DebuggerStatement\")\n};\n\npp$8.parseDoStatement = function(node) {\n this.next();\n this.labels.push(loopLabel);\n node.body = this.parseStatement(\"do\");\n this.labels.pop();\n this.expect(types$1._while);\n node.test = this.parseParenExpression();\n if (this.options.ecmaVersion >= 6)\n { this.eat(types$1.semi); }\n else\n { this.semicolon(); }\n return this.finishNode(node, \"DoWhileStatement\")\n};\n\n// Disambiguating between a `for` and a `for`/`in` or `for`/`of`\n// loop is non-trivial. Basically, we have to parse the init `var`\n// statement or expression, disallowing the `in` operator (see\n// the second parameter to `parseExpression`), and then check\n// whether the next token is `in` or `of`. When there is no init\n// part (semicolon immediately after the opening parenthesis), it\n// is a regular `for` loop.\n\npp$8.parseForStatement = function(node) {\n this.next();\n var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual(\"await\")) ? this.lastTokStart : -1;\n this.labels.push(loopLabel);\n this.enterScope(0);\n this.expect(types$1.parenL);\n if (this.type === types$1.semi) {\n if (awaitAt > -1) { this.unexpected(awaitAt); }\n return this.parseFor(node, null)\n }\n var isLet = this.isLet();\n if (this.type === types$1._var || this.type === types$1._const || isLet) {\n var init$1 = this.startNode(), kind = isLet ? \"let\" : this.value;\n this.next();\n this.parseVar(init$1, true, kind);\n this.finishNode(init$1, \"VariableDeclaration\");\n return this.parseForAfterInit(node, init$1, awaitAt)\n }\n var startsWithLet = this.isContextual(\"let\"), isForOf = false;\n\n var usingKind = this.isUsing(true) ? \"using\" : this.isAwaitUsing(true) ? \"await using\" : null;\n if (usingKind) {\n var init$2 = this.startNode();\n this.next();\n if (usingKind === \"await using\") {\n if (!this.canAwait) {\n this.raise(this.start, \"Await using cannot appear outside of async function\");\n }\n this.next();\n }\n this.parseVar(init$2, true, usingKind);\n this.finishNode(init$2, \"VariableDeclaration\");\n return this.parseForAfterInit(node, init$2, awaitAt)\n }\n var containsEsc = this.containsEsc;\n var refDestructuringErrors = new DestructuringErrors;\n var initPos = this.start;\n var init = awaitAt > -1\n ? this.parseExprSubscripts(refDestructuringErrors, \"await\")\n : this.parseExpression(true, refDestructuringErrors);\n if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual(\"of\"))) {\n if (awaitAt > -1) { // implies `ecmaVersion >= 9` (see declaration of awaitAt)\n if (this.type === types$1._in) { this.unexpected(awaitAt); }\n node.await = true;\n } else if (isForOf && this.options.ecmaVersion >= 8) {\n if (init.start === initPos && !containsEsc && init.type === \"Identifier\" && init.name === \"async\") { this.unexpected(); }\n else if (this.options.ecmaVersion >= 9) { node.await = false; }\n }\n if (startsWithLet && isForOf) { this.raise(init.start, \"The left-hand side of a for-of loop may not start with 'let'.\"); }\n this.toAssignable(init, false, refDestructuringErrors);\n this.checkLValPattern(init);\n return this.parseForIn(node, init)\n } else {\n this.checkExpressionErrors(refDestructuringErrors, true);\n }\n if (awaitAt > -1) { this.unexpected(awaitAt); }\n return this.parseFor(node, init)\n};\n\n// Helper method to parse for loop after variable initialization\npp$8.parseForAfterInit = function(node, init, awaitAt) {\n if ((this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual(\"of\"))) && init.declarations.length === 1) {\n if (this.type === types$1._in) {\n if ((init.kind === \"using\" || init.kind === \"await using\") && !init.declarations[0].init) {\n this.raise(this.start, \"Using declaration is not allowed in for-in loops\");\n }\n if (this.options.ecmaVersion >= 9 && awaitAt > -1) { this.unexpected(awaitAt); }\n } else if (this.options.ecmaVersion >= 9) { node.await = awaitAt > -1; }\n return this.parseForIn(node, init)\n }\n if (awaitAt > -1) { this.unexpected(awaitAt); }\n return this.parseFor(node, init)\n};\n\npp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) {\n this.next();\n return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)\n};\n\npp$8.parseIfStatement = function(node) {\n this.next();\n node.test = this.parseParenExpression();\n // allow function declarations in branches, but only in non-strict mode\n node.consequent = this.parseStatement(\"if\");\n node.alternate = this.eat(types$1._else) ? this.parseStatement(\"if\") : null;\n return this.finishNode(node, \"IfStatement\")\n};\n\npp$8.parseReturnStatement = function(node) {\n if (!this.allowReturn)\n { this.raise(this.start, \"'return' outside of function\"); }\n this.next();\n\n // In `return` (and `break`/`continue`), the keywords with\n // optional arguments, we eagerly look for a semicolon or the\n // possibility to insert one.\n\n if (this.eat(types$1.semi) || this.insertSemicolon()) { node.argument = null; }\n else { node.argument = this.parseExpression(); this.semicolon(); }\n return this.finishNode(node, \"ReturnStatement\")\n};\n\npp$8.parseSwitchStatement = function(node) {\n this.next();\n node.discriminant = this.parseParenExpression();\n node.cases = [];\n this.expect(types$1.braceL);\n this.labels.push(switchLabel);\n this.enterScope(SCOPE_SWITCH);\n\n // Statements under must be grouped (by label) in SwitchCase\n // nodes. `cur` is used to keep the node that we are currently\n // adding statements to.\n\n var cur;\n for (var sawDefault = false; this.type !== types$1.braceR;) {\n if (this.type === types$1._case || this.type === types$1._default) {\n var isCase = this.type === types$1._case;\n if (cur) { this.finishNode(cur, \"SwitchCase\"); }\n node.cases.push(cur = this.startNode());\n cur.consequent = [];\n this.next();\n if (isCase) {\n cur.test = this.parseExpression();\n } else {\n if (sawDefault) { this.raiseRecoverable(this.lastTokStart, \"Multiple default clauses\"); }\n sawDefault = true;\n cur.test = null;\n }\n this.expect(types$1.colon);\n } else {\n if (!cur) { this.unexpected(); }\n cur.consequent.push(this.parseStatement(null));\n }\n }\n this.exitScope();\n if (cur) { this.finishNode(cur, \"SwitchCase\"); }\n this.next(); // Closing brace\n this.labels.pop();\n return this.finishNode(node, \"SwitchStatement\")\n};\n\npp$8.parseThrowStatement = function(node) {\n this.next();\n if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))\n { this.raise(this.lastTokEnd, \"Illegal newline after throw\"); }\n node.argument = this.parseExpression();\n this.semicolon();\n return this.finishNode(node, \"ThrowStatement\")\n};\n\n// Reused empty array added for node fields that are always empty.\n\nvar empty$1 = [];\n\npp$8.parseCatchClauseParam = function() {\n var param = this.parseBindingAtom();\n var simple = param.type === \"Identifier\";\n this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);\n this.checkLValPattern(param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);\n this.expect(types$1.parenR);\n\n return param\n};\n\npp$8.parseTryStatement = function(node) {\n this.next();\n node.block = this.parseBlock();\n node.handler = null;\n if (this.type === types$1._catch) {\n var clause = this.startNode();\n this.next();\n if (this.eat(types$1.parenL)) {\n clause.param = this.parseCatchClauseParam();\n } else {\n if (this.options.ecmaVersion < 10) { this.unexpected(); }\n clause.param = null;\n this.enterScope(0);\n }\n clause.body = this.parseBlock(false);\n this.exitScope();\n node.handler = this.finishNode(clause, \"CatchClause\");\n }\n node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null;\n if (!node.handler && !node.finalizer)\n { this.raise(node.start, \"Missing catch or finally clause\"); }\n return this.finishNode(node, \"TryStatement\")\n};\n\npp$8.parseVarStatement = function(node, kind, allowMissingInitializer) {\n this.next();\n this.parseVar(node, false, kind, allowMissingInitializer);\n this.semicolon();\n return this.finishNode(node, \"VariableDeclaration\")\n};\n\npp$8.parseWhileStatement = function(node) {\n this.next();\n node.test = this.parseParenExpression();\n this.labels.push(loopLabel);\n node.body = this.parseStatement(\"while\");\n this.labels.pop();\n return this.finishNode(node, \"WhileStatement\")\n};\n\npp$8.parseWithStatement = function(node) {\n if (this.strict) { this.raise(this.start, \"'with' in strict mode\"); }\n this.next();\n node.object = this.parseParenExpression();\n node.body = this.parseStatement(\"with\");\n return this.finishNode(node, \"WithStatement\")\n};\n\npp$8.parseEmptyStatement = function(node) {\n this.next();\n return this.finishNode(node, \"EmptyStatement\")\n};\n\npp$8.parseLabeledStatement = function(node, maybeName, expr, context) {\n for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)\n {\n var label = list[i$1];\n\n if (label.name === maybeName)\n { this.raise(expr.start, \"Label '\" + maybeName + \"' is already declared\");\n } }\n var kind = this.type.isLoop ? \"loop\" : this.type === types$1._switch ? \"switch\" : null;\n for (var i = this.labels.length - 1; i >= 0; i--) {\n var label$1 = this.labels[i];\n if (label$1.statementStart === node.start) {\n // Update information about previous labels on this node\n label$1.statementStart = this.start;\n label$1.kind = kind;\n } else { break }\n }\n this.labels.push({name: maybeName, kind: kind, statementStart: this.start});\n node.body = this.parseStatement(context ? context.indexOf(\"label\") === -1 ? context + \"label\" : context : \"label\");\n this.labels.pop();\n node.label = expr;\n return this.finishNode(node, \"LabeledStatement\")\n};\n\npp$8.parseExpressionStatement = function(node, expr) {\n node.expression = expr;\n this.semicolon();\n return this.finishNode(node, \"ExpressionStatement\")\n};\n\n// Parse a semicolon-enclosed block of statements, handling `\"use\n// strict\"` declarations when `allowStrict` is true (used for\n// function bodies).\n\npp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) {\n if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;\n if ( node === void 0 ) node = this.startNode();\n\n node.body = [];\n this.expect(types$1.braceL);\n if (createNewLexicalScope) { this.enterScope(0); }\n while (this.type !== types$1.braceR) {\n var stmt = this.parseStatement(null);\n node.body.push(stmt);\n }\n if (exitStrict) { this.strict = false; }\n this.next();\n if (createNewLexicalScope) { this.exitScope(); }\n return this.finishNode(node, \"BlockStatement\")\n};\n\n// Parse a regular `for` loop. The disambiguation code in\n// `parseStatement` will already have parsed the init statement or\n// expression.\n\npp$8.parseFor = function(node, init) {\n node.init = init;\n this.expect(types$1.semi);\n node.test = this.type === types$1.semi ? null : this.parseExpression();\n this.expect(types$1.semi);\n node.update = this.type === types$1.parenR ? null : this.parseExpression();\n this.expect(types$1.parenR);\n node.body = this.parseStatement(\"for\");\n this.exitScope();\n this.labels.pop();\n return this.finishNode(node, \"ForStatement\")\n};\n\n// Parse a `for`/`in` and `for`/`of` loop, which are almost\n// same from parser's perspective.\n\npp$8.parseForIn = function(node, init) {\n var isForIn = this.type === types$1._in;\n this.next();\n\n if (\n init.type === \"VariableDeclaration\" &&\n init.declarations[0].init != null &&\n (\n !isForIn ||\n this.options.ecmaVersion < 8 ||\n this.strict ||\n init.kind !== \"var\" ||\n init.declarations[0].id.type !== \"Identifier\"\n )\n ) {\n this.raise(\n init.start,\n ((isForIn ? \"for-in\" : \"for-of\") + \" loop variable declaration may not have an initializer\")\n );\n }\n node.left = init;\n node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();\n this.expect(types$1.parenR);\n node.body = this.parseStatement(\"for\");\n this.exitScope();\n this.labels.pop();\n return this.finishNode(node, isForIn ? \"ForInStatement\" : \"ForOfStatement\")\n};\n\n// Parse a list of variable declarations.\n\npp$8.parseVar = function(node, isFor, kind, allowMissingInitializer) {\n node.declarations = [];\n node.kind = kind;\n for (;;) {\n var decl = this.startNode();\n this.parseVarId(decl, kind);\n if (this.eat(types$1.eq)) {\n decl.init = this.parseMaybeAssign(isFor);\n } else if (!allowMissingInitializer && kind === \"const\" && !(this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual(\"of\")))) {\n this.unexpected();\n } else if (!allowMissingInitializer && (kind === \"using\" || kind === \"await using\") && this.options.ecmaVersion >= 17 && this.type !== types$1._in && !this.isContextual(\"of\")) {\n this.raise(this.lastTokEnd, (\"Missing initializer in \" + kind + \" declaration\"));\n } else if (!allowMissingInitializer && decl.id.type !== \"Identifier\" && !(isFor && (this.type === types$1._in || this.isContextual(\"of\")))) {\n this.raise(this.lastTokEnd, \"Complex binding patterns require an initialization value\");\n } else {\n decl.init = null;\n }\n node.declarations.push(this.finishNode(decl, \"VariableDeclarator\"));\n if (!this.eat(types$1.comma)) { break }\n }\n return node\n};\n\npp$8.parseVarId = function(decl, kind) {\n decl.id = kind === \"using\" || kind === \"await using\"\n ? this.parseIdent()\n : this.parseBindingAtom();\n\n this.checkLValPattern(decl.id, kind === \"var\" ? BIND_VAR : BIND_LEXICAL, false);\n};\n\nvar FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;\n\n// Parse a function declaration or literal (depending on the\n// `statement & FUNC_STATEMENT`).\n\n// Remove `allowExpressionBody` for 7.0.0, as it is only called with false\npp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) {\n this.initFunction(node);\n if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {\n if (this.type === types$1.star && (statement & FUNC_HANGING_STATEMENT))\n { this.unexpected(); }\n node.generator = this.eat(types$1.star);\n }\n if (this.options.ecmaVersion >= 8)\n { node.async = !!isAsync; }\n\n if (statement & FUNC_STATEMENT) {\n node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types$1.name ? null : this.parseIdent();\n if (node.id && !(statement & FUNC_HANGING_STATEMENT))\n // If it is a regular function declaration in sloppy mode, then it is\n // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding\n // mode depends on properties of the current scope (see\n // treatFunctionsAsVar).\n { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }\n }\n\n var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;\n this.yieldPos = 0;\n this.awaitPos = 0;\n this.awaitIdentPos = 0;\n this.enterScope(functionFlags(node.async, node.generator));\n\n if (!(statement & FUNC_STATEMENT))\n { node.id = this.type === types$1.name ? this.parseIdent() : null; }\n\n this.parseFunctionParams(node);\n this.parseFunctionBody(node, allowExpressionBody, false, forInit);\n\n this.yieldPos = oldYieldPos;\n this.awaitPos = oldAwaitPos;\n this.awaitIdentPos = oldAwaitIdentPos;\n return this.finishNode(node, (statement & FUNC_STATEMENT) ? \"FunctionDeclaration\" : \"FunctionExpression\")\n};\n\npp$8.parseFunctionParams = function(node) {\n this.expect(types$1.parenL);\n node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);\n this.checkYieldAwaitInDefaultParams();\n};\n\n// Parse a class declaration or literal (depending on the\n// `isStatement` parameter).\n\npp$8.parseClass = function(node, isStatement) {\n this.next();\n\n // ecma-262 14.6 Class Definitions\n // A class definition is always strict mode code.\n var oldStrict = this.strict;\n this.strict = true;\n\n this.parseClassId(node, isStatement);\n this.parseClassSuper(node);\n var privateNameMap = this.enterClassBody();\n var classBody = this.startNode();\n var hadConstructor = false;\n classBody.body = [];\n this.expect(types$1.braceL);\n while (this.type !== types$1.braceR) {\n var element = this.parseClassElement(node.superClass !== null);\n if (element) {\n classBody.body.push(element);\n if (element.type === \"MethodDefinition\" && element.kind === \"constructor\") {\n if (hadConstructor) { this.raiseRecoverable(element.start, \"Duplicate constructor in the same class\"); }\n hadConstructor = true;\n } else if (element.key && element.key.type === \"PrivateIdentifier\" && isPrivateNameConflicted(privateNameMap, element)) {\n this.raiseRecoverable(element.key.start, (\"Identifier '#\" + (element.key.name) + \"' has already been declared\"));\n }\n }\n }\n this.strict = oldStrict;\n this.next();\n node.body = this.finishNode(classBody, \"ClassBody\");\n this.exitClassBody();\n return this.finishNode(node, isStatement ? \"ClassDeclaration\" : \"ClassExpression\")\n};\n\npp$8.parseClassElement = function(constructorAllowsSuper) {\n if (this.eat(types$1.semi)) { return null }\n\n var ecmaVersion = this.options.ecmaVersion;\n var node = this.startNode();\n var keyName = \"\";\n var isGenerator = false;\n var isAsync = false;\n var kind = \"method\";\n var isStatic = false;\n\n if (this.eatContextual(\"static\")) {\n // Parse static init block\n if (ecmaVersion >= 13 && this.eat(types$1.braceL)) {\n this.parseClassStaticBlock(node);\n return node\n }\n if (this.isClassElementNameStart() || this.type === types$1.star) {\n isStatic = true;\n } else {\n keyName = \"static\";\n }\n }\n node.static = isStatic;\n if (!keyName && ecmaVersion >= 8 && this.eatContextual(\"async\")) {\n if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) {\n isAsync = true;\n } else {\n keyName = \"async\";\n }\n }\n if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1.star)) {\n isGenerator = true;\n }\n if (!keyName && !isAsync && !isGenerator) {\n var lastValue = this.value;\n if (this.eatContextual(\"get\") || this.eatContextual(\"set\")) {\n if (this.isClassElementNameStart()) {\n kind = lastValue;\n } else {\n keyName = lastValue;\n }\n }\n }\n\n // Parse element name\n if (keyName) {\n // 'async', 'get', 'set', or 'static' were not a keyword contextually.\n // The last token is any of those. Make it the element name.\n node.computed = false;\n node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);\n node.key.name = keyName;\n this.finishNode(node.key, \"Identifier\");\n } else {\n this.parseClassElementName(node);\n }\n\n // Parse element value\n if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== \"method\" || isGenerator || isAsync) {\n var isConstructor = !node.static && checkKeyName(node, \"constructor\");\n var allowsDirectSuper = isConstructor && constructorAllowsSuper;\n // Couldn't move this check into the 'parseClassMethod' method for backward compatibility.\n if (isConstructor && kind !== \"method\") { this.raise(node.key.start, \"Constructor can't have get/set modifier\"); }\n node.kind = isConstructor ? \"constructor\" : kind;\n this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper);\n } else {\n this.parseClassField(node);\n }\n\n return node\n};\n\npp$8.isClassElementNameStart = function() {\n return (\n this.type === types$1.name ||\n this.type === types$1.privateId ||\n this.type === types$1.num ||\n this.type === types$1.string ||\n this.type === types$1.bracketL ||\n this.type.keyword\n )\n};\n\npp$8.parseClassElementName = function(element) {\n if (this.type === types$1.privateId) {\n if (this.value === \"constructor\") {\n this.raise(this.start, \"Classes can't have an element named '#constructor'\");\n }\n element.computed = false;\n element.key = this.parsePrivateIdent();\n } else {\n this.parsePropertyName(element);\n }\n};\n\npp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {\n // Check key and flags\n var key = method.key;\n if (method.kind === \"constructor\") {\n if (isGenerator) { this.raise(key.start, \"Constructor can't be a generator\"); }\n if (isAsync) { this.raise(key.start, \"Constructor can't be an async method\"); }\n } else if (method.static && checkKeyName(method, \"prototype\")) {\n this.raise(key.start, \"Classes may not have a static property named prototype\");\n }\n\n // Parse value\n var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);\n\n // Check value\n if (method.kind === \"get\" && value.params.length !== 0)\n { this.raiseRecoverable(value.start, \"getter should have no params\"); }\n if (method.kind === \"set\" && value.params.length !== 1)\n { this.raiseRecoverable(value.start, \"setter should have exactly one param\"); }\n if (method.kind === \"set\" && value.params[0].type === \"RestElement\")\n { this.raiseRecoverable(value.params[0].start, \"Setter cannot use rest params\"); }\n\n return this.finishNode(method, \"MethodDefinition\")\n};\n\npp$8.parseClassField = function(field) {\n if (checkKeyName(field, \"constructor\")) {\n this.raise(field.key.start, \"Classes can't have a field named 'constructor'\");\n } else if (field.static && checkKeyName(field, \"prototype\")) {\n this.raise(field.key.start, \"Classes can't have a static field named 'prototype'\");\n }\n\n if (this.eat(types$1.eq)) {\n // To raise SyntaxError if 'arguments' exists in the initializer.\n this.enterScope(SCOPE_CLASS_FIELD_INIT | SCOPE_SUPER);\n field.value = this.parseMaybeAssign();\n this.exitScope();\n } else {\n field.value = null;\n }\n this.semicolon();\n\n return this.finishNode(field, \"PropertyDefinition\")\n};\n\npp$8.parseClassStaticBlock = function(node) {\n node.body = [];\n\n var oldLabels = this.labels;\n this.labels = [];\n this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER);\n while (this.type !== types$1.braceR) {\n var stmt = this.parseStatement(null);\n node.body.push(stmt);\n }\n this.next();\n this.exitScope();\n this.labels = oldLabels;\n\n return this.finishNode(node, \"StaticBlock\")\n};\n\npp$8.parseClassId = function(node, isStatement) {\n if (this.type === types$1.name) {\n node.id = this.parseIdent();\n if (isStatement)\n { this.checkLValSimple(node.id, BIND_LEXICAL, false); }\n } else {\n if (isStatement === true)\n { this.unexpected(); }\n node.id = null;\n }\n};\n\npp$8.parseClassSuper = function(node) {\n node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(null, false) : null;\n};\n\npp$8.enterClassBody = function() {\n var element = {declared: Object.create(null), used: []};\n this.privateNameStack.push(element);\n return element.declared\n};\n\npp$8.exitClassBody = function() {\n var ref = this.privateNameStack.pop();\n var declared = ref.declared;\n var used = ref.used;\n if (!this.options.checkPrivateFields) { return }\n var len = this.privateNameStack.length;\n var parent = len === 0 ? null : this.privateNameStack[len - 1];\n for (var i = 0; i < used.length; ++i) {\n var id = used[i];\n if (!hasOwn(declared, id.name)) {\n if (parent) {\n parent.used.push(id);\n } else {\n this.raiseRecoverable(id.start, (\"Private field '#\" + (id.name) + \"' must be declared in an enclosing class\"));\n }\n }\n }\n};\n\nfunction isPrivateNameConflicted(privateNameMap, element) {\n var name = element.key.name;\n var curr = privateNameMap[name];\n\n var next = \"true\";\n if (element.type === \"MethodDefinition\" && (element.kind === \"get\" || element.kind === \"set\")) {\n next = (element.static ? \"s\" : \"i\") + element.kind;\n }\n\n // `class { get #a(){}; static set #a(_){} }` is also conflict.\n if (\n curr === \"iget\" && next === \"iset\" ||\n curr === \"iset\" && next === \"iget\" ||\n curr === \"sget\" && next === \"sset\" ||\n curr === \"sset\" && next === \"sget\"\n ) {\n privateNameMap[name] = \"true\";\n return false\n } else if (!curr) {\n privateNameMap[name] = next;\n return false\n } else {\n return true\n }\n}\n\nfunction checkKeyName(node, name) {\n var computed = node.computed;\n var key = node.key;\n return !computed && (\n key.type === \"Identifier\" && key.name === name ||\n key.type === \"Literal\" && key.value === name\n )\n}\n\n// Parses module export declaration.\n\npp$8.parseExportAllDeclaration = function(node, exports$1) {\n if (this.options.ecmaVersion >= 11) {\n if (this.eatContextual(\"as\")) {\n node.exported = this.parseModuleExportName();\n this.checkExport(exports$1, node.exported, this.lastTokStart);\n } else {\n node.exported = null;\n }\n }\n this.expectContextual(\"from\");\n if (this.type !== types$1.string) { this.unexpected(); }\n node.source = this.parseExprAtom();\n if (this.options.ecmaVersion >= 16)\n { node.attributes = this.parseWithClause(); }\n this.semicolon();\n return this.finishNode(node, \"ExportAllDeclaration\")\n};\n\npp$8.parseExport = function(node, exports$1) {\n this.next();\n // export * from '...'\n if (this.eat(types$1.star)) {\n return this.parseExportAllDeclaration(node, exports$1)\n }\n if (this.eat(types$1._default)) { // export default ...\n this.checkExport(exports$1, \"default\", this.lastTokStart);\n node.declaration = this.parseExportDefaultDeclaration();\n return this.finishNode(node, \"ExportDefaultDeclaration\")\n }\n // export var|const|let|function|class ...\n if (this.shouldParseExportStatement()) {\n node.declaration = this.parseExportDeclaration(node);\n if (node.declaration.type === \"VariableDeclaration\")\n { this.checkVariableExport(exports$1, node.declaration.declarations); }\n else\n { this.checkExport(exports$1, node.declaration.id, node.declaration.id.start); }\n node.specifiers = [];\n node.source = null;\n if (this.options.ecmaVersion >= 16)\n { node.attributes = []; }\n } else { // export { x, y as z } [from '...']\n node.declaration = null;\n node.specifiers = this.parseExportSpecifiers(exports$1);\n if (this.eatContextual(\"from\")) {\n if (this.type !== types$1.string) { this.unexpected(); }\n node.source = this.parseExprAtom();\n if (this.options.ecmaVersion >= 16)\n { node.attributes = this.parseWithClause(); }\n } else {\n for (var i = 0, list = node.specifiers; i < list.length; i += 1) {\n // check for keywords used as local names\n var spec = list[i];\n\n this.checkUnreserved(spec.local);\n // check if export is defined\n this.checkLocalExport(spec.local);\n\n if (spec.local.type === \"Literal\") {\n this.raise(spec.local.start, \"A string literal cannot be used as an exported binding without `from`.\");\n }\n }\n\n node.source = null;\n if (this.options.ecmaVersion >= 16)\n { node.attributes = []; }\n }\n this.semicolon();\n }\n return this.finishNode(node, \"ExportNamedDeclaration\")\n};\n\npp$8.parseExportDeclaration = function(node) {\n return this.parseStatement(null)\n};\n\npp$8.parseExportDefaultDeclaration = function() {\n var isAsync;\n if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) {\n var fNode = this.startNode();\n this.next();\n if (isAsync) { this.next(); }\n return this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync)\n } else if (this.type === types$1._class) {\n var cNode = this.startNode();\n return this.parseClass(cNode, \"nullableID\")\n } else {\n var declaration = this.parseMaybeAssign();\n this.semicolon();\n return declaration\n }\n};\n\npp$8.checkExport = function(exports$1, name, pos) {\n if (!exports$1) { return }\n if (typeof name !== \"string\")\n { name = name.type === \"Identifier\" ? name.name : name.value; }\n if (hasOwn(exports$1, name))\n { this.raiseRecoverable(pos, \"Duplicate export '\" + name + \"'\"); }\n exports$1[name] = true;\n};\n\npp$8.checkPatternExport = function(exports$1, pat) {\n var type = pat.type;\n if (type === \"Identifier\")\n { this.checkExport(exports$1, pat, pat.start); }\n else if (type === \"ObjectPattern\")\n { for (var i = 0, list = pat.properties; i < list.length; i += 1)\n {\n var prop = list[i];\n\n this.checkPatternExport(exports$1, prop);\n } }\n else if (type === \"ArrayPattern\")\n { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {\n var elt = list$1[i$1];\n\n if (elt) { this.checkPatternExport(exports$1, elt); }\n } }\n else if (type === \"Property\")\n { this.checkPatternExport(exports$1, pat.value); }\n else if (type === \"AssignmentPattern\")\n { this.checkPatternExport(exports$1, pat.left); }\n else if (type === \"RestElement\")\n { this.checkPatternExport(exports$1, pat.argument); }\n};\n\npp$8.checkVariableExport = function(exports$1, decls) {\n if (!exports$1) { return }\n for (var i = 0, list = decls; i < list.length; i += 1)\n {\n var decl = list[i];\n\n this.checkPatternExport(exports$1, decl.id);\n }\n};\n\npp$8.shouldParseExportStatement = function() {\n return this.type.keyword === \"var\" ||\n this.type.keyword === \"const\" ||\n this.type.keyword === \"class\" ||\n this.type.keyword === \"function\" ||\n this.isLet() ||\n this.isAsyncFunction()\n};\n\n// Parses a comma-separated list of module exports.\n\npp$8.parseExportSpecifier = function(exports$1) {\n var node = this.startNode();\n node.local = this.parseModuleExportName();\n\n node.exported = this.eatContextual(\"as\") ? this.parseModuleExportName() : node.local;\n this.checkExport(\n exports$1,\n node.exported,\n node.exported.start\n );\n\n return this.finishNode(node, \"ExportSpecifier\")\n};\n\npp$8.parseExportSpecifiers = function(exports$1) {\n var nodes = [], first = true;\n // export { x, y as z } [from '...']\n this.expect(types$1.braceL);\n while (!this.eat(types$1.braceR)) {\n if (!first) {\n this.expect(types$1.comma);\n if (this.afterTrailingComma(types$1.braceR)) { break }\n } else { first = false; }\n\n nodes.push(this.parseExportSpecifier(exports$1));\n }\n return nodes\n};\n\n// Parses import declaration.\n\npp$8.parseImport = function(node) {\n this.next();\n\n // import '...'\n if (this.type === types$1.string) {\n node.specifiers = empty$1;\n node.source = this.parseExprAtom();\n } else {\n node.specifiers = this.parseImportSpecifiers();\n this.expectContextual(\"from\");\n node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected();\n }\n if (this.options.ecmaVersion >= 16)\n { node.attributes = this.parseWithClause(); }\n this.semicolon();\n return this.finishNode(node, \"ImportDeclaration\")\n};\n\n// Parses a comma-separated list of module imports.\n\npp$8.parseImportSpecifier = function() {\n var node = this.startNode();\n node.imported = this.parseModuleExportName();\n\n if (this.eatContextual(\"as\")) {\n node.local = this.parseIdent();\n } else {\n this.checkUnreserved(node.imported);\n node.local = node.imported;\n }\n this.checkLValSimple(node.local, BIND_LEXICAL);\n\n return this.finishNode(node, \"ImportSpecifier\")\n};\n\npp$8.parseImportDefaultSpecifier = function() {\n // import defaultObj, { x, y as z } from '...'\n var node = this.startNode();\n node.local = this.parseIdent();\n this.checkLValSimple(node.local, BIND_LEXICAL);\n return this.finishNode(node, \"ImportDefaultSpecifier\")\n};\n\npp$8.parseImportNamespaceSpecifier = function() {\n var node = this.startNode();\n this.next();\n this.expectContextual(\"as\");\n node.local = this.parseIdent();\n this.checkLValSimple(node.local, BIND_LEXICAL);\n return this.finishNode(node, \"ImportNamespaceSpecifier\")\n};\n\npp$8.parseImportSpecifiers = function() {\n var nodes = [], first = true;\n if (this.type === types$1.name) {\n nodes.push(this.parseImportDefaultSpecifier());\n if (!this.eat(types$1.comma)) { return nodes }\n }\n if (this.type === types$1.star) {\n nodes.push(this.parseImportNamespaceSpecifier());\n return nodes\n }\n this.expect(types$1.braceL);\n while (!this.eat(types$1.braceR)) {\n if (!first) {\n this.expect(types$1.comma);\n if (this.afterTrailingComma(types$1.braceR)) { break }\n } else { first = false; }\n\n nodes.push(this.parseImportSpecifier());\n }\n return nodes\n};\n\npp$8.parseWithClause = function() {\n var nodes = [];\n if (!this.eat(types$1._with)) {\n return nodes\n }\n this.expect(types$1.braceL);\n var attributeKeys = {};\n var first = true;\n while (!this.eat(types$1.braceR)) {\n if (!first) {\n this.expect(types$1.comma);\n if (this.afterTrailingComma(types$1.braceR)) { break }\n } else { first = false; }\n\n var attr = this.parseImportAttribute();\n var keyName = attr.key.type === \"Identifier\" ? attr.key.name : attr.key.value;\n if (hasOwn(attributeKeys, keyName))\n { this.raiseRecoverable(attr.key.start, \"Duplicate attribute key '\" + keyName + \"'\"); }\n attributeKeys[keyName] = true;\n nodes.push(attr);\n }\n return nodes\n};\n\npp$8.parseImportAttribute = function() {\n var node = this.startNode();\n node.key = this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== \"never\");\n this.expect(types$1.colon);\n if (this.type !== types$1.string) {\n this.unexpected();\n }\n node.value = this.parseExprAtom();\n return this.finishNode(node, \"ImportAttribute\")\n};\n\npp$8.parseModuleExportName = function() {\n if (this.options.ecmaVersion >= 13 && this.type === types$1.string) {\n var stringLiteral = this.parseLiteral(this.value);\n if (loneSurrogate.test(stringLiteral.value)) {\n this.raise(stringLiteral.start, \"An export name cannot include a lone surrogate.\");\n }\n return stringLiteral\n }\n return this.parseIdent(true)\n};\n\n// Set `ExpressionStatement#directive` property for directive prologues.\npp$8.adaptDirectivePrologue = function(statements) {\n for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {\n statements[i].directive = statements[i].expression.raw.slice(1, -1);\n }\n};\npp$8.isDirectiveCandidate = function(statement) {\n return (\n this.options.ecmaVersion >= 5 &&\n statement.type === \"ExpressionStatement\" &&\n statement.expression.type === \"Literal\" &&\n typeof statement.expression.value === \"string\" &&\n // Reject parenthesized strings.\n (this.input[statement.start] === \"\\\"\" || this.input[statement.start] === \"'\")\n )\n};\n\nvar pp$7 = Parser.prototype;\n\n// Convert existing expression atom to assignable pattern\n// if possible.\n\npp$7.toAssignable = function(node, isBinding, refDestructuringErrors) {\n if (this.options.ecmaVersion >= 6 && node) {\n switch (node.type) {\n case \"Identifier\":\n if (this.inAsync && node.name === \"await\")\n { this.raise(node.start, \"Cannot use 'await' as identifier inside an async function\"); }\n break\n\n case \"ObjectPattern\":\n case \"ArrayPattern\":\n case \"AssignmentPattern\":\n case \"RestElement\":\n break\n\n case \"ObjectExpression\":\n node.type = \"ObjectPattern\";\n if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }\n for (var i = 0, list = node.properties; i < list.length; i += 1) {\n var prop = list[i];\n\n this.toAssignable(prop, isBinding);\n // Early error:\n // AssignmentRestProperty[Yield, Await] :\n // `...` DestructuringAssignmentTarget[Yield, Await]\n //\n // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.\n if (\n prop.type === \"RestElement\" &&\n (prop.argument.type === \"ArrayPattern\" || prop.argument.type === \"ObjectPattern\")\n ) {\n this.raise(prop.argument.start, \"Unexpected token\");\n }\n }\n break\n\n case \"Property\":\n // AssignmentProperty has type === \"Property\"\n if (node.kind !== \"init\") { this.raise(node.key.start, \"Object pattern can't contain getter or setter\"); }\n this.toAssignable(node.value, isBinding);\n break\n\n case \"ArrayExpression\":\n node.type = \"ArrayPattern\";\n if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }\n this.toAssignableList(node.elements, isBinding);\n break\n\n case \"SpreadElement\":\n node.type = \"RestElement\";\n this.toAssignable(node.argument, isBinding);\n if (node.argument.type === \"AssignmentPattern\")\n { this.raise(node.argument.start, \"Rest elements cannot have a default value\"); }\n break\n\n case \"AssignmentExpression\":\n if (node.operator !== \"=\") { this.raise(node.left.end, \"Only '=' operator can be used for specifying default value.\"); }\n node.type = \"AssignmentPattern\";\n delete node.operator;\n this.toAssignable(node.left, isBinding);\n break\n\n case \"ParenthesizedExpression\":\n this.toAssignable(node.expression, isBinding, refDestructuringErrors);\n break\n\n case \"ChainExpression\":\n this.raiseRecoverable(node.start, \"Optional chaining cannot appear in left-hand side\");\n break\n\n case \"MemberExpression\":\n if (!isBinding) { break }\n\n default:\n this.raise(node.start, \"Assigning to rvalue\");\n }\n } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }\n return node\n};\n\n// Convert list of expression atoms to binding list.\n\npp$7.toAssignableList = function(exprList, isBinding) {\n var end = exprList.length;\n for (var i = 0; i < end; i++) {\n var elt = exprList[i];\n if (elt) { this.toAssignable(elt, isBinding); }\n }\n if (end) {\n var last = exprList[end - 1];\n if (this.options.ecmaVersion === 6 && isBinding && last && last.type === \"RestElement\" && last.argument.type !== \"Identifier\")\n { this.unexpected(last.argument.start); }\n }\n return exprList\n};\n\n// Parses spread element.\n\npp$7.parseSpread = function(refDestructuringErrors) {\n var node = this.startNode();\n this.next();\n node.argument = this.parseMaybeAssign(false, refDestructuringErrors);\n return this.finishNode(node, \"SpreadElement\")\n};\n\npp$7.parseRestBinding = function() {\n var node = this.startNode();\n this.next();\n\n // RestElement inside of a function parameter must be an identifier\n if (this.options.ecmaVersion === 6 && this.type !== types$1.name)\n { this.unexpected(); }\n\n node.argument = this.parseBindingAtom();\n\n return this.finishNode(node, \"RestElement\")\n};\n\n// Parses lvalue (assignable) atom.\n\npp$7.parseBindingAtom = function() {\n if (this.options.ecmaVersion >= 6) {\n switch (this.type) {\n case types$1.bracketL:\n var node = this.startNode();\n this.next();\n node.elements = this.parseBindingList(types$1.bracketR, true, true);\n return this.finishNode(node, \"ArrayPattern\")\n\n case types$1.braceL:\n return this.parseObj(true)\n }\n }\n return this.parseIdent()\n};\n\npp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma, allowModifiers) {\n var elts = [], first = true;\n while (!this.eat(close)) {\n if (first) { first = false; }\n else { this.expect(types$1.comma); }\n if (allowEmpty && this.type === types$1.comma) {\n elts.push(null);\n } else if (allowTrailingComma && this.afterTrailingComma(close)) {\n break\n } else if (this.type === types$1.ellipsis) {\n var rest = this.parseRestBinding();\n this.parseBindingListItem(rest);\n elts.push(rest);\n if (this.type === types$1.comma) { this.raiseRecoverable(this.start, \"Comma is not permitted after the rest element\"); }\n this.expect(close);\n break\n } else {\n elts.push(this.parseAssignableListItem(allowModifiers));\n }\n }\n return elts\n};\n\npp$7.parseAssignableListItem = function(allowModifiers) {\n var elem = this.parseMaybeDefault(this.start, this.startLoc);\n this.parseBindingListItem(elem);\n return elem\n};\n\npp$7.parseBindingListItem = function(param) {\n return param\n};\n\n// Parses assignment pattern around given atom if possible.\n\npp$7.parseMaybeDefault = function(startPos, startLoc, left) {\n left = left || this.parseBindingAtom();\n if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) { return left }\n var node = this.startNodeAt(startPos, startLoc);\n node.left = left;\n node.right = this.parseMaybeAssign();\n return this.finishNode(node, \"AssignmentPattern\")\n};\n\n// The following three functions all verify that a node is an lvalue \u2014\n// something that can be bound, or assigned to. In order to do so, they perform\n// a variety of checks:\n//\n// - Check that none of the bound/assigned-to identifiers are reserved words.\n// - Record name declarations for bindings in the appropriate scope.\n// - Check duplicate argument names, if checkClashes is set.\n//\n// If a complex binding pattern is encountered (e.g., object and array\n// destructuring), the entire pattern is recursively checked.\n//\n// There are three versions of checkLVal*() appropriate for different\n// circumstances:\n//\n// - checkLValSimple() shall be used if the syntactic construct supports\n// nothing other than identifiers and member expressions. Parenthesized\n// expressions are also correctly handled. This is generally appropriate for\n// constructs for which the spec says\n//\n// > It is a Syntax Error if AssignmentTargetType of [the production] is not\n// > simple.\n//\n// It is also appropriate for checking if an identifier is valid and not\n// defined elsewhere, like import declarations or function/class identifiers.\n//\n// Examples where this is used include:\n// a += \u2026;\n// import a from '\u2026';\n// where a is the node to be checked.\n//\n// - checkLValPattern() shall be used if the syntactic construct supports\n// anything checkLValSimple() supports, as well as object and array\n// destructuring patterns. This is generally appropriate for constructs for\n// which the spec says\n//\n// > It is a Syntax Error if [the production] is neither an ObjectLiteral nor\n// > an ArrayLiteral and AssignmentTargetType of [the production] is not\n// > simple.\n//\n// Examples where this is used include:\n// (a = \u2026);\n// const a = \u2026;\n// try { \u2026 } catch (a) { \u2026 }\n// where a is the node to be checked.\n//\n// - checkLValInnerPattern() shall be used if the syntactic construct supports\n// anything checkLValPattern() supports, as well as default assignment\n// patterns, rest elements, and other constructs that may appear within an\n// object or array destructuring pattern.\n//\n// As a special case, function parameters also use checkLValInnerPattern(),\n// as they also support defaults and rest constructs.\n//\n// These functions deliberately support both assignment and binding constructs,\n// as the logic for both is exceedingly similar. If the node is the target of\n// an assignment, then bindingType should be set to BIND_NONE. Otherwise, it\n// should be set to the appropriate BIND_* constant, like BIND_VAR or\n// BIND_LEXICAL.\n//\n// If the function is called with a non-BIND_NONE bindingType, then\n// additionally a checkClashes object may be specified to allow checking for\n// duplicate argument names. checkClashes is ignored if the provided construct\n// is an assignment (i.e., bindingType is BIND_NONE).\n\npp$7.checkLValSimple = function(expr, bindingType, checkClashes) {\n if ( bindingType === void 0 ) bindingType = BIND_NONE;\n\n var isBind = bindingType !== BIND_NONE;\n\n switch (expr.type) {\n case \"Identifier\":\n if (this.strict && this.reservedWordsStrictBind.test(expr.name))\n { this.raiseRecoverable(expr.start, (isBind ? \"Binding \" : \"Assigning to \") + expr.name + \" in strict mode\"); }\n if (isBind) {\n if (bindingType === BIND_LEXICAL && expr.name === \"let\")\n { this.raiseRecoverable(expr.start, \"let is disallowed as a lexically bound name\"); }\n if (checkClashes) {\n if (hasOwn(checkClashes, expr.name))\n { this.raiseRecoverable(expr.start, \"Argument name clash\"); }\n checkClashes[expr.name] = true;\n }\n if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }\n }\n break\n\n case \"ChainExpression\":\n this.raiseRecoverable(expr.start, \"Optional chaining cannot appear in left-hand side\");\n break\n\n case \"MemberExpression\":\n if (isBind) { this.raiseRecoverable(expr.start, \"Binding member expression\"); }\n break\n\n case \"ParenthesizedExpression\":\n if (isBind) { this.raiseRecoverable(expr.start, \"Binding parenthesized expression\"); }\n return this.checkLValSimple(expr.expression, bindingType, checkClashes)\n\n default:\n this.raise(expr.start, (isBind ? \"Binding\" : \"Assigning to\") + \" rvalue\");\n }\n};\n\npp$7.checkLValPattern = function(expr, bindingType, checkClashes) {\n if ( bindingType === void 0 ) bindingType = BIND_NONE;\n\n switch (expr.type) {\n case \"ObjectPattern\":\n for (var i = 0, list = expr.properties; i < list.length; i += 1) {\n var prop = list[i];\n\n this.checkLValInnerPattern(prop, bindingType, checkClashes);\n }\n break\n\n case \"ArrayPattern\":\n for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {\n var elem = list$1[i$1];\n\n if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }\n }\n break\n\n default:\n this.checkLValSimple(expr, bindingType, checkClashes);\n }\n};\n\npp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) {\n if ( bindingType === void 0 ) bindingType = BIND_NONE;\n\n switch (expr.type) {\n case \"Property\":\n // AssignmentProperty has type === \"Property\"\n this.checkLValInnerPattern(expr.value, bindingType, checkClashes);\n break\n\n case \"AssignmentPattern\":\n this.checkLValPattern(expr.left, bindingType, checkClashes);\n break\n\n case \"RestElement\":\n this.checkLValPattern(expr.argument, bindingType, checkClashes);\n break\n\n default:\n this.checkLValPattern(expr, bindingType, checkClashes);\n }\n};\n\n// The algorithm used to determine whether a regexp can appear at a\n// given point in the program is loosely based on sweet.js' approach.\n// See https://github.com/mozilla/sweet.js/wiki/design\n\n\nvar TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {\n this.token = token;\n this.isExpr = !!isExpr;\n this.preserveSpace = !!preserveSpace;\n this.override = override;\n this.generator = !!generator;\n};\n\nvar types = {\n b_stat: new TokContext(\"{\", false),\n b_expr: new TokContext(\"{\", true),\n b_tmpl: new TokContext(\"${\", false),\n p_stat: new TokContext(\"(\", false),\n p_expr: new TokContext(\"(\", true),\n q_tmpl: new TokContext(\"`\", true, true, function (p) { return p.tryReadTemplateToken(); }),\n f_stat: new TokContext(\"function\", false),\n f_expr: new TokContext(\"function\", true),\n f_expr_gen: new TokContext(\"function\", true, false, null, true),\n f_gen: new TokContext(\"function\", false, false, null, true)\n};\n\nvar pp$6 = Parser.prototype;\n\npp$6.initialContext = function() {\n return [types.b_stat]\n};\n\npp$6.curContext = function() {\n return this.context[this.context.length - 1]\n};\n\npp$6.braceIsBlock = function(prevType) {\n var parent = this.curContext();\n if (parent === types.f_expr || parent === types.f_stat)\n { return true }\n if (prevType === types$1.colon && (parent === types.b_stat || parent === types.b_expr))\n { return !parent.isExpr }\n\n // The check for `tt.name && exprAllowed` detects whether we are\n // after a `yield` or `of` construct. See the `updateContext` for\n // `tt.name`.\n if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed)\n { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }\n if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow)\n { return true }\n if (prevType === types$1.braceL)\n { return parent === types.b_stat }\n if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name)\n { return false }\n return !this.exprAllowed\n};\n\npp$6.inGeneratorContext = function() {\n for (var i = this.context.length - 1; i >= 1; i--) {\n var context = this.context[i];\n if (context.token === \"function\")\n { return context.generator }\n }\n return false\n};\n\npp$6.updateContext = function(prevType) {\n var update, type = this.type;\n if (type.keyword && prevType === types$1.dot)\n { this.exprAllowed = false; }\n else if (update = type.updateContext)\n { update.call(this, prevType); }\n else\n { this.exprAllowed = type.beforeExpr; }\n};\n\n// Used to handle edge cases when token context could not be inferred correctly during tokenization phase\n\npp$6.overrideContext = function(tokenCtx) {\n if (this.curContext() !== tokenCtx) {\n this.context[this.context.length - 1] = tokenCtx;\n }\n};\n\n// Token-specific context update code\n\ntypes$1.parenR.updateContext = types$1.braceR.updateContext = function() {\n if (this.context.length === 1) {\n this.exprAllowed = true;\n return\n }\n var out = this.context.pop();\n if (out === types.b_stat && this.curContext().token === \"function\") {\n out = this.context.pop();\n }\n this.exprAllowed = !out.isExpr;\n};\n\ntypes$1.braceL.updateContext = function(prevType) {\n this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr);\n this.exprAllowed = true;\n};\n\ntypes$1.dollarBraceL.updateContext = function() {\n this.context.push(types.b_tmpl);\n this.exprAllowed = true;\n};\n\ntypes$1.parenL.updateContext = function(prevType) {\n var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while;\n this.context.push(statementParens ? types.p_stat : types.p_expr);\n this.exprAllowed = true;\n};\n\ntypes$1.incDec.updateContext = function() {\n // tokExprAllowed stays unchanged\n};\n\ntypes$1._function.updateContext = types$1._class.updateContext = function(prevType) {\n if (prevType.beforeExpr && prevType !== types$1._else &&\n !(prevType === types$1.semi && this.curContext() !== types.p_stat) &&\n !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&\n !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types.b_stat))\n { this.context.push(types.f_expr); }\n else\n { this.context.push(types.f_stat); }\n this.exprAllowed = false;\n};\n\ntypes$1.colon.updateContext = function() {\n if (this.curContext().token === \"function\") { this.context.pop(); }\n this.exprAllowed = true;\n};\n\ntypes$1.backQuote.updateContext = function() {\n if (this.curContext() === types.q_tmpl)\n { this.context.pop(); }\n else\n { this.context.push(types.q_tmpl); }\n this.exprAllowed = false;\n};\n\ntypes$1.star.updateContext = function(prevType) {\n if (prevType === types$1._function) {\n var index = this.context.length - 1;\n if (this.context[index] === types.f_expr)\n { this.context[index] = types.f_expr_gen; }\n else\n { this.context[index] = types.f_gen; }\n }\n this.exprAllowed = true;\n};\n\ntypes$1.name.updateContext = function(prevType) {\n var allowed = false;\n if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) {\n if (this.value === \"of\" && !this.exprAllowed ||\n this.value === \"yield\" && this.inGeneratorContext())\n { allowed = true; }\n }\n this.exprAllowed = allowed;\n};\n\n// A recursive descent parser operates by defining functions for all\n// syntactic elements, and recursively calling those, each function\n// advancing the input stream and returning an AST node. Precedence\n// of constructs (for example, the fact that `!x[1]` means `!(x[1])`\n// instead of `(!x)[1]` is handled by the fact that the parser\n// function that parses unary prefix operators is called first, and\n// in turn calls the function that parses `[]` subscripts \u2014 that\n// way, it'll receive the node for `x[1]` already parsed, and wraps\n// *that* in the unary operator node.\n//\n// Acorn uses an [operator precedence parser][opp] to handle binary\n// operator precedence, because it is much more compact than using\n// the technique outlined above, which uses different, nesting\n// functions to specify precedence, for all of the ten binary\n// precedence levels that JavaScript defines.\n//\n// [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser\n\n\nvar pp$5 = Parser.prototype;\n\n// Check if property name clashes with already added.\n// Object/class getters and setters are not allowed to clash \u2014\n// either with each other or with an init property \u2014 and in\n// strict mode, init properties are also not allowed to be repeated.\n\npp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {\n if (this.options.ecmaVersion >= 9 && prop.type === \"SpreadElement\")\n { return }\n if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))\n { return }\n var key = prop.key;\n var name;\n switch (key.type) {\n case \"Identifier\": name = key.name; break\n case \"Literal\": name = String(key.value); break\n default: return\n }\n var kind = prop.kind;\n if (this.options.ecmaVersion >= 6) {\n if (name === \"__proto__\" && kind === \"init\") {\n if (propHash.proto) {\n if (refDestructuringErrors) {\n if (refDestructuringErrors.doubleProto < 0) {\n refDestructuringErrors.doubleProto = key.start;\n }\n } else {\n this.raiseRecoverable(key.start, \"Redefinition of __proto__ property\");\n }\n }\n propHash.proto = true;\n }\n return\n }\n name = \"$\" + name;\n var other = propHash[name];\n if (other) {\n var redefinition;\n if (kind === \"init\") {\n redefinition = this.strict && other.init || other.get || other.set;\n } else {\n redefinition = other.init || other[kind];\n }\n if (redefinition)\n { this.raiseRecoverable(key.start, \"Redefinition of property\"); }\n } else {\n other = propHash[name] = {\n init: false,\n get: false,\n set: false\n };\n }\n other[kind] = true;\n};\n\n// ### Expression parsing\n\n// These nest, from the most general expression type at the top to\n// 'atomic', nondivisible expression types at the bottom. Most of\n// the functions will simply let the function(s) below them parse,\n// and, *if* the syntactic construct they handle is present, wrap\n// the AST node that the inner parser gave them in another node.\n\n// Parse a full expression. The optional arguments are used to\n// forbid the `in` operator (in for loops initalization expressions)\n// and provide reference for storing '=' operator inside shorthand\n// property assignment in contexts where both object expression\n// and object pattern might appear (so it's possible to raise\n// delayed syntax error at correct position).\n\npp$5.parseExpression = function(forInit, refDestructuringErrors) {\n var this$1$1 = this;\n\n return this.catchStackOverflow(function () {\n var startPos = this$1$1.start, startLoc = this$1$1.startLoc;\n var expr = this$1$1.parseMaybeAssign(forInit, refDestructuringErrors);\n if (this$1$1.type === types$1.comma) {\n var node = this$1$1.startNodeAt(startPos, startLoc);\n node.expressions = [expr];\n while (this$1$1.eat(types$1.comma)) { node.expressions.push(this$1$1.parseMaybeAssign(forInit, refDestructuringErrors)); }\n return this$1$1.finishNode(node, \"SequenceExpression\")\n }\n return expr\n })\n};\n\n// Parse an assignment expression. This includes applications of\n// operators like `+=`.\n\npp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {\n if (this.isContextual(\"yield\")) {\n if (this.inGenerator) { return this.parseYield(forInit) }\n // The tokenizer will assume an expression is allowed after\n // `yield`, but this isn't that kind of yield\n else { this.exprAllowed = false; }\n }\n\n var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1;\n if (refDestructuringErrors) {\n oldParenAssign = refDestructuringErrors.parenthesizedAssign;\n oldTrailingComma = refDestructuringErrors.trailingComma;\n oldDoubleProto = refDestructuringErrors.doubleProto;\n refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;\n } else {\n refDestructuringErrors = new DestructuringErrors;\n ownDestructuringErrors = true;\n }\n\n var startPos = this.start, startLoc = this.startLoc;\n if (this.type === types$1.parenL || this.type === types$1.name) {\n this.potentialArrowAt = this.start;\n this.potentialArrowInForAwait = forInit === \"await\";\n }\n var left = this.parseMaybeConditional(forInit, refDestructuringErrors);\n if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }\n if (this.type.isAssign) {\n var node = this.startNodeAt(startPos, startLoc);\n node.operator = this.value;\n if (this.type === types$1.eq)\n { left = this.toAssignable(left, false, refDestructuringErrors); }\n if (!ownDestructuringErrors) {\n refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;\n }\n if (refDestructuringErrors.shorthandAssign >= left.start)\n { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly\n if (this.type === types$1.eq)\n { this.checkLValPattern(left); }\n else\n { this.checkLValSimple(left); }\n node.left = left;\n this.next();\n node.right = this.parseMaybeAssign(forInit);\n if (oldDoubleProto > -1) { refDestructuringErrors.doubleProto = oldDoubleProto; }\n return this.finishNode(node, \"AssignmentExpression\")\n } else {\n if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }\n }\n if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }\n if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }\n return left\n};\n\n// Parse a ternary conditional (`?:`) operator.\n\npp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) {\n var startPos = this.start, startLoc = this.startLoc;\n var expr = this.parseExprOps(forInit, refDestructuringErrors);\n if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }\n if (!(expr.type === \"ArrowFunctionExpression\" && expr.start === startPos) && this.eat(types$1.question)) {\n var node = this.startNodeAt(startPos, startLoc);\n node.test = expr;\n node.consequent = this.parseMaybeAssign();\n this.expect(types$1.colon);\n node.alternate = this.parseMaybeAssign(forInit);\n return this.finishNode(node, \"ConditionalExpression\")\n }\n return expr\n};\n\n// Start the precedence parser.\n\npp$5.parseExprOps = function(forInit, refDestructuringErrors) {\n var startPos = this.start, startLoc = this.startLoc;\n var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit);\n if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }\n return expr.start === startPos && expr.type === \"ArrowFunctionExpression\" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit)\n};\n\n// Parse binary operators with the operator precedence parsing\n// algorithm. `left` is the left-hand side of the operator.\n// `minPrec` provides context that allows the function to stop and\n// defer further parser to one of its callers when it encounters an\n// operator that has a lower precedence than the set it is parsing.\n\npp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {\n var prec = this.type.binop;\n if (prec != null && (!forInit || this.type !== types$1._in)) {\n if (prec > minPrec) {\n var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND;\n var coalesce = this.type === types$1.coalesce;\n if (coalesce) {\n // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.\n // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.\n prec = types$1.logicalAND.binop;\n }\n var op = this.value;\n this.next();\n var startPos = this.start, startLoc = this.startLoc;\n var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit);\n var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);\n if ((logical && this.type === types$1.coalesce) || (coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND))) {\n this.raiseRecoverable(this.start, \"Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses\");\n }\n return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit)\n }\n }\n return left\n};\n\npp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) {\n if (right.type === \"PrivateIdentifier\") { this.raise(right.start, \"Private identifier can only be left side of binary expression\"); }\n var node = this.startNodeAt(startPos, startLoc);\n node.left = left;\n node.operator = op;\n node.right = right;\n return this.finishNode(node, logical ? \"LogicalExpression\" : \"BinaryExpression\")\n};\n\n// Parse unary operators, both prefix and postfix.\n\npp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) {\n var startPos = this.start, startLoc = this.startLoc, expr;\n if (this.isContextual(\"await\") && this.canAwait) {\n expr = this.parseAwait(forInit);\n sawUnary = true;\n } else if (this.type.prefix) {\n var node = this.startNode(), update = this.type === types$1.incDec;\n node.operator = this.value;\n node.prefix = true;\n this.next();\n node.argument = this.parseMaybeUnary(null, true, update, forInit);\n this.checkExpressionErrors(refDestructuringErrors, true);\n if (update) { this.checkLValSimple(node.argument); }\n else if (this.strict && node.operator === \"delete\" && isLocalVariableAccess(node.argument))\n { this.raiseRecoverable(node.start, \"Deleting local variable in strict mode\"); }\n else if (node.operator === \"delete\" && isPrivateFieldAccess(node.argument))\n { this.raiseRecoverable(node.start, \"Private fields can not be deleted\"); }\n else { sawUnary = true; }\n expr = this.finishNode(node, update ? \"UpdateExpression\" : \"UnaryExpression\");\n } else if (!sawUnary && this.type === types$1.privateId) {\n if ((forInit || this.privateNameStack.length === 0) && this.options.checkPrivateFields) { this.unexpected(); }\n expr = this.parsePrivateIdent();\n // only could be private fields in 'in', such as #x in obj\n if (this.type !== types$1._in) { this.unexpected(); }\n } else {\n expr = this.parseExprSubscripts(refDestructuringErrors, forInit);\n if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }\n while (this.type.postfix && !this.canInsertSemicolon()) {\n var node$1 = this.startNodeAt(startPos, startLoc);\n node$1.operator = this.value;\n node$1.prefix = false;\n node$1.argument = expr;\n this.checkLValSimple(expr);\n this.next();\n expr = this.finishNode(node$1, \"UpdateExpression\");\n }\n }\n\n if (!incDec && !(expr.type === \"ArrowFunctionExpression\" && expr.start === startPos) && this.eat(types$1.starstar)) {\n if (sawUnary)\n { this.unexpected(this.lastTokStart); }\n else\n { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), \"**\", false) }\n } else {\n return expr\n }\n};\n\nfunction isLocalVariableAccess(node) {\n return (\n node.type === \"Identifier\" ||\n node.type === \"ParenthesizedExpression\" && isLocalVariableAccess(node.expression)\n )\n}\n\nfunction isPrivateFieldAccess(node) {\n return (\n node.type === \"MemberExpression\" && node.property.type === \"PrivateIdentifier\" ||\n node.type === \"ChainExpression\" && isPrivateFieldAccess(node.expression) ||\n node.type === \"ParenthesizedExpression\" && isPrivateFieldAccess(node.expression)\n )\n}\n\n// Parse call, dot, and `[]`-subscript expressions.\n\npp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) {\n var startPos = this.start, startLoc = this.startLoc;\n var expr = this.parseExprAtom(refDestructuringErrors, forInit);\n if (expr.type === \"ArrowFunctionExpression\" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== \")\")\n { return expr }\n var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit);\n if (refDestructuringErrors && result.type === \"MemberExpression\") {\n if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }\n if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }\n if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; }\n }\n return result\n};\n\npp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) {\n var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === \"Identifier\" && base.name === \"async\" &&\n this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&\n this.potentialArrowAt === base.start;\n var optionalChained = false;\n\n while (true) {\n var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit);\n\n if (element.optional) { optionalChained = true; }\n if (element === base || element.type === \"ArrowFunctionExpression\") {\n if (optionalChained) {\n var chainNode = this.startNodeAt(startPos, startLoc);\n chainNode.expression = element;\n element = this.finishNode(chainNode, \"ChainExpression\");\n }\n return element\n }\n\n base = element;\n }\n};\n\npp$5.shouldParseAsyncArrow = function() {\n return !this.canInsertSemicolon() && this.eat(types$1.arrow)\n};\n\npp$5.parseSubscriptAsyncArrow = function(startPos, startLoc, exprList, forInit) {\n return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit)\n};\n\npp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) {\n var optionalSupported = this.options.ecmaVersion >= 11;\n var optional = optionalSupported && this.eat(types$1.questionDot);\n if (noCalls && optional) { this.raise(this.lastTokStart, \"Optional chaining cannot appear in the callee of new expressions\"); }\n\n var computed = this.eat(types$1.bracketL);\n if (computed || (optional && this.type !== types$1.parenL && this.type !== types$1.backQuote) || this.eat(types$1.dot)) {\n var node = this.startNodeAt(startPos, startLoc);\n node.object = base;\n if (computed) {\n node.property = this.parseExpression();\n this.expect(types$1.bracketR);\n } else if (this.type === types$1.privateId && base.type !== \"Super\") {\n node.property = this.parsePrivateIdent();\n } else {\n node.property = this.parseIdent(this.options.allowReserved !== \"never\");\n }\n node.computed = !!computed;\n if (optionalSupported) {\n node.optional = optional;\n }\n base = this.finishNode(node, \"MemberExpression\");\n } else if (!noCalls && this.eat(types$1.parenL)) {\n var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;\n this.yieldPos = 0;\n this.awaitPos = 0;\n this.awaitIdentPos = 0;\n var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);\n if (maybeAsyncArrow && !optional && this.shouldParseAsyncArrow()) {\n this.checkPatternErrors(refDestructuringErrors, false);\n this.checkYieldAwaitInDefaultParams();\n if (this.awaitIdentPos > 0)\n { this.raise(this.awaitIdentPos, \"Cannot use 'await' as identifier inside an async function\"); }\n this.yieldPos = oldYieldPos;\n this.awaitPos = oldAwaitPos;\n this.awaitIdentPos = oldAwaitIdentPos;\n return this.parseSubscriptAsyncArrow(startPos, startLoc, exprList, forInit)\n }\n this.checkExpressionErrors(refDestructuringErrors, true);\n this.yieldPos = oldYieldPos || this.yieldPos;\n this.awaitPos = oldAwaitPos || this.awaitPos;\n this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;\n var node$1 = this.startNodeAt(startPos, startLoc);\n node$1.callee = base;\n node$1.arguments = exprList;\n if (optionalSupported) {\n node$1.optional = optional;\n }\n base = this.finishNode(node$1, \"CallExpression\");\n } else if (this.type === types$1.backQuote) {\n if (optional || optionalChained) {\n this.raise(this.start, \"Optional chaining cannot appear in the tag of tagged template expressions\");\n }\n var node$2 = this.startNodeAt(startPos, startLoc);\n node$2.tag = base;\n node$2.quasi = this.parseTemplate({isTagged: true});\n base = this.finishNode(node$2, \"TaggedTemplateExpression\");\n }\n return base\n};\n\n// Parse an atomic expression \u2014 either a single token that is an\n// expression, an expression started by a keyword like `function` or\n// `new`, or an expression wrapped in punctuation like `()`, `[]`,\n// or `{}`.\n\npp$5.parseExprAtom = function(refDestructuringErrors, forInit, forNew) {\n // If a division operator appears in an expression position, the\n // tokenizer got confused, and we force it to read a regexp instead.\n if (this.type === types$1.slash) { this.readRegexp(); }\n\n var node, canBeArrow = this.potentialArrowAt === this.start;\n switch (this.type) {\n case types$1._super:\n if (!this.allowSuper)\n { this.raise(this.start, \"'super' keyword outside a method\"); }\n node = this.startNode();\n this.next();\n if (this.type === types$1.parenL && !this.allowDirectSuper)\n { this.raise(node.start, \"super() call outside constructor of a subclass\"); }\n // The `super` keyword can appear at below:\n // SuperProperty:\n // super [ Expression ]\n // super . IdentifierName\n // SuperCall:\n // super ( Arguments )\n if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL)\n { this.unexpected(); }\n return this.finishNode(node, \"Super\")\n\n case types$1._this:\n node = this.startNode();\n this.next();\n return this.finishNode(node, \"ThisExpression\")\n\n case types$1.name:\n var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;\n var id = this.parseIdent(false);\n if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === \"async\" && !this.canInsertSemicolon() && this.eat(types$1._function)) {\n this.overrideContext(types.f_expr);\n return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit)\n }\n if (canBeArrow && !this.canInsertSemicolon()) {\n if (this.eat(types$1.arrow))\n { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) }\n if (this.options.ecmaVersion >= 8 && id.name === \"async\" && this.type === types$1.name && !containsEsc &&\n (!this.potentialArrowInForAwait || this.value !== \"of\" || this.containsEsc)) {\n id = this.parseIdent(false);\n if (this.canInsertSemicolon() || !this.eat(types$1.arrow))\n { this.unexpected(); }\n return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit)\n }\n }\n return id\n\n case types$1.regexp:\n var value = this.value;\n node = this.parseLiteral(value.value);\n node.regex = {pattern: value.pattern, flags: value.flags};\n return node\n\n case types$1.num: case types$1.string:\n return this.parseLiteral(this.value)\n\n case types$1._null: case types$1._true: case types$1._false:\n node = this.startNode();\n node.value = this.type === types$1._null ? null : this.type === types$1._true;\n node.raw = this.type.keyword;\n this.next();\n return this.finishNode(node, \"Literal\")\n\n case types$1.parenL:\n var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit);\n if (refDestructuringErrors) {\n if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))\n { refDestructuringErrors.parenthesizedAssign = start; }\n if (refDestructuringErrors.parenthesizedBind < 0)\n { refDestructuringErrors.parenthesizedBind = start; }\n }\n return expr\n\n case types$1.bracketL:\n node = this.startNode();\n this.next();\n node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors);\n return this.finishNode(node, \"ArrayExpression\")\n\n case types$1.braceL:\n this.overrideContext(types.b_expr);\n return this.parseObj(false, refDestructuringErrors)\n\n case types$1._function:\n node = this.startNode();\n this.next();\n return this.parseFunction(node, 0)\n\n case types$1._class:\n return this.parseClass(this.startNode(), false)\n\n case types$1._new:\n return this.parseNew()\n\n case types$1.backQuote:\n return this.parseTemplate()\n\n case types$1._import:\n if (this.options.ecmaVersion >= 11) {\n return this.parseExprImport(forNew)\n } else {\n return this.unexpected()\n }\n\n default:\n return this.parseExprAtomDefault()\n }\n};\n\npp$5.parseExprAtomDefault = function() {\n this.unexpected();\n};\n\npp$5.parseExprImport = function(forNew) {\n var node = this.startNode();\n\n // Consume `import` as an identifier for `import.meta`.\n // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.\n if (this.containsEsc) { this.raiseRecoverable(this.start, \"Escape sequence in keyword import\"); }\n this.next();\n\n if (this.type === types$1.parenL && !forNew) {\n return this.parseDynamicImport(node)\n } else if (this.type === types$1.dot) {\n var meta = this.startNodeAt(node.start, node.loc && node.loc.start);\n meta.name = \"import\";\n node.meta = this.finishNode(meta, \"Identifier\");\n return this.parseImportMeta(node)\n } else {\n this.unexpected();\n }\n};\n\npp$5.parseDynamicImport = function(node) {\n this.next(); // skip `(`\n\n // Parse node.source.\n node.source = this.parseMaybeAssign();\n\n if (this.options.ecmaVersion >= 16) {\n if (!this.eat(types$1.parenR)) {\n this.expect(types$1.comma);\n if (!this.afterTrailingComma(types$1.parenR)) {\n node.options = this.parseMaybeAssign();\n if (!this.eat(types$1.parenR)) {\n this.expect(types$1.comma);\n if (!this.afterTrailingComma(types$1.parenR)) {\n this.unexpected();\n }\n }\n } else {\n node.options = null;\n }\n } else {\n node.options = null;\n }\n } else {\n // Verify ending.\n if (!this.eat(types$1.parenR)) {\n var errorPos = this.start;\n if (this.eat(types$1.comma) && this.eat(types$1.parenR)) {\n this.raiseRecoverable(errorPos, \"Trailing comma is not allowed in import()\");\n } else {\n this.unexpected(errorPos);\n }\n }\n }\n\n return this.finishNode(node, \"ImportExpression\")\n};\n\npp$5.parseImportMeta = function(node) {\n this.next(); // skip `.`\n\n var containsEsc = this.containsEsc;\n node.property = this.parseIdent(true);\n\n if (node.property.name !== \"meta\")\n { this.raiseRecoverable(node.property.start, \"The only valid meta property for import is 'import.meta'\"); }\n if (containsEsc)\n { this.raiseRecoverable(node.start, \"'import.meta' must not contain escaped characters\"); }\n if (this.options.sourceType !== \"module\" && !this.options.allowImportExportEverywhere)\n { this.raiseRecoverable(node.start, \"Cannot use 'import.meta' outside a module\"); }\n\n return this.finishNode(node, \"MetaProperty\")\n};\n\npp$5.parseLiteral = function(value) {\n var node = this.startNode();\n node.value = value;\n node.raw = this.input.slice(this.start, this.end);\n if (node.raw.charCodeAt(node.raw.length - 1) === 110)\n { node.bigint = node.value != null ? node.value.toString() : node.raw.slice(0, -1).replace(/_/g, \"\"); }\n this.next();\n return this.finishNode(node, \"Literal\")\n};\n\npp$5.parseParenExpression = function() {\n this.expect(types$1.parenL);\n var val = this.parseExpression();\n this.expect(types$1.parenR);\n return val\n};\n\npp$5.shouldParseArrow = function(exprList) {\n return !this.canInsertSemicolon()\n};\n\npp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) {\n var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;\n if (this.options.ecmaVersion >= 6) {\n this.next();\n\n var innerStartPos = this.start, innerStartLoc = this.startLoc;\n var exprList = [], first = true, lastIsComma = false;\n var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;\n this.yieldPos = 0;\n this.awaitPos = 0;\n // Do not save awaitIdentPos to allow checking awaits nested in parameters\n while (this.type !== types$1.parenR) {\n first ? first = false : this.expect(types$1.comma);\n if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) {\n lastIsComma = true;\n break\n } else if (this.type === types$1.ellipsis) {\n spreadStart = this.start;\n exprList.push(this.parseParenItem(this.parseRestBinding()));\n if (this.type === types$1.comma) {\n this.raiseRecoverable(\n this.start,\n \"Comma is not permitted after the rest element\"\n );\n }\n break\n } else {\n exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));\n }\n }\n var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc;\n this.expect(types$1.parenR);\n\n if (canBeArrow && this.shouldParseArrow(exprList) && this.eat(types$1.arrow)) {\n this.checkPatternErrors(refDestructuringErrors, false);\n this.checkYieldAwaitInDefaultParams();\n this.yieldPos = oldYieldPos;\n this.awaitPos = oldAwaitPos;\n return this.parseParenArrowList(startPos, startLoc, exprList, forInit)\n }\n\n if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }\n if (spreadStart) { this.unexpected(spreadStart); }\n this.checkExpressionErrors(refDestructuringErrors, true);\n this.yieldPos = oldYieldPos || this.yieldPos;\n this.awaitPos = oldAwaitPos || this.awaitPos;\n\n if (exprList.length > 1) {\n val = this.startNodeAt(innerStartPos, innerStartLoc);\n val.expressions = exprList;\n this.finishNodeAt(val, \"SequenceExpression\", innerEndPos, innerEndLoc);\n } else {\n val = exprList[0];\n }\n } else {\n val = this.parseParenExpression();\n }\n\n if (this.options.preserveParens) {\n var par = this.startNodeAt(startPos, startLoc);\n par.expression = val;\n return this.finishNode(par, \"ParenthesizedExpression\")\n } else {\n return val\n }\n};\n\npp$5.parseParenItem = function(item) {\n return item\n};\n\npp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) {\n return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit)\n};\n\n// New's precedence is slightly tricky. It must allow its argument to\n// be a `[]` or dot subscript expression, but not a call \u2014 at least,\n// not without wrapping it in parentheses. Thus, it uses the noCalls\n// argument to parseSubscripts to prevent it from consuming the\n// argument list.\n\nvar empty = [];\n\npp$5.parseNew = function() {\n if (this.containsEsc) { this.raiseRecoverable(this.start, \"Escape sequence in keyword new\"); }\n var node = this.startNode();\n this.next();\n if (this.options.ecmaVersion >= 6 && this.type === types$1.dot) {\n var meta = this.startNodeAt(node.start, node.loc && node.loc.start);\n meta.name = \"new\";\n node.meta = this.finishNode(meta, \"Identifier\");\n this.next();\n var containsEsc = this.containsEsc;\n node.property = this.parseIdent(true);\n if (node.property.name !== \"target\")\n { this.raiseRecoverable(node.property.start, \"The only valid meta property for new is 'new.target'\"); }\n if (containsEsc)\n { this.raiseRecoverable(node.start, \"'new.target' must not contain escaped characters\"); }\n if (!this.allowNewDotTarget)\n { this.raiseRecoverable(node.start, \"'new.target' can only be used in functions and class static block\"); }\n return this.finishNode(node, \"MetaProperty\")\n }\n var startPos = this.start, startLoc = this.startLoc;\n node.callee = this.parseSubscripts(this.parseExprAtom(null, false, true), startPos, startLoc, true, false);\n if (node.callee.type === \"Super\")\n { this.raiseRecoverable(startPos, \"Invalid use of 'super'\"); }\n if (this.eat(types$1.parenL)) { node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false); }\n else { node.arguments = empty; }\n return this.finishNode(node, \"NewExpression\")\n};\n\n// Parse template expression.\n\npp$5.parseTemplateElement = function(ref) {\n var isTagged = ref.isTagged;\n\n var elem = this.startNode();\n if (this.type === types$1.invalidTemplate) {\n if (!isTagged) {\n this.raiseRecoverable(this.start, \"Bad escape sequence in untagged template literal\");\n }\n elem.value = {\n raw: this.value.replace(/\\r\\n?/g, \"\\n\"),\n cooked: null\n };\n } else {\n elem.value = {\n raw: this.input.slice(this.start, this.end).replace(/\\r\\n?/g, \"\\n\"),\n cooked: this.value\n };\n }\n this.next();\n elem.tail = this.type === types$1.backQuote;\n return this.finishNode(elem, \"TemplateElement\")\n};\n\npp$5.parseTemplate = function(ref) {\n if ( ref === void 0 ) ref = {};\n var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;\n\n var node = this.startNode();\n this.next();\n node.expressions = [];\n var curElt = this.parseTemplateElement({isTagged: isTagged});\n node.quasis = [curElt];\n while (!curElt.tail) {\n if (this.type === types$1.eof) { this.raise(this.pos, \"Unterminated template literal\"); }\n this.expect(types$1.dollarBraceL);\n node.expressions.push(this.parseExpression());\n this.expect(types$1.braceR);\n node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));\n }\n this.next();\n return this.finishNode(node, \"TemplateLiteral\")\n};\n\npp$5.isAsyncProp = function(prop) {\n return !prop.computed && prop.key.type === \"Identifier\" && prop.key.name === \"async\" &&\n (this.type === types$1.name || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types$1.star)) &&\n !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))\n};\n\n// Parse an object literal or binding pattern.\n\npp$5.parseObj = function(isPattern, refDestructuringErrors) {\n var node = this.startNode(), first = true, propHash = {};\n node.properties = [];\n this.next();\n while (!this.eat(types$1.braceR)) {\n if (!first) {\n this.expect(types$1.comma);\n if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) { break }\n } else { first = false; }\n\n var prop = this.parseProperty(isPattern, refDestructuringErrors);\n if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }\n node.properties.push(prop);\n }\n return this.finishNode(node, isPattern ? \"ObjectPattern\" : \"ObjectExpression\")\n};\n\npp$5.parseProperty = function(isPattern, refDestructuringErrors) {\n var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;\n if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) {\n if (isPattern) {\n prop.argument = this.parseIdent(false);\n if (this.type === types$1.comma) {\n this.raiseRecoverable(this.start, \"Comma is not permitted after the rest element\");\n }\n return this.finishNode(prop, \"RestElement\")\n }\n // Parse argument.\n prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);\n // To disallow trailing comma via `this.toAssignable()`.\n if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {\n refDestructuringErrors.trailingComma = this.start;\n }\n // Finish\n return this.finishNode(prop, \"SpreadElement\")\n }\n if (this.options.ecmaVersion >= 6) {\n prop.method = false;\n prop.shorthand = false;\n if (isPattern || refDestructuringErrors) {\n startPos = this.start;\n startLoc = this.startLoc;\n }\n if (!isPattern)\n { isGenerator = this.eat(types$1.star); }\n }\n var containsEsc = this.containsEsc;\n this.parsePropertyName(prop);\n if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {\n isAsync = true;\n isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star);\n this.parsePropertyName(prop);\n } else {\n isAsync = false;\n }\n this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);\n return this.finishNode(prop, \"Property\")\n};\n\npp$5.parseGetterSetter = function(prop) {\n var kind = prop.key.name;\n this.parsePropertyName(prop);\n prop.value = this.parseMethod(false);\n prop.kind = kind;\n var paramCount = prop.kind === \"get\" ? 0 : 1;\n if (prop.value.params.length !== paramCount) {\n var start = prop.value.start;\n if (prop.kind === \"get\")\n { this.raiseRecoverable(start, \"getter should have no params\"); }\n else\n { this.raiseRecoverable(start, \"setter should have exactly one param\"); }\n } else {\n if (prop.kind === \"set\" && prop.value.params[0].type === \"RestElement\")\n { this.raiseRecoverable(prop.value.params[0].start, \"Setter cannot use rest params\"); }\n }\n};\n\npp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {\n if ((isGenerator || isAsync) && this.type === types$1.colon)\n { this.unexpected(); }\n\n if (this.eat(types$1.colon)) {\n prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);\n prop.kind = \"init\";\n } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) {\n if (isPattern) { this.unexpected(); }\n prop.method = true;\n prop.value = this.parseMethod(isGenerator, isAsync);\n prop.kind = \"init\";\n } else if (!isPattern && !containsEsc &&\n this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === \"Identifier\" &&\n (prop.key.name === \"get\" || prop.key.name === \"set\") &&\n (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) {\n if (isGenerator || isAsync) { this.unexpected(); }\n this.parseGetterSetter(prop);\n } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === \"Identifier\") {\n if (isGenerator || isAsync) { this.unexpected(); }\n this.checkUnreserved(prop.key);\n if (prop.key.name === \"await\" && !this.awaitIdentPos)\n { this.awaitIdentPos = startPos; }\n if (isPattern) {\n prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));\n } else if (this.type === types$1.eq && refDestructuringErrors) {\n if (refDestructuringErrors.shorthandAssign < 0)\n { refDestructuringErrors.shorthandAssign = this.start; }\n prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));\n } else {\n prop.value = this.copyNode(prop.key);\n }\n prop.kind = \"init\";\n prop.shorthand = true;\n } else { this.unexpected(); }\n};\n\npp$5.parsePropertyName = function(prop) {\n if (this.options.ecmaVersion >= 6) {\n if (this.eat(types$1.bracketL)) {\n prop.computed = true;\n prop.key = this.parseMaybeAssign();\n this.expect(types$1.bracketR);\n return prop.key\n } else {\n prop.computed = false;\n }\n }\n return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== \"never\")\n};\n\n// Initialize empty function node.\n\npp$5.initFunction = function(node) {\n node.id = null;\n if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }\n if (this.options.ecmaVersion >= 8) { node.async = false; }\n};\n\n// Parse object or class method.\n\npp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {\n var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;\n\n this.initFunction(node);\n if (this.options.ecmaVersion >= 6)\n { node.generator = isGenerator; }\n if (this.options.ecmaVersion >= 8)\n { node.async = !!isAsync; }\n\n this.yieldPos = 0;\n this.awaitPos = 0;\n this.awaitIdentPos = 0;\n this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));\n\n this.expect(types$1.parenL);\n node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);\n this.checkYieldAwaitInDefaultParams();\n this.parseFunctionBody(node, false, true, false);\n\n this.yieldPos = oldYieldPos;\n this.awaitPos = oldAwaitPos;\n this.awaitIdentPos = oldAwaitIdentPos;\n return this.finishNode(node, \"FunctionExpression\")\n};\n\n// Parse arrow function expression with given parameters.\n\npp$5.parseArrowExpression = function(node, params, isAsync, forInit) {\n var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;\n\n this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);\n this.initFunction(node);\n if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }\n\n this.yieldPos = 0;\n this.awaitPos = 0;\n this.awaitIdentPos = 0;\n\n node.params = this.toAssignableList(params, true);\n this.parseFunctionBody(node, true, false, forInit);\n\n this.yieldPos = oldYieldPos;\n this.awaitPos = oldAwaitPos;\n this.awaitIdentPos = oldAwaitIdentPos;\n return this.finishNode(node, \"ArrowFunctionExpression\")\n};\n\n// Parse function body and check parameters.\n\npp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) {\n var isExpression = isArrowFunction && this.type !== types$1.braceL;\n var oldStrict = this.strict, useStrict = false;\n\n if (isExpression) {\n node.body = this.parseMaybeAssign(forInit);\n node.expression = true;\n this.checkParams(node, false);\n } else {\n var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);\n if (!oldStrict || nonSimple) {\n useStrict = this.strictDirective(this.end);\n // If this is a strict mode function, verify that argument names\n // are not repeated, and it does not try to bind the words `eval`\n // or `arguments`.\n if (useStrict && nonSimple)\n { this.raiseRecoverable(node.start, \"Illegal 'use strict' directive in function with non-simple parameter list\"); }\n }\n // Start a new scope with regard to labels and the `inFunction`\n // flag (restore them to their old value afterwards).\n var oldLabels = this.labels;\n this.labels = [];\n if (useStrict) { this.strict = true; }\n\n // Add the params to varDeclaredNames to ensure that an error is thrown\n // if a let/const declaration in the function clashes with one of the params.\n this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));\n // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'\n if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); }\n node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);\n node.expression = false;\n this.adaptDirectivePrologue(node.body.body);\n this.labels = oldLabels;\n }\n this.exitScope();\n};\n\npp$5.isSimpleParamList = function(params) {\n for (var i = 0, list = params; i < list.length; i += 1)\n {\n var param = list[i];\n\n if (param.type !== \"Identifier\") { return false\n } }\n return true\n};\n\n// Checks function params for various disallowed patterns such as using \"eval\"\n// or \"arguments\" and duplicate parameters.\n\npp$5.checkParams = function(node, allowDuplicates) {\n var nameHash = Object.create(null);\n for (var i = 0, list = node.params; i < list.length; i += 1)\n {\n var param = list[i];\n\n this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);\n }\n};\n\n// Parses a comma-separated list of expressions, and returns them as\n// an array. `close` is the token type that ends the list, and\n// `allowEmpty` can be turned on to allow subsequent commas with\n// nothing in between them to be parsed as `null` (which is needed\n// for array literals).\n\npp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {\n var elts = [], first = true;\n while (!this.eat(close)) {\n if (!first) {\n this.expect(types$1.comma);\n if (allowTrailingComma && this.afterTrailingComma(close)) { break }\n } else { first = false; }\n\n var elt = (void 0);\n if (allowEmpty && this.type === types$1.comma)\n { elt = null; }\n else if (this.type === types$1.ellipsis) {\n elt = this.parseSpread(refDestructuringErrors);\n if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0)\n { refDestructuringErrors.trailingComma = this.start; }\n } else {\n elt = this.parseMaybeAssign(false, refDestructuringErrors);\n }\n elts.push(elt);\n }\n return elts\n};\n\npp$5.checkUnreserved = function(ref) {\n var start = ref.start;\n var end = ref.end;\n var name = ref.name;\n\n if (this.inGenerator && name === \"yield\")\n { this.raiseRecoverable(start, \"Cannot use 'yield' as identifier inside a generator\"); }\n if (this.inAsync && name === \"await\")\n { this.raiseRecoverable(start, \"Cannot use 'await' as identifier inside an async function\"); }\n if (!(this.currentThisScope().flags & SCOPE_VAR) && name === \"arguments\")\n { this.raiseRecoverable(start, \"Cannot use 'arguments' in class field initializer\"); }\n if (this.inClassStaticBlock && (name === \"arguments\" || name === \"await\"))\n { this.raise(start, (\"Cannot use \" + name + \" in class static initialization block\")); }\n if (this.keywords.test(name))\n { this.raise(start, (\"Unexpected keyword '\" + name + \"'\")); }\n if (this.options.ecmaVersion < 6 &&\n this.input.slice(start, end).indexOf(\"\\\\\") !== -1) { return }\n var re = this.strict ? this.reservedWordsStrict : this.reservedWords;\n if (re.test(name)) {\n if (!this.inAsync && name === \"await\")\n { this.raiseRecoverable(start, \"Cannot use keyword 'await' outside an async function\"); }\n this.raiseRecoverable(start, (\"The keyword '\" + name + \"' is reserved\"));\n }\n};\n\n// Parse the next token as an identifier. If `liberal` is true (used\n// when parsing properties), it will also convert keywords into\n// identifiers.\n\npp$5.parseIdent = function(liberal) {\n var node = this.parseIdentNode();\n this.next(!!liberal);\n this.finishNode(node, \"Identifier\");\n if (!liberal) {\n this.checkUnreserved(node);\n if (node.name === \"await\" && !this.awaitIdentPos)\n { this.awaitIdentPos = node.start; }\n }\n return node\n};\n\npp$5.parseIdentNode = function() {\n var node = this.startNode();\n if (this.type === types$1.name) {\n node.name = this.value;\n } else if (this.type.keyword) {\n node.name = this.type.keyword;\n\n // To fix https://github.com/acornjs/acorn/issues/575\n // `class` and `function` keywords push new context into this.context.\n // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.\n // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword\n if ((node.name === \"class\" || node.name === \"function\") &&\n (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {\n this.context.pop();\n }\n this.type = types$1.name;\n } else {\n this.unexpected();\n }\n return node\n};\n\npp$5.parsePrivateIdent = function() {\n var node = this.startNode();\n if (this.type === types$1.privateId) {\n node.name = this.value;\n } else {\n this.unexpected();\n }\n this.next();\n this.finishNode(node, \"PrivateIdentifier\");\n\n // For validating existence\n if (this.options.checkPrivateFields) {\n if (this.privateNameStack.length === 0) {\n this.raise(node.start, (\"Private field '#\" + (node.name) + \"' must be declared in an enclosing class\"));\n } else {\n this.privateNameStack[this.privateNameStack.length - 1].used.push(node);\n }\n }\n\n return node\n};\n\n// Parses yield expression inside generator.\n\npp$5.parseYield = function(forInit) {\n if (!this.yieldPos) { this.yieldPos = this.start; }\n\n var node = this.startNode();\n this.next();\n if (this.type === types$1.semi || this.canInsertSemicolon() || (this.type !== types$1.star && !this.type.startsExpr)) {\n node.delegate = false;\n node.argument = null;\n } else {\n node.delegate = this.eat(types$1.star);\n node.argument = this.parseMaybeAssign(forInit);\n }\n return this.finishNode(node, \"YieldExpression\")\n};\n\npp$5.parseAwait = function(forInit) {\n if (!this.awaitPos) { this.awaitPos = this.start; }\n\n var node = this.startNode();\n this.next();\n node.argument = this.parseMaybeUnary(null, true, false, forInit);\n return this.finishNode(node, \"AwaitExpression\")\n};\n\nvar pp$4 = Parser.prototype;\n\n// This function is used to raise exceptions on parse errors. It\n// takes an offset integer (into the current `input`) to indicate\n// the location of the error, attaches the position to the end\n// of the error message, and then raises a `SyntaxError` with that\n// message.\n\npp$4.raise = function(pos, message) {\n var loc = getLineInfo(this.input, pos);\n message += \" (\" + loc.line + \":\" + loc.column + \")\";\n if (this.sourceFile) {\n message += \" in \" + this.sourceFile;\n }\n var err = new SyntaxError(message);\n err.pos = pos; err.loc = loc; err.raisedAt = this.pos;\n throw err\n};\n\npp$4.raiseRecoverable = pp$4.raise;\n\npp$4.curPosition = function() {\n if (this.options.locations) {\n return new Position(this.curLine, this.pos - this.lineStart)\n }\n};\n\nvar pp$3 = Parser.prototype;\n\nvar Scope = function Scope(flags) {\n this.flags = flags;\n // A list of var-declared names in the current lexical scope\n this.var = [];\n // A list of lexically-declared names in the current lexical scope\n this.lexical = [];\n // A list of lexically-declared FunctionDeclaration names in the current lexical scope\n this.functions = [];\n};\n\n// The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.\n\npp$3.enterScope = function(flags) {\n this.scopeStack.push(new Scope(flags));\n};\n\npp$3.exitScope = function() {\n this.scopeStack.pop();\n};\n\n// The spec says:\n// > At the top level of a function, or script, function declarations are\n// > treated like var declarations rather than like lexical declarations.\npp$3.treatFunctionsAsVarInScope = function(scope) {\n return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)\n};\n\npp$3.declareName = function(name, bindingType, pos) {\n var redeclared = false;\n if (bindingType === BIND_LEXICAL) {\n var scope = this.currentScope();\n redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;\n scope.lexical.push(name);\n if (this.inModule && (scope.flags & SCOPE_TOP))\n { delete this.undefinedExports[name]; }\n } else if (bindingType === BIND_SIMPLE_CATCH) {\n var scope$1 = this.currentScope();\n scope$1.lexical.push(name);\n } else if (bindingType === BIND_FUNCTION) {\n var scope$2 = this.currentScope();\n if (this.treatFunctionsAsVar)\n { redeclared = scope$2.lexical.indexOf(name) > -1; }\n else\n { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }\n scope$2.functions.push(name);\n } else {\n for (var i = this.scopeStack.length - 1; i >= 0; --i) {\n var scope$3 = this.scopeStack[i];\n if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||\n !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {\n redeclared = true;\n break\n }\n scope$3.var.push(name);\n if (this.inModule && (scope$3.flags & SCOPE_TOP))\n { delete this.undefinedExports[name]; }\n if (scope$3.flags & SCOPE_VAR) { break }\n }\n }\n if (redeclared) { this.raiseRecoverable(pos, (\"Identifier '\" + name + \"' has already been declared\")); }\n};\n\npp$3.checkLocalExport = function(id) {\n // scope.functions must be empty as Module code is always strict.\n if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&\n this.scopeStack[0].var.indexOf(id.name) === -1) {\n this.undefinedExports[id.name] = id;\n }\n};\n\npp$3.currentScope = function() {\n return this.scopeStack[this.scopeStack.length - 1]\n};\n\npp$3.currentVarScope = function() {\n for (var i = this.scopeStack.length - 1;; i--) {\n var scope = this.scopeStack[i];\n if (scope.flags & (SCOPE_VAR | SCOPE_CLASS_FIELD_INIT | SCOPE_CLASS_STATIC_BLOCK)) { return scope }\n }\n};\n\n// Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.\npp$3.currentThisScope = function() {\n for (var i = this.scopeStack.length - 1;; i--) {\n var scope = this.scopeStack[i];\n if (scope.flags & (SCOPE_VAR | SCOPE_CLASS_FIELD_INIT | SCOPE_CLASS_STATIC_BLOCK) &&\n !(scope.flags & SCOPE_ARROW)) { return scope }\n }\n};\n\nvar Node = function Node(parser, pos, loc) {\n this.type = \"\";\n this.start = pos;\n this.end = 0;\n if (parser.options.locations)\n { this.loc = new SourceLocation(parser, loc); }\n if (parser.options.directSourceFile)\n { this.sourceFile = parser.options.directSourceFile; }\n if (parser.options.ranges)\n { this.range = [pos, 0]; }\n};\n\n// Start an AST node, attaching a start offset.\n\nvar pp$2 = Parser.prototype;\n\npp$2.startNode = function() {\n return new Node(this, this.start, this.startLoc)\n};\n\npp$2.startNodeAt = function(pos, loc) {\n return new Node(this, pos, loc)\n};\n\n// Finish an AST node, adding `type` and `end` properties.\n\nfunction finishNodeAt(node, type, pos, loc) {\n node.type = type;\n node.end = pos;\n if (this.options.locations)\n { node.loc.end = loc; }\n if (this.options.ranges)\n { node.range[1] = pos; }\n return node\n}\n\npp$2.finishNode = function(node, type) {\n return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)\n};\n\n// Finish node at given position\n\npp$2.finishNodeAt = function(node, type, pos, loc) {\n return finishNodeAt.call(this, node, type, pos, loc)\n};\n\npp$2.copyNode = function(node) {\n var newNode = new Node(this, node.start, this.startLoc);\n for (var prop in node) { newNode[prop] = node[prop]; }\n return newNode\n};\n\n// This file was generated by \"bin/generate-unicode-script-values.js\". Do not modify manually!\nvar scriptValuesAddedInUnicode = \"Berf Beria_Erfe Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sidetic Sidt Sunu Sunuwar Tai_Yo Tayo Todhri Todr Tolong_Siki Tols Tulu_Tigalari Tutg Unknown Zzzz\";\n\n// This file contains Unicode properties extracted from the ECMAScript specification.\n// The lists are extracted like so:\n// $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)\n\n// #table-binary-unicode-properties\nvar ecma9BinaryProperties = \"ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS\";\nvar ecma10BinaryProperties = ecma9BinaryProperties + \" Extended_Pictographic\";\nvar ecma11BinaryProperties = ecma10BinaryProperties;\nvar ecma12BinaryProperties = ecma11BinaryProperties + \" EBase EComp EMod EPres ExtPict\";\nvar ecma13BinaryProperties = ecma12BinaryProperties;\nvar ecma14BinaryProperties = ecma13BinaryProperties;\n\nvar unicodeBinaryProperties = {\n 9: ecma9BinaryProperties,\n 10: ecma10BinaryProperties,\n 11: ecma11BinaryProperties,\n 12: ecma12BinaryProperties,\n 13: ecma13BinaryProperties,\n 14: ecma14BinaryProperties\n};\n\n// #table-binary-unicode-properties-of-strings\nvar ecma14BinaryPropertiesOfStrings = \"Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji\";\n\nvar unicodeBinaryPropertiesOfStrings = {\n 9: \"\",\n 10: \"\",\n 11: \"\",\n 12: \"\",\n 13: \"\",\n 14: ecma14BinaryPropertiesOfStrings\n};\n\n// #table-unicode-general-category-values\nvar unicodeGeneralCategoryValues = \"Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu\";\n\n// #table-unicode-script-values\nvar ecma9ScriptValues = \"Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb\";\nvar ecma10ScriptValues = ecma9ScriptValues + \" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd\";\nvar ecma11ScriptValues = ecma10ScriptValues + \" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho\";\nvar ecma12ScriptValues = ecma11ScriptValues + \" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi\";\nvar ecma13ScriptValues = ecma12ScriptValues + \" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith\";\nvar ecma14ScriptValues = ecma13ScriptValues + \" \" + scriptValuesAddedInUnicode;\n\nvar unicodeScriptValues = {\n 9: ecma9ScriptValues,\n 10: ecma10ScriptValues,\n 11: ecma11ScriptValues,\n 12: ecma12ScriptValues,\n 13: ecma13ScriptValues,\n 14: ecma14ScriptValues\n};\n\nvar data = {};\nfunction buildUnicodeData(ecmaVersion) {\n var d = data[ecmaVersion] = {\n binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + \" \" + unicodeGeneralCategoryValues),\n binaryOfStrings: wordsRegexp(unicodeBinaryPropertiesOfStrings[ecmaVersion]),\n nonBinary: {\n General_Category: wordsRegexp(unicodeGeneralCategoryValues),\n Script: wordsRegexp(unicodeScriptValues[ecmaVersion])\n }\n };\n d.nonBinary.Script_Extensions = d.nonBinary.Script;\n\n d.nonBinary.gc = d.nonBinary.General_Category;\n d.nonBinary.sc = d.nonBinary.Script;\n d.nonBinary.scx = d.nonBinary.Script_Extensions;\n}\n\nfor (var i = 0, list = [9, 10, 11, 12, 13, 14]; i < list.length; i += 1) {\n var ecmaVersion = list[i];\n\n buildUnicodeData(ecmaVersion);\n}\n\nvar pp$1 = Parser.prototype;\n\n// Track disjunction structure to determine whether a duplicate\n// capture group name is allowed because it is in a separate branch.\nvar BranchID = function BranchID(parent, base) {\n // Parent disjunction branch\n this.parent = parent;\n // Identifies this set of sibling branches\n this.base = base || this;\n};\n\nBranchID.prototype.separatedFrom = function separatedFrom (alt) {\n // A branch is separate from another branch if they or any of\n // their parents are siblings in a given disjunction\n for (var self = this; self; self = self.parent) {\n for (var other = alt; other; other = other.parent) {\n if (self.base === other.base && self !== other) { return true }\n }\n }\n return false\n};\n\nBranchID.prototype.sibling = function sibling () {\n return new BranchID(this.parent, this.base)\n};\n\nvar RegExpValidationState = function RegExpValidationState(parser) {\n this.parser = parser;\n this.validFlags = \"gim\" + (parser.options.ecmaVersion >= 6 ? \"uy\" : \"\") + (parser.options.ecmaVersion >= 9 ? \"s\" : \"\") + (parser.options.ecmaVersion >= 13 ? \"d\" : \"\") + (parser.options.ecmaVersion >= 15 ? \"v\" : \"\");\n this.unicodeProperties = data[parser.options.ecmaVersion >= 14 ? 14 : parser.options.ecmaVersion];\n this.source = \"\";\n this.flags = \"\";\n this.start = 0;\n this.switchU = false;\n this.switchV = false;\n this.switchN = false;\n this.pos = 0;\n this.lastIntValue = 0;\n this.lastStringValue = \"\";\n this.lastAssertionIsQuantifiable = false;\n this.numCapturingParens = 0;\n this.maxBackReference = 0;\n this.groupNames = Object.create(null);\n this.backReferenceNames = [];\n this.branchID = null;\n};\n\nRegExpValidationState.prototype.reset = function reset (start, pattern, flags) {\n var unicodeSets = flags.indexOf(\"v\") !== -1;\n var unicode = flags.indexOf(\"u\") !== -1;\n this.start = start | 0;\n this.source = pattern + \"\";\n this.flags = flags;\n if (unicodeSets && this.parser.options.ecmaVersion >= 15) {\n this.switchU = true;\n this.switchV = true;\n this.switchN = true;\n } else {\n this.switchU = unicode && this.parser.options.ecmaVersion >= 6;\n this.switchV = false;\n this.switchN = unicode && this.parser.options.ecmaVersion >= 9;\n }\n};\n\nRegExpValidationState.prototype.raise = function raise (message) {\n this.parser.raiseRecoverable(this.start, (\"Invalid regular expression: /\" + (this.source) + \"/: \" + message));\n};\n\n// If u flag is given, this returns the code point at the index (it combines a surrogate pair).\n// Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).\nRegExpValidationState.prototype.at = function at (i, forceU) {\n if ( forceU === void 0 ) forceU = false;\n\n var s = this.source;\n var l = s.length;\n if (i >= l) {\n return -1\n }\n var c = s.charCodeAt(i);\n if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {\n return c\n }\n var next = s.charCodeAt(i + 1);\n return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c\n};\n\nRegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {\n if ( forceU === void 0 ) forceU = false;\n\n var s = this.source;\n var l = s.length;\n if (i >= l) {\n return l\n }\n var c = s.charCodeAt(i), next;\n if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||\n (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {\n return i + 1\n }\n return i + 2\n};\n\nRegExpValidationState.prototype.current = function current (forceU) {\n if ( forceU === void 0 ) forceU = false;\n\n return this.at(this.pos, forceU)\n};\n\nRegExpValidationState.prototype.lookahead = function lookahead (forceU) {\n if ( forceU === void 0 ) forceU = false;\n\n return this.at(this.nextIndex(this.pos, forceU), forceU)\n};\n\nRegExpValidationState.prototype.advance = function advance (forceU) {\n if ( forceU === void 0 ) forceU = false;\n\n this.pos = this.nextIndex(this.pos, forceU);\n};\n\nRegExpValidationState.prototype.eat = function eat (ch, forceU) {\n if ( forceU === void 0 ) forceU = false;\n\n if (this.current(forceU) === ch) {\n this.advance(forceU);\n return true\n }\n return false\n};\n\nRegExpValidationState.prototype.eatChars = function eatChars (chs, forceU) {\n if ( forceU === void 0 ) forceU = false;\n\n var pos = this.pos;\n for (var i = 0, list = chs; i < list.length; i += 1) {\n var ch = list[i];\n\n var current = this.at(pos, forceU);\n if (current === -1 || current !== ch) {\n return false\n }\n pos = this.nextIndex(pos, forceU);\n }\n this.pos = pos;\n return true\n};\n\n/**\n * Validate the flags part of a given RegExpLiteral.\n *\n * @param {RegExpValidationState} state The state to validate RegExp.\n * @returns {void}\n */\npp$1.validateRegExpFlags = function(state) {\n var validFlags = state.validFlags;\n var flags = state.flags;\n\n var u = false;\n var v = false;\n\n for (var i = 0; i < flags.length; i++) {\n var flag = flags.charAt(i);\n if (validFlags.indexOf(flag) === -1) {\n this.raise(state.start, \"Invalid regular expression flag\");\n }\n if (flags.indexOf(flag, i + 1) > -1) {\n this.raise(state.start, \"Duplicate regular expression flag\");\n }\n if (flag === \"u\") { u = true; }\n if (flag === \"v\") { v = true; }\n }\n if (this.options.ecmaVersion >= 15 && u && v) {\n this.raise(state.start, \"Invalid regular expression flag\");\n }\n};\n\nfunction hasProp(obj) {\n for (var _ in obj) { return true }\n return false\n}\n\n/**\n * Validate the pattern part of a given RegExpLiteral.\n *\n * @param {RegExpValidationState} state The state to validate RegExp.\n * @returns {void}\n */\npp$1.validateRegExpPattern = function(state) {\n this.regexp_pattern(state);\n\n // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of\n // parsing contains a |GroupName|, reparse with the goal symbol\n // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*\n // exception if _P_ did not conform to the grammar, if any elements of _P_\n // were not matched by the parse, or if any Early Error conditions exist.\n if (!state.switchN && this.options.ecmaVersion >= 9 && hasProp(state.groupNames)) {\n state.switchN = true;\n this.regexp_pattern(state);\n }\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern\npp$1.regexp_pattern = function(state) {\n state.pos = 0;\n state.lastIntValue = 0;\n state.lastStringValue = \"\";\n state.lastAssertionIsQuantifiable = false;\n state.numCapturingParens = 0;\n state.maxBackReference = 0;\n state.groupNames = Object.create(null);\n state.backReferenceNames.length = 0;\n state.branchID = null;\n\n this.regexp_disjunction(state);\n\n if (state.pos !== state.source.length) {\n // Make the same messages as V8.\n if (state.eat(0x29 /* ) */)) {\n state.raise(\"Unmatched ')'\");\n }\n if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {\n state.raise(\"Lone quantifier brackets\");\n }\n }\n if (state.maxBackReference > state.numCapturingParens) {\n state.raise(\"Invalid escape\");\n }\n for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {\n var name = list[i];\n\n if (!state.groupNames[name]) {\n state.raise(\"Invalid named capture referenced\");\n }\n }\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction\npp$1.regexp_disjunction = function(state) {\n var trackDisjunction = this.options.ecmaVersion >= 16;\n if (trackDisjunction) { state.branchID = new BranchID(state.branchID, null); }\n this.regexp_alternative(state);\n while (state.eat(0x7C /* | */)) {\n if (trackDisjunction) { state.branchID = state.branchID.sibling(); }\n this.regexp_alternative(state);\n }\n if (trackDisjunction) { state.branchID = state.branchID.parent; }\n\n // Make the same message as V8.\n if (this.regexp_eatQuantifier(state, true)) {\n state.raise(\"Nothing to repeat\");\n }\n if (state.eat(0x7B /* { */)) {\n state.raise(\"Lone quantifier brackets\");\n }\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative\npp$1.regexp_alternative = function(state) {\n while (state.pos < state.source.length && this.regexp_eatTerm(state)) {}\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term\npp$1.regexp_eatTerm = function(state) {\n if (this.regexp_eatAssertion(state)) {\n // Handle `QuantifiableAssertion Quantifier` alternative.\n // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion\n // is a QuantifiableAssertion.\n if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {\n // Make the same message as V8.\n if (state.switchU) {\n state.raise(\"Invalid quantifier\");\n }\n }\n return true\n }\n\n if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {\n this.regexp_eatQuantifier(state);\n return true\n }\n\n return false\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion\npp$1.regexp_eatAssertion = function(state) {\n var start = state.pos;\n state.lastAssertionIsQuantifiable = false;\n\n // ^, $\n if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {\n return true\n }\n\n // \\b \\B\n if (state.eat(0x5C /* \\ */)) {\n if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {\n return true\n }\n state.pos = start;\n }\n\n // Lookahead / Lookbehind\n if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {\n var lookbehind = false;\n if (this.options.ecmaVersion >= 9) {\n lookbehind = state.eat(0x3C /* < */);\n }\n if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {\n this.regexp_disjunction(state);\n if (!state.eat(0x29 /* ) */)) {\n state.raise(\"Unterminated group\");\n }\n state.lastAssertionIsQuantifiable = !lookbehind;\n return true\n }\n }\n\n state.pos = start;\n return false\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier\npp$1.regexp_eatQuantifier = function(state, noError) {\n if ( noError === void 0 ) noError = false;\n\n if (this.regexp_eatQuantifierPrefix(state, noError)) {\n state.eat(0x3F /* ? */);\n return true\n }\n return false\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix\npp$1.regexp_eatQuantifierPrefix = function(state, noError) {\n return (\n state.eat(0x2A /* * */) ||\n state.eat(0x2B /* + */) ||\n state.eat(0x3F /* ? */) ||\n this.regexp_eatBracedQuantifier(state, noError)\n )\n};\npp$1.regexp_eatBracedQuantifier = function(state, noError) {\n var start = state.pos;\n if (state.eat(0x7B /* { */)) {\n var min = 0, max = -1;\n if (this.regexp_eatDecimalDigits(state)) {\n min = state.lastIntValue;\n if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {\n max = state.lastIntValue;\n }\n if (state.eat(0x7D /* } */)) {\n // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term\n if (max !== -1 && max < min && !noError) {\n state.raise(\"numbers out of order in {} quantifier\");\n }\n return true\n }\n }\n if (state.switchU && !noError) {\n state.raise(\"Incomplete quantifier\");\n }\n state.pos = start;\n }\n return false\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-Atom\npp$1.regexp_eatAtom = function(state) {\n return (\n this.regexp_eatPatternCharacters(state) ||\n state.eat(0x2E /* . */) ||\n this.regexp_eatReverseSolidusAtomEscape(state) ||\n this.regexp_eatCharacterClass(state) ||\n this.regexp_eatUncapturingGroup(state) ||\n this.regexp_eatCapturingGroup(state)\n )\n};\npp$1.regexp_eatReverseSolidusAtomEscape = function(state) {\n var start = state.pos;\n if (state.eat(0x5C /* \\ */)) {\n if (this.regexp_eatAtomEscape(state)) {\n return true\n }\n state.pos = start;\n }\n return false\n};\npp$1.regexp_eatUncapturingGroup = function(state) {\n var start = state.pos;\n if (state.eat(0x28 /* ( */)) {\n if (state.eat(0x3F /* ? */)) {\n if (this.options.ecmaVersion >= 16) {\n var addModifiers = this.regexp_eatModifiers(state);\n var hasHyphen = state.eat(0x2D /* - */);\n if (addModifiers || hasHyphen) {\n for (var i = 0; i < addModifiers.length; i++) {\n var modifier = addModifiers.charAt(i);\n if (addModifiers.indexOf(modifier, i + 1) > -1) {\n state.raise(\"Duplicate regular expression modifiers\");\n }\n }\n if (hasHyphen) {\n var removeModifiers = this.regexp_eatModifiers(state);\n if (!addModifiers && !removeModifiers && state.current() === 0x3A /* : */) {\n state.raise(\"Invalid regular expression modifiers\");\n }\n for (var i$1 = 0; i$1 < removeModifiers.length; i$1++) {\n var modifier$1 = removeModifiers.charAt(i$1);\n if (\n removeModifiers.indexOf(modifier$1, i$1 + 1) > -1 ||\n addModifiers.indexOf(modifier$1) > -1\n ) {\n state.raise(\"Duplicate regular expression modifiers\");\n }\n }\n }\n }\n }\n if (state.eat(0x3A /* : */)) {\n this.regexp_disjunction(state);\n if (state.eat(0x29 /* ) */)) {\n return true\n }\n state.raise(\"Unterminated group\");\n }\n }\n state.pos = start;\n }\n return false\n};\npp$1.regexp_eatCapturingGroup = function(state) {\n if (state.eat(0x28 /* ( */)) {\n if (this.options.ecmaVersion >= 9) {\n this.regexp_groupSpecifier(state);\n } else if (state.current() === 0x3F /* ? */) {\n state.raise(\"Invalid group\");\n }\n this.regexp_disjunction(state);\n if (state.eat(0x29 /* ) */)) {\n state.numCapturingParens += 1;\n return true\n }\n state.raise(\"Unterminated group\");\n }\n return false\n};\n// RegularExpressionModifiers ::\n// [empty]\n// RegularExpressionModifiers RegularExpressionModifier\npp$1.regexp_eatModifiers = function(state) {\n var modifiers = \"\";\n var ch = 0;\n while ((ch = state.current()) !== -1 && isRegularExpressionModifier(ch)) {\n modifiers += codePointToString(ch);\n state.advance();\n }\n return modifiers\n};\n// RegularExpressionModifier :: one of\n// `i` `m` `s`\nfunction isRegularExpressionModifier(ch) {\n return ch === 0x69 /* i */ || ch === 0x6d /* m */ || ch === 0x73 /* s */\n}\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom\npp$1.regexp_eatExtendedAtom = function(state) {\n return (\n state.eat(0x2E /* . */) ||\n this.regexp_eatReverseSolidusAtomEscape(state) ||\n this.regexp_eatCharacterClass(state) ||\n this.regexp_eatUncapturingGroup(state) ||\n this.regexp_eatCapturingGroup(state) ||\n this.regexp_eatInvalidBracedQuantifier(state) ||\n this.regexp_eatExtendedPatternCharacter(state)\n )\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier\npp$1.regexp_eatInvalidBracedQuantifier = function(state) {\n if (this.regexp_eatBracedQuantifier(state, true)) {\n state.raise(\"Nothing to repeat\");\n }\n return false\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter\npp$1.regexp_eatSyntaxCharacter = function(state) {\n var ch = state.current();\n if (isSyntaxCharacter(ch)) {\n state.lastIntValue = ch;\n state.advance();\n return true\n }\n return false\n};\nfunction isSyntaxCharacter(ch) {\n return (\n ch === 0x24 /* $ */ ||\n ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||\n ch === 0x2E /* . */ ||\n ch === 0x3F /* ? */ ||\n ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||\n ch >= 0x7B /* { */ && ch <= 0x7D /* } */\n )\n}\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter\n// But eat eager.\npp$1.regexp_eatPatternCharacters = function(state) {\n var start = state.pos;\n var ch = 0;\n while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {\n state.advance();\n }\n return state.pos !== start\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter\npp$1.regexp_eatExtendedPatternCharacter = function(state) {\n var ch = state.current();\n if (\n ch !== -1 &&\n ch !== 0x24 /* $ */ &&\n !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&\n ch !== 0x2E /* . */ &&\n ch !== 0x3F /* ? */ &&\n ch !== 0x5B /* [ */ &&\n ch !== 0x5E /* ^ */ &&\n ch !== 0x7C /* | */\n ) {\n state.advance();\n return true\n }\n return false\n};\n\n// GroupSpecifier ::\n// [empty]\n// `?` GroupName\npp$1.regexp_groupSpecifier = function(state) {\n if (state.eat(0x3F /* ? */)) {\n if (!this.regexp_eatGroupName(state)) { state.raise(\"Invalid group\"); }\n var trackDisjunction = this.options.ecmaVersion >= 16;\n var known = state.groupNames[state.lastStringValue];\n if (known) {\n if (trackDisjunction) {\n for (var i = 0, list = known; i < list.length; i += 1) {\n var altID = list[i];\n\n if (!altID.separatedFrom(state.branchID))\n { state.raise(\"Duplicate capture group name\"); }\n }\n } else {\n state.raise(\"Duplicate capture group name\");\n }\n }\n if (trackDisjunction) {\n (known || (state.groupNames[state.lastStringValue] = [])).push(state.branchID);\n } else {\n state.groupNames[state.lastStringValue] = true;\n }\n }\n};\n\n// GroupName ::\n// `<` RegExpIdentifierName `>`\n// Note: this updates `state.lastStringValue` property with the eaten name.\npp$1.regexp_eatGroupName = function(state) {\n state.lastStringValue = \"\";\n if (state.eat(0x3C /* < */)) {\n if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {\n return true\n }\n state.raise(\"Invalid capture group name\");\n }\n return false\n};\n\n// RegExpIdentifierName ::\n// RegExpIdentifierStart\n// RegExpIdentifierName RegExpIdentifierPart\n// Note: this updates `state.lastStringValue` property with the eaten name.\npp$1.regexp_eatRegExpIdentifierName = function(state) {\n state.lastStringValue = \"\";\n if (this.regexp_eatRegExpIdentifierStart(state)) {\n state.lastStringValue += codePointToString(state.lastIntValue);\n while (this.regexp_eatRegExpIdentifierPart(state)) {\n state.lastStringValue += codePointToString(state.lastIntValue);\n }\n return true\n }\n return false\n};\n\n// RegExpIdentifierStart ::\n// UnicodeIDStart\n// `$`\n// `_`\n// `\\` RegExpUnicodeEscapeSequence[+U]\npp$1.regexp_eatRegExpIdentifierStart = function(state) {\n var start = state.pos;\n var forceU = this.options.ecmaVersion >= 11;\n var ch = state.current(forceU);\n state.advance(forceU);\n\n if (ch === 0x5C /* \\ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {\n ch = state.lastIntValue;\n }\n if (isRegExpIdentifierStart(ch)) {\n state.lastIntValue = ch;\n return true\n }\n\n state.pos = start;\n return false\n};\nfunction isRegExpIdentifierStart(ch) {\n return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */\n}\n\n// RegExpIdentifierPart ::\n// UnicodeIDContinue\n// `$`\n// `_`\n// `\\` RegExpUnicodeEscapeSequence[+U]\n// <ZWNJ>\n// <ZWJ>\npp$1.regexp_eatRegExpIdentifierPart = function(state) {\n var start = state.pos;\n var forceU = this.options.ecmaVersion >= 11;\n var ch = state.current(forceU);\n state.advance(forceU);\n\n if (ch === 0x5C /* \\ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {\n ch = state.lastIntValue;\n }\n if (isRegExpIdentifierPart(ch)) {\n state.lastIntValue = ch;\n return true\n }\n\n state.pos = start;\n return false\n};\nfunction isRegExpIdentifierPart(ch) {\n return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */\n}\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape\npp$1.regexp_eatAtomEscape = function(state) {\n if (\n this.regexp_eatBackReference(state) ||\n this.regexp_eatCharacterClassEscape(state) ||\n this.regexp_eatCharacterEscape(state) ||\n (state.switchN && this.regexp_eatKGroupName(state))\n ) {\n return true\n }\n if (state.switchU) {\n // Make the same message as V8.\n if (state.current() === 0x63 /* c */) {\n state.raise(\"Invalid unicode escape\");\n }\n state.raise(\"Invalid escape\");\n }\n return false\n};\npp$1.regexp_eatBackReference = function(state) {\n var start = state.pos;\n if (this.regexp_eatDecimalEscape(state)) {\n var n = state.lastIntValue;\n if (state.switchU) {\n // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape\n if (n > state.maxBackReference) {\n state.maxBackReference = n;\n }\n return true\n }\n if (n <= state.numCapturingParens) {\n return true\n }\n state.pos = start;\n }\n return false\n};\npp$1.regexp_eatKGroupName = function(state) {\n if (state.eat(0x6B /* k */)) {\n if (this.regexp_eatGroupName(state)) {\n state.backReferenceNames.push(state.lastStringValue);\n return true\n }\n state.raise(\"Invalid named reference\");\n }\n return false\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape\npp$1.regexp_eatCharacterEscape = function(state) {\n return (\n this.regexp_eatControlEscape(state) ||\n this.regexp_eatCControlLetter(state) ||\n this.regexp_eatZero(state) ||\n this.regexp_eatHexEscapeSequence(state) ||\n this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||\n (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||\n this.regexp_eatIdentityEscape(state)\n )\n};\npp$1.regexp_eatCControlLetter = function(state) {\n var start = state.pos;\n if (state.eat(0x63 /* c */)) {\n if (this.regexp_eatControlLetter(state)) {\n return true\n }\n state.pos = start;\n }\n return false\n};\npp$1.regexp_eatZero = function(state) {\n if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {\n state.lastIntValue = 0;\n state.advance();\n return true\n }\n return false\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape\npp$1.regexp_eatControlEscape = function(state) {\n var ch = state.current();\n if (ch === 0x74 /* t */) {\n state.lastIntValue = 0x09; /* \\t */\n state.advance();\n return true\n }\n if (ch === 0x6E /* n */) {\n state.lastIntValue = 0x0A; /* \\n */\n state.advance();\n return true\n }\n if (ch === 0x76 /* v */) {\n state.lastIntValue = 0x0B; /* \\v */\n state.advance();\n return true\n }\n if (ch === 0x66 /* f */) {\n state.lastIntValue = 0x0C; /* \\f */\n state.advance();\n return true\n }\n if (ch === 0x72 /* r */) {\n state.lastIntValue = 0x0D; /* \\r */\n state.advance();\n return true\n }\n return false\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter\npp$1.regexp_eatControlLetter = function(state) {\n var ch = state.current();\n if (isControlLetter(ch)) {\n state.lastIntValue = ch % 0x20;\n state.advance();\n return true\n }\n return false\n};\nfunction isControlLetter(ch) {\n return (\n (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||\n (ch >= 0x61 /* a */ && ch <= 0x7A /* z */)\n )\n}\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence\npp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {\n if ( forceU === void 0 ) forceU = false;\n\n var start = state.pos;\n var switchU = forceU || state.switchU;\n\n if (state.eat(0x75 /* u */)) {\n if (this.regexp_eatFixedHexDigits(state, 4)) {\n var lead = state.lastIntValue;\n if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {\n var leadSurrogateEnd = state.pos;\n if (state.eat(0x5C /* \\ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {\n var trail = state.lastIntValue;\n if (trail >= 0xDC00 && trail <= 0xDFFF) {\n state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;\n return true\n }\n }\n state.pos = leadSurrogateEnd;\n state.lastIntValue = lead;\n }\n return true\n }\n if (\n switchU &&\n state.eat(0x7B /* { */) &&\n this.regexp_eatHexDigits(state) &&\n state.eat(0x7D /* } */) &&\n isValidUnicode(state.lastIntValue)\n ) {\n return true\n }\n if (switchU) {\n state.raise(\"Invalid unicode escape\");\n }\n state.pos = start;\n }\n\n return false\n};\nfunction isValidUnicode(ch) {\n return ch >= 0 && ch <= 0x10FFFF\n}\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape\npp$1.regexp_eatIdentityEscape = function(state) {\n if (state.switchU) {\n if (this.regexp_eatSyntaxCharacter(state)) {\n return true\n }\n if (state.eat(0x2F /* / */)) {\n state.lastIntValue = 0x2F; /* / */\n return true\n }\n return false\n }\n\n var ch = state.current();\n if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {\n state.lastIntValue = ch;\n state.advance();\n return true\n }\n\n return false\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape\npp$1.regexp_eatDecimalEscape = function(state) {\n state.lastIntValue = 0;\n var ch = state.current();\n if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {\n do {\n state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);\n state.advance();\n } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)\n return true\n }\n return false\n};\n\n// Return values used by character set parsing methods, needed to\n// forbid negation of sets that can match strings.\nvar CharSetNone = 0; // Nothing parsed\nvar CharSetOk = 1; // Construct parsed, cannot contain strings\nvar CharSetString = 2; // Construct parsed, can contain strings\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape\npp$1.regexp_eatCharacterClassEscape = function(state) {\n var ch = state.current();\n\n if (isCharacterClassEscape(ch)) {\n state.lastIntValue = -1;\n state.advance();\n return CharSetOk\n }\n\n var negate = false;\n if (\n state.switchU &&\n this.options.ecmaVersion >= 9 &&\n ((negate = ch === 0x50 /* P */) || ch === 0x70 /* p */)\n ) {\n state.lastIntValue = -1;\n state.advance();\n var result;\n if (\n state.eat(0x7B /* { */) &&\n (result = this.regexp_eatUnicodePropertyValueExpression(state)) &&\n state.eat(0x7D /* } */)\n ) {\n if (negate && result === CharSetString) { state.raise(\"Invalid property name\"); }\n return result\n }\n state.raise(\"Invalid property name\");\n }\n\n return CharSetNone\n};\n\nfunction isCharacterClassEscape(ch) {\n return (\n ch === 0x64 /* d */ ||\n ch === 0x44 /* D */ ||\n ch === 0x73 /* s */ ||\n ch === 0x53 /* S */ ||\n ch === 0x77 /* w */ ||\n ch === 0x57 /* W */\n )\n}\n\n// UnicodePropertyValueExpression ::\n// UnicodePropertyName `=` UnicodePropertyValue\n// LoneUnicodePropertyNameOrValue\npp$1.regexp_eatUnicodePropertyValueExpression = function(state) {\n var start = state.pos;\n\n // UnicodePropertyName `=` UnicodePropertyValue\n if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {\n var name = state.lastStringValue;\n if (this.regexp_eatUnicodePropertyValue(state)) {\n var value = state.lastStringValue;\n this.regexp_validateUnicodePropertyNameAndValue(state, name, value);\n return CharSetOk\n }\n }\n state.pos = start;\n\n // LoneUnicodePropertyNameOrValue\n if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {\n var nameOrValue = state.lastStringValue;\n return this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue)\n }\n return CharSetNone\n};\n\npp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {\n if (!hasOwn(state.unicodeProperties.nonBinary, name))\n { state.raise(\"Invalid property name\"); }\n if (!state.unicodeProperties.nonBinary[name].test(value))\n { state.raise(\"Invalid property value\"); }\n};\n\npp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {\n if (state.unicodeProperties.binary.test(nameOrValue)) { return CharSetOk }\n if (state.switchV && state.unicodeProperties.binaryOfStrings.test(nameOrValue)) { return CharSetString }\n state.raise(\"Invalid property name\");\n};\n\n// UnicodePropertyName ::\n// UnicodePropertyNameCharacters\npp$1.regexp_eatUnicodePropertyName = function(state) {\n var ch = 0;\n state.lastStringValue = \"\";\n while (isUnicodePropertyNameCharacter(ch = state.current())) {\n state.lastStringValue += codePointToString(ch);\n state.advance();\n }\n return state.lastStringValue !== \"\"\n};\n\nfunction isUnicodePropertyNameCharacter(ch) {\n return isControlLetter(ch) || ch === 0x5F /* _ */\n}\n\n// UnicodePropertyValue ::\n// UnicodePropertyValueCharacters\npp$1.regexp_eatUnicodePropertyValue = function(state) {\n var ch = 0;\n state.lastStringValue = \"\";\n while (isUnicodePropertyValueCharacter(ch = state.current())) {\n state.lastStringValue += codePointToString(ch);\n state.advance();\n }\n return state.lastStringValue !== \"\"\n};\nfunction isUnicodePropertyValueCharacter(ch) {\n return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)\n}\n\n// LoneUnicodePropertyNameOrValue ::\n// UnicodePropertyValueCharacters\npp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {\n return this.regexp_eatUnicodePropertyValue(state)\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass\npp$1.regexp_eatCharacterClass = function(state) {\n if (state.eat(0x5B /* [ */)) {\n var negate = state.eat(0x5E /* ^ */);\n var result = this.regexp_classContents(state);\n if (!state.eat(0x5D /* ] */))\n { state.raise(\"Unterminated character class\"); }\n if (negate && result === CharSetString)\n { state.raise(\"Negated character class may contain strings\"); }\n return true\n }\n return false\n};\n\n// https://tc39.es/ecma262/#prod-ClassContents\n// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges\npp$1.regexp_classContents = function(state) {\n if (state.current() === 0x5D /* ] */) { return CharSetOk }\n if (state.switchV) { return this.regexp_classSetExpression(state) }\n this.regexp_nonEmptyClassRanges(state);\n return CharSetOk\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges\n// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash\npp$1.regexp_nonEmptyClassRanges = function(state) {\n while (this.regexp_eatClassAtom(state)) {\n var left = state.lastIntValue;\n if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {\n var right = state.lastIntValue;\n if (state.switchU && (left === -1 || right === -1)) {\n state.raise(\"Invalid character class\");\n }\n if (left !== -1 && right !== -1 && left > right) {\n state.raise(\"Range out of order in character class\");\n }\n }\n }\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom\n// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash\npp$1.regexp_eatClassAtom = function(state) {\n var start = state.pos;\n\n if (state.eat(0x5C /* \\ */)) {\n if (this.regexp_eatClassEscape(state)) {\n return true\n }\n if (state.switchU) {\n // Make the same message as V8.\n var ch$1 = state.current();\n if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {\n state.raise(\"Invalid class escape\");\n }\n state.raise(\"Invalid escape\");\n }\n state.pos = start;\n }\n\n var ch = state.current();\n if (ch !== 0x5D /* ] */) {\n state.lastIntValue = ch;\n state.advance();\n return true\n }\n\n return false\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape\npp$1.regexp_eatClassEscape = function(state) {\n var start = state.pos;\n\n if (state.eat(0x62 /* b */)) {\n state.lastIntValue = 0x08; /* <BS> */\n return true\n }\n\n if (state.switchU && state.eat(0x2D /* - */)) {\n state.lastIntValue = 0x2D; /* - */\n return true\n }\n\n if (!state.switchU && state.eat(0x63 /* c */)) {\n if (this.regexp_eatClassControlLetter(state)) {\n return true\n }\n state.pos = start;\n }\n\n return (\n this.regexp_eatCharacterClassEscape(state) ||\n this.regexp_eatCharacterEscape(state)\n )\n};\n\n// https://tc39.es/ecma262/#prod-ClassSetExpression\n// https://tc39.es/ecma262/#prod-ClassUnion\n// https://tc39.es/ecma262/#prod-ClassIntersection\n// https://tc39.es/ecma262/#prod-ClassSubtraction\npp$1.regexp_classSetExpression = function(state) {\n var result = CharSetOk, subResult;\n if (this.regexp_eatClassSetRange(state)) ; else if (subResult = this.regexp_eatClassSetOperand(state)) {\n if (subResult === CharSetString) { result = CharSetString; }\n // https://tc39.es/ecma262/#prod-ClassIntersection\n var start = state.pos;\n while (state.eatChars([0x26, 0x26] /* && */)) {\n if (\n state.current() !== 0x26 /* & */ &&\n (subResult = this.regexp_eatClassSetOperand(state))\n ) {\n if (subResult !== CharSetString) { result = CharSetOk; }\n continue\n }\n state.raise(\"Invalid character in character class\");\n }\n if (start !== state.pos) { return result }\n // https://tc39.es/ecma262/#prod-ClassSubtraction\n while (state.eatChars([0x2D, 0x2D] /* -- */)) {\n if (this.regexp_eatClassSetOperand(state)) { continue }\n state.raise(\"Invalid character in character class\");\n }\n if (start !== state.pos) { return result }\n } else {\n state.raise(\"Invalid character in character class\");\n }\n // https://tc39.es/ecma262/#prod-ClassUnion\n for (;;) {\n if (this.regexp_eatClassSetRange(state)) { continue }\n subResult = this.regexp_eatClassSetOperand(state);\n if (!subResult) { return result }\n if (subResult === CharSetString) { result = CharSetString; }\n }\n};\n\n// https://tc39.es/ecma262/#prod-ClassSetRange\npp$1.regexp_eatClassSetRange = function(state) {\n var start = state.pos;\n if (this.regexp_eatClassSetCharacter(state)) {\n var left = state.lastIntValue;\n if (state.eat(0x2D /* - */) && this.regexp_eatClassSetCharacter(state)) {\n var right = state.lastIntValue;\n if (left !== -1 && right !== -1 && left > right) {\n state.raise(\"Range out of order in character class\");\n }\n return true\n }\n state.pos = start;\n }\n return false\n};\n\n// https://tc39.es/ecma262/#prod-ClassSetOperand\npp$1.regexp_eatClassSetOperand = function(state) {\n if (this.regexp_eatClassSetCharacter(state)) { return CharSetOk }\n return this.regexp_eatClassStringDisjunction(state) || this.regexp_eatNestedClass(state)\n};\n\n// https://tc39.es/ecma262/#prod-NestedClass\npp$1.regexp_eatNestedClass = function(state) {\n var start = state.pos;\n if (state.eat(0x5B /* [ */)) {\n var negate = state.eat(0x5E /* ^ */);\n var result = this.regexp_classContents(state);\n if (state.eat(0x5D /* ] */)) {\n if (negate && result === CharSetString) {\n state.raise(\"Negated character class may contain strings\");\n }\n return result\n }\n state.pos = start;\n }\n if (state.eat(0x5C /* \\ */)) {\n var result$1 = this.regexp_eatCharacterClassEscape(state);\n if (result$1) {\n return result$1\n }\n state.pos = start;\n }\n return null\n};\n\n// https://tc39.es/ecma262/#prod-ClassStringDisjunction\npp$1.regexp_eatClassStringDisjunction = function(state) {\n var start = state.pos;\n if (state.eatChars([0x5C, 0x71] /* \\q */)) {\n if (state.eat(0x7B /* { */)) {\n var result = this.regexp_classStringDisjunctionContents(state);\n if (state.eat(0x7D /* } */)) {\n return result\n }\n } else {\n // Make the same message as V8.\n state.raise(\"Invalid escape\");\n }\n state.pos = start;\n }\n return null\n};\n\n// https://tc39.es/ecma262/#prod-ClassStringDisjunctionContents\npp$1.regexp_classStringDisjunctionContents = function(state) {\n var result = this.regexp_classString(state);\n while (state.eat(0x7C /* | */)) {\n if (this.regexp_classString(state) === CharSetString) { result = CharSetString; }\n }\n return result\n};\n\n// https://tc39.es/ecma262/#prod-ClassString\n// https://tc39.es/ecma262/#prod-NonEmptyClassString\npp$1.regexp_classString = function(state) {\n var count = 0;\n while (this.regexp_eatClassSetCharacter(state)) { count++; }\n return count === 1 ? CharSetOk : CharSetString\n};\n\n// https://tc39.es/ecma262/#prod-ClassSetCharacter\npp$1.regexp_eatClassSetCharacter = function(state) {\n var start = state.pos;\n if (state.eat(0x5C /* \\ */)) {\n if (\n this.regexp_eatCharacterEscape(state) ||\n this.regexp_eatClassSetReservedPunctuator(state)\n ) {\n return true\n }\n if (state.eat(0x62 /* b */)) {\n state.lastIntValue = 0x08; /* <BS> */\n return true\n }\n state.pos = start;\n return false\n }\n var ch = state.current();\n if (ch < 0 || ch === state.lookahead() && isClassSetReservedDoublePunctuatorCharacter(ch)) { return false }\n if (isClassSetSyntaxCharacter(ch)) { return false }\n state.advance();\n state.lastIntValue = ch;\n return true\n};\n\n// https://tc39.es/ecma262/#prod-ClassSetReservedDoublePunctuator\nfunction isClassSetReservedDoublePunctuatorCharacter(ch) {\n return (\n ch === 0x21 /* ! */ ||\n ch >= 0x23 /* # */ && ch <= 0x26 /* & */ ||\n ch >= 0x2A /* * */ && ch <= 0x2C /* , */ ||\n ch === 0x2E /* . */ ||\n ch >= 0x3A /* : */ && ch <= 0x40 /* @ */ ||\n ch === 0x5E /* ^ */ ||\n ch === 0x60 /* ` */ ||\n ch === 0x7E /* ~ */\n )\n}\n\n// https://tc39.es/ecma262/#prod-ClassSetSyntaxCharacter\nfunction isClassSetSyntaxCharacter(ch) {\n return (\n ch === 0x28 /* ( */ ||\n ch === 0x29 /* ) */ ||\n ch === 0x2D /* - */ ||\n ch === 0x2F /* / */ ||\n ch >= 0x5B /* [ */ && ch <= 0x5D /* ] */ ||\n ch >= 0x7B /* { */ && ch <= 0x7D /* } */\n )\n}\n\n// https://tc39.es/ecma262/#prod-ClassSetReservedPunctuator\npp$1.regexp_eatClassSetReservedPunctuator = function(state) {\n var ch = state.current();\n if (isClassSetReservedPunctuator(ch)) {\n state.lastIntValue = ch;\n state.advance();\n return true\n }\n return false\n};\n\n// https://tc39.es/ecma262/#prod-ClassSetReservedPunctuator\nfunction isClassSetReservedPunctuator(ch) {\n return (\n ch === 0x21 /* ! */ ||\n ch === 0x23 /* # */ ||\n ch === 0x25 /* % */ ||\n ch === 0x26 /* & */ ||\n ch === 0x2C /* , */ ||\n ch === 0x2D /* - */ ||\n ch >= 0x3A /* : */ && ch <= 0x3E /* > */ ||\n ch === 0x40 /* @ */ ||\n ch === 0x60 /* ` */ ||\n ch === 0x7E /* ~ */\n )\n}\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter\npp$1.regexp_eatClassControlLetter = function(state) {\n var ch = state.current();\n if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {\n state.lastIntValue = ch % 0x20;\n state.advance();\n return true\n }\n return false\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence\npp$1.regexp_eatHexEscapeSequence = function(state) {\n var start = state.pos;\n if (state.eat(0x78 /* x */)) {\n if (this.regexp_eatFixedHexDigits(state, 2)) {\n return true\n }\n if (state.switchU) {\n state.raise(\"Invalid escape\");\n }\n state.pos = start;\n }\n return false\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits\npp$1.regexp_eatDecimalDigits = function(state) {\n var start = state.pos;\n var ch = 0;\n state.lastIntValue = 0;\n while (isDecimalDigit(ch = state.current())) {\n state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);\n state.advance();\n }\n return state.pos !== start\n};\nfunction isDecimalDigit(ch) {\n return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */\n}\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits\npp$1.regexp_eatHexDigits = function(state) {\n var start = state.pos;\n var ch = 0;\n state.lastIntValue = 0;\n while (isHexDigit(ch = state.current())) {\n state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);\n state.advance();\n }\n return state.pos !== start\n};\nfunction isHexDigit(ch) {\n return (\n (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||\n (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||\n (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)\n )\n}\nfunction hexToInt(ch) {\n if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {\n return 10 + (ch - 0x41 /* A */)\n }\n if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {\n return 10 + (ch - 0x61 /* a */)\n }\n return ch - 0x30 /* 0 */\n}\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence\n// Allows only 0-377(octal) i.e. 0-255(decimal).\npp$1.regexp_eatLegacyOctalEscapeSequence = function(state) {\n if (this.regexp_eatOctalDigit(state)) {\n var n1 = state.lastIntValue;\n if (this.regexp_eatOctalDigit(state)) {\n var n2 = state.lastIntValue;\n if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {\n state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;\n } else {\n state.lastIntValue = n1 * 8 + n2;\n }\n } else {\n state.lastIntValue = n1;\n }\n return true\n }\n return false\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit\npp$1.regexp_eatOctalDigit = function(state) {\n var ch = state.current();\n if (isOctalDigit(ch)) {\n state.lastIntValue = ch - 0x30; /* 0 */\n state.advance();\n return true\n }\n state.lastIntValue = 0;\n return false\n};\nfunction isOctalDigit(ch) {\n return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */\n}\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits\n// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit\n// And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence\npp$1.regexp_eatFixedHexDigits = function(state, length) {\n var start = state.pos;\n state.lastIntValue = 0;\n for (var i = 0; i < length; ++i) {\n var ch = state.current();\n if (!isHexDigit(ch)) {\n state.pos = start;\n return false\n }\n state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);\n state.advance();\n }\n return true\n};\n\n// Object type used to represent tokens. Note that normally, tokens\n// simply exist as properties on the parser object. This is only\n// used for the onToken callback and the external tokenizer.\n\nvar Token = function Token(p) {\n this.type = p.type;\n this.value = p.value;\n this.start = p.start;\n this.end = p.end;\n if (p.options.locations)\n { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }\n if (p.options.ranges)\n { this.range = [p.start, p.end]; }\n};\n\n// ## Tokenizer\n\nvar pp = Parser.prototype;\n\n// Move to the next token\n\npp.next = function(ignoreEscapeSequenceInKeyword) {\n if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)\n { this.raiseRecoverable(this.start, \"Escape sequence in keyword \" + this.type.keyword); }\n if (this.options.onToken)\n { this.options.onToken(new Token(this)); }\n\n this.lastTokEnd = this.end;\n this.lastTokStart = this.start;\n this.lastTokEndLoc = this.endLoc;\n this.lastTokStartLoc = this.startLoc;\n this.nextToken();\n};\n\npp.getToken = function() {\n this.next();\n return new Token(this)\n};\n\n// If we're in an ES6 environment, make parsers iterable\nif (typeof Symbol !== \"undefined\")\n { pp[Symbol.iterator] = function() {\n var this$1$1 = this;\n\n return {\n next: function () {\n var token = this$1$1.getToken();\n return {\n done: token.type === types$1.eof,\n value: token\n }\n }\n }\n }; }\n\n// Toggle strict mode. Re-reads the next number or string to please\n// pedantic tests (`\"use strict\"; 010;` should fail).\n\n// Read a single token, updating the parser object's token-related\n// properties.\n\npp.nextToken = function() {\n var curContext = this.curContext();\n if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }\n\n this.start = this.pos;\n if (this.options.locations) { this.startLoc = this.curPosition(); }\n if (this.pos >= this.input.length) { return this.finishToken(types$1.eof) }\n\n if (curContext.override) { return curContext.override(this) }\n else { this.readToken(this.fullCharCodeAtPos()); }\n};\n\npp.readToken = function(code) {\n // Identifier or keyword. '\\uXXXX' sequences are allowed in\n // identifiers, so '\\' also dispatches to that.\n if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\\' */)\n { return this.readWord() }\n\n return this.getTokenFromCode(code)\n};\n\npp.fullCharCodeAt = function(pos) {\n var code = this.input.charCodeAt(pos);\n if (code <= 0xd7ff || code >= 0xdc00) { return code }\n var next = this.input.charCodeAt(pos + 1);\n return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00\n};\n\npp.fullCharCodeAtPos = function() {\n return this.fullCharCodeAt(this.pos)\n};\n\npp.skipBlockComment = function() {\n var startLoc = this.options.onComment && this.curPosition();\n var start = this.pos, end = this.input.indexOf(\"*/\", this.pos += 2);\n if (end === -1) { this.raise(this.pos - 2, \"Unterminated comment\"); }\n this.pos = end + 2;\n if (this.options.locations) {\n for (var nextBreak = (void 0), pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1;) {\n ++this.curLine;\n pos = this.lineStart = nextBreak;\n }\n }\n if (this.options.onComment)\n { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,\n startLoc, this.curPosition()); }\n};\n\npp.skipLineComment = function(startSkip) {\n var start = this.pos;\n var startLoc = this.options.onComment && this.curPosition();\n var ch = this.input.charCodeAt(this.pos += startSkip);\n while (this.pos < this.input.length && !isNewLine(ch)) {\n ch = this.input.charCodeAt(++this.pos);\n }\n if (this.options.onComment)\n { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,\n startLoc, this.curPosition()); }\n};\n\n// Called at the start of the parse and after every token. Skips\n// whitespace and comments, and.\n\npp.skipSpace = function() {\n loop: while (this.pos < this.input.length) {\n var ch = this.input.charCodeAt(this.pos);\n switch (ch) {\n case 32: case 160: // ' '\n ++this.pos;\n break\n case 13:\n if (this.input.charCodeAt(this.pos + 1) === 10) {\n ++this.pos;\n }\n case 10: case 8232: case 8233:\n ++this.pos;\n if (this.options.locations) {\n ++this.curLine;\n this.lineStart = this.pos;\n }\n break\n case 47: // '/'\n switch (this.input.charCodeAt(this.pos + 1)) {\n case 42: // '*'\n this.skipBlockComment();\n break\n case 47:\n this.skipLineComment(2);\n break\n default:\n break loop\n }\n break\n default:\n if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {\n ++this.pos;\n } else {\n break loop\n }\n }\n }\n};\n\n// Called at the end of every token. Sets `end`, `val`, and\n// maintains `context` and `exprAllowed`, and skips the space after\n// the token, so that the next one's `start` will point at the\n// right position.\n\npp.finishToken = function(type, val) {\n this.end = this.pos;\n if (this.options.locations) { this.endLoc = this.curPosition(); }\n var prevType = this.type;\n this.type = type;\n this.value = val;\n\n this.updateContext(prevType);\n};\n\n// ### Token reading\n\n// This is the function that is called to fetch the next token. It\n// is somewhat obscure, because it works in character codes rather\n// than characters, and because operator parsing has been inlined\n// into it.\n//\n// All in the name of speed.\n//\npp.readToken_dot = function() {\n var next = this.input.charCodeAt(this.pos + 1);\n if (next >= 48 && next <= 57) { return this.readNumber(true) }\n var next2 = this.input.charCodeAt(this.pos + 2);\n if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'\n this.pos += 3;\n return this.finishToken(types$1.ellipsis)\n } else {\n ++this.pos;\n return this.finishToken(types$1.dot)\n }\n};\n\npp.readToken_slash = function() { // '/'\n var next = this.input.charCodeAt(this.pos + 1);\n if (this.exprAllowed) { ++this.pos; return this.readRegexp() }\n if (next === 61) { return this.finishOp(types$1.assign, 2) }\n return this.finishOp(types$1.slash, 1)\n};\n\npp.readToken_mult_modulo_exp = function(code) { // '%*'\n var next = this.input.charCodeAt(this.pos + 1);\n var size = 1;\n var tokentype = code === 42 ? types$1.star : types$1.modulo;\n\n // exponentiation operator ** and **=\n if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {\n ++size;\n tokentype = types$1.starstar;\n next = this.input.charCodeAt(this.pos + 2);\n }\n\n if (next === 61) { return this.finishOp(types$1.assign, size + 1) }\n return this.finishOp(tokentype, size)\n};\n\npp.readToken_pipe_amp = function(code) { // '|&'\n var next = this.input.charCodeAt(this.pos + 1);\n if (next === code) {\n if (this.options.ecmaVersion >= 12) {\n var next2 = this.input.charCodeAt(this.pos + 2);\n if (next2 === 61) { return this.finishOp(types$1.assign, 3) }\n }\n return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2)\n }\n if (next === 61) { return this.finishOp(types$1.assign, 2) }\n return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1)\n};\n\npp.readToken_caret = function() { // '^'\n var next = this.input.charCodeAt(this.pos + 1);\n if (next === 61) { return this.finishOp(types$1.assign, 2) }\n return this.finishOp(types$1.bitwiseXOR, 1)\n};\n\npp.readToken_plus_min = function(code) { // '+-'\n var next = this.input.charCodeAt(this.pos + 1);\n if (next === code) {\n if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&\n (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {\n // A `-->` line comment\n this.skipLineComment(3);\n this.skipSpace();\n return this.nextToken()\n }\n return this.finishOp(types$1.incDec, 2)\n }\n if (next === 61) { return this.finishOp(types$1.assign, 2) }\n return this.finishOp(types$1.plusMin, 1)\n};\n\npp.readToken_lt_gt = function(code) { // '<>'\n var next = this.input.charCodeAt(this.pos + 1);\n var size = 1;\n if (next === code) {\n size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;\n if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) }\n return this.finishOp(types$1.bitShift, size)\n }\n if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&\n this.input.charCodeAt(this.pos + 3) === 45) {\n // `<!--`, an XML-style comment that should be interpreted as a line comment\n this.skipLineComment(4);\n this.skipSpace();\n return this.nextToken()\n }\n if (next === 61) { size = 2; }\n return this.finishOp(types$1.relational, size)\n};\n\npp.readToken_eq_excl = function(code) { // '=!'\n var next = this.input.charCodeAt(this.pos + 1);\n if (next === 61) { return this.finishOp(types$1.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }\n if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'\n this.pos += 2;\n return this.finishToken(types$1.arrow)\n }\n return this.finishOp(code === 61 ? types$1.eq : types$1.prefix, 1)\n};\n\npp.readToken_question = function() { // '?'\n var ecmaVersion = this.options.ecmaVersion;\n if (ecmaVersion >= 11) {\n var next = this.input.charCodeAt(this.pos + 1);\n if (next === 46) {\n var next2 = this.input.charCodeAt(this.pos + 2);\n if (next2 < 48 || next2 > 57) { return this.finishOp(types$1.questionDot, 2) }\n }\n if (next === 63) {\n if (ecmaVersion >= 12) {\n var next2$1 = this.input.charCodeAt(this.pos + 2);\n if (next2$1 === 61) { return this.finishOp(types$1.assign, 3) }\n }\n return this.finishOp(types$1.coalesce, 2)\n }\n }\n return this.finishOp(types$1.question, 1)\n};\n\npp.readToken_numberSign = function() { // '#'\n var ecmaVersion = this.options.ecmaVersion;\n var code = 35; // '#'\n if (ecmaVersion >= 13) {\n ++this.pos;\n code = this.fullCharCodeAtPos();\n if (isIdentifierStart(code, true) || code === 92 /* '\\' */) {\n return this.finishToken(types$1.privateId, this.readWord1())\n }\n }\n\n this.raise(this.pos, \"Unexpected character '\" + codePointToString(code) + \"'\");\n};\n\npp.getTokenFromCode = function(code) {\n switch (code) {\n // The interpretation of a dot depends on whether it is followed\n // by a digit or another two dots.\n case 46: // '.'\n return this.readToken_dot()\n\n // Punctuation tokens.\n case 40: ++this.pos; return this.finishToken(types$1.parenL)\n case 41: ++this.pos; return this.finishToken(types$1.parenR)\n case 59: ++this.pos; return this.finishToken(types$1.semi)\n case 44: ++this.pos; return this.finishToken(types$1.comma)\n case 91: ++this.pos; return this.finishToken(types$1.bracketL)\n case 93: ++this.pos; return this.finishToken(types$1.bracketR)\n case 123: ++this.pos; return this.finishToken(types$1.braceL)\n case 125: ++this.pos; return this.finishToken(types$1.braceR)\n case 58: ++this.pos; return this.finishToken(types$1.colon)\n\n case 96: // '`'\n if (this.options.ecmaVersion < 6) { break }\n ++this.pos;\n return this.finishToken(types$1.backQuote)\n\n case 48: // '0'\n var next = this.input.charCodeAt(this.pos + 1);\n if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number\n if (this.options.ecmaVersion >= 6) {\n if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number\n if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number\n }\n\n // Anything else beginning with a digit is an integer, octal\n // number, or float.\n case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9\n return this.readNumber(false)\n\n // Quotes produce strings.\n case 34: case 39: // '\"', \"'\"\n return this.readString(code)\n\n // Operators are parsed inline in tiny state machines. '=' (61) is\n // often referred to. `finishOp` simply skips the amount of\n // characters it is given as second argument, and returns a token\n // of the type given by its first argument.\n case 47: // '/'\n return this.readToken_slash()\n\n case 37: case 42: // '%*'\n return this.readToken_mult_modulo_exp(code)\n\n case 124: case 38: // '|&'\n return this.readToken_pipe_amp(code)\n\n case 94: // '^'\n return this.readToken_caret()\n\n case 43: case 45: // '+-'\n return this.readToken_plus_min(code)\n\n case 60: case 62: // '<>'\n return this.readToken_lt_gt(code)\n\n case 61: case 33: // '=!'\n return this.readToken_eq_excl(code)\n\n case 63: // '?'\n return this.readToken_question()\n\n case 126: // '~'\n return this.finishOp(types$1.prefix, 1)\n\n case 35: // '#'\n return this.readToken_numberSign()\n }\n\n this.raise(this.pos, \"Unexpected character '\" + codePointToString(code) + \"'\");\n};\n\npp.finishOp = function(type, size) {\n var str = this.input.slice(this.pos, this.pos + size);\n this.pos += size;\n return this.finishToken(type, str)\n};\n\npp.readRegexp = function() {\n var escaped, inClass, start = this.pos;\n for (;;) {\n if (this.pos >= this.input.length) { this.raise(start, \"Unterminated regular expression\"); }\n var ch = this.input.charAt(this.pos);\n if (lineBreak.test(ch)) { this.raise(start, \"Unterminated regular expression\"); }\n if (!escaped) {\n if (ch === \"[\") { inClass = true; }\n else if (ch === \"]\" && inClass) { inClass = false; }\n else if (ch === \"/\" && !inClass) { break }\n escaped = ch === \"\\\\\";\n } else { escaped = false; }\n ++this.pos;\n }\n var pattern = this.input.slice(start, this.pos);\n ++this.pos;\n var flagsStart = this.pos;\n var flags = this.readWord1();\n if (this.containsEsc) { this.unexpected(flagsStart); }\n\n // Validate pattern\n var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));\n state.reset(start, pattern, flags);\n this.validateRegExpFlags(state);\n this.validateRegExpPattern(state);\n\n // Create Literal#value property value.\n var value = null;\n try {\n value = new RegExp(pattern, flags);\n } catch (e) {\n // ESTree requires null if it failed to instantiate RegExp object.\n // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral\n }\n\n return this.finishToken(types$1.regexp, {pattern: pattern, flags: flags, value: value})\n};\n\n// Read an integer in the given radix. Return null if zero digits\n// were read, the integer value otherwise. When `len` is given, this\n// will return `null` unless the integer has exactly `len` digits.\n\npp.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {\n // `len` is used for character escape sequences. In that case, disallow separators.\n var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;\n\n // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)\n // and isn't fraction part nor exponent part. In that case, if the first digit\n // is zero then disallow separators.\n var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;\n\n var start = this.pos, total = 0, lastCode = 0;\n for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {\n var code = this.input.charCodeAt(this.pos), val = (void 0);\n\n if (allowSeparators && code === 95) {\n if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, \"Numeric separator is not allowed in legacy octal numeric literals\"); }\n if (lastCode === 95) { this.raiseRecoverable(this.pos, \"Numeric separator must be exactly one underscore\"); }\n if (i === 0) { this.raiseRecoverable(this.pos, \"Numeric separator is not allowed at the first of digits\"); }\n lastCode = code;\n continue\n }\n\n if (code >= 97) { val = code - 97 + 10; } // a\n else if (code >= 65) { val = code - 65 + 10; } // A\n else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9\n else { val = Infinity; }\n if (val >= radix) { break }\n lastCode = code;\n total = total * radix + val;\n }\n\n if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, \"Numeric separator is not allowed at the last of digits\"); }\n if (this.pos === start || len != null && this.pos - start !== len) { return null }\n\n return total\n};\n\nfunction stringToNumber(str, isLegacyOctalNumericLiteral) {\n if (isLegacyOctalNumericLiteral) {\n return parseInt(str, 8)\n }\n\n // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.\n return parseFloat(str.replace(/_/g, \"\"))\n}\n\nfunction stringToBigInt(str) {\n if (typeof BigInt !== \"function\") {\n return null\n }\n\n // `BigInt(value)` throws syntax error if the string contains numeric separators.\n return BigInt(str.replace(/_/g, \"\"))\n}\n\npp.readRadixNumber = function(radix) {\n var start = this.pos;\n this.pos += 2; // 0x\n var val = this.readInt(radix);\n if (val == null) { this.raise(this.start + 2, \"Expected number in radix \" + radix); }\n if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {\n val = stringToBigInt(this.input.slice(start, this.pos));\n ++this.pos;\n } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, \"Identifier directly after number\"); }\n return this.finishToken(types$1.num, val)\n};\n\n// Read an integer, octal integer, or floating-point number.\n\npp.readNumber = function(startsWithDot) {\n var start = this.pos;\n if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, \"Invalid number\"); }\n var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;\n if (octal && this.strict) { this.raise(start, \"Invalid number\"); }\n var next = this.input.charCodeAt(this.pos);\n if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {\n var val$1 = stringToBigInt(this.input.slice(start, this.pos));\n ++this.pos;\n if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, \"Identifier directly after number\"); }\n return this.finishToken(types$1.num, val$1)\n }\n if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }\n if (next === 46 && !octal) { // '.'\n ++this.pos;\n this.readInt(10);\n next = this.input.charCodeAt(this.pos);\n }\n if ((next === 69 || next === 101) && !octal) { // 'eE'\n next = this.input.charCodeAt(++this.pos);\n if (next === 43 || next === 45) { ++this.pos; } // '+-'\n if (this.readInt(10) === null) { this.raise(start, \"Invalid number\"); }\n }\n if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, \"Identifier directly after number\"); }\n\n var val = stringToNumber(this.input.slice(start, this.pos), octal);\n return this.finishToken(types$1.num, val)\n};\n\n// Read a string value, interpreting backslash-escapes.\n\npp.readCodePoint = function() {\n var ch = this.input.charCodeAt(this.pos), code;\n\n if (ch === 123) { // '{'\n if (this.options.ecmaVersion < 6) { this.unexpected(); }\n var codePos = ++this.pos;\n code = this.readHexChar(this.input.indexOf(\"}\", this.pos) - this.pos);\n ++this.pos;\n if (code > 0x10FFFF) { this.invalidStringToken(codePos, \"Code point out of bounds\"); }\n } else {\n code = this.readHexChar(4);\n }\n return code\n};\n\npp.readString = function(quote) {\n var out = \"\", chunkStart = ++this.pos;\n for (;;) {\n if (this.pos >= this.input.length) { this.raise(this.start, \"Unterminated string constant\"); }\n var ch = this.input.charCodeAt(this.pos);\n if (ch === quote) { break }\n if (ch === 92) { // '\\'\n out += this.input.slice(chunkStart, this.pos);\n out += this.readEscapedChar(false);\n chunkStart = this.pos;\n } else if (ch === 0x2028 || ch === 0x2029) {\n if (this.options.ecmaVersion < 10) { this.raise(this.start, \"Unterminated string constant\"); }\n ++this.pos;\n if (this.options.locations) {\n this.curLine++;\n this.lineStart = this.pos;\n }\n } else {\n if (isNewLine(ch)) { this.raise(this.start, \"Unterminated string constant\"); }\n ++this.pos;\n }\n }\n out += this.input.slice(chunkStart, this.pos++);\n return this.finishToken(types$1.string, out)\n};\n\n// Reads template string tokens.\n\nvar INVALID_TEMPLATE_ESCAPE_ERROR = {};\n\npp.tryReadTemplateToken = function() {\n this.inTemplateElement = true;\n try {\n this.readTmplToken();\n } catch (err) {\n if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {\n this.readInvalidTemplateToken();\n } else {\n throw err\n }\n }\n\n this.inTemplateElement = false;\n};\n\npp.invalidStringToken = function(position, message) {\n if (this.inTemplateElement && this.options.ecmaVersion >= 9) {\n throw INVALID_TEMPLATE_ESCAPE_ERROR\n } else {\n this.raise(position, message);\n }\n};\n\npp.readTmplToken = function() {\n var out = \"\", chunkStart = this.pos;\n for (;;) {\n if (this.pos >= this.input.length) { this.raise(this.start, \"Unterminated template\"); }\n var ch = this.input.charCodeAt(this.pos);\n if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'\n if (this.pos === this.start && (this.type === types$1.template || this.type === types$1.invalidTemplate)) {\n if (ch === 36) {\n this.pos += 2;\n return this.finishToken(types$1.dollarBraceL)\n } else {\n ++this.pos;\n return this.finishToken(types$1.backQuote)\n }\n }\n out += this.input.slice(chunkStart, this.pos);\n return this.finishToken(types$1.template, out)\n }\n if (ch === 92) { // '\\'\n out += this.input.slice(chunkStart, this.pos);\n out += this.readEscapedChar(true);\n chunkStart = this.pos;\n } else if (isNewLine(ch)) {\n out += this.input.slice(chunkStart, this.pos);\n ++this.pos;\n switch (ch) {\n case 13:\n if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }\n case 10:\n out += \"\\n\";\n break\n default:\n out += String.fromCharCode(ch);\n break\n }\n if (this.options.locations) {\n ++this.curLine;\n this.lineStart = this.pos;\n }\n chunkStart = this.pos;\n } else {\n ++this.pos;\n }\n }\n};\n\n// Reads a template token to search for the end, without validating any escape sequences\npp.readInvalidTemplateToken = function() {\n for (; this.pos < this.input.length; this.pos++) {\n switch (this.input[this.pos]) {\n case \"\\\\\":\n ++this.pos;\n break\n\n case \"$\":\n if (this.input[this.pos + 1] !== \"{\") { break }\n // fall through\n case \"`\":\n return this.finishToken(types$1.invalidTemplate, this.input.slice(this.start, this.pos))\n\n case \"\\r\":\n if (this.input[this.pos + 1] === \"\\n\") { ++this.pos; }\n // fall through\n case \"\\n\": case \"\\u2028\": case \"\\u2029\":\n ++this.curLine;\n this.lineStart = this.pos + 1;\n break\n }\n }\n this.raise(this.start, \"Unterminated template\");\n};\n\n// Used to read escaped characters\n\npp.readEscapedChar = function(inTemplate) {\n var ch = this.input.charCodeAt(++this.pos);\n ++this.pos;\n switch (ch) {\n case 110: return \"\\n\" // 'n' -> '\\n'\n case 114: return \"\\r\" // 'r' -> '\\r'\n case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'\n case 117: return codePointToString(this.readCodePoint()) // 'u'\n case 116: return \"\\t\" // 't' -> '\\t'\n case 98: return \"\\b\" // 'b' -> '\\b'\n case 118: return \"\\u000b\" // 'v' -> '\\u000b'\n case 102: return \"\\f\" // 'f' -> '\\f'\n case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\\r\\n'\n case 10: // ' \\n'\n if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }\n return \"\"\n case 56:\n case 57:\n if (this.strict) {\n this.invalidStringToken(\n this.pos - 1,\n \"Invalid escape sequence\"\n );\n }\n if (inTemplate) {\n var codePos = this.pos - 1;\n\n this.invalidStringToken(\n codePos,\n \"Invalid escape sequence in template string\"\n );\n }\n default:\n if (ch >= 48 && ch <= 55) {\n var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];\n var octal = parseInt(octalStr, 8);\n if (octal > 255) {\n octalStr = octalStr.slice(0, -1);\n octal = parseInt(octalStr, 8);\n }\n this.pos += octalStr.length - 1;\n ch = this.input.charCodeAt(this.pos);\n if ((octalStr !== \"0\" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {\n this.invalidStringToken(\n this.pos - 1 - octalStr.length,\n inTemplate\n ? \"Octal literal in template string\"\n : \"Octal literal in strict mode\"\n );\n }\n return String.fromCharCode(octal)\n }\n if (isNewLine(ch)) {\n // Unicode new line characters after \\ get removed from output in both\n // template literals and strings\n if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }\n return \"\"\n }\n return String.fromCharCode(ch)\n }\n};\n\n// Used to read character escape sequences ('\\x', '\\u', '\\U').\n\npp.readHexChar = function(len) {\n var codePos = this.pos;\n var n = this.readInt(16, len);\n if (n === null) { this.invalidStringToken(codePos, \"Bad character escape sequence\"); }\n return n\n};\n\n// Read an identifier, and return it as a string. Sets `this.containsEsc`\n// to whether the word contained a '\\u' escape.\n//\n// Incrementally adds only escaped chars, adding other chunks as-is\n// as a micro-optimization.\n\npp.readWord1 = function() {\n this.containsEsc = false;\n var word = \"\", first = true, chunkStart = this.pos;\n var astral = this.options.ecmaVersion >= 6;\n while (this.pos < this.input.length) {\n var ch = this.fullCharCodeAtPos();\n if (isIdentifierChar(ch, astral)) {\n this.pos += ch <= 0xffff ? 1 : 2;\n } else if (ch === 92) { // \"\\\"\n this.containsEsc = true;\n word += this.input.slice(chunkStart, this.pos);\n var escStart = this.pos;\n if (this.input.charCodeAt(++this.pos) !== 117) // \"u\"\n { this.invalidStringToken(this.pos, \"Expecting Unicode escape sequence \\\\uXXXX\"); }\n ++this.pos;\n var esc = this.readCodePoint();\n if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))\n { this.invalidStringToken(escStart, \"Invalid Unicode escape\"); }\n word += codePointToString(esc);\n chunkStart = this.pos;\n } else {\n break\n }\n first = false;\n }\n return word + this.input.slice(chunkStart, this.pos)\n};\n\n// Read an identifier or keyword token. Will check for reserved\n// words when necessary.\n\npp.readWord = function() {\n var word = this.readWord1();\n var type = types$1.name;\n if (this.keywords.test(word)) {\n type = keywords[word];\n }\n return this.finishToken(type, word)\n};\n\n// Acorn is a tiny, fast JavaScript parser written in JavaScript.\n//\n// Acorn was written by Marijn Haverbeke, Ingvar Stepanyan, and\n// various contributors and released under an MIT license.\n//\n// Git repositories for Acorn are available at\n//\n// http://marijnhaverbeke.nl/git/acorn\n// https://github.com/acornjs/acorn.git\n//\n// Please use the [github bug tracker][ghbt] to report issues.\n//\n// [ghbt]: https://github.com/acornjs/acorn/issues\n\n\nvar version = \"8.18.0\";\n\nParser.acorn = {\n Parser: Parser,\n version: version,\n defaultOptions: defaultOptions,\n Position: Position,\n SourceLocation: SourceLocation,\n getLineInfo: getLineInfo,\n Node: Node,\n TokenType: TokenType,\n tokTypes: types$1,\n keywordTypes: keywords,\n TokContext: TokContext,\n tokContexts: types,\n isIdentifierChar: isIdentifierChar,\n isIdentifierStart: isIdentifierStart,\n Token: Token,\n isNewLine: isNewLine,\n lineBreak: lineBreak,\n lineBreakG: lineBreakG,\n nonASCIIwhitespace: nonASCIIwhitespace\n};\n\n// The main exported interface (under `self.acorn` when in the\n// browser) is a `parse` function that takes a code string and returns\n// an abstract syntax tree as specified by the [ESTree spec][estree].\n//\n// [estree]: https://github.com/estree/estree\n\nfunction parse(input, options) {\n return Parser.parse(input, options)\n}\n\n// This function tries to parse a single expression at a given\n// offset in a string. Useful for parsing mixed-language formats\n// that embed JavaScript expressions.\n\nfunction parseExpressionAt(input, pos, options) {\n return Parser.parseExpressionAt(input, pos, options)\n}\n\n// Acorn is organized as a tokenizer and a recursive-descent parser.\n// The `tokenizer` export provides an interface to the tokenizer.\n\nfunction tokenizer(input, options) {\n return Parser.tokenizer(input, options)\n}\n\nexport { Node, Parser, Position, SourceLocation, TokContext, Token, TokenType, defaultOptions, getLineInfo, isIdentifierChar, isIdentifierStart, isNewLine, keywords as keywordTypes, lineBreak, lineBreakG, nonASCIIwhitespace, parse, parseExpressionAt, types as tokContexts, types$1 as tokTypes, tokenizer, version };\n", "import { parse, type Program } from \"acorn\";\r\n\r\n/**\r\n * QUIKTR-1458 \u2014 the one place JavaScript is parsed, for both halves of the in-memory check (`syntaxCheck.ts`, `nameScope.ts`).\r\n *\r\n * JavaScript only: `.js`, `.mjs`, `.cjs`. A plain `.js` file is either a CommonJS script or an ES module, so it is read as whichever\r\n * it parses as; `.mjs` is always a module and `.cjs` always a script.\r\n */\r\n\r\nexport type SourceType = \"script\" | \"module\";\r\n\r\nconst CHECKABLE = /\\.(c|m)?js$/i;\r\n\r\nexport function isCheckablePath(path: string): boolean {\r\n return CHECKABLE.test(path);\r\n}\r\n\r\n/** `import x from`, `import {`, `import *`, `import \"x\"`, `export ...` at the start of a line. Not `import(` or `import.meta`. */\r\nexport const MODULE_SYNTAX = /^[ \\t]*(import[ \\t]*[\\w{*'\"$]|export[ \\t]+)/m;\r\n\r\nexport interface RawError {\r\n message: string;\r\n line: number;\r\n column: number;\r\n}\r\n\r\nexport function attempt(text: string, sourceType: SourceType): RawError | null {\r\n try {\r\n parse(text, {\r\n ecmaVersion: \"latest\",\r\n sourceType,\r\n allowHashBang: true,\r\n // A CommonJS file is a function body to Node, so a top-level `return` is legal there.\r\n allowReturnOutsideFunction: sourceType === \"script\",\r\n });\r\n return null;\r\n } catch (err) {\r\n // The parser's SyntaxError always carries `loc`, whether or not locations were asked for.\r\n const e = err as { message?: unknown; loc?: { line?: unknown; column?: unknown } };\r\n const line = typeof e.loc?.line === \"number\" ? e.loc.line : 1;\r\n const column = typeof e.loc?.column === \"number\" ? e.loc.column : 0;\r\n return { message: typeof e.message === \"string\" ? e.message : \"\", line, column };\r\n }\r\n}\r\n\r\n/** Which readings of a file to try, in order. */\r\nexport function readingsFor(path: string, text: string): SourceType[] {\r\n const lower = path.toLowerCase();\r\n if (lower.endsWith(\".mjs\")) return [\"module\"];\r\n if (lower.endsWith(\".cjs\")) return [\"script\"];\r\n return MODULE_SYNTAX.test(text) ? [\"module\", \"script\"] : [\"script\", \"module\"];\r\n}\r\n\r\n/** The syntax tree of a file that parses, with node ranges, or `null` (not a file this reads, or it does not parse). */\r\nexport function parseProgram(path: string, text: string): { ast: Program; sourceType: SourceType } | null {\r\n if (!isCheckablePath(path)) return null;\r\n for (const sourceType of readingsFor(path, text)) {\r\n try {\r\n const ast = parse(text, {\r\n ecmaVersion: \"latest\",\r\n sourceType,\r\n allowHashBang: true,\r\n allowReturnOutsideFunction: sourceType === \"script\",\r\n ranges: true,\r\n });\r\n return { ast, sourceType };\r\n } catch {\r\n // try the other reading\r\n }\r\n }\r\n return null;\r\n}\r\n", "/*\n Copyright (C) 2012-2014 Yusuke Suzuki <utatane.tea@gmail.com>\n Copyright (C) 2013 Alex Seville <hi@alexanderseville.com>\n Copyright (C) 2014 Thiago de Arruda <tpadilha84@gmail.com>\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\n DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n/**\n * Escope (<a href=\"http://github.com/estools/escope\">escope</a>) is an <a\n * href=\"http://www.ecma-international.org/publications/standards/Ecma-262.htm\">ECMAScript</a>\n * scope analyzer extracted from the <a\n * href=\"http://github.com/estools/esmangle\">esmangle project</a/>.\n * <p>\n * <em>escope</em> finds lexical scopes in a source program, i.e. areas of that\n * program where different occurrences of the same identifier refer to the same\n * variable. With each scope the contained variables are collected, and each\n * identifier reference in code is linked to its corresponding variable (if\n * possible).\n * <p>\n * <em>escope</em> works on a syntax tree of the parsed source code which has\n * to adhere to the <a\n * href=\"https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API\">\n * Mozilla Parser API</a>. E.g. <a href=\"https://github.com/eslint/espree\">espree</a> is a parser\n * that produces such syntax trees.\n * <p>\n * The main interface is the {@link analyze} function.\n * @module escope\n */\n/* eslint no-underscore-dangle: [\"error\", { \"allow\": [\"__currentScope\"] }] */\n\nimport assert from \"assert\";\n\nimport ScopeManager from \"./scope-manager.js\";\nimport Referencer from \"./referencer.js\";\nimport Reference from \"./reference.js\";\nimport Variable from \"./variable.js\";\n\nimport eslintScopeVersion from \"./version.js\";\n\n/**\n * Set the default options\n * @returns {Object} options\n */\nfunction defaultOptions() {\n return {\n optimistic: false,\n directive: false,\n nodejsScope: false,\n impliedStrict: false,\n sourceType: \"script\", // one of ['script', 'module', 'commonjs']\n ecmaVersion: 5,\n childVisitorKeys: null,\n fallback: \"iteration\"\n };\n}\n\n/**\n * Preform deep update on option object\n * @param {Object} target Options\n * @param {Object} override Updates\n * @returns {Object} Updated options\n */\nfunction updateDeeply(target, override) {\n\n /**\n * Is hash object\n * @param {Object} value Test value\n * @returns {boolean} Result\n */\n function isHashObject(value) {\n return typeof value === \"object\" && value instanceof Object && !(value instanceof Array) && !(value instanceof RegExp);\n }\n\n for (const key in override) {\n if (Object.prototype.hasOwnProperty.call(override, key)) {\n const val = override[key];\n\n if (isHashObject(val)) {\n if (isHashObject(target[key])) {\n updateDeeply(target[key], val);\n } else {\n target[key] = updateDeeply({}, val);\n }\n } else {\n target[key] = val;\n }\n }\n }\n return target;\n}\n\n/**\n * Main interface function. Takes an Espree syntax tree and returns the\n * analyzed scopes.\n * @function analyze\n * @param {espree.Tree} tree Abstract Syntax Tree\n * @param {Object} providedOptions Options that tailor the scope analysis\n * @param {boolean} [providedOptions.optimistic=false] the optimistic flag\n * @param {boolean} [providedOptions.directive=false] the directive flag\n * @param {boolean} [providedOptions.ignoreEval=false] whether to check 'eval()' calls\n * @param {boolean} [providedOptions.nodejsScope=false] whether the whole\n * script is executed under node.js environment. When enabled, escope adds\n * a function scope immediately following the global scope.\n * @param {boolean} [providedOptions.impliedStrict=false] implied strict mode\n * (if ecmaVersion >= 5).\n * @param {string} [providedOptions.sourceType='script'] the source type of the script. one of 'script', 'module', and 'commonjs'\n * @param {number} [providedOptions.ecmaVersion=5] which ECMAScript version is considered\n * @param {Object} [providedOptions.childVisitorKeys=null] Additional known visitor keys. See [esrecurse](https://github.com/estools/esrecurse)'s the `childVisitorKeys` option.\n * @param {string} [providedOptions.fallback='iteration'] A kind of the fallback in order to encounter with unknown node. See [esrecurse](https://github.com/estools/esrecurse)'s the `fallback` option.\n * @returns {ScopeManager} ScopeManager\n */\nfunction analyze(tree, providedOptions) {\n const options = updateDeeply(defaultOptions(), providedOptions);\n const scopeManager = new ScopeManager(options);\n const referencer = new Referencer(options, scopeManager);\n\n referencer.visit(tree);\n\n assert(scopeManager.__currentScope === null, \"currentScope should be null.\");\n\n return scopeManager;\n}\n\nexport {\n\n /** @name module:escope.version */\n eslintScopeVersion as version,\n\n /** @name module:escope.Reference */\n Reference,\n\n /** @name module:escope.Variable */\n Variable,\n\n /** @name module:escope.ScopeManager */\n ScopeManager,\n\n /** @name module:escope.Referencer */\n Referencer,\n\n analyze\n};\n\n/** @name module:escope.Definition */\nexport { Definition } from \"./definition.js\";\n\n/** @name module:escope.PatternVisitor */\nexport { default as PatternVisitor } from \"./pattern-visitor.js\";\n\n/** @name module:escope.Scope */\nexport { Scope } from \"./scope.js\";\n\n/* vim: set sw=4 ts=4 et tw=80 : */\n", "/*\n Copyright (C) 2015 Yusuke Suzuki <utatane.tea@gmail.com>\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\n DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n/* eslint-disable no-underscore-dangle */\n/* eslint-disable no-undefined */\n\nimport estraverse from \"estraverse\";\n\nimport Reference from \"./reference.js\";\nimport Variable from \"./variable.js\";\nimport { Definition } from \"./definition.js\";\nimport assert from \"assert\";\n\nconst { Syntax } = estraverse;\n\n/**\n * Test if scope is struct\n * @param {Scope} scope scope\n * @param {Block} block block\n * @param {boolean} isMethodDefinition is method definition\n * @param {boolean} useDirective use directive\n * @returns {boolean} is strict scope\n */\nfunction isStrictScope(scope, block, isMethodDefinition, useDirective) {\n let body;\n\n // When upper scope is exists and strict, inner scope is also strict.\n if (scope.upper && scope.upper.isStrict) {\n return true;\n }\n\n if (isMethodDefinition) {\n return true;\n }\n\n if (scope.type === \"class\" || scope.type === \"module\") {\n return true;\n }\n\n if (scope.type === \"block\" || scope.type === \"switch\") {\n return false;\n }\n\n if (scope.type === \"function\") {\n if (block.type === Syntax.ArrowFunctionExpression && block.body.type !== Syntax.BlockStatement) {\n return false;\n }\n\n if (block.type === Syntax.Program) {\n body = block;\n } else {\n body = block.body;\n }\n\n if (!body) {\n return false;\n }\n } else if (scope.type === \"global\") {\n body = block;\n } else {\n return false;\n }\n\n // Search 'use strict' directive.\n if (useDirective) {\n for (let i = 0, iz = body.body.length; i < iz; ++i) {\n const stmt = body.body[i];\n\n if (stmt.type !== Syntax.DirectiveStatement) {\n break;\n }\n if (stmt.raw === \"\\\"use strict\\\"\" || stmt.raw === \"'use strict'\") {\n return true;\n }\n }\n } else {\n for (let i = 0, iz = body.body.length; i < iz; ++i) {\n const stmt = body.body[i];\n\n if (stmt.type !== Syntax.ExpressionStatement) {\n break;\n }\n const expr = stmt.expression;\n\n if (expr.type !== Syntax.Literal || typeof expr.value !== \"string\") {\n break;\n }\n if (expr.raw !== null && expr.raw !== undefined) {\n if (expr.raw === \"\\\"use strict\\\"\" || expr.raw === \"'use strict'\") {\n return true;\n }\n } else {\n if (expr.value === \"use strict\") {\n return true;\n }\n }\n }\n }\n return false;\n}\n\n/**\n * Register scope\n * @param {ScopeManager} scopeManager scope manager\n * @param {Scope} scope scope\n * @returns {void}\n */\nfunction registerScope(scopeManager, scope) {\n scopeManager.scopes.push(scope);\n\n const scopes = scopeManager.__nodeToScope.get(scope.block);\n\n if (scopes) {\n scopes.push(scope);\n } else {\n scopeManager.__nodeToScope.set(scope.block, [scope]);\n }\n}\n\n/**\n * Should be statically\n * @param {Object} def def\n * @returns {boolean} should be statically\n */\nfunction shouldBeStatically(def) {\n return (\n (def.type === Variable.ClassName) ||\n (def.type === Variable.Variable && def.parent.kind !== \"var\")\n );\n}\n\n/**\n * @constructor Scope\n */\nclass Scope {\n constructor(scopeManager, type, upperScope, block, isMethodDefinition) {\n\n /**\n * One of \"global\", \"module\", \"function\", \"function-expression-name\", \"block\", \"switch\", \"catch\", \"with\", \"for\",\n * \"class\", \"class-field-initializer\", \"class-static-block\".\n * @member {string} Scope#type\n */\n this.type = type;\n\n /**\n * The scoped {@link Variable}s of this scope, as <code>{ Variable.name\n * : Variable }</code>.\n * @member {Map} Scope#set\n */\n this.set = new Map();\n\n /**\n * The tainted variables of this scope, as <code>{ Variable.name :\n * boolean }</code>.\n * @member {Map} Scope#taints */\n this.taints = new Map();\n\n /**\n * Generally, through the lexical scoping of JS you can always know\n * which variable an identifier in the source code refers to. There are\n * a few exceptions to this rule. With 'global' and 'with' scopes you\n * can only decide at runtime which variable a reference refers to.\n * Moreover, if 'eval()' is used in a scope, it might introduce new\n * bindings in this or its parent scopes.\n * All those scopes are considered 'dynamic'.\n * @member {boolean} Scope#dynamic\n */\n this.dynamic = this.type === \"global\" || this.type === \"with\";\n\n /**\n * A reference to the scope-defining syntax node.\n * @member {espree.Node} Scope#block\n */\n this.block = block;\n\n /**\n * The {@link Reference|references} that are not resolved with this scope.\n * @member {Reference[]} Scope#through\n */\n this.through = [];\n\n /**\n * The scoped {@link Variable}s of this scope. In the case of a\n * 'function' scope this includes the automatic argument <em>arguments</em> as\n * its first element, as well as all further formal arguments.\n * @member {Variable[]} Scope#variables\n */\n this.variables = [];\n\n /**\n * Any variable {@link Reference|reference} found in this scope. This\n * includes occurrences of local variables as well as variables from\n * parent scopes (including the global scope). For local variables\n * this also includes defining occurrences (like in a 'var' statement).\n * In a 'function' scope this does not include the occurrences of the\n * formal parameter in the parameter list.\n * @member {Reference[]} Scope#references\n */\n this.references = [];\n\n /**\n * For 'global' and 'function' scopes, this is a self-reference. For\n * other scope types this is the <em>variableScope</em> value of the\n * parent scope.\n * @member {Scope} Scope#variableScope\n */\n this.variableScope =\n this.type === \"global\" ||\n this.type === \"module\" ||\n this.type === \"function\" ||\n this.type === \"class-field-initializer\" ||\n this.type === \"class-static-block\"\n ? this\n : upperScope.variableScope;\n\n /**\n * Whether this scope is created by a FunctionExpression.\n * @member {boolean} Scope#functionExpressionScope\n */\n this.functionExpressionScope = false;\n\n /**\n * Whether this is a scope that contains an 'eval()' invocation.\n * @member {boolean} Scope#directCallToEvalScope\n */\n this.directCallToEvalScope = false;\n\n /**\n * @member {boolean} Scope#thisFound\n */\n this.thisFound = false;\n\n this.__left = [];\n\n /**\n * Reference to the parent {@link Scope|scope}.\n * @member {Scope} Scope#upper\n */\n this.upper = upperScope;\n\n /**\n * Whether 'use strict' is in effect in this scope.\n * @member {boolean} Scope#isStrict\n */\n this.isStrict = scopeManager.isStrictModeSupported()\n ? isStrictScope(this, block, isMethodDefinition, scopeManager.__useDirective())\n : false;\n\n /**\n * List of nested {@link Scope}s.\n * @member {Scope[]} Scope#childScopes\n */\n this.childScopes = [];\n if (this.upper) {\n this.upper.childScopes.push(this);\n }\n\n this.__declaredVariables = scopeManager.__declaredVariables;\n\n registerScope(scopeManager, this);\n }\n\n __shouldStaticallyClose(scopeManager) {\n return (!this.dynamic || scopeManager.__isOptimistic());\n }\n\n __shouldStaticallyCloseForGlobal(ref) {\n\n // On global scope, let/const/class declarations should be resolved statically.\n const name = ref.identifier.name;\n\n if (!this.set.has(name)) {\n return false;\n }\n\n const variable = this.set.get(name);\n const defs = variable.defs;\n\n return defs.length > 0 && defs.every(shouldBeStatically);\n }\n\n __staticCloseRef(ref) {\n if (!this.__resolve(ref)) {\n this.__delegateToUpperScope(ref);\n }\n }\n\n __dynamicCloseRef(ref) {\n\n // notify all names are through to global\n let current = this;\n\n do {\n current.through.push(ref);\n current = current.upper;\n } while (current);\n }\n\n __globalCloseRef(ref) {\n\n // let/const/class declarations should be resolved statically.\n // others should be resolved dynamically.\n if (this.__shouldStaticallyCloseForGlobal(ref)) {\n this.__staticCloseRef(ref);\n } else {\n this.__dynamicCloseRef(ref);\n }\n }\n\n __close(scopeManager) {\n let closeRef;\n\n if (this.__shouldStaticallyClose(scopeManager)) {\n closeRef = this.__staticCloseRef;\n } else if (this.type !== \"global\") {\n closeRef = this.__dynamicCloseRef;\n } else {\n closeRef = this.__globalCloseRef;\n }\n\n // Try Resolving all references in this scope.\n for (let i = 0, iz = this.__left.length; i < iz; ++i) {\n const ref = this.__left[i];\n\n closeRef.call(this, ref);\n }\n this.__left = null;\n\n return this.upper;\n }\n\n // To override by function scopes.\n // References in default parameters isn't resolved to variables which are in their function body.\n __isValidResolution(ref, variable) { // eslint-disable-line class-methods-use-this, no-unused-vars\n return true;\n }\n\n __resolve(ref) {\n const name = ref.identifier.name;\n\n if (!this.set.has(name)) {\n return false;\n }\n const variable = this.set.get(name);\n\n if (!this.__isValidResolution(ref, variable)) {\n return false;\n }\n variable.references.push(ref);\n variable.stack = variable.stack && ref.from.variableScope === this.variableScope;\n if (ref.tainted) {\n variable.tainted = true;\n this.taints.set(variable.name, true);\n }\n ref.resolved = variable;\n\n return true;\n }\n\n __delegateToUpperScope(ref) {\n if (this.upper) {\n this.upper.__left.push(ref);\n }\n this.through.push(ref);\n }\n\n __addDeclaredVariablesOfNode(variable, node) {\n if (node === null || node === undefined) {\n return;\n }\n\n let variables = this.__declaredVariables.get(node);\n\n if (variables === null || variables === undefined) {\n variables = [];\n this.__declaredVariables.set(node, variables);\n }\n if (variables.indexOf(variable) === -1) {\n variables.push(variable);\n }\n }\n\n __defineGeneric(name, set, variables, node, def) {\n let variable;\n\n variable = set.get(name);\n if (!variable) {\n variable = new Variable(name, this);\n set.set(name, variable);\n variables.push(variable);\n }\n\n if (def) {\n variable.defs.push(def);\n this.__addDeclaredVariablesOfNode(variable, def.node);\n this.__addDeclaredVariablesOfNode(variable, def.parent);\n }\n if (node) {\n variable.identifiers.push(node);\n }\n }\n\n __define(node, def) {\n if (node && node.type === Syntax.Identifier) {\n this.__defineGeneric(\n node.name,\n this.set,\n this.variables,\n node,\n def\n );\n }\n }\n\n __referencing(node, assign, writeExpr, maybeImplicitGlobal, partial, init) {\n\n // because Array element may be null\n if (!node || node.type !== Syntax.Identifier) {\n return;\n }\n\n // Specially handle like `this`.\n if (node.name === \"super\") {\n return;\n }\n\n const ref = new Reference(node, this, assign || Reference.READ, writeExpr, maybeImplicitGlobal, !!partial, !!init);\n\n this.references.push(ref);\n this.__left.push(ref);\n }\n\n __detectEval() {\n let current = this;\n\n this.directCallToEvalScope = true;\n do {\n current.dynamic = true;\n current = current.upper;\n } while (current);\n }\n\n __detectThis() {\n this.thisFound = true;\n }\n\n __isClosed() {\n return this.__left === null;\n }\n\n /**\n * returns resolved {Reference}\n * @function Scope#resolve\n * @param {Espree.Identifier} ident identifier to be resolved.\n * @returns {Reference} reference\n */\n resolve(ident) {\n let ref, i, iz;\n\n assert(this.__isClosed(), \"Scope should be closed.\");\n assert(ident.type === Syntax.Identifier, \"Target should be identifier.\");\n for (i = 0, iz = this.references.length; i < iz; ++i) {\n ref = this.references[i];\n if (ref.identifier === ident) {\n return ref;\n }\n }\n return null;\n }\n\n /**\n * returns this scope is static\n * @function Scope#isStatic\n * @returns {boolean} static\n */\n isStatic() {\n return !this.dynamic;\n }\n\n /**\n * returns this scope has materialized arguments\n * @function Scope#isArgumentsMaterialized\n * @returns {boolean} arguemnts materialized\n */\n isArgumentsMaterialized() { // eslint-disable-line class-methods-use-this\n return true;\n }\n\n /**\n * returns this scope has materialized `this` reference\n * @function Scope#isThisMaterialized\n * @returns {boolean} this materialized\n */\n isThisMaterialized() { // eslint-disable-line class-methods-use-this\n return true;\n }\n\n isUsedName(name) {\n if (this.set.has(name)) {\n return true;\n }\n for (let i = 0, iz = this.through.length; i < iz; ++i) {\n if (this.through[i].identifier.name === name) {\n return true;\n }\n }\n return false;\n }\n}\n\nclass GlobalScope extends Scope {\n constructor(scopeManager, block) {\n super(scopeManager, \"global\", null, block, false);\n this.implicit = {\n set: new Map(),\n variables: [],\n\n /**\n * List of {@link Reference}s that are left to be resolved (i.e. which\n * need to be linked to the variable they refer to).\n * @member {Reference[]} Scope#implicit#left\n */\n left: []\n };\n }\n\n __close(scopeManager) {\n const implicit = [];\n\n for (let i = 0, iz = this.__left.length; i < iz; ++i) {\n const ref = this.__left[i];\n\n if (ref.__maybeImplicitGlobal && !this.set.has(ref.identifier.name)) {\n implicit.push(ref.__maybeImplicitGlobal);\n }\n }\n\n // create an implicit global variable from assignment expression\n for (let i = 0, iz = implicit.length; i < iz; ++i) {\n const info = implicit[i];\n\n this.__defineImplicit(info.pattern,\n new Definition(\n Variable.ImplicitGlobalVariable,\n info.pattern,\n info.node,\n null,\n null,\n null\n ));\n\n }\n\n this.implicit.left = this.__left;\n\n return super.__close(scopeManager);\n }\n\n __defineImplicit(node, def) {\n if (node && node.type === Syntax.Identifier) {\n this.__defineGeneric(\n node.name,\n this.implicit.set,\n this.implicit.variables,\n node,\n def\n );\n }\n }\n}\n\nclass ModuleScope extends Scope {\n constructor(scopeManager, upperScope, block) {\n super(scopeManager, \"module\", upperScope, block, false);\n }\n}\n\nclass FunctionExpressionNameScope extends Scope {\n constructor(scopeManager, upperScope, block) {\n super(scopeManager, \"function-expression-name\", upperScope, block, false);\n this.__define(block.id,\n new Definition(\n Variable.FunctionName,\n block.id,\n block,\n null,\n null,\n null\n ));\n this.functionExpressionScope = true;\n }\n}\n\nclass CatchScope extends Scope {\n constructor(scopeManager, upperScope, block) {\n super(scopeManager, \"catch\", upperScope, block, false);\n }\n}\n\nclass WithScope extends Scope {\n constructor(scopeManager, upperScope, block) {\n super(scopeManager, \"with\", upperScope, block, false);\n }\n\n __close(scopeManager) {\n if (this.__shouldStaticallyClose(scopeManager)) {\n return super.__close(scopeManager);\n }\n\n for (let i = 0, iz = this.__left.length; i < iz; ++i) {\n const ref = this.__left[i];\n\n ref.tainted = true;\n this.__delegateToUpperScope(ref);\n }\n this.__left = null;\n\n return this.upper;\n }\n}\n\nclass BlockScope extends Scope {\n constructor(scopeManager, upperScope, block) {\n super(scopeManager, \"block\", upperScope, block, false);\n }\n}\n\nclass SwitchScope extends Scope {\n constructor(scopeManager, upperScope, block) {\n super(scopeManager, \"switch\", upperScope, block, false);\n }\n}\n\nclass FunctionScope extends Scope {\n constructor(scopeManager, upperScope, block, isMethodDefinition) {\n super(scopeManager, \"function\", upperScope, block, isMethodDefinition);\n\n // section 9.2.13, FunctionDeclarationInstantiation.\n // NOTE Arrow functions never have an arguments objects.\n if (this.block.type !== Syntax.ArrowFunctionExpression) {\n this.__defineArguments();\n }\n }\n\n isArgumentsMaterialized() {\n\n // TODO(Constellation)\n // We can more aggressive on this condition like this.\n //\n // function t() {\n // // arguments of t is always hidden.\n // function arguments() {\n // }\n // }\n if (this.block.type === Syntax.ArrowFunctionExpression) {\n return false;\n }\n\n if (!this.isStatic()) {\n return true;\n }\n\n const variable = this.set.get(\"arguments\");\n\n assert(variable, \"Always have arguments variable.\");\n return variable.tainted || variable.references.length !== 0;\n }\n\n isThisMaterialized() {\n if (!this.isStatic()) {\n return true;\n }\n return this.thisFound;\n }\n\n __defineArguments() {\n this.__defineGeneric(\n \"arguments\",\n this.set,\n this.variables,\n null,\n null\n );\n this.taints.set(\"arguments\", true);\n }\n\n // References in default parameters isn't resolved to variables which are in their function body.\n // const x = 1\n // function f(a = x) { // This `x` is resolved to the `x` in the outer scope.\n // const x = 2\n // console.log(a)\n // }\n __isValidResolution(ref, variable) {\n\n // If `options.nodejsScope` is true, `this.block` becomes a Program node.\n if (this.block.type === \"Program\") {\n return true;\n }\n\n const bodyStart = this.block.body.range[0];\n\n // It's invalid resolution in the following case:\n return !(\n variable.scope === this &&\n ref.identifier.range[0] < bodyStart && // the reference is in the parameter part.\n variable.defs.every(d => d.name.range[0] >= bodyStart) // the variable is in the body.\n );\n }\n}\n\nclass ForScope extends Scope {\n constructor(scopeManager, upperScope, block) {\n super(scopeManager, \"for\", upperScope, block, false);\n }\n}\n\nclass ClassScope extends Scope {\n constructor(scopeManager, upperScope, block) {\n super(scopeManager, \"class\", upperScope, block, false);\n }\n}\n\nclass ClassFieldInitializerScope extends Scope {\n constructor(scopeManager, upperScope, block) {\n super(scopeManager, \"class-field-initializer\", upperScope, block, true);\n }\n}\n\nclass ClassStaticBlockScope extends Scope {\n constructor(scopeManager, upperScope, block) {\n super(scopeManager, \"class-static-block\", upperScope, block, true);\n }\n}\n\nexport {\n Scope,\n GlobalScope,\n ModuleScope,\n FunctionExpressionNameScope,\n CatchScope,\n WithScope,\n BlockScope,\n SwitchScope,\n FunctionScope,\n ForScope,\n ClassScope,\n ClassFieldInitializerScope,\n ClassStaticBlockScope\n};\n\n/* vim: set sw=4 ts=4 et tw=80 : */\n", "/*\n Copyright (C) 2015 Yusuke Suzuki <utatane.tea@gmail.com>\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\n DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\nconst READ = 0x1;\nconst WRITE = 0x2;\nconst RW = READ | WRITE;\n\n/**\n * A Reference represents a single occurrence of an identifier in code.\n * @constructor Reference\n */\nclass Reference {\n constructor(ident, scope, flag, writeExpr, maybeImplicitGlobal, partial, init) {\n\n /**\n * Identifier syntax node.\n * @member {espreeIdentifier} Reference#identifier\n */\n this.identifier = ident;\n\n /**\n * Reference to the enclosing Scope.\n * @member {Scope} Reference#from\n */\n this.from = scope;\n\n /**\n * Whether the reference comes from a dynamic scope (such as 'eval',\n * 'with', etc.), and may be trapped by dynamic scopes.\n * @member {boolean} Reference#tainted\n */\n this.tainted = false;\n\n /**\n * The variable this reference is resolved with.\n * @member {Variable} Reference#resolved\n */\n this.resolved = null;\n\n /**\n * The read-write mode of the reference. (Value is one of {@link\n * Reference.READ}, {@link Reference.RW}, {@link Reference.WRITE}).\n * @member {number} Reference#flag\n * @private\n */\n this.flag = flag;\n if (this.isWrite()) {\n\n /**\n * If reference is writeable, this is the tree being written to it.\n * @member {espreeNode} Reference#writeExpr\n */\n this.writeExpr = writeExpr;\n\n /**\n * Whether the Reference might refer to a partial value of writeExpr.\n * @member {boolean} Reference#partial\n */\n this.partial = partial;\n\n /**\n * Whether the Reference is to write of initialization.\n * @member {boolean} Reference#init\n */\n this.init = init;\n }\n this.__maybeImplicitGlobal = maybeImplicitGlobal;\n }\n\n /**\n * Whether the reference is static.\n * @function Reference#isStatic\n * @returns {boolean} static\n */\n isStatic() {\n return !this.tainted && this.resolved && this.resolved.scope.isStatic();\n }\n\n /**\n * Whether the reference is writeable.\n * @function Reference#isWrite\n * @returns {boolean} write\n */\n isWrite() {\n return !!(this.flag & Reference.WRITE);\n }\n\n /**\n * Whether the reference is readable.\n * @function Reference#isRead\n * @returns {boolean} read\n */\n isRead() {\n return !!(this.flag & Reference.READ);\n }\n\n /**\n * Whether the reference is read-only.\n * @function Reference#isReadOnly\n * @returns {boolean} read only\n */\n isReadOnly() {\n return this.flag === Reference.READ;\n }\n\n /**\n * Whether the reference is write-only.\n * @function Reference#isWriteOnly\n * @returns {boolean} write only\n */\n isWriteOnly() {\n return this.flag === Reference.WRITE;\n }\n\n /**\n * Whether the reference is read-write.\n * @function Reference#isReadWrite\n * @returns {boolean} read write\n */\n isReadWrite() {\n return this.flag === Reference.RW;\n }\n}\n\n/**\n * @constant Reference.READ\n * @private\n */\nReference.READ = READ;\n\n/**\n * @constant Reference.WRITE\n * @private\n */\nReference.WRITE = WRITE;\n\n/**\n * @constant Reference.RW\n * @private\n */\nReference.RW = RW;\n\nexport default Reference;\n\n/* vim: set sw=4 ts=4 et tw=80 : */\n", "/*\n Copyright (C) 2015 Yusuke Suzuki <utatane.tea@gmail.com>\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\n DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n/**\n * A Variable represents a locally scoped identifier. These include arguments to\n * functions.\n * @constructor Variable\n */\nclass Variable {\n constructor(name, scope) {\n\n /**\n * The variable name, as given in the source code.\n * @member {string} Variable#name\n */\n this.name = name;\n\n /**\n * List of defining occurrences of this variable (like in 'var ...'\n * statements or as parameter), as AST nodes.\n * @member {espree.Identifier[]} Variable#identifiers\n */\n this.identifiers = [];\n\n /**\n * List of {@link Reference|references} of this variable (excluding parameter entries)\n * in its defining scope and all nested scopes. For defining\n * occurrences only see {@link Variable#defs}.\n * @member {Reference[]} Variable#references\n */\n this.references = [];\n\n /**\n * List of defining occurrences of this variable (like in 'var ...'\n * statements or as parameter), as custom objects.\n * @member {Definition[]} Variable#defs\n */\n this.defs = [];\n\n this.tainted = false;\n\n /**\n * Whether this is a stack variable.\n * @member {boolean} Variable#stack\n */\n this.stack = true;\n\n /**\n * Reference to the enclosing Scope.\n * @member {Scope} Variable#scope\n */\n this.scope = scope;\n }\n}\n\nVariable.CatchClause = \"CatchClause\";\nVariable.Parameter = \"Parameter\";\nVariable.FunctionName = \"FunctionName\";\nVariable.ClassName = \"ClassName\";\nVariable.Variable = \"Variable\";\nVariable.ImportBinding = \"ImportBinding\";\nVariable.ImplicitGlobalVariable = \"ImplicitGlobalVariable\";\n\nexport default Variable;\n\n/* vim: set sw=4 ts=4 et tw=80 : */\n", "/*\n Copyright (C) 2015 Yusuke Suzuki <utatane.tea@gmail.com>\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\n DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\nimport Variable from \"./variable.js\";\n\n/**\n * @constructor Definition\n */\nclass Definition {\n constructor(type, name, node, parent, index, kind) {\n\n /**\n * @member {string} Definition#type - type of the occurrence (e.g. \"Parameter\", \"Variable\", ...).\n */\n this.type = type;\n\n /**\n * @member {espree.Identifier} Definition#name - the identifier AST node of the occurrence.\n */\n this.name = name;\n\n /**\n * @member {espree.Node} Definition#node - the enclosing node of the identifier.\n */\n this.node = node;\n\n /**\n * @member {espree.Node?} Definition#parent - the enclosing statement node of the identifier.\n */\n this.parent = parent;\n\n /**\n * @member {number?} Definition#index - the index in the declaration statement.\n */\n this.index = index;\n\n /**\n * @member {string?} Definition#kind - the kind of the declaration statement.\n */\n this.kind = kind;\n }\n}\n\n/**\n * @constructor ParameterDefinition\n */\nclass ParameterDefinition extends Definition {\n constructor(name, node, index, rest) {\n super(Variable.Parameter, name, node, null, index, null);\n\n /**\n * Whether the parameter definition is a part of a rest parameter.\n * @member {boolean} ParameterDefinition#rest\n */\n this.rest = rest;\n }\n}\n\nexport {\n ParameterDefinition,\n Definition\n};\n\n/* vim: set sw=4 ts=4 et tw=80 : */\n", "/*\n Copyright (C) 2015 Yusuke Suzuki <utatane.tea@gmail.com>\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\n DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n/* eslint-disable no-underscore-dangle */\n\nimport {\n BlockScope,\n CatchScope,\n ClassFieldInitializerScope,\n ClassStaticBlockScope,\n ClassScope,\n ForScope,\n FunctionExpressionNameScope,\n FunctionScope,\n GlobalScope,\n ModuleScope,\n SwitchScope,\n WithScope\n} from \"./scope.js\";\nimport assert from \"assert\";\n\n/**\n * @constructor ScopeManager\n */\nclass ScopeManager {\n constructor(options) {\n this.scopes = [];\n this.globalScope = null;\n this.__nodeToScope = new WeakMap();\n this.__currentScope = null;\n this.__options = options;\n this.__declaredVariables = new WeakMap();\n }\n\n __useDirective() {\n return this.__options.directive;\n }\n\n __isOptimistic() {\n return this.__options.optimistic;\n }\n\n __ignoreEval() {\n return this.__options.ignoreEval;\n }\n\n isGlobalReturn() {\n return this.__options.nodejsScope || this.__options.sourceType === \"commonjs\";\n }\n\n isModule() {\n return this.__options.sourceType === \"module\";\n }\n\n isImpliedStrict() {\n return this.__options.impliedStrict;\n }\n\n isStrictModeSupported() {\n return this.__options.ecmaVersion >= 5;\n }\n\n // Returns appropriate scope for this node.\n __get(node) {\n return this.__nodeToScope.get(node);\n }\n\n /**\n * Get variables that are declared by the node.\n *\n * \"are declared by the node\" means the node is same as `Variable.defs[].node` or `Variable.defs[].parent`.\n * If the node declares nothing, this method returns an empty array.\n * CAUTION: This API is experimental. See https://github.com/estools/escope/pull/69 for more details.\n * @param {Espree.Node} node a node to get.\n * @returns {Variable[]} variables that declared by the node.\n */\n getDeclaredVariables(node) {\n return this.__declaredVariables.get(node) || [];\n }\n\n /**\n * acquire scope from node.\n * @function ScopeManager#acquire\n * @param {Espree.Node} node node for the acquired scope.\n * @param {?boolean} [inner=false] look up the most inner scope, default value is false.\n * @returns {Scope?} Scope from node\n */\n acquire(node, inner) {\n\n /**\n * predicate\n * @param {Scope} testScope scope to test\n * @returns {boolean} predicate\n */\n function predicate(testScope) {\n if (testScope.type === \"function\" && testScope.functionExpressionScope) {\n return false;\n }\n return true;\n }\n\n const scopes = this.__get(node);\n\n if (!scopes || scopes.length === 0) {\n return null;\n }\n\n // Heuristic selection from all scopes.\n // If you would like to get all scopes, please use ScopeManager#acquireAll.\n if (scopes.length === 1) {\n return scopes[0];\n }\n\n if (inner) {\n for (let i = scopes.length - 1; i >= 0; --i) {\n const scope = scopes[i];\n\n if (predicate(scope)) {\n return scope;\n }\n }\n } else {\n for (let i = 0, iz = scopes.length; i < iz; ++i) {\n const scope = scopes[i];\n\n if (predicate(scope)) {\n return scope;\n }\n }\n }\n\n return null;\n }\n\n /**\n * acquire all scopes from node.\n * @function ScopeManager#acquireAll\n * @param {Espree.Node} node node for the acquired scope.\n * @returns {Scopes?} Scope array\n */\n acquireAll(node) {\n return this.__get(node);\n }\n\n /**\n * release the node.\n * @function ScopeManager#release\n * @param {Espree.Node} node releasing node.\n * @param {?boolean} [inner=false] look up the most inner scope, default value is false.\n * @returns {Scope?} upper scope for the node.\n */\n release(node, inner) {\n const scopes = this.__get(node);\n\n if (scopes && scopes.length) {\n const scope = scopes[0].upper;\n\n if (!scope) {\n return null;\n }\n return this.acquire(scope.block, inner);\n }\n return null;\n }\n\n attach() { } // eslint-disable-line class-methods-use-this\n\n detach() { } // eslint-disable-line class-methods-use-this\n\n __nestScope(scope) {\n if (scope instanceof GlobalScope) {\n assert(this.__currentScope === null);\n this.globalScope = scope;\n }\n this.__currentScope = scope;\n return scope;\n }\n\n __nestGlobalScope(node) {\n return this.__nestScope(new GlobalScope(this, node));\n }\n\n __nestBlockScope(node) {\n return this.__nestScope(new BlockScope(this, this.__currentScope, node));\n }\n\n __nestFunctionScope(node, isMethodDefinition) {\n return this.__nestScope(new FunctionScope(this, this.__currentScope, node, isMethodDefinition));\n }\n\n __nestForScope(node) {\n return this.__nestScope(new ForScope(this, this.__currentScope, node));\n }\n\n __nestCatchScope(node) {\n return this.__nestScope(new CatchScope(this, this.__currentScope, node));\n }\n\n __nestWithScope(node) {\n return this.__nestScope(new WithScope(this, this.__currentScope, node));\n }\n\n __nestClassScope(node) {\n return this.__nestScope(new ClassScope(this, this.__currentScope, node));\n }\n\n __nestClassFieldInitializerScope(node) {\n return this.__nestScope(new ClassFieldInitializerScope(this, this.__currentScope, node));\n }\n\n __nestClassStaticBlockScope(node) {\n return this.__nestScope(new ClassStaticBlockScope(this, this.__currentScope, node));\n }\n\n __nestSwitchScope(node) {\n return this.__nestScope(new SwitchScope(this, this.__currentScope, node));\n }\n\n __nestModuleScope(node) {\n return this.__nestScope(new ModuleScope(this, this.__currentScope, node));\n }\n\n __nestFunctionExpressionNameScope(node) {\n return this.__nestScope(new FunctionExpressionNameScope(this, this.__currentScope, node));\n }\n\n __isES6() {\n return this.__options.ecmaVersion >= 6;\n }\n}\n\nexport default ScopeManager;\n\n/* vim: set sw=4 ts=4 et tw=80 : */\n", "/*\n Copyright (C) 2015 Yusuke Suzuki <utatane.tea@gmail.com>\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\n DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n/* eslint-disable no-underscore-dangle */\n/* eslint-disable no-undefined */\n\nimport estraverse from \"estraverse\";\nimport esrecurse from \"esrecurse\";\nimport Reference from \"./reference.js\";\nimport Variable from \"./variable.js\";\nimport PatternVisitor from \"./pattern-visitor.js\";\nimport { Definition, ParameterDefinition } from \"./definition.js\";\nimport assert from \"assert\";\n\nconst { Syntax } = estraverse;\n\n/**\n * Traverse identifier in pattern\n * @param {Object} options options\n * @param {pattern} rootPattern root pattern\n * @param {Refencer} referencer referencer\n * @param {callback} callback callback\n * @returns {void}\n */\nfunction traverseIdentifierInPattern(options, rootPattern, referencer, callback) {\n\n // Call the callback at left hand identifier nodes, and Collect right hand nodes.\n const visitor = new PatternVisitor(options, rootPattern, callback);\n\n visitor.visit(rootPattern);\n\n // Process the right hand nodes recursively.\n if (referencer !== null && referencer !== undefined) {\n visitor.rightHandNodes.forEach(referencer.visit, referencer);\n }\n}\n\n// Importing ImportDeclaration.\n// http://people.mozilla.org/~jorendorff/es6-draft.html#sec-moduledeclarationinstantiation\n// https://github.com/estree/estree/blob/master/es6.md#importdeclaration\n// FIXME: Now, we don't create module environment, because the context is\n// implementation dependent.\n\nclass Importer extends esrecurse.Visitor {\n constructor(declaration, referencer) {\n super(null, referencer.options);\n this.declaration = declaration;\n this.referencer = referencer;\n }\n\n visitImport(id, specifier) {\n this.referencer.visitPattern(id, pattern => {\n this.referencer.currentScope().__define(pattern,\n new Definition(\n Variable.ImportBinding,\n pattern,\n specifier,\n this.declaration,\n null,\n null\n ));\n });\n }\n\n ImportNamespaceSpecifier(node) {\n const local = (node.local || node.id);\n\n if (local) {\n this.visitImport(local, node);\n }\n }\n\n ImportDefaultSpecifier(node) {\n const local = (node.local || node.id);\n\n this.visitImport(local, node);\n }\n\n ImportSpecifier(node) {\n const local = (node.local || node.id);\n\n if (node.name) {\n this.visitImport(node.name, node);\n } else {\n this.visitImport(local, node);\n }\n }\n}\n\n// Referencing variables and creating bindings.\nclass Referencer extends esrecurse.Visitor {\n constructor(options, scopeManager) {\n super(null, options);\n this.options = options;\n this.scopeManager = scopeManager;\n this.parent = null;\n this.isInnerMethodDefinition = false;\n }\n\n currentScope() {\n return this.scopeManager.__currentScope;\n }\n\n close(node) {\n while (this.currentScope() && node === this.currentScope().block) {\n this.scopeManager.__currentScope = this.currentScope().__close(this.scopeManager);\n }\n }\n\n pushInnerMethodDefinition(isInnerMethodDefinition) {\n const previous = this.isInnerMethodDefinition;\n\n this.isInnerMethodDefinition = isInnerMethodDefinition;\n return previous;\n }\n\n popInnerMethodDefinition(isInnerMethodDefinition) {\n this.isInnerMethodDefinition = isInnerMethodDefinition;\n }\n\n referencingDefaultValue(pattern, assignments, maybeImplicitGlobal, init) {\n const scope = this.currentScope();\n\n assignments.forEach(assignment => {\n scope.__referencing(\n pattern,\n Reference.WRITE,\n assignment.right,\n maybeImplicitGlobal,\n pattern !== assignment.left,\n init\n );\n });\n }\n\n visitPattern(node, options, callback) {\n let visitPatternOptions = options;\n let visitPatternCallback = callback;\n\n if (typeof options === \"function\") {\n visitPatternCallback = options;\n visitPatternOptions = { processRightHandNodes: false };\n }\n\n traverseIdentifierInPattern(\n this.options,\n node,\n visitPatternOptions.processRightHandNodes ? this : null,\n visitPatternCallback\n );\n }\n\n visitFunction(node) {\n let i, iz;\n\n // FunctionDeclaration name is defined in upper scope\n // NOTE: Not referring variableScope. It is intended.\n // Since\n // in ES5, FunctionDeclaration should be in FunctionBody.\n // in ES6, FunctionDeclaration should be block scoped.\n\n if (node.type === Syntax.FunctionDeclaration) {\n\n // id is defined in upper scope\n this.currentScope().__define(node.id,\n new Definition(\n Variable.FunctionName,\n node.id,\n node,\n null,\n null,\n null\n ));\n }\n\n // FunctionExpression with name creates its special scope;\n // FunctionExpressionNameScope.\n if (node.type === Syntax.FunctionExpression && node.id) {\n this.scopeManager.__nestFunctionExpressionNameScope(node);\n }\n\n // Consider this function is in the MethodDefinition.\n this.scopeManager.__nestFunctionScope(node, this.isInnerMethodDefinition);\n\n const that = this;\n\n /**\n * Visit pattern callback\n * @param {pattern} pattern pattern\n * @param {Object} info info\n * @returns {void}\n */\n function visitPatternCallback(pattern, info) {\n that.currentScope().__define(pattern,\n new ParameterDefinition(\n pattern,\n node,\n i,\n info.rest\n ));\n\n that.referencingDefaultValue(pattern, info.assignments, null, true);\n }\n\n // Process parameter declarations.\n for (i = 0, iz = node.params.length; i < iz; ++i) {\n this.visitPattern(node.params[i], { processRightHandNodes: true }, visitPatternCallback);\n }\n\n // if there's a rest argument, add that\n if (node.rest) {\n this.visitPattern({\n type: \"RestElement\",\n argument: node.rest\n }, pattern => {\n this.currentScope().__define(pattern,\n new ParameterDefinition(\n pattern,\n node,\n node.params.length,\n true\n ));\n });\n }\n\n // In TypeScript there are a number of function-like constructs which have no body,\n // so check it exists before traversing\n if (node.body) {\n\n // Skip BlockStatement to prevent creating BlockStatement scope.\n if (node.body.type === Syntax.BlockStatement) {\n this.visitChildren(node.body);\n } else {\n this.visit(node.body);\n }\n }\n\n this.close(node);\n }\n\n visitClass(node) {\n if (node.type === Syntax.ClassDeclaration) {\n this.currentScope().__define(node.id,\n new Definition(\n Variable.ClassName,\n node.id,\n node,\n null,\n null,\n null\n ));\n }\n\n this.visit(node.superClass);\n\n this.scopeManager.__nestClassScope(node);\n\n if (node.id) {\n this.currentScope().__define(node.id,\n new Definition(\n Variable.ClassName,\n node.id,\n node\n ));\n }\n this.visit(node.body);\n\n this.close(node);\n }\n\n visitProperty(node) {\n let previous;\n\n if (node.computed) {\n this.visit(node.key);\n }\n\n const isMethodDefinition = node.type === Syntax.MethodDefinition;\n\n if (isMethodDefinition) {\n previous = this.pushInnerMethodDefinition(true);\n }\n this.visit(node.value);\n if (isMethodDefinition) {\n this.popInnerMethodDefinition(previous);\n }\n }\n\n visitForIn(node) {\n if (node.left.type === Syntax.VariableDeclaration && node.left.kind !== \"var\") {\n this.scopeManager.__nestForScope(node);\n }\n\n if (node.left.type === Syntax.VariableDeclaration) {\n this.visit(node.left);\n this.visitPattern(node.left.declarations[0].id, pattern => {\n this.currentScope().__referencing(pattern, Reference.WRITE, node.right, null, true, true);\n });\n } else {\n this.visitPattern(node.left, { processRightHandNodes: true }, (pattern, info) => {\n let maybeImplicitGlobal = null;\n\n if (!this.currentScope().isStrict) {\n maybeImplicitGlobal = {\n pattern,\n node\n };\n }\n this.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false);\n this.currentScope().__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, true, false);\n });\n }\n this.visit(node.right);\n this.visit(node.body);\n\n this.close(node);\n }\n\n visitVariableDeclaration(variableTargetScope, type, node, index) {\n\n const decl = node.declarations[index];\n const init = decl.init;\n\n this.visitPattern(decl.id, { processRightHandNodes: true }, (pattern, info) => {\n variableTargetScope.__define(\n pattern,\n new Definition(\n type,\n pattern,\n decl,\n node,\n index,\n node.kind\n )\n );\n\n this.referencingDefaultValue(pattern, info.assignments, null, true);\n if (init) {\n this.currentScope().__referencing(pattern, Reference.WRITE, init, null, !info.topLevel, true);\n }\n });\n }\n\n AssignmentExpression(node) {\n if (PatternVisitor.isPattern(node.left)) {\n if (node.operator === \"=\") {\n this.visitPattern(node.left, { processRightHandNodes: true }, (pattern, info) => {\n let maybeImplicitGlobal = null;\n\n if (!this.currentScope().isStrict) {\n maybeImplicitGlobal = {\n pattern,\n node\n };\n }\n this.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false);\n this.currentScope().__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, !info.topLevel, false);\n });\n } else {\n this.currentScope().__referencing(node.left, Reference.RW, node.right);\n }\n } else {\n this.visit(node.left);\n }\n this.visit(node.right);\n }\n\n CatchClause(node) {\n this.scopeManager.__nestCatchScope(node);\n\n this.visitPattern(node.param, { processRightHandNodes: true }, (pattern, info) => {\n this.currentScope().__define(pattern,\n new Definition(\n Variable.CatchClause,\n node.param,\n node,\n null,\n null,\n null\n ));\n this.referencingDefaultValue(pattern, info.assignments, null, true);\n });\n this.visit(node.body);\n\n this.close(node);\n }\n\n Program(node) {\n this.scopeManager.__nestGlobalScope(node);\n\n if (this.scopeManager.isGlobalReturn()) {\n\n // Force strictness of GlobalScope to false when using node.js scope.\n this.currentScope().isStrict = false;\n this.scopeManager.__nestFunctionScope(node, false);\n }\n\n if (this.scopeManager.__isES6() && this.scopeManager.isModule()) {\n this.scopeManager.__nestModuleScope(node);\n }\n\n if (this.scopeManager.isStrictModeSupported() && this.scopeManager.isImpliedStrict()) {\n this.currentScope().isStrict = true;\n }\n\n this.visitChildren(node);\n this.close(node);\n }\n\n Identifier(node) {\n this.currentScope().__referencing(node);\n }\n\n // eslint-disable-next-line class-methods-use-this\n PrivateIdentifier() {\n\n // Do nothing.\n }\n\n UpdateExpression(node) {\n if (PatternVisitor.isPattern(node.argument)) {\n this.currentScope().__referencing(node.argument, Reference.RW, null);\n } else {\n this.visitChildren(node);\n }\n }\n\n MemberExpression(node) {\n this.visit(node.object);\n if (node.computed) {\n this.visit(node.property);\n }\n }\n\n Property(node) {\n this.visitProperty(node);\n }\n\n PropertyDefinition(node) {\n const { computed, key, value } = node;\n\n if (computed) {\n this.visit(key);\n }\n if (value) {\n this.scopeManager.__nestClassFieldInitializerScope(value);\n this.visit(value);\n this.close(value);\n }\n }\n\n StaticBlock(node) {\n this.scopeManager.__nestClassStaticBlockScope(node);\n\n this.visitChildren(node);\n\n this.close(node);\n }\n\n MethodDefinition(node) {\n this.visitProperty(node);\n }\n\n BreakStatement() {} // eslint-disable-line class-methods-use-this\n\n ContinueStatement() {} // eslint-disable-line class-methods-use-this\n\n LabeledStatement(node) {\n this.visit(node.body);\n }\n\n ForStatement(node) {\n\n // Create ForStatement declaration.\n // NOTE: In ES6, ForStatement dynamically generates\n // per iteration environment. However, escope is\n // a static analyzer, we only generate one scope for ForStatement.\n if (node.init && node.init.type === Syntax.VariableDeclaration && node.init.kind !== \"var\") {\n this.scopeManager.__nestForScope(node);\n }\n\n this.visitChildren(node);\n\n this.close(node);\n }\n\n ClassExpression(node) {\n this.visitClass(node);\n }\n\n ClassDeclaration(node) {\n this.visitClass(node);\n }\n\n CallExpression(node) {\n\n // Check this is direct call to eval\n if (!this.scopeManager.__ignoreEval() && node.callee.type === Syntax.Identifier && node.callee.name === \"eval\") {\n\n // NOTE: This should be `variableScope`. Since direct eval call always creates Lexical environment and\n // let / const should be enclosed into it. Only VariableDeclaration affects on the caller's environment.\n this.currentScope().variableScope.__detectEval();\n }\n this.visitChildren(node);\n }\n\n BlockStatement(node) {\n if (this.scopeManager.__isES6()) {\n this.scopeManager.__nestBlockScope(node);\n }\n\n this.visitChildren(node);\n\n this.close(node);\n }\n\n ThisExpression() {\n this.currentScope().variableScope.__detectThis();\n }\n\n WithStatement(node) {\n this.visit(node.object);\n\n // Then nest scope for WithStatement.\n this.scopeManager.__nestWithScope(node);\n\n this.visit(node.body);\n\n this.close(node);\n }\n\n VariableDeclaration(node) {\n const variableTargetScope = (node.kind === \"var\") ? this.currentScope().variableScope : this.currentScope();\n\n for (let i = 0, iz = node.declarations.length; i < iz; ++i) {\n const decl = node.declarations[i];\n\n this.visitVariableDeclaration(variableTargetScope, Variable.Variable, node, i);\n if (decl.init) {\n this.visit(decl.init);\n }\n }\n }\n\n // sec 13.11.8\n SwitchStatement(node) {\n this.visit(node.discriminant);\n\n if (this.scopeManager.__isES6()) {\n this.scopeManager.__nestSwitchScope(node);\n }\n\n for (let i = 0, iz = node.cases.length; i < iz; ++i) {\n this.visit(node.cases[i]);\n }\n\n this.close(node);\n }\n\n FunctionDeclaration(node) {\n this.visitFunction(node);\n }\n\n FunctionExpression(node) {\n this.visitFunction(node);\n }\n\n ForOfStatement(node) {\n this.visitForIn(node);\n }\n\n ForInStatement(node) {\n this.visitForIn(node);\n }\n\n ArrowFunctionExpression(node) {\n this.visitFunction(node);\n }\n\n ImportDeclaration(node) {\n assert(this.scopeManager.__isES6() && this.scopeManager.isModule(), \"ImportDeclaration should appear when the mode is ES6 and in the module context.\");\n\n const importer = new Importer(node, this);\n\n importer.visit(node);\n }\n\n visitExportDeclaration(node) {\n if (node.source) {\n return;\n }\n if (node.declaration) {\n this.visit(node.declaration);\n return;\n }\n\n this.visitChildren(node);\n }\n\n // TODO: ExportDeclaration doesn't exist. for bc?\n ExportDeclaration(node) {\n this.visitExportDeclaration(node);\n }\n\n ExportAllDeclaration(node) {\n this.visitExportDeclaration(node);\n }\n\n ExportDefaultDeclaration(node) {\n this.visitExportDeclaration(node);\n }\n\n ExportNamedDeclaration(node) {\n this.visitExportDeclaration(node);\n }\n\n ExportSpecifier(node) {\n\n // TODO: `node.id` doesn't exist. for bc?\n const local = (node.id || node.local);\n\n this.visit(local);\n }\n\n MetaProperty() { // eslint-disable-line class-methods-use-this\n\n // do nothing.\n }\n}\n\nexport default Referencer;\n\n/* vim: set sw=4 ts=4 et tw=80 : */\n", "/*\n Copyright (C) 2015 Yusuke Suzuki <utatane.tea@gmail.com>\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\n DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n/* eslint-disable no-undefined */\n\nimport estraverse from \"estraverse\";\nimport esrecurse from \"esrecurse\";\n\nconst { Syntax } = estraverse;\n\n/**\n * Get last array element\n * @param {Array} xs array\n * @returns {any} Last elment\n */\nfunction getLast(xs) {\n return xs[xs.length - 1] || null;\n}\n\nclass PatternVisitor extends esrecurse.Visitor {\n static isPattern(node) {\n const nodeType = node.type;\n\n return (\n nodeType === Syntax.Identifier ||\n nodeType === Syntax.ObjectPattern ||\n nodeType === Syntax.ArrayPattern ||\n nodeType === Syntax.SpreadElement ||\n nodeType === Syntax.RestElement ||\n nodeType === Syntax.AssignmentPattern\n );\n }\n\n constructor(options, rootPattern, callback) {\n super(null, options);\n this.rootPattern = rootPattern;\n this.callback = callback;\n this.assignments = [];\n this.rightHandNodes = [];\n this.restElements = [];\n }\n\n Identifier(pattern) {\n const lastRestElement = getLast(this.restElements);\n\n this.callback(pattern, {\n topLevel: pattern === this.rootPattern,\n rest: lastRestElement !== null && lastRestElement !== undefined && lastRestElement.argument === pattern,\n assignments: this.assignments\n });\n }\n\n Property(property) {\n\n // Computed property's key is a right hand node.\n if (property.computed) {\n this.rightHandNodes.push(property.key);\n }\n\n // If it's shorthand, its key is same as its value.\n // If it's shorthand and has its default value, its key is same as its value.left (the value is AssignmentPattern).\n // If it's not shorthand, the name of new variable is its value's.\n this.visit(property.value);\n }\n\n ArrayPattern(pattern) {\n for (let i = 0, iz = pattern.elements.length; i < iz; ++i) {\n const element = pattern.elements[i];\n\n this.visit(element);\n }\n }\n\n AssignmentPattern(pattern) {\n this.assignments.push(pattern);\n this.visit(pattern.left);\n this.rightHandNodes.push(pattern.right);\n this.assignments.pop();\n }\n\n RestElement(pattern) {\n this.restElements.push(pattern);\n this.visit(pattern.argument);\n this.restElements.pop();\n }\n\n MemberExpression(node) {\n\n // Computed property's key is a right hand node.\n if (node.computed) {\n this.rightHandNodes.push(node.property);\n }\n\n // the object is only read, write to its property.\n this.rightHandNodes.push(node.object);\n }\n\n //\n // ForInStatement.left and AssignmentExpression.left are LeftHandSideExpression.\n // By spec, LeftHandSideExpression is Pattern or MemberExpression.\n // (see also: https://github.com/estree/estree/pull/20#issuecomment-74584758)\n // But espree 2.0 parses to ArrayExpression, ObjectExpression, etc...\n //\n\n SpreadElement(node) {\n this.visit(node.argument);\n }\n\n ArrayExpression(node) {\n node.elements.forEach(this.visit, this);\n }\n\n AssignmentExpression(node) {\n this.assignments.push(node);\n this.visit(node.left);\n this.rightHandNodes.push(node.right);\n this.assignments.pop();\n }\n\n CallExpression(node) {\n\n // arguments are right hand nodes.\n node.arguments.forEach(a => {\n this.rightHandNodes.push(a);\n });\n this.visit(node.callee);\n }\n}\n\nexport default PatternVisitor;\n\n/* vim: set sw=4 ts=4 et tw=80 : */\n", "import * as eslintScope from \"eslint-scope\";\r\nimport * as estraverse from \"estraverse\";\r\nimport { KNOWN_GLOBALS } from \"./knownGlobals\";\r\nimport { parseProgram } from \"./jsParse\";\r\n\r\n/**\r\n * QUIKTR-1458 \u2014 the scope half of the in-memory check.\r\n *\r\n * Of the eight failed Bug 4 runs on rc.6, one file did not parse and FOUR used a name wrongly, which a parse cannot see:\r\n * - a new test called a function it never imported (`updateExactSplit is not defined`) -> undefined_name\r\n * - a `const` was used higher up in the same function than the line that declares it -> used_before_declaration\r\n * Both are found from the file alone, in milliseconds, with no disk write and no test run. This module only FINDS them; whether a\r\n * finding is the AI's doing is `SyntaxGuard`'s job (a finding that was already in the file before the change is not).\r\n *\r\n * What it reports is a kind, the name, and a position. The name is for the guard's before/after comparison; it never goes into a\r\n * result the AI reads (the line is enough, and a result carries no file text).\r\n *\r\n * What it will NOT do: find a wrong value, a wrong import path, a call with the wrong arguments, or any wrong behaviour. A name\r\n * that exists but is the wrong one passes.\r\n */\r\n\r\nexport type ScopeKind = \"undefined_name\" | \"used_before_declaration\";\r\n\r\nexport interface ScopeFinding {\r\n kind: ScopeKind;\r\n name: string;\r\n /** 1-based. */\r\n line: number;\r\n /** 0-based. */\r\n column: number;\r\n}\r\n\r\nfunction lineStartsOf(text: string): number[] {\r\n const starts = [0];\r\n for (let i = 0; i < text.length; i++) if (text.charCodeAt(i) === 10) starts.push(i + 1);\r\n return starts;\r\n}\r\n\r\nfunction positionOf(starts: number[], offset: number): { line: number; column: number } {\r\n let lo = 0;\r\n let hi = starts.length - 1;\r\n while (lo < hi) {\r\n const mid = (lo + hi + 1) >> 1;\r\n if (starts[mid]! <= offset) lo = mid;\r\n else hi = mid - 1;\r\n }\r\n return { line: lo + 1, column: offset - starts[lo]! };\r\n}\r\n\r\n/**\r\n * `null` when the file is not one this reads or does not parse. Otherwise every undefined name (not a known global) and every\r\n * let/const/class used before its declaration in the same function, in file order.\r\n */\r\nexport function analyzeScope(path: string, text: string): ScopeFinding[] | null {\r\n try {\r\n const parsed = parseProgram(path, text);\r\n if (!parsed) return null;\r\n const { ast, sourceType } = parsed;\r\n\r\n // Two places a bare name is NOT a use: the operand of `typeof` (it does not throw), and the local name in `export { x }`\r\n // (a live binding, read later, so it may sit above the declaration).\r\n const skip = new Set<number>();\r\n estraverse.traverse(ast, {\r\n fallback: \"iteration\",\r\n enter(node) {\r\n if (node.type === \"UnaryExpression\" && node.operator === \"typeof\") {\r\n const arg = node.argument as { type?: string; range?: [number, number] } | undefined;\r\n if (arg?.type === \"Identifier\" && arg.range) skip.add(arg.range[0]);\r\n } else if (node.type === \"ExportNamedDeclaration\" && !node.source) {\r\n for (const spec of (node.specifiers as { local?: { range?: [number, number] } }[] | undefined) ?? []) {\r\n if (spec.local?.range) skip.add(spec.local.range[0]);\r\n }\r\n }\r\n },\r\n });\r\n\r\n const manager = eslintScope.analyze(ast, {\r\n ecmaVersion: 2022,\r\n sourceType,\r\n // A CommonJS file runs inside a function, so its top-level names are not globals.\r\n nodejsScope: sourceType === \"script\",\r\n ignoreEval: true,\r\n fallback: \"iteration\",\r\n });\r\n\r\n const starts = lineStartsOf(text);\r\n const out: (ScopeFinding & { at: number })[] = [];\r\n\r\n for (const ref of manager.globalScope?.through ?? []) {\r\n const name = ref.identifier.name;\r\n if (KNOWN_GLOBALS.has(name) || skip.has(ref.identifier.range[0])) continue;\r\n const at = ref.identifier.range[0];\r\n out.push({ kind: \"undefined_name\", name, at, ...positionOf(starts, at) });\r\n }\r\n\r\n for (const scope of manager.scopes) {\r\n for (const variable of scope.variables) {\r\n for (const def of variable.defs) {\r\n const isLexical = (def.type === \"Variable\" && (def.parent?.kind === \"let\" || def.parent?.kind === \"const\")) || def.type === \"ClassName\";\r\n if (!isLexical) continue;\r\n const declStart = def.name.range[0];\r\n const initRange = def.type === \"Variable\" ? def.node.init?.range : undefined;\r\n for (const ref of variable.references) {\r\n if (ref.identifier === def.name || ref.init) continue;\r\n // Only inside the same function: a nested function runs later, when the declaration has long since executed.\r\n if (ref.from.variableScope !== variable.scope.variableScope) continue;\r\n const at = ref.identifier.range[0];\r\n if (skip.has(at)) continue;\r\n const above = at < declStart;\r\n // `const x = x + 1`: still before the binding is initialised.\r\n const inOwnInitialiser = initRange !== undefined && at >= initRange[0] && at < def.node.range[1];\r\n if (above || inOwnInitialiser) out.push({ kind: \"used_before_declaration\", name: variable.name, at, ...positionOf(starts, at) });\r\n }\r\n }\r\n }\r\n }\r\n\r\n out.sort((a, b) => a.at - b.at);\r\n return out.map(({ at: _at, ...finding }) => finding);\r\n } catch {\r\n // A bug in the analysis must never take a run down; \"cannot judge\" is the honest answer.\r\n return null;\r\n }\r\n}\r\n", "// Generated from the `globals` package (builtin, es5-es2021, browser, worker, serviceworker, node, nodeBuiltin, commonjs, shared-node-browser, jest, mocha, jasmine)\r\n// plus names newer than that package (fetch, structuredClone, vitest's globals, ...). The scope check treats these as defined.\r\n// A name missing here is reported only if it is also not unresolved in the file before the change, so a gap costs a warning, never a regression.\r\nexport const KNOWN_GLOBALS: ReadonlySet<string> = new Set([\r\n \"AbortController\", \"AbortSignal\", \"AggregateError\", \"AnalyserNode\", \"Animation\", \"AnimationEffectReadOnly\", \"AnimationEffectTiming\", \"AnimationEffectTimingReadOnly\",\r\n \"AnimationEvent\", \"AnimationPlaybackEvent\", \"AnimationTimeline\", \"ApplicationCache\", \"ApplicationCacheErrorEvent\", \"Array\", \"ArrayBuffer\", \"Atomics\",\r\n \"Attr\", \"Audio\", \"AudioBuffer\", \"AudioBufferSourceNode\", \"AudioContext\", \"AudioDestinationNode\", \"AudioListener\", \"AudioNode\",\r\n \"AudioParam\", \"AudioProcessingEvent\", \"AudioScheduledSourceNode\", \"AudioWorkletGlobalScope\", \"AudioWorkletNode\", \"AudioWorkletProcessor\", \"BarProp\", \"BaseAudioContext\",\r\n \"BatteryManager\", \"BeforeUnloadEvent\", \"BigInt\", \"BigInt64Array\", \"BigUint64Array\", \"BiquadFilterNode\", \"Blob\", \"BlobEvent\",\r\n \"Boolean\", \"BroadcastChannel\", \"BudgetService\", \"Buffer\", \"ByteLengthQueuingStrategy\", \"CSS\", \"CSSConditionRule\", \"CSSFontFaceRule\",\r\n \"CSSGroupingRule\", \"CSSImportRule\", \"CSSKeyframeRule\", \"CSSKeyframesRule\", \"CSSMatrixComponent\", \"CSSMediaRule\", \"CSSNamespaceRule\", \"CSSPageRule\",\r\n \"CSSPerspective\", \"CSSRotate\", \"CSSRule\", \"CSSRuleList\", \"CSSScale\", \"CSSSkew\", \"CSSSkewX\", \"CSSSkewY\",\r\n \"CSSStyleDeclaration\", \"CSSStyleRule\", \"CSSStyleSheet\", \"CSSSupportsRule\", \"CSSTransformValue\", \"CSSTranslate\", \"Cache\", \"CacheStorage\",\r\n \"CanvasCaptureMediaStreamTrack\", \"CanvasGradient\", \"CanvasPattern\", \"CanvasRenderingContext2D\", \"ChannelMergerNode\", \"ChannelSplitterNode\", \"CharacterData\", \"Client\",\r\n \"Clients\", \"ClipboardEvent\", \"ClipboardItem\", \"CloseEvent\", \"Comment\", \"CompositionEvent\", \"CompressionStream\", \"ConstantSourceNode\",\r\n \"ConvolverNode\", \"CountQueuingStrategy\", \"Credential\", \"CredentialsContainer\", \"Crypto\", \"CryptoKey\", \"CustomElementRegistry\", \"CustomEvent\",\r\n \"DOMError\", \"DOMException\", \"DOMImplementation\", \"DOMMatrix\", \"DOMMatrixReadOnly\", \"DOMParser\", \"DOMPoint\", \"DOMPointReadOnly\",\r\n \"DOMQuad\", \"DOMRect\", \"DOMRectList\", \"DOMRectReadOnly\", \"DOMStringList\", \"DOMStringMap\", \"DOMTokenList\", \"DataTransfer\",\r\n \"DataTransferItem\", \"DataTransferItemList\", \"DataView\", \"Date\", \"DecompressionStream\", \"DelayNode\", \"DeviceMotionEvent\", \"DeviceOrientationEvent\",\r\n \"Document\", \"DocumentFragment\", \"DocumentType\", \"DragEvent\", \"DynamicsCompressorNode\", \"Element\", \"Error\", \"ErrorEvent\",\r\n \"EvalError\", \"Event\", \"EventSource\", \"EventTarget\", \"ExtendableEvent\", \"ExtendableMessageEvent\", \"FetchEvent\", \"File\",\r\n \"FileList\", \"FileReader\", \"FileReaderSync\", \"FinalizationRegistry\", \"Float32Array\", \"Float64Array\", \"FocusEvent\", \"FontFace\",\r\n \"FontFaceSetLoadEvent\", \"FormData\", \"FormDataEvent\", \"Function\", \"GainNode\", \"Gamepad\", \"GamepadButton\", \"GamepadEvent\",\r\n \"HTMLAllCollection\", \"HTMLAnchorElement\", \"HTMLAreaElement\", \"HTMLAudioElement\", \"HTMLBRElement\", \"HTMLBaseElement\", \"HTMLBodyElement\", \"HTMLButtonElement\",\r\n \"HTMLCanvasElement\", \"HTMLCollection\", \"HTMLContentElement\", \"HTMLDListElement\", \"HTMLDataElement\", \"HTMLDataListElement\", \"HTMLDetailsElement\", \"HTMLDialogElement\",\r\n \"HTMLDirectoryElement\", \"HTMLDivElement\", \"HTMLDocument\", \"HTMLElement\", \"HTMLEmbedElement\", \"HTMLFieldSetElement\", \"HTMLFontElement\", \"HTMLFormControlsCollection\",\r\n \"HTMLFormElement\", \"HTMLFrameElement\", \"HTMLFrameSetElement\", \"HTMLHRElement\", \"HTMLHeadElement\", \"HTMLHeadingElement\", \"HTMLHtmlElement\", \"HTMLIFrameElement\",\r\n \"HTMLImageElement\", \"HTMLInputElement\", \"HTMLLIElement\", \"HTMLLabelElement\", \"HTMLLegendElement\", \"HTMLLinkElement\", \"HTMLMapElement\", \"HTMLMarqueeElement\",\r\n \"HTMLMediaElement\", \"HTMLMenuElement\", \"HTMLMetaElement\", \"HTMLMeterElement\", \"HTMLModElement\", \"HTMLOListElement\", \"HTMLObjectElement\", \"HTMLOptGroupElement\",\r\n \"HTMLOptionElement\", \"HTMLOptionsCollection\", \"HTMLOutputElement\", \"HTMLParagraphElement\", \"HTMLParamElement\", \"HTMLPictureElement\", \"HTMLPreElement\", \"HTMLProgressElement\",\r\n \"HTMLQuoteElement\", \"HTMLScriptElement\", \"HTMLSelectElement\", \"HTMLShadowElement\", \"HTMLSlotElement\", \"HTMLSourceElement\", \"HTMLSpanElement\", \"HTMLStyleElement\",\r\n \"HTMLTableCaptionElement\", \"HTMLTableCellElement\", \"HTMLTableColElement\", \"HTMLTableElement\", \"HTMLTableRowElement\", \"HTMLTableSectionElement\", \"HTMLTemplateElement\", \"HTMLTextAreaElement\",\r\n \"HTMLTimeElement\", \"HTMLTitleElement\", \"HTMLTrackElement\", \"HTMLUListElement\", \"HTMLUnknownElement\", \"HTMLVideoElement\", \"HashChangeEvent\", \"Headers\",\r\n \"History\", \"IDBCursor\", \"IDBCursorWithValue\", \"IDBDatabase\", \"IDBFactory\", \"IDBIndex\", \"IDBKeyRange\", \"IDBObjectStore\",\r\n \"IDBOpenDBRequest\", \"IDBRequest\", \"IDBTransaction\", \"IDBVersionChangeEvent\", \"IIRFilterNode\", \"IdleDeadline\", \"Image\", \"ImageBitmap\",\r\n \"ImageBitmapRenderingContext\", \"ImageCapture\", \"ImageData\", \"Infinity\", \"InputEvent\", \"Int16Array\", \"Int32Array\", \"Int8Array\",\r\n \"IntersectionObserver\", \"IntersectionObserverEntry\", \"Intl\", \"Iterator\", \"JSON\", \"KeyboardEvent\", \"KeyframeEffect\", \"KeyframeEffectReadOnly\",\r\n \"Location\", \"MIDIAccess\", \"MIDIConnectionEvent\", \"MIDIInput\", \"MIDIInputMap\", \"MIDIMessageEvent\", \"MIDIOutput\", \"MIDIOutputMap\",\r\n \"MIDIPort\", \"Map\", \"Math\", \"MediaDeviceInfo\", \"MediaDevices\", \"MediaElementAudioSourceNode\", \"MediaEncryptedEvent\", \"MediaError\",\r\n \"MediaKeyMessageEvent\", \"MediaKeySession\", \"MediaKeyStatusMap\", \"MediaKeySystemAccess\", \"MediaList\", \"MediaMetadata\", \"MediaQueryList\", \"MediaQueryListEvent\",\r\n \"MediaRecorder\", \"MediaSettingsRange\", \"MediaSource\", \"MediaStream\", \"MediaStreamAudioDestinationNode\", \"MediaStreamAudioSourceNode\", \"MediaStreamConstraints\", \"MediaStreamEvent\",\r\n \"MediaStreamTrack\", \"MediaStreamTrackEvent\", \"MessageChannel\", \"MessageEvent\", \"MessagePort\", \"MimeType\", \"MimeTypeArray\", \"MouseEvent\",\r\n \"MutationEvent\", \"MutationObserver\", \"MutationRecord\", \"NaN\", \"NamedNodeMap\", \"NavigationPreloadManager\", \"Navigator\", \"NavigatorUAData\",\r\n \"NetworkInformation\", \"Node\", \"NodeFilter\", \"NodeIterator\", \"NodeList\", \"Notification\", \"Number\", \"Object\",\r\n \"OfflineAudioCompletionEvent\", \"OfflineAudioContext\", \"OffscreenCanvas\", \"OffscreenCanvasRenderingContext2D\", \"Option\", \"OscillatorNode\", \"OverconstrainedError\", \"PageTransitionEvent\",\r\n \"PannerNode\", \"Path2D\", \"PaymentAddress\", \"PaymentRequest\", \"PaymentRequestUpdateEvent\", \"PaymentResponse\", \"Performance\", \"PerformanceEntry\",\r\n \"PerformanceLongTaskTiming\", \"PerformanceMark\", \"PerformanceMeasure\", \"PerformanceNavigation\", \"PerformanceNavigationTiming\", \"PerformanceObserver\", \"PerformanceObserverEntryList\", \"PerformancePaintTiming\",\r\n \"PerformanceResourceTiming\", \"PerformanceTiming\", \"PeriodicWave\", \"PermissionStatus\", \"Permissions\", \"PhotoCapabilities\", \"Plugin\", \"PluginArray\",\r\n \"PointerEvent\", \"PopStateEvent\", \"Presentation\", \"PresentationAvailability\", \"PresentationConnection\", \"PresentationConnectionAvailableEvent\", \"PresentationConnectionCloseEvent\", \"PresentationConnectionList\",\r\n \"PresentationReceiver\", \"PresentationRequest\", \"ProcessingInstruction\", \"ProgressEvent\", \"Promise\", \"PromiseRejectionEvent\", \"Proxy\", \"PushManager\",\r\n \"PushSubscription\", \"PushSubscriptionOptions\", \"RTCCertificate\", \"RTCDataChannel\", \"RTCDataChannelEvent\", \"RTCDtlsTransport\", \"RTCIceCandidate\", \"RTCIceGatherer\",\r\n \"RTCIceTransport\", \"RTCPeerConnection\", \"RTCPeerConnectionIceEvent\", \"RTCRtpContributingSource\", \"RTCRtpReceiver\", \"RTCRtpSender\", \"RTCSctpTransport\", \"RTCSessionDescription\",\r\n \"RTCStatsReport\", \"RTCTrackEvent\", \"RadioNodeList\", \"Range\", \"RangeError\", \"ReadableByteStreamController\", \"ReadableStream\", \"ReadableStreamBYOBReader\",\r\n \"ReadableStreamBYOBRequest\", \"ReadableStreamDefaultController\", \"ReadableStreamDefaultReader\", \"ReferenceError\", \"Reflect\", \"RegExp\", \"RemotePlayback\", \"Request\",\r\n \"ResizeObserver\", \"ResizeObserverEntry\", \"Response\", \"SVGAElement\", \"SVGAngle\", \"SVGAnimateElement\", \"SVGAnimateMotionElement\", \"SVGAnimateTransformElement\",\r\n \"SVGAnimatedAngle\", \"SVGAnimatedBoolean\", \"SVGAnimatedEnumeration\", \"SVGAnimatedInteger\", \"SVGAnimatedLength\", \"SVGAnimatedLengthList\", \"SVGAnimatedNumber\", \"SVGAnimatedNumberList\",\r\n \"SVGAnimatedPreserveAspectRatio\", \"SVGAnimatedRect\", \"SVGAnimatedString\", \"SVGAnimatedTransformList\", \"SVGAnimationElement\", \"SVGCircleElement\", \"SVGClipPathElement\", \"SVGComponentTransferFunctionElement\",\r\n \"SVGDefsElement\", \"SVGDescElement\", \"SVGDiscardElement\", \"SVGElement\", \"SVGEllipseElement\", \"SVGFEBlendElement\", \"SVGFEColorMatrixElement\", \"SVGFEComponentTransferElement\",\r\n \"SVGFECompositeElement\", \"SVGFEConvolveMatrixElement\", \"SVGFEDiffuseLightingElement\", \"SVGFEDisplacementMapElement\", \"SVGFEDistantLightElement\", \"SVGFEDropShadowElement\", \"SVGFEFloodElement\", \"SVGFEFuncAElement\",\r\n \"SVGFEFuncBElement\", \"SVGFEFuncGElement\", \"SVGFEFuncRElement\", \"SVGFEGaussianBlurElement\", \"SVGFEImageElement\", \"SVGFEMergeElement\", \"SVGFEMergeNodeElement\", \"SVGFEMorphologyElement\",\r\n \"SVGFEOffsetElement\", \"SVGFEPointLightElement\", \"SVGFESpecularLightingElement\", \"SVGFESpotLightElement\", \"SVGFETileElement\", \"SVGFETurbulenceElement\", \"SVGFilterElement\", \"SVGForeignObjectElement\",\r\n \"SVGGElement\", \"SVGGeometryElement\", \"SVGGradientElement\", \"SVGGraphicsElement\", \"SVGImageElement\", \"SVGLength\", \"SVGLengthList\", \"SVGLineElement\",\r\n \"SVGLinearGradientElement\", \"SVGMPathElement\", \"SVGMarkerElement\", \"SVGMaskElement\", \"SVGMatrix\", \"SVGMetadataElement\", \"SVGNumber\", \"SVGNumberList\",\r\n \"SVGPathElement\", \"SVGPatternElement\", \"SVGPoint\", \"SVGPointList\", \"SVGPolygonElement\", \"SVGPolylineElement\", \"SVGPreserveAspectRatio\", \"SVGRadialGradientElement\",\r\n \"SVGRect\", \"SVGRectElement\", \"SVGSVGElement\", \"SVGScriptElement\", \"SVGSetElement\", \"SVGStopElement\", \"SVGStringList\", \"SVGStyleElement\",\r\n \"SVGSwitchElement\", \"SVGSymbolElement\", \"SVGTSpanElement\", \"SVGTextContentElement\", \"SVGTextElement\", \"SVGTextPathElement\", \"SVGTextPositioningElement\", \"SVGTitleElement\",\r\n \"SVGTransform\", \"SVGTransformList\", \"SVGUnitTypes\", \"SVGUseElement\", \"SVGViewElement\", \"Screen\", \"ScreenOrientation\", \"ScriptProcessorNode\",\r\n \"SecurityPolicyViolationEvent\", \"Selection\", \"ServiceWorker\", \"ServiceWorkerContainer\", \"ServiceWorkerGlobalScope\", \"ServiceWorkerMessageEvent\", \"ServiceWorkerRegistration\", \"Set\",\r\n \"ShadowRoot\", \"SharedArrayBuffer\", \"SharedWorker\", \"SourceBuffer\", \"SourceBufferList\", \"SpeechSynthesisEvent\", \"SpeechSynthesisUtterance\", \"StaticRange\",\r\n \"StereoPannerNode\", \"Storage\", \"StorageEvent\", \"StorageManager\", \"String\", \"StyleSheet\", \"StyleSheetList\", \"SubmitEvent\",\r\n \"SubtleCrypto\", \"Symbol\", \"SyntaxError\", \"TaskAttributionTiming\", \"Text\", \"TextDecoder\", \"TextDecoderStream\", \"TextEncoder\",\r\n \"TextEncoderStream\", \"TextEvent\", \"TextMetrics\", \"TextTrack\", \"TextTrackCue\", \"TextTrackCueList\", \"TextTrackList\", \"TimeRanges\",\r\n \"ToggleEvent\", \"Touch\", \"TouchEvent\", \"TouchList\", \"TrackEvent\", \"TransformStream\", \"TransformStreamDefaultController\", \"TransitionEvent\",\r\n \"TreeWalker\", \"TypeError\", \"UIEvent\", \"URIError\", \"URL\", \"URLSearchParams\", \"Uint16Array\", \"Uint32Array\",\r\n \"Uint8Array\", \"Uint8ClampedArray\", \"VTTCue\", \"ValidityState\", \"VisualViewport\", \"WaveShaperNode\", \"WeakMap\", \"WeakRef\",\r\n \"WeakSet\", \"WebAssembly\", \"WebGL2RenderingContext\", \"WebGLActiveInfo\", \"WebGLBuffer\", \"WebGLContextEvent\", \"WebGLFramebuffer\", \"WebGLProgram\",\r\n \"WebGLQuery\", \"WebGLRenderbuffer\", \"WebGLRenderingContext\", \"WebGLSampler\", \"WebGLShader\", \"WebGLShaderPrecisionFormat\", \"WebGLSync\", \"WebGLTexture\",\r\n \"WebGLTransformFeedback\", \"WebGLUniformLocation\", \"WebGLVertexArrayObject\", \"WebSocket\", \"WheelEvent\", \"Window\", \"WindowClient\", \"Worker\",\r\n \"WorkerGlobalScope\", \"WritableStream\", \"WritableStreamDefaultController\", \"WritableStreamDefaultWriter\", \"XMLDocument\", \"XMLHttpRequest\", \"XMLHttpRequestEventTarget\", \"XMLHttpRequestUpload\",\r\n \"XMLSerializer\", \"XPathEvaluator\", \"XPathExpression\", \"XPathResult\", \"XRAnchor\", \"XRBoundedReferenceSpace\", \"XRCPUDepthInformation\", \"XRDepthInformation\",\r\n \"XRFrame\", \"XRInputSource\", \"XRInputSourceArray\", \"XRInputSourceEvent\", \"XRInputSourcesChangeEvent\", \"XRPose\", \"XRReferenceSpace\", \"XRReferenceSpaceEvent\",\r\n \"XRRenderState\", \"XRRigidTransform\", \"XRSession\", \"XRSessionEvent\", \"XRSpace\", \"XRSystem\", \"XRView\", \"XRViewerPose\",\r\n \"XRViewport\", \"XRWebGLBinding\", \"XRWebGLDepthInformation\", \"XRWebGLLayer\", \"XSLTProcessor\", \"__dirname\", \"__filename\", \"addEventListener\",\r\n \"after\", \"afterAll\", \"afterEach\", \"alert\", \"applicationCache\", \"atob\", \"before\", \"beforeAll\",\r\n \"beforeEach\", \"bench\", \"blur\", \"btoa\", \"caches\", \"cancelAnimationFrame\", \"cancelIdleCallback\", \"clearImmediate\",\r\n \"clearInterval\", \"clearTimeout\", \"clientInformation\", \"clients\", \"close\", \"closed\", \"confirm\", \"console\",\r\n \"constructor\", \"context\", \"createImageBitmap\", \"crypto\", \"customElements\", \"decodeURI\", \"decodeURIComponent\", \"defaultStatus\",\r\n \"defaultstatus\", \"describe\", \"devicePixelRatio\", \"dispatchEvent\", \"document\", \"encodeURI\", \"encodeURIComponent\", \"escape\",\r\n \"eval\", \"event\", \"expect\", \"expectAsync\", \"exports\", \"external\", \"fail\", \"fdescribe\",\r\n \"fetch\", \"find\", \"fit\", \"focus\", \"frameElement\", \"frames\", \"getComputedStyle\", \"getSelection\",\r\n \"global\", \"globalThis\", \"hasOwnProperty\", \"history\", \"importScripts\", \"indexedDB\", \"innerHeight\", \"innerWidth\",\r\n \"isFinite\", \"isNaN\", \"isPrototypeOf\", \"isSecureContext\", \"it\", \"jasmine\", \"jest\", \"length\",\r\n \"localStorage\", \"location\", \"locationbar\", \"matchMedia\", \"menubar\", \"mocha\", \"module\", \"moveBy\",\r\n \"moveTo\", \"name\", \"navigator\", \"offscreenBuffering\", \"onabort\", \"onafterprint\", \"onanimationend\", \"onanimationiteration\",\r\n \"onanimationstart\", \"onappinstalled\", \"onauxclick\", \"onbeforeinstallprompt\", \"onbeforeprint\", \"onbeforeunload\", \"onblur\", \"oncancel\",\r\n \"oncanplay\", \"oncanplaythrough\", \"onchange\", \"onclick\", \"onclose\", \"onconnect\", \"oncontextmenu\", \"oncuechange\",\r\n \"ondblclick\", \"ondevicemotion\", \"ondeviceorientation\", \"ondeviceorientationabsolute\", \"ondrag\", \"ondragend\", \"ondragenter\", \"ondragleave\",\r\n \"ondragover\", \"ondragstart\", \"ondrop\", \"ondurationchange\", \"onemptied\", \"onended\", \"onerror\", \"onfetch\",\r\n \"onfocus\", \"ongotpointercapture\", \"onhashchange\", \"oninput\", \"oninstall\", \"oninvalid\", \"onkeydown\", \"onkeypress\",\r\n \"onkeyup\", \"onlanguagechange\", \"onload\", \"onloadeddata\", \"onloadedmetadata\", \"onloadstart\", \"onlostpointercapture\", \"onmessage\",\r\n \"onmessageerror\", \"onmousedown\", \"onmouseenter\", \"onmouseleave\", \"onmousemove\", \"onmouseout\", \"onmouseover\", \"onmouseup\",\r\n \"onmousewheel\", \"onnotificationclick\", \"onnotificationclose\", \"onoffline\", \"ononline\", \"onpagehide\", \"onpageshow\", \"onpause\",\r\n \"onplay\", \"onplaying\", \"onpointercancel\", \"onpointerdown\", \"onpointerenter\", \"onpointerleave\", \"onpointermove\", \"onpointerout\",\r\n \"onpointerover\", \"onpointerup\", \"onpopstate\", \"onprogress\", \"onpush\", \"onpushsubscriptionchange\", \"onratechange\", \"onrejectionhandled\",\r\n \"onreset\", \"onresize\", \"onscroll\", \"onsearch\", \"onseeked\", \"onseeking\", \"onselect\", \"onstalled\",\r\n \"onstorage\", \"onsubmit\", \"onsuspend\", \"onsync\", \"ontimeupdate\", \"ontoggle\", \"ontransitionend\", \"onunhandledrejection\",\r\n \"onunload\", \"onvolumechange\", \"onwaiting\", \"onwheel\", \"open\", \"openDatabase\", \"opener\", \"origin\",\r\n \"outerHeight\", \"outerWidth\", \"pageXOffset\", \"pageYOffset\", \"parent\", \"parseFloat\", \"parseInt\", \"pending\",\r\n \"performance\", \"personalbar\", \"pit\", \"postMessage\", \"print\", \"process\", \"prompt\", \"propertyIsEnumerable\",\r\n \"queueMicrotask\", \"registerProcessor\", \"registration\", \"removeEventListener\", \"reportError\", \"requestAnimationFrame\", \"requestIdleCallback\", \"require\",\r\n \"resizeBy\", \"resizeTo\", \"run\", \"runs\", \"screen\", \"screenLeft\", \"screenTop\", \"screenX\",\r\n \"screenY\", \"scroll\", \"scrollBy\", \"scrollTo\", \"scrollX\", \"scrollY\", \"scrollbars\", \"self\",\r\n \"sessionStorage\", \"setImmediate\", \"setInterval\", \"setTimeout\", \"setup\", \"skipWaiting\", \"specify\", \"speechSynthesis\",\r\n \"spyOn\", \"spyOnAllFunctions\", \"spyOnProperty\", \"status\", \"statusbar\", \"stop\", \"structuredClone\", \"styleMedia\",\r\n \"suite\", \"suiteSetup\", \"suiteTeardown\", \"teardown\", \"test\", \"toLocaleString\", \"toString\", \"toolbar\",\r\n \"top\", \"undefined\", \"unescape\", \"valueOf\", \"vi\", \"visualViewport\", \"vitest\", \"waits\",\r\n \"waitsFor\", \"window\", \"xcontext\", \"xdescribe\", \"xit\", \"xspecify\", \"xtest\",\r\n]);\r\n", "import { attempt, isCheckablePath, readingsFor } from \"./jsParse\";\r\nimport { analyzeScope, type ScopeFinding, type ScopeKind } from \"./nameScope\";\r\n\r\nexport { isCheckablePath };\r\n\r\n/**\r\n * QUIKTR-1458 \u2014 an in-memory check for JavaScript the code-writing loop changes.\r\n *\r\n * The rc.6 runs failed in ways nothing in the loop could see until lint or the tests ran after it: files that do not parse (a name\r\n * declared twice, an `import` inside a function) and, on a second bug, files that parse but use a name wrongly (a function a new\r\n * test never imported, a `const` used above its declaration). A parse and a scope analysis take milliseconds, need no disk write\r\n * and no test run, so the loop can tell the AI the moment it breaks a file.\r\n *\r\n * What it will and will not do, on purpose:\r\n * - JavaScript only (`.js`, `.mjs`, `.cjs`). TypeScript, JSX and everything else is not judged: a parser that cannot read a\r\n * language would call every file in it broken.\r\n * - A finding is the AI's doing only if it is NEW. For an edit that means the file parsed BEFORE the run changed it, and a name\r\n * problem counts only if the file did not already have it. For a NEW file it means the project is known to parse (some existing\r\n * file was read and parsed, and none turned out unreadable), and a name the project's own files already use without defining\r\n * (a global the build supplies) is not reported.\r\n * - It finds syntax errors, early errors (a duplicate declaration is one), a name that resolves to nothing, and a let/const/class\r\n * used above its declaration in the same function. It does NOT find a wrong value, a wrong import path, a wrong call or any wrong\r\n * behaviour: a name that exists but is the wrong one passes. Tests are what find those.\r\n * - What it reports is a closed word, a line and a column. Never the text of the file, the name of anything in it, or the\r\n * parser's own message.\r\n */\r\n\r\nexport type SyntaxKind =\r\n | \"duplicate_declaration\"\r\n | \"misplaced_import_export\"\r\n | \"unterminated\"\r\n | \"unexpected_token\"\r\n | \"syntax_error\"\r\n | ScopeKind;\r\n\r\nexport interface SyntaxProblem {\r\n kind: SyntaxKind;\r\n /** 1-based. */\r\n line: number;\r\n /** 0-based, as the parser counts. */\r\n column: number;\r\n}\r\n\r\nfunction classify(message: string): SyntaxKind {\r\n if (/already been declared/i.test(message)) return \"duplicate_declaration\";\r\n if (/'import' and 'export' may/i.test(message)) return \"misplaced_import_export\";\r\n if (/^Unterminated/i.test(message)) return \"unterminated\";\r\n if (/^Unexpected/i.test(message)) return \"unexpected_token\";\r\n return \"syntax_error\";\r\n}\r\n\r\n/**\r\n * `null` when the file parses (as a script or as a module: a plain `.js` file is either) or is not a file this judges. Otherwise\r\n * the first problem. When both readings fail, the report is the module one if the file uses import/export syntax and the script\r\n * one if not \u2014 the other reading would only say \"import is not allowed here\" about a file that is plainly a module.\r\n */\r\nexport function syntaxProblem(path: string, text: string): SyntaxProblem | null {\r\n if (!isCheckablePath(path)) return null;\r\n try {\r\n const readings = readingsFor(path, text);\r\n let first: ReturnType<typeof attempt> = null;\r\n for (const [i, sourceType] of readings.entries()) {\r\n const failure = attempt(text, sourceType);\r\n if (failure === null) return null;\r\n if (i === 0) first = failure;\r\n }\r\n // `readings[0]` is the reading the file's own syntax points to, so its error is the informative one.\r\n if (!first) return null;\r\n return { kind: classify(first.message), line: first.line, column: first.column };\r\n } catch {\r\n // A parser bug must never take a run down; \"cannot judge\" is the honest answer.\r\n return null;\r\n }\r\n}\r\n\r\nconst WORDS: Record<SyntaxKind, string> = {\r\n duplicate_declaration: \"a name declared twice\",\r\n misplaced_import_export: \"an import or export that is not at the top of the file\",\r\n unterminated: \"an unterminated string, comment or template\",\r\n unexpected_token: \"an unexpected character\",\r\n syntax_error: \"a syntax error\",\r\n undefined_name: \"a name that is not defined or imported\",\r\n used_before_declaration: \"a name used above the line that declares it\",\r\n};\r\n\r\n/** Fixed words plus a number: safe to put in a result the AI reads, never carries file text. */\r\nexport function describeSyntaxProblem(problem: SyntaxProblem): string {\r\n return `${WORDS[problem.kind]} at line ${problem.line}`;\r\n}\r\n\r\nfunction isNameProblem(kind: SyntaxKind): kind is ScopeKind {\r\n return kind === \"undefined_name\" || kind === \"used_before_declaration\";\r\n}\r\n\r\n/** What the AI is told in the result of the write that caused the problem. */\r\nexport function syntaxWarningMessage(problem: SyntaxProblem): string {\r\n if (isNameProblem(problem.kind)) {\r\n return `This change introduced ${describeSyntaxProblem(problem)}, which would fail when the code runs. Read it around that line and fix it before you finish.`;\r\n }\r\n return `The file no longer parses (${describeSyntaxProblem(problem)}). Read it around that line and fix it before you finish.`;\r\n}\r\n\r\nconst keyOf = (f: ScopeFinding): string => `${f.kind}:${f.name}`;\r\n\r\n/**\r\n * Decides, per file, whether a problem is the AI's doing. See the header for why a file is sometimes not judged.\r\n */\r\nexport class SyntaxGuard {\r\n private projectParses = false;\r\n private sawUnreadable = false;\r\n /** Names that files of this project use without defining: globals the build or the test runner supplies. */\r\n private readonly projectGlobals = new Set<string>();\r\n\r\n /** Existing files already in view (the context shown before the first turn): evidence about whether the project parses. */\r\n seed(files: { path: string; text: string }[]): void {\r\n for (const f of files) this.learn(f.path, f.text);\r\n }\r\n\r\n private learn(path: string, text: string): boolean {\r\n if (!isCheckablePath(path)) return false;\r\n if (syntaxProblem(path, text) !== null) {\r\n this.sawUnreadable = true;\r\n return false;\r\n }\r\n this.projectParses = true;\r\n for (const f of analyzeScope(path, text) ?? []) if (f.kind === \"undefined_name\") this.projectGlobals.add(f.name);\r\n return true;\r\n }\r\n\r\n private firstNew(found: ScopeFinding[], already: Set<string>): SyntaxProblem | null {\r\n for (const f of found) {\r\n if (already.has(keyOf(f))) continue;\r\n if (f.kind === \"undefined_name\" && this.projectGlobals.has(f.name)) continue;\r\n return { kind: f.kind, line: f.line, column: f.column };\r\n }\r\n return null;\r\n }\r\n\r\n /** `original` is the file as it was BEFORE this run changed it; `next` is what it is now. */\r\n judgeEdit(path: string, original: string, next: string): SyntaxProblem | null {\r\n if (!isCheckablePath(path)) return null;\r\n if (!this.learn(path, original)) return null;\r\n const broken = syntaxProblem(path, next);\r\n if (broken) return broken;\r\n const after = analyzeScope(path, next);\r\n if (!after) return null;\r\n const before = new Set((analyzeScope(path, original) ?? []).map(keyOf));\r\n return this.firstNew(after, before);\r\n }\r\n\r\n judgeCreated(path: string, next: string): SyntaxProblem | null {\r\n if (!isCheckablePath(path)) return null;\r\n if (!this.projectParses || this.sawUnreadable) return null;\r\n const broken = syntaxProblem(path, next);\r\n if (broken) return broken;\r\n const after = analyzeScope(path, next);\r\n return after ? this.firstNew(after, new Set()) : null;\r\n }\r\n}\r\n", "import { posix } from \"node:path\";\r\nimport { matchesDeniedPath } from \"./deniedPaths\";\r\n\r\n/**\r\n * QUIKTR-1458 \u2014 the first gate for every path the AI names in the read-only targeting loop.\r\n *\r\n * This decides only whether a string could be a repo-relative path at all. Whether it is a tracked,\r\n * allowed file is the next gate's job: membership in the checkout listing, then the denied list.\r\n * (`deniedPaths.ts` does no normalising of its own and matches case-sensitively against a\r\n * forward-slash, repo-relative path exactly as `git ls-files` prints it, so everything has to be\r\n * brought to that shape first, or refused.)\r\n *\r\n * Order matters and is pinned by tests: a `..` segment is refused BEFORE the path is normalised,\r\n * because normalising `a/../b.js` quietly turns it into `b.js`, which would look perfectly fine.\r\n */\r\n\r\nexport type PathRefusal = \"path_invalid\" | \"outside_workspace\";\r\n\r\nexport type NormalisedPath = { ok: true; path: string } | { ok: false; reason: PathRefusal };\r\n\r\nconst MAX_PATH_CHARS = 300;\r\n\r\n// Any ASCII control character (NUL, newline, BEL, ESC, DEL, ...).\r\nfunction hasControlChar(s: string): boolean {\r\n for (let i = 0; i < s.length; i++) {\r\n const c = s.charCodeAt(i);\r\n if (c < 0x20 || c === 0x7f) return true;\r\n }\r\n return false;\r\n}\r\n\r\nexport function normaliseToolPath(raw: unknown, options: { allowRoot?: boolean } = {}): NormalisedPath {\r\n const allowRoot = options.allowRoot === true;\r\n\r\n if ((raw === undefined || raw === null || raw === \"\") && allowRoot) return { ok: true, path: \"\" };\r\n if (typeof raw !== \"string\" || raw.length === 0 || raw.length > MAX_PATH_CHARS) {\r\n return { ok: false, reason: \"path_invalid\" };\r\n }\r\n if (hasControlChar(raw)) return { ok: false, reason: \"path_invalid\" };\r\n // Never convert backslashes: a path the AI wrote with them is not a git path, and quietly\r\n // \"fixing\" it would hide that it is guessing.\r\n if (raw.includes(\"\\\\\")) return { ok: false, reason: \"path_invalid\" };\r\n if (raw.startsWith(\"/\") || /^[A-Za-z]:/.test(raw)) return { ok: false, reason: \"path_invalid\" };\r\n\r\n // Before normalising, on purpose (see the header).\r\n if (raw.split(\"/\").includes(\"..\")) return { ok: false, reason: \"outside_workspace\" };\r\n\r\n const normalised = posix.normalize(raw).replace(/\\/+$/, \"\");\r\n if (normalised === \"\" || normalised === \".\") {\r\n return allowRoot ? { ok: true, path: \"\" } : { ok: false, reason: \"path_invalid\" };\r\n }\r\n return { ok: true, path: normalised };\r\n}\r\n\r\n/** True when `path` is `prefix` or lives under it, on a whole path segment (`src` is not `srcx`). */\r\nexport function matchesPrefix(path: string, prefix: string): boolean {\r\n if (prefix === \"\") return true;\r\n return path === prefix || path.startsWith(`${prefix}/`);\r\n}\r\n\r\n/**\r\n * The listing with every denied path removed, sorted. Anything the AI is told about files comes\r\n * from this, so a protected file is never named, counted or hinted at. Sorting makes every answer\r\n * deterministic. The input is not changed.\r\n */\r\nexport function buildVisibleListing(listing: readonly string[], deniedPaths: string[]): string[] {\r\n return listing.filter((p) => !matchesDeniedPath(p, deniedPaths)).sort();\r\n}\r\n", "import { lstatSync, readFileSync, realpathSync } from \"node:fs\";\r\nimport { isAbsolute, join, relative } from \"node:path\";\r\nimport { matchesDeniedPath } from \"./deniedPaths\";\r\nimport { matchesPrefix, normaliseToolPath } from \"./targetingPaths\";\r\n\r\n/**\r\n * QUIKTR-1458 \u2014 the three READ-ONLY tools the AI may use while it chooses which files to change:\r\n * `list_files`, `read_file`, `grep`. Nothing here can write, run or fetch anything.\r\n *\r\n * The AI's arguments are untrusted input and the files are a customer's, so every rule below is\r\n * about safety first:\r\n * - a protected (denied) path is never read, listed, searched, counted or hinted at;\r\n * - nothing outside the checkout is reachable (no `..`, no absolute paths, no symlinks);\r\n * - only files git tracks can be named, so a made-up path simply is not found;\r\n * - every limit turns into a plain RESULT the AI can act on (`refused`, `budget_exhausted`, ...),\r\n * never an exception, and never echoes what the AI sent or what a file contained into an error;\r\n * - `grep` is a FIXED-STRING search. The pattern is model-supplied and runs over customer files in\r\n * CI; a regular expression there is a way to hang the job, and a name like `validateExpense` is\r\n * all the AI needs.\r\n *\r\n * File access goes through `ToolFs` so tests can simulate symlinks, escapes and binary files\r\n * without touching a real checkout; `createNodeToolFs` is the real one.\r\n */\r\n\r\nexport type ToolName = \"list_files\" | \"read_file\" | \"grep\";\r\n\r\nexport interface ToolCall {\r\n id: string;\r\n name: string;\r\n args: unknown;\r\n}\r\n\r\nexport type ToolStatus =\r\n | \"ok\"\r\n | \"refused\"\r\n | \"not_found\"\r\n | \"unreadable\"\r\n | \"bad_args\"\r\n | \"unknown_tool\"\r\n | \"duplicate\"\r\n | \"budget_exhausted\"\r\n // QUIKTR-1458 \u00A724 \u2014 the write tools' own answers (codegenTools.ts). A refused edit is information for the AI, not a\r\n // failure: it changes its anchor and tries again.\r\n | \"no_match\"\r\n | \"ambiguous\"\r\n | \"protected\"\r\n | \"exists\"\r\n | \"too_large\";\r\n\r\nexport interface ToolResult {\r\n id: string;\r\n name: string;\r\n status: ToolStatus;\r\n /** A fixed vocabulary word (or, for `duplicate`, the id of the earlier call). Never model or file text. */\r\n reason?: string;\r\n /** Runner-authored fixed text. Never echoes the AI's input or a file's content. */\r\n message?: string;\r\n output?: unknown;\r\n}\r\n\r\nexport interface ToolLimits {\r\n maxTurns: number;\r\n maxToolCalls: number;\r\n maxCallsPerTurn: number;\r\n readCharsPerRead: number;\r\n readCharsTotal: number;\r\n resultCharsTotal: number;\r\n /** The per-turn ceiling on one request, in estimated TOKENS (`tokenEstimate.ts`). */\r\n maxRequestTokens: number;\r\n grepMaxMatches: number;\r\n grepLineChars: number;\r\n grepFileBytes: number;\r\n grepMaxFiles: number;\r\n grepMaxBytes: number;\r\n fileBytesMax: number;\r\n listMaxEntries: number;\r\n maxReasoningChars: number;\r\n maxPatternChars: number;\r\n}\r\n\r\n/** Starting values; to be tuned by measurement (QUIKTR-1458). */\r\nexport const DEFAULT_LIMITS: ToolLimits = {\r\n maxTurns: 12,\r\n maxToolCalls: 25,\r\n maxCallsPerTurn: 8,\r\n readCharsPerRead: 20_000,\r\n // The per-run read cap stops the COST; the per-turn ceiling below stops the FAILURE. Different jobs.\r\n readCharsTotal: 60_000,\r\n resultCharsTotal: 80_000,\r\n // 131,072 (the smallest 128k-class window) - 8,192 reserved output - a 3,741-token real request leaves\r\n // ~116,000; 90,000 keeps ~26,000 for a repository whose listing is thousands of paths, and stays well\r\n // clear of the per-minute quota, which binds before the window does. Set by the AI Runtime owner.\r\n maxRequestTokens: 90_000,\r\n grepMaxMatches: 40,\r\n grepLineChars: 200,\r\n grepFileBytes: 262_144,\r\n grepMaxFiles: 3_000,\r\n grepMaxBytes: 20_000_000,\r\n fileBytesMax: 1_000_000,\r\n listMaxEntries: 500,\r\n maxReasoningChars: 500,\r\n maxPatternChars: 200,\r\n};\r\n\r\nexport interface ToolFs {\r\n /** The real path of the checkout root. */\r\n rootReal: string;\r\n /** Throws if the file is gone. Never follows a symlink. */\r\n lstat(rel: string): { isSymlink: boolean; isFile: boolean; size: number };\r\n /** True when the file's real location (after following any links) is inside the checkout. */\r\n realpathInside(rel: string): boolean;\r\n readBytes(rel: string): Uint8Array;\r\n}\r\n\r\nexport function createNodeToolFs(rootDir: string = process.cwd()): ToolFs {\r\n const rootReal = realpathSync(rootDir);\r\n return {\r\n rootReal,\r\n lstat(rel) {\r\n const s = lstatSync(join(rootDir, rel));\r\n return { isSymlink: s.isSymbolicLink(), isFile: s.isFile(), size: s.size };\r\n },\r\n realpathInside(rel) {\r\n const real = realpathSync(join(rootDir, rel));\r\n const r = relative(rootReal, real);\r\n return r !== \"\" && !r.startsWith(\"..\") && !isAbsolute(r);\r\n },\r\n readBytes(rel) {\r\n return readFileSync(join(rootDir, rel));\r\n },\r\n };\r\n}\r\n\r\nexport interface ToolEnv {\r\n /** Every tracked file, exactly as `git ls-files` printed it (membership gate). */\r\n listing: ReadonlySet<string>;\r\n /** The listing with denied paths removed, sorted: the only thing the AI is ever told about. */\r\n visible: readonly string[];\r\n deniedPaths: string[];\r\n fs: ToolFs;\r\n limits: ToolLimits;\r\n /**\r\n * QUIKTR-1458 \u00A724 \u2014 tools beyond the three read-only ones (`edit_file`, `write_file`), supplied by the code-writing\r\n * loop. They go through exactly the same budget, duplicate and accounting path as a read; absent for targeting.\r\n */\r\n extraTools?: Readonly<Record<string, ExtraToolPreparer>>;\r\n}\r\n\r\nexport type ExtraToolPreparer = (args: Record<string, unknown>, env: ToolEnv, ledger: ToolLedger) => Prepared;\r\n\r\nexport interface ToolLedger {\r\n toolCalls: number;\r\n readChars: number;\r\n resultChars: number;\r\n refused: number;\r\n /** canonical call -> id of the first call that made it */\r\n seen: Map<string, string>;\r\n}\r\n\r\nexport function newLedger(): ToolLedger {\r\n return { toolCalls: 0, readChars: 0, resultChars: 0, refused: 0, seen: new Map() };\r\n}\r\n\r\n/** What was read, for the run's audit record. Paths only, never content. */\r\nexport interface ReadRecord {\r\n path: string;\r\n startLine?: number;\r\n endLine?: number;\r\n chars: number;\r\n refused?: true;\r\n}\r\n\r\nexport type Partial_ = Omit<ToolResult, \"id\" | \"name\">;\r\nexport type Executed = { result: Partial_; read?: ReadRecord };\r\nexport type Prepared =\r\n | { fail: Partial_; read?: ReadRecord }\r\n | { key: string; exec: () => Executed };\r\n\r\nconst INVALID_PATH = \"(invalid path)\";\r\nconst CUT = \"\u2026[line cut]\";\r\n\r\nfunction isPlainObject(x: unknown): x is Record<string, unknown> {\r\n return typeof x === \"object\" && x !== null && !Array.isArray(x);\r\n}\r\n\r\nfunction bad(message: string): { fail: Partial_ } {\r\n return { fail: { status: \"bad_args\", message } };\r\n}\r\n\r\nfunction optionalInt(v: unknown): number | undefined | \"bad\" {\r\n if (v === undefined || v === null) return undefined;\r\n return typeof v === \"number\" && Number.isInteger(v) ? v : \"bad\";\r\n}\r\n\r\nfunction hasNul(bytes: Uint8Array): boolean {\r\n const n = Math.min(bytes.length, 8000);\r\n for (let i = 0; i < n; i++) if (bytes[i] === 0) return true;\r\n return false;\r\n}\r\n\r\n/** Path gates shared by read_file: shape, then denied, then membership. No file is touched. */\r\nfunction gatePath(raw: unknown, env: ToolEnv): { ok: true; path: string } | { ok: false; fail: Partial_; path: string } {\r\n const n = normaliseToolPath(raw);\r\n if (!n.ok) {\r\n return { ok: false, path: INVALID_PATH, fail: { status: \"refused\", reason: n.reason, message: \"That path is not allowed.\" } };\r\n }\r\n // Denied BEFORE membership: a protected file and a made-up file inside a protected folder give the\r\n // same answer, so the answer cannot be used to find out what exists there.\r\n if (matchesDeniedPath(n.path, env.deniedPaths)) {\r\n return { ok: false, path: n.path, fail: { status: \"refused\", reason: \"denied\", message: \"That path is protected and cannot be read.\" } };\r\n }\r\n if (!env.listing.has(n.path)) {\r\n return { ok: false, path: n.path, fail: { status: \"not_found\", message: \"Not a tracked file. Use list_files to see the available paths.\" } };\r\n }\r\n return { ok: true, path: n.path };\r\n}\r\n\r\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 read_file \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\nfunction prepareReadFile(args: Record<string, unknown>, env: ToolEnv, ledger: ToolLedger): Prepared {\r\n const start = optionalInt(args.startLine);\r\n const end = optionalInt(args.endLine);\r\n if (start === \"bad\" || end === \"bad\") return bad(\"startLine and endLine must be whole numbers.\");\r\n if (start !== undefined && end !== undefined && end < start) return bad(\"endLine must not be before startLine.\");\r\n\r\n if (typeof args.path !== \"string\") return bad(\"path must be a string.\");\r\n const gate = gatePath(args.path, env);\r\n if (!gate.ok) {\r\n const read: ReadRecord | undefined = gate.fail.status === \"refused\" ? { path: gate.path, chars: 0, refused: true } : undefined;\r\n return { fail: gate.fail, ...(read ? { read } : {}) };\r\n }\r\n const path = gate.path;\r\n const key = JSON.stringify({ path, startLine: start ?? null, endLine: end ?? null });\r\n\r\n return {\r\n key,\r\n exec: () => {\r\n let size: number;\r\n try {\r\n const st = env.fs.lstat(path);\r\n if (st.isSymlink) {\r\n return { result: { status: \"refused\", reason: \"symlink\", message: \"Links are not followed.\" }, read: { path, chars: 0, refused: true } };\r\n }\r\n if (!st.isFile) return { result: { status: \"unreadable\", reason: \"not_a_file\", message: \"That entry is not a regular file.\" } };\r\n size = st.size;\r\n if (size > env.limits.fileBytesMax) {\r\n return { result: { status: \"unreadable\", reason: \"too_large\", message: \"That file is too large to read.\" } };\r\n }\r\n if (!env.fs.realpathInside(path)) {\r\n return { result: { status: \"refused\", reason: \"outside_workspace\", message: \"That path is not allowed.\" }, read: { path, chars: 0, refused: true } };\r\n }\r\n } catch {\r\n return { result: { status: \"unreadable\", reason: \"io\", message: \"That file could not be read.\" } };\r\n }\r\n\r\n let bytes: Uint8Array;\r\n try {\r\n bytes = env.fs.readBytes(path);\r\n } catch {\r\n return { result: { status: \"unreadable\", reason: \"io\", message: \"That file could not be read.\" } };\r\n }\r\n if (hasNul(bytes)) return { result: { status: \"unreadable\", reason: \"binary\", message: \"That file is binary.\" } };\r\n let text: string;\r\n try {\r\n text = new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\r\n } catch {\r\n return { result: { status: \"unreadable\", reason: \"not_utf8\", message: \"That file is not valid UTF-8 text.\" } };\r\n }\r\n if (text.charCodeAt(0) === 0xfeff) text = text.slice(1);\r\n text = text.replace(/\\r\\n/g, \"\\n\");\r\n\r\n const lines = text === \"\" ? [] : text.split(\"\\n\");\r\n if (lines.length > 0 && lines[lines.length - 1] === \"\") lines.pop();\r\n const totalLines = lines.length;\r\n\r\n const startLine = Math.max(1, start ?? 1);\r\n const endWanted = Math.min(totalLines, end ?? totalLines);\r\n if (startLine > totalLines) {\r\n return {\r\n result: { status: \"ok\", output: { path, startLine, endLine: totalLines, totalLines, truncated: false, content: \"\" } },\r\n read: { path, startLine, endLine: totalLines, chars: 0 },\r\n };\r\n }\r\n\r\n const budget = Math.max(0, Math.min(env.limits.readCharsPerRead, env.limits.readCharsTotal - ledger.readChars));\r\n const out: string[] = [];\r\n let used = 0;\r\n let endLine = startLine - 1;\r\n let truncated = false;\r\n for (let n = startLine; n <= endWanted; n++) {\r\n const line = `${n}\\t${lines[n - 1]}`;\r\n const cost = line.length + (out.length > 0 ? 1 : 0);\r\n if (used + cost <= budget) {\r\n out.push(line);\r\n used += cost;\r\n endLine = n;\r\n continue;\r\n }\r\n truncated = true;\r\n if (out.length === 0) {\r\n // One line on its own is bigger than the whole allowance: cut inside it.\r\n const keep = Math.max(0, budget - CUT.length);\r\n out.push(line.slice(0, keep) + CUT);\r\n used = out[0].length;\r\n endLine = n;\r\n }\r\n break;\r\n }\r\n\r\n let content = out.join(\"\\n\");\r\n ledger.readChars += used;\r\n const output: Record<string, unknown> = { path, startLine, endLine, totalLines, truncated };\r\n if (truncated) {\r\n if (endLine < totalLines) {\r\n output.nextStartLine = endLine + 1;\r\n content += `\\n[truncated: showing lines ${startLine}-${endLine} of ${totalLines}; call read_file with startLine=${endLine + 1}]`;\r\n } else {\r\n content += `\\n[truncated: line ${endLine} was cut]`;\r\n }\r\n }\r\n output.content = content;\r\n return { result: { status: \"ok\", output }, read: { path, startLine, endLine, chars: used } };\r\n },\r\n };\r\n}\r\n\r\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 list_files \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\nfunction prepareListFiles(args: Record<string, unknown>, env: ToolEnv): Prepared {\r\n const max = optionalInt(args.maxEntries);\r\n if (max === \"bad\" || (max !== undefined && max < 1)) return bad(\"maxEntries must be a whole number of at least 1.\");\r\n if (args.prefix !== undefined && args.prefix !== null && typeof args.prefix !== \"string\") return bad(\"prefix must be a string.\");\r\n const n = normaliseToolPath(args.prefix, { allowRoot: true });\r\n if (!n.ok) return { fail: { status: \"refused\", reason: n.reason, message: \"That path is not allowed.\" } };\r\n const prefix = n.path;\r\n const cap = Math.min(max ?? env.limits.listMaxEntries, env.limits.listMaxEntries);\r\n\r\n return {\r\n key: JSON.stringify({ prefix, maxEntries: cap }),\r\n exec: () => {\r\n const matching = env.visible.filter((p) => matchesPrefix(p, prefix));\r\n const entries = matching.slice(0, cap);\r\n const truncated = matching.length > cap;\r\n const output: Record<string, unknown> = { entries, total: matching.length, truncated };\r\n if (truncated) {\r\n const counts = new Map<string, number>();\r\n for (const p of matching) {\r\n const rest = prefix === \"\" ? p : p.slice(prefix.length + 1);\r\n const slash = rest.indexOf(\"/\");\r\n if (slash > 0) counts.set(rest.slice(0, slash), (counts.get(rest.slice(0, slash)) ?? 0) + 1);\r\n }\r\n output.subdirs = [...counts.entries()]\r\n .map(([name, count]) => ({ name, count }))\r\n .sort((a, b) => b.count - a.count || (a.name < b.name ? -1 : 1))\r\n .slice(0, 50);\r\n }\r\n return { result: { status: \"ok\", output } };\r\n },\r\n };\r\n}\r\n\r\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 grep \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\nconst WORD_CHAR = /[A-Za-z0-9_$]/;\r\n\r\nfunction lineMatches(line: string, needle: string, ignoreCase: boolean, wholeWord: boolean): number {\r\n const hay = ignoreCase ? line.toLowerCase() : line;\r\n let from = 0;\r\n for (;;) {\r\n const i = hay.indexOf(needle, from);\r\n if (i === -1) return -1;\r\n if (!wholeWord) return i;\r\n const before = i > 0 ? hay[i - 1] : \"\";\r\n const after = i + needle.length < hay.length ? hay[i + needle.length] : \"\";\r\n if (!(before && WORD_CHAR.test(before)) && !(after && WORD_CHAR.test(after))) return i;\r\n from = i + 1;\r\n }\r\n}\r\n\r\n/** Trim a matching line and, when it is long, show the stretch around the match. */\r\nfunction excerpt(line: string, at: number, max: number): string {\r\n const t = line.trim();\r\n if (t.length <= max) return t;\r\n const lead = line.length - line.trimStart().length;\r\n const pos = Math.max(0, at - lead);\r\n const from = Math.max(0, Math.min(pos - 40, t.length - max));\r\n const piece = t.slice(from, from + max);\r\n return `${from > 0 ? \"\u2026\" : \"\"}${piece}${from + max < t.length ? \"\u2026\" : \"\"}`;\r\n}\r\n\r\nfunction prepareGrep(args: Record<string, unknown>, env: ToolEnv): Prepared {\r\n const pattern = args.pattern;\r\n if (typeof pattern !== \"string\" || pattern.length === 0 || pattern.length > env.limits.maxPatternChars) {\r\n return bad(\"pattern must be a non-empty string within the length limit.\");\r\n }\r\n if (/[\\u0000\\r\\n]/.test(pattern)) return bad(\"pattern must be a single line of plain text.\");\r\n for (const flag of [\"ignoreCase\", \"wholeWord\"] as const) {\r\n if (args[flag] !== undefined && typeof args[flag] !== \"boolean\") return bad(`${flag} must be true or false.`);\r\n }\r\n const maxIn = optionalInt(args.maxResults);\r\n if (maxIn === \"bad\" || (maxIn !== undefined && maxIn < 1)) return bad(\"maxResults must be a whole number of at least 1.\");\r\n if (args.pathPrefix !== undefined && args.pathPrefix !== null && typeof args.pathPrefix !== \"string\") return bad(\"pathPrefix must be a string.\");\r\n const n = normaliseToolPath(args.pathPrefix, { allowRoot: true });\r\n if (!n.ok) return { fail: { status: \"refused\", reason: n.reason, message: \"That path is not allowed.\" } };\r\n\r\n const prefix = n.path;\r\n const ignoreCase = args.ignoreCase === true;\r\n const wholeWord = args.wholeWord === true;\r\n const maxMatches = Math.min(maxIn ?? env.limits.grepMaxMatches, env.limits.grepMaxMatches);\r\n const needle = ignoreCase ? pattern.toLowerCase() : pattern;\r\n\r\n return {\r\n key: JSON.stringify({ pattern, pathPrefix: prefix, maxResults: maxMatches, ignoreCase, wholeWord }),\r\n exec: () => {\r\n const matches: { path: string; line: number; text: string }[] = [];\r\n const skipped = { large: 0, binary: 0 };\r\n let filesScanned = 0;\r\n let bytesScanned = 0;\r\n let scanCapped = false;\r\n let truncated = false;\r\n\r\n scan: for (const path of env.visible) {\r\n if (!matchesPrefix(path, prefix)) continue;\r\n if (filesScanned >= env.limits.grepMaxFiles || bytesScanned >= env.limits.grepMaxBytes) {\r\n scanCapped = true;\r\n break;\r\n }\r\n filesScanned += 1;\r\n let bytes: Uint8Array;\r\n try {\r\n const st = env.fs.lstat(path);\r\n if (st.isSymlink || !st.isFile) continue;\r\n if (st.size > env.limits.grepFileBytes) {\r\n skipped.large += 1;\r\n continue;\r\n }\r\n if (!env.fs.realpathInside(path)) continue;\r\n bytes = env.fs.readBytes(path);\r\n } catch {\r\n continue;\r\n }\r\n bytesScanned += bytes.length;\r\n if (hasNul(bytes)) {\r\n skipped.binary += 1;\r\n continue;\r\n }\r\n const lines = new TextDecoder(\"utf-8\").decode(bytes).replace(/\\r\\n/g, \"\\n\").split(\"\\n\");\r\n for (let i = 0; i < lines.length; i++) {\r\n const at = lineMatches(lines[i], needle, ignoreCase, wholeWord);\r\n if (at === -1) continue;\r\n if (matches.length >= maxMatches) {\r\n truncated = true;\r\n break scan;\r\n }\r\n matches.push({ path, line: i + 1, text: excerpt(lines[i], at, env.limits.grepLineChars) });\r\n }\r\n }\r\n\r\n const output: Record<string, unknown> = { matches, truncated, filesScanned, skipped };\r\n if (scanCapped) output.scanCapped = true;\r\n return { result: { status: \"ok\", output } };\r\n },\r\n };\r\n}\r\n\r\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 the entry point \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\nfunction budgetResult(reason: string): Partial_ {\r\n return { status: \"budget_exhausted\", reason, message: \"That limit has been reached; give your answer from what you have.\" };\r\n}\r\n\r\n/**\r\n * Run one tool call. Never throws for a tool-level problem: every outcome is a result the AI is told\r\n * about. Every call counts toward the total (refused, invalid and repeated ones too, so probing is\r\n * bounded), except one turned away because the budget is already gone.\r\n */\r\nexport function executeToolCall(call: ToolCall, env: ToolEnv, ledger: ToolLedger): { result: ToolResult; read?: ReadRecord } {\r\n const wrap = (r: Partial_): ToolResult => ({ id: call.id, name: call.name, ...r });\r\n const finish = (r: Partial_, read?: ReadRecord) => {\r\n const result = wrap(r);\r\n ledger.resultChars += JSON.stringify(result).length;\r\n if (result.status === \"refused\") ledger.refused += 1;\r\n return read ? { result, read } : { result };\r\n };\r\n\r\n if (ledger.toolCalls >= env.limits.maxToolCalls) return finish(budgetResult(\"tool_calls\"));\r\n if (ledger.resultChars >= env.limits.resultCharsTotal) return finish(budgetResult(\"result_chars\"));\r\n if (call.name === \"read_file\" && ledger.readChars >= env.limits.readCharsTotal) return finish(budgetResult(\"read_chars\"));\r\n\r\n ledger.toolCalls += 1;\r\n\r\n let prepared: Prepared;\r\n try {\r\n const extra = env.extraTools && Object.prototype.hasOwnProperty.call(env.extraTools, call.name) ? env.extraTools[call.name] : undefined;\r\n if (call.name !== \"read_file\" && call.name !== \"list_files\" && call.name !== \"grep\" && !extra) {\r\n return finish({ status: \"unknown_tool\", message: \"Unknown tool. Use list_files, read_file or grep.\" });\r\n }\r\n if (!isPlainObject(call.args)) return finish({ status: \"bad_args\", message: \"Arguments must be an object.\" });\r\n prepared = extra\r\n ? extra(call.args, env, ledger)\r\n : call.name === \"read_file\"\r\n ? prepareReadFile(call.args, env, ledger)\r\n : call.name === \"list_files\"\r\n ? prepareListFiles(call.args, env)\r\n : prepareGrep(call.args, env);\r\n } catch {\r\n return finish({ status: \"bad_args\", message: \"Those arguments could not be used.\" });\r\n }\r\n\r\n if (\"fail\" in prepared) return finish(prepared.fail, prepared.read);\r\n\r\n const dupKey = `${call.name}:${prepared.key}`;\r\n const earlier = ledger.seen.get(dupKey);\r\n if (earlier !== undefined) {\r\n return finish({ status: \"duplicate\", reason: earlier, message: \"Identical call already made; see its result.\" });\r\n }\r\n ledger.seen.set(dupKey, call.id);\r\n\r\n let executed: Executed;\r\n try {\r\n executed = prepared.exec();\r\n } catch {\r\n executed = { result: { status: \"unreadable\", reason: \"io\", message: \"That could not be read.\" } };\r\n }\r\n return finish(executed.result, executed.read);\r\n}\r\n", "import { lstatSync, realpathSync } from \"node:fs\";\r\nimport { dirname, isAbsolute, join, relative } from \"node:path\";\r\nimport { detectLineEnding, fromLf, toLf, type LineEnding } from \"./editsApply\";\r\nimport { createNodeToolFs, type Partial_, type ToolFs } from \"./targetingTools\";\r\n\r\n/**\r\n * QUIKTR-1458 \u00A724 \u2014 where the code-writing loop keeps its changes.\r\n *\r\n * Nothing the AI edits or creates touches the checkout. Every change lives here, in memory, on top of the files on disk, and\r\n * the AI sees its own work when it reads or searches (`createOverlayFs`). When the loop ends the overlay becomes the same\r\n * `{targetPath, newContent}` list the per-file path produces, so every check after codegen is unchanged \u2014 and a loop that fails\r\n * is thrown away without a trace, which is what lets the run fall back to the per-file path.\r\n *\r\n * Text is held with LF endings and no BOM, exactly as `read_file` shows it, because that is what the AI copies its anchors\r\n * from. The file's own convention (CRLF, BOM) is remembered and put back when the result is produced.\r\n */\r\n\r\n/** A file system the code-writing loop can use: the read-only one plus the two questions a write has to ask. */\r\nexport interface WriteFs extends ToolFs {\r\n /** True when the nearest existing ancestor directory of `rel` really lies inside the checkout (no link leads out). */\r\n parentInside(rel: string): boolean;\r\n /** True when anything exists at `rel` (a file, a link, a directory), tracked or not. */\r\n exists(rel: string): boolean;\r\n}\r\n\r\nexport function createNodeWriteFs(rootDir: string = process.cwd()): WriteFs {\r\n const base = createNodeToolFs(rootDir);\r\n const inside = (real: string): boolean => {\r\n const r = relative(base.rootReal, real);\r\n return !r.startsWith(\"..\") && !isAbsolute(r);\r\n };\r\n return {\r\n ...base,\r\n parentInside(rel) {\r\n let dir = dirname(join(rootDir, rel));\r\n for (;;) {\r\n try {\r\n return inside(realpathSync(dir));\r\n } catch {\r\n const up = dirname(dir);\r\n if (up === dir) return false;\r\n dir = up;\r\n }\r\n }\r\n },\r\n exists(rel) {\r\n try {\r\n lstatSync(join(rootDir, rel));\r\n return true;\r\n } catch {\r\n return false;\r\n }\r\n },\r\n };\r\n}\r\n\r\nexport interface OverlayEntry {\r\n /** What the AI sees and edits: LF, no BOM. */\r\n lf: string;\r\n ending: LineEnding;\r\n bom: boolean;\r\n /** True for a file the loop created; false for an existing file it edited. */\r\n created: boolean;\r\n /** The file as it was on disk (LF, no BOM) before the first edit; null for a created file. */\r\n originalLf: string | null;\r\n}\r\n\r\nexport class WorkspaceOverlay {\r\n private readonly entries = new Map<string, OverlayEntry>();\r\n\r\n get(path: string): OverlayEntry | undefined {\r\n return this.entries.get(path);\r\n }\r\n\r\n has(path: string): boolean {\r\n return this.entries.has(path);\r\n }\r\n\r\n isCreated(path: string): boolean {\r\n return this.entries.get(path)?.created === true;\r\n }\r\n\r\n /** Record new text for an existing file. The first call remembers the original; later calls only replace the text. */\r\n setEdited(path: string, lf: string, base: { ending: LineEnding; bom: boolean; originalLf: string }): void {\r\n const current = this.entries.get(path);\r\n if (current) {\r\n current.lf = lf;\r\n return;\r\n }\r\n this.entries.set(path, { lf, ending: base.ending, bom: base.bom, created: false, originalLf: base.originalLf });\r\n }\r\n\r\n /** Create a file, or replace one the loop itself created earlier. */\r\n setCreated(path: string, lf: string): void {\r\n this.entries.set(path, { lf, ending: \"LF\", bom: false, created: true, originalLf: null });\r\n }\r\n\r\n /** Paths whose final text differs from what is on disk, in the order they were first touched. */\r\n changedPaths(): string[] {\r\n return [...this.entries.entries()].filter(([, e]) => e.created || e.lf !== e.originalLf).map(([p]) => p);\r\n }\r\n\r\n /** The full text of an entry as it would be written to disk. */\r\n fullText(path: string): string | undefined {\r\n const e = this.entries.get(path);\r\n return e ? `${e.bom ? \"\uFEFF\" : \"\"}${fromLf(e.lf, e.ending)}` : undefined;\r\n }\r\n\r\n results(): { targetPath: string; newContent: string }[] {\r\n return this.changedPaths().map((path) => ({ targetPath: path, newContent: this.fullText(path) as string }));\r\n }\r\n}\r\n\r\n/** Reads and writes through the overlay first, the real checkout second. */\r\nexport function createOverlayFs(base: WriteFs, overlay: WorkspaceOverlay): WriteFs {\r\n const encode = (path: string): Uint8Array => new TextEncoder().encode(overlay.fullText(path) as string);\r\n return {\r\n rootReal: base.rootReal,\r\n lstat(rel) {\r\n if (overlay.has(rel)) return { isSymlink: false, isFile: true, size: encode(rel).length };\r\n return base.lstat(rel);\r\n },\r\n realpathInside(rel) {\r\n if (overlay.isCreated(rel)) return base.parentInside(rel);\r\n return base.realpathInside(rel);\r\n },\r\n readBytes(rel) {\r\n return overlay.has(rel) ? encode(rel) : base.readBytes(rel);\r\n },\r\n parentInside: (rel) => base.parentInside(rel),\r\n exists: (rel) => overlay.has(rel) || base.exists(rel),\r\n };\r\n}\r\n\r\nexport type LoadedText =\r\n | { ok: true; lf: string; ending: LineEnding; bom: boolean }\r\n | { ok: false; result: Partial_ };\r\n\r\nfunction hasNul(bytes: Uint8Array): boolean {\r\n const n = Math.min(bytes.length, 8000);\r\n for (let i = 0; i < n; i++) if (bytes[i] === 0) return true;\r\n return false;\r\n}\r\n\r\n/**\r\n * Load a file for editing, with the same refusals `read_file` has (a link, a binary or non-UTF-8 file, one too large, one that\r\n * leads outside the checkout) plus one more: a file with MIXED line endings cannot be written back faithfully, so it is not\r\n * edited at all. Never throws; every outcome is a result the AI is told about, with fixed text.\r\n */\r\nexport function loadTextForEdit(fs: ToolFs, path: string, maxBytes: number): LoadedText {\r\n let bytes: Uint8Array;\r\n try {\r\n const st = fs.lstat(path);\r\n if (st.isSymlink) return { ok: false, result: { status: \"refused\", reason: \"symlink\", message: \"Links are not followed.\" } };\r\n if (!st.isFile) return { ok: false, result: { status: \"unreadable\", reason: \"not_a_file\", message: \"That entry is not a regular file.\" } };\r\n if (st.size > maxBytes) return { ok: false, result: { status: \"too_large\", reason: \"too_large\", message: \"That file is too large to edit.\" } };\r\n if (!fs.realpathInside(path)) {\r\n return { ok: false, result: { status: \"refused\", reason: \"outside_workspace\", message: \"That path is not allowed.\" } };\r\n }\r\n bytes = fs.readBytes(path);\r\n } catch {\r\n return { ok: false, result: { status: \"unreadable\", reason: \"io\", message: \"That file could not be read.\" } };\r\n }\r\n if (hasNul(bytes)) return { ok: false, result: { status: \"unreadable\", reason: \"binary\", message: \"That file is binary.\" } };\r\n let text: string;\r\n try {\r\n text = new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\r\n } catch {\r\n return { ok: false, result: { status: \"unreadable\", reason: \"not_utf8\", message: \"That file is not valid UTF-8 text.\" } };\r\n }\r\n // The decoder drops a leading BOM without saying so, so it is read from the bytes: a file that had one must get it back.\r\n const bom = bytes.length >= 3 && bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf;\r\n if (text.charCodeAt(0) === 0xfeff) text = text.slice(1);\r\n const ending = detectLineEnding(text);\r\n if (ending === \"mixed\") {\r\n return {\r\n ok: false,\r\n result: { status: \"refused\", reason: \"mixed_line_endings\", message: \"That file mixes line endings and cannot be edited faithfully.\" },\r\n };\r\n }\r\n return { ok: true, lf: toLf(text), ending, bom };\r\n}\r\n", "import { isAddOnly } from \"./addOnly\";\r\nimport { matchesDeniedPath } from \"./deniedPaths\";\r\nimport { applyEdits, toLf, type LineEnding } from \"./editsApply\";\r\nimport { SyntaxGuard, syntaxWarningMessage, type SyntaxProblem } from \"./syntaxCheck\";\r\nimport { normaliseToolPath, buildVisibleListing } from \"./targetingPaths\";\r\nimport {\r\n DEFAULT_LIMITS,\r\n newLedger,\r\n type ExtraToolPreparer,\r\n type Partial_,\r\n type Prepared,\r\n type ToolEnv,\r\n type ToolLedger,\r\n type ToolLimits,\r\n} from \"./targetingTools\";\r\nimport { createNodeWriteFs, createOverlayFs, loadTextForEdit, WorkspaceOverlay, type WriteFs } from \"./workspaceOverlay\";\r\n\r\n/**\r\n * QUIKTR-1458 \u00A724 \u2014 the two WRITE tools of the code-writing loop, `edit_file` and `write_file`, and the workspace they act on.\r\n *\r\n * Nothing here writes to the checkout. Both tools change the in-memory overlay (`workspaceOverlay.ts`), and every change goes\r\n * through one funnel of rules, in this order, each one a plain RESULT the AI can act on rather than an exception:\r\n * 1. the path is a well-formed, in-workspace path (`normaliseToolPath`: no `..`, no absolute path, no control characters);\r\n * 2. it is not a protected (denied) path \u2014 BEFORE anything about the file is looked at, so the answer cannot be used to find\r\n * out what exists there;\r\n * 3. `edit_file` names a file git tracks or one this run created; `write_file` names a file that does NOT exist yet;\r\n * 4. `write_file` cannot reach outside the checkout through a link in a parent directory, or put a file where a file or a\r\n * folder already is;\r\n * 5. an existing TEST file is only ever added to: the replacement must start or end with the anchor, so what is there is\r\n * never weakened (doc 62 \u00A74: \"a test is NEVER edited to make generated code pass\");\r\n * 6. the anchor matches exactly once in the file as the AI last saw it (`applyEdits`);\r\n * 7. the run's budget for written characters.\r\n *\r\n * Results never echo what the AI sent or what a file contained.\r\n */\r\n\r\nexport interface CodegenLimits extends ToolLimits {\r\n /** Characters the AI may write in all (every `replace` and every `content`). */\r\n writeCharsTotal: number;\r\n findChars: number;\r\n replaceChars: number;\r\n contentChars: number;\r\n}\r\n\r\n/** Starting values; to be tuned by measurement (\u00A724.14). */\r\nexport const CODEGEN_LIMITS: CodegenLimits = {\r\n ...DEFAULT_LIMITS,\r\n maxTurns: 20,\r\n maxToolCalls: 40,\r\n writeCharsTotal: 120_000,\r\n findChars: 8_000,\r\n replaceChars: 20_000,\r\n contentChars: 200_000,\r\n};\r\n\r\nexport interface CodegenLedger extends ToolLedger {\r\n writeChars: number;\r\n}\r\n\r\nexport function newCodegenLedger(): CodegenLedger {\r\n return { ...newLedger(), writeChars: 0 };\r\n}\r\n\r\nexport interface CodegenWorkspace {\r\n env: ToolEnv;\r\n ledger: CodegenLedger;\r\n overlay: WorkspaceOverlay;\r\n limits: CodegenLimits;\r\n /** Successful edits per path, for the run's audit record. Paths and counts only. */\r\n edits: Map<string, number>;\r\n /** Files created, with their size. */\r\n created: Map<string, number>;\r\n /** How many write results told the AI a file no longer parses (QUIKTR-1458). */\r\n readonly syntaxWarnings: number;\r\n /** The files that still do not parse as the overlay stands now. Paths, a closed word and a position: never text. */\r\n syntaxProblems(): { path: string; problem: SyntaxProblem }[];\r\n}\r\n\r\nexport interface CodegenWorkspaceArgs {\r\n /** Every tracked file, as `git ls-files` printed it. */\r\n listing: string[];\r\n deniedPaths: string[];\r\n /** Existing test files: they accept only additions (rule 5). */\r\n protectedTestPaths: string[];\r\n fs?: WriteFs;\r\n limits?: Partial<CodegenLimits>;\r\n /** Existing files already in view (the context shown before the first turn): evidence that the project parses, for `SyntaxGuard`. */\r\n syntaxSeed?: { path: string; text: string }[];\r\n}\r\n\r\nfunction bad(message: string): { fail: Partial_ } {\r\n return { fail: { status: \"bad_args\", message } };\r\n}\r\n\r\nfunction refused(reason: string, message: string): { fail: Partial_ } {\r\n return { fail: { status: \"refused\", reason, message } };\r\n}\r\n\r\nfunction countLines(text: string): number {\r\n if (text === \"\") return 0;\r\n const n = text.split(\"\\n\").length;\r\n return text.endsWith(\"\\n\") ? n - 1 : n;\r\n}\r\n\r\nexport function createCodegenWorkspace(args: CodegenWorkspaceArgs): CodegenWorkspace {\r\n const limits: CodegenLimits = { ...CODEGEN_LIMITS, ...args.limits };\r\n const baseFs = args.fs ?? createNodeWriteFs();\r\n const overlay = new WorkspaceOverlay();\r\n const listing = new Set(args.listing);\r\n const visible = buildVisibleListing(args.listing, args.deniedPaths);\r\n const protectedTests = new Set(args.protectedTestPaths);\r\n const edits = new Map<string, number>();\r\n const created = new Map<string, number>();\r\n const guard = new SyntaxGuard();\r\n if (args.syntaxSeed) guard.seed(args.syntaxSeed);\r\n let syntaxWarnings = 0;\r\n\r\n /** The result of a change that applied: plain `ok`, plus a warning the AI can act on when the file no longer parses. */\r\n const withSyntaxNote = (output: Record<string, unknown>, problem: SyntaxProblem | null): Partial_ => {\r\n if (!problem) return { status: \"ok\", output };\r\n syntaxWarnings += 1;\r\n return {\r\n status: \"ok\",\r\n output: { ...output, syntax: { kind: problem.kind, line: problem.line, column: problem.column } },\r\n message: syntaxWarningMessage(problem),\r\n };\r\n };\r\n\r\n const noteCreated = (path: string): void => {\r\n listing.add(path);\r\n if (!visible.includes(path)) {\r\n visible.push(path);\r\n visible.sort();\r\n }\r\n };\r\n\r\n // A change makes any earlier read, search or listing stale: forget them so the AI can look again without being told \"duplicate\".\r\n const forgetReads = (ledger: ToolLedger): void => {\r\n for (const key of [...ledger.seen.keys()]) {\r\n if (key.startsWith(\"read_file:\") || key.startsWith(\"grep:\") || key.startsWith(\"list_files:\")) ledger.seen.delete(key);\r\n }\r\n };\r\n\r\n const gate = (raw: unknown, deniedPaths: string[]): { ok: true; path: string } | { ok: false; fail: Partial_ } => {\r\n const n = normaliseToolPath(raw);\r\n if (!n.ok) return { ok: false, fail: { status: \"refused\", reason: n.reason, message: \"That path is not allowed.\" } };\r\n if (matchesDeniedPath(n.path, deniedPaths)) {\r\n return { ok: false, fail: { status: \"refused\", reason: \"denied\", message: \"That path is protected and cannot be changed.\" } };\r\n }\r\n return { ok: true, path: n.path };\r\n };\r\n\r\n const prepareEdit: ExtraToolPreparer = (a, env, ledger): Prepared => {\r\n if (typeof a.path !== \"string\") return bad(\"path must be a string.\");\r\n if (typeof a.find !== \"string\" || a.find.length === 0 || a.find.length > limits.findChars) {\r\n return bad(\"find must be a non-empty string within the length limit.\");\r\n }\r\n if (typeof a.replace !== \"string\" || a.replace.length > limits.replaceChars) return bad(\"replace must be a string within the length limit.\");\r\n const g = gate(a.path, env.deniedPaths);\r\n if (!g.ok) return { fail: g.fail };\r\n const path = g.path;\r\n if (!env.listing.has(path)) {\r\n return { fail: { status: \"not_found\", message: \"Not a tracked file. Use edit_file on an existing file, or write_file for a new one.\" } };\r\n }\r\n const find = a.find;\r\n const replace = a.replace;\r\n return {\r\n key: JSON.stringify({ path, find, replace }),\r\n exec: () => {\r\n const cl = ledger as CodegenLedger;\r\n if (cl.writeChars + replace.length > limits.writeCharsTotal) {\r\n return { result: { status: \"budget_exhausted\", reason: \"write_chars\", message: \"The limit on text written has been reached; finish with what you have.\" } };\r\n }\r\n const entry = overlay.get(path);\r\n let lf: string;\r\n let base: { ending: LineEnding; bom: boolean; originalLf: string };\r\n if (entry) {\r\n lf = entry.lf;\r\n base = { ending: entry.ending, bom: entry.bom, originalLf: entry.originalLf ?? entry.lf };\r\n } else {\r\n const loaded = loadTextForEdit(baseFs, path, limits.fileBytesMax);\r\n if (!loaded.ok) return { result: loaded.result };\r\n lf = loaded.lf;\r\n base = { ending: loaded.ending, bom: loaded.bom, originalLf: loaded.lf };\r\n }\r\n // A file that existed before this run and holds tests may be added to, never changed (`isAddOnly`: one block of whole new\r\n // lines, a new test, before the matched text, after it or between two of its lines). `protected` is an ordinary answer: the\r\n // AI reads the message and sends the edit again, so one misplaced edit never ends the run.\r\n if (protectedTests.has(path) && !isAddOnly(path, find, replace)) {\r\n return {\r\n result: {\r\n status: \"protected\",\r\n reason: \"existing_test\",\r\n message:\r\n \"An existing test can only be added to. Keep every character of the text you matched, in the same order, and add only whole new lines that declare a new test (it, test or describe), before the text, after it, or between two of its lines. To add a test to a block, match the last lines of that block and put the new test after them.\",\r\n },\r\n };\r\n }\r\n const applied = applyEdits(lf, [{ find, replace }]);\r\n if (!applied.ok) {\r\n const refusal = applied.refusals[0];\r\n if (refusal?.kind === \"no_match\") {\r\n return { result: { status: \"no_match\", message: \"That text was not found in the file. Read it again and copy it exactly.\" } };\r\n }\r\n if (refusal?.kind === \"ambiguous\") {\r\n const n = refusal.matchCount ?? 0;\r\n return { result: { status: \"ambiguous\", message: `That text matches ${n} places. Include more surrounding text so it matches exactly once.` } };\r\n }\r\n return { result: { status: \"bad_args\", message: \"That edit could not be applied.\" } };\r\n }\r\n overlay.setEdited(path, applied.content, base);\r\n cl.writeChars += replace.length;\r\n edits.set(path, (edits.get(path) ?? 0) + 1);\r\n forgetReads(ledger);\r\n const problem = guard.judgeEdit(path, base.originalLf, applied.content);\r\n return { result: withSyntaxNote({ path, replaced: 1, totalLines: countLines(applied.content) }, problem) };\r\n },\r\n };\r\n };\r\n\r\n const prepareWrite: ExtraToolPreparer = (a, env, ledger): Prepared => {\r\n if (typeof a.path !== \"string\") return bad(\"path must be a string.\");\r\n if (typeof a.content !== \"string\") return bad(\"content must be a string.\");\r\n const g = gate(a.path, env.deniedPaths);\r\n if (!g.ok) return { fail: g.fail };\r\n const path = g.path;\r\n if (a.content.length > limits.contentChars) return { fail: { status: \"too_large\", message: \"That file is too large to write.\" } };\r\n const own = overlay.isCreated(path);\r\n if (!own && (env.listing.has(path) || baseFs.exists(path))) {\r\n return { fail: { status: \"exists\", message: \"That file already exists. Use edit_file to change it.\" } };\r\n }\r\n // A new file cannot sit inside a file, or on top of a folder.\r\n const parts = path.split(\"/\");\r\n for (let i = 1; i < parts.length; i++) {\r\n if (env.listing.has(parts.slice(0, i).join(\"/\"))) return refused(\"parent_is_file\", \"That path is not allowed.\");\r\n }\r\n if (env.visible.some((p) => p.startsWith(`${path}/`))) return refused(\"is_directory\", \"That path is not allowed.\");\r\n if (!baseFs.parentInside(path)) return refused(\"outside_workspace\", \"That path is not allowed.\");\r\n const content = a.content;\r\n return {\r\n key: JSON.stringify({ path, content }),\r\n exec: () => {\r\n const cl = ledger as CodegenLedger;\r\n if (cl.writeChars + content.length > limits.writeCharsTotal) {\r\n return { result: { status: \"budget_exhausted\", reason: \"write_chars\", message: \"The limit on text written has been reached; finish with what you have.\" } };\r\n }\r\n const lf = toLf(content);\r\n overlay.setCreated(path, lf);\r\n noteCreated(path);\r\n cl.writeChars += content.length;\r\n created.set(path, content.length);\r\n forgetReads(ledger);\r\n const problem = guard.judgeCreated(path, lf);\r\n return { result: withSyntaxNote({ path, totalLines: countLines(lf), chars: content.length }, problem) };\r\n },\r\n };\r\n };\r\n\r\n const env: ToolEnv = {\r\n listing,\r\n visible,\r\n deniedPaths: args.deniedPaths,\r\n fs: createOverlayFs(baseFs, overlay),\r\n limits,\r\n extraTools: { edit_file: prepareEdit, write_file: prepareWrite },\r\n };\r\n const syntaxProblems = (): { path: string; problem: SyntaxProblem }[] => {\r\n const out: { path: string; problem: SyntaxProblem }[] = [];\r\n for (const path of overlay.changedPaths()) {\r\n const entry = overlay.get(path);\r\n if (!entry) continue;\r\n const problem =\r\n entry.created || entry.originalLf === null ? guard.judgeCreated(path, entry.lf) : guard.judgeEdit(path, entry.originalLf, entry.lf);\r\n if (problem) out.push({ path, problem });\r\n }\r\n return out;\r\n };\r\n return {\r\n env,\r\n ledger: newCodegenLedger(),\r\n overlay,\r\n limits,\r\n edits,\r\n created,\r\n get syntaxWarnings() {\r\n return syntaxWarnings;\r\n },\r\n syntaxProblems,\r\n };\r\n}\r\n", "/**\r\n * Error types shared by `targeting.ts` and the read-only targeting loop (QUIKTR-1458). They live in\r\n * a module of their own so the loop can recognise them without importing `targeting.ts`, which\r\n * imports the loop.\r\n */\r\n\r\n/**\r\n * A proposed target, or a cited context file, that matches a denied path. A class of its own so the\r\n * read-only loop can tell \"the AI asked for something we never allow\" - which must never be retried\r\n * by falling back - from \"the AI's answer was merely invalid\". The message text is exactly what it\r\n * was before, so nothing that read it changes.\r\n */\r\nexport class DeniedPathError extends Error {\r\n constructor(message: string) {\r\n super(message);\r\n this.name = \"DeniedPathError\";\r\n }\r\n}\r\n\r\n/** The call itself came back non-2xx (after retryFetch's own retries). Same message as ever. */\r\nexport class TargetingHttpError extends Error {\r\n readonly status: number;\r\n constructor(status: number, statusText: string) {\r\n super(`Targeting call failed: ${status} ${statusText}`);\r\n this.name = \"TargetingHttpError\";\r\n this.status = status;\r\n }\r\n}\r\n", "/**\r\n * QUIKTR-1458 \u2014 an estimate of what a request costs in TOKENS (contract section 23.5).\r\n *\r\n * The per-turn ceiling is in tokens and has to be counted the way the provider counts them. A character\r\n * budget is wrong, and so is chars / 4: measured against Gemini's own `count_tokens`, chars / 4\r\n * undercounts a path listing at 0.5x-0.9x and non-ASCII text at 0.5x-0.8x, so a repository with a long\r\n * listing or non-ASCII paths and comments would blow the cap while appearing inside it.\r\n *\r\n * So: a per-character-CLASS estimate. The weights were fitted against `count_tokens` on 14 real samples\r\n * (gemini-2.5-flash, 6 Oct 2026: real repository path listings of 40 to 3,000 paths, TypeScript plain and\r\n * wrapped in the JSON a tool result travels in, non-ASCII comments and paths), then rounded UP. Every\r\n * sample came out 1.14x to 1.50x ABOVE the real count; none under. Over-counting is the safe direction \u2014\r\n * the loop stops sooner and a run falls back to today's single call \u2014 so do not tidy these toward the\r\n * fitted values (0.26 / 0.16 / 0 / 0.92 / 0.66) without re-measuring.\r\n *\r\n * The AI Runtime carries the SAME estimator (`pilot_targeting_loop.estimate_tokens`) and both are pinned\r\n * to the same reference values. Class counts are integers and the weights are applied in one fixed order,\r\n * so the two agree to the token. A change to either is a change to both.\r\n */\r\n\r\nexport const TOKENS_PER_ALPHA_CHAR = 0.3;\r\nexport const TOKENS_PER_DIGIT_CHAR = 0.18;\r\nexport const TOKENS_PER_SPACE_CHAR = 0.05;\r\nexport const TOKENS_PER_PUNCTUATION_CHAR = 1.05;\r\nexport const TOKENS_PER_NON_ASCII_CHAR = 1.0;\r\n\r\n/**\r\n * What a request costs beyond the JSON `contextData` it carries: the system prompt, the loop\r\n * instruction, the response schema and the user turn. Measured at roughly 3,300 to 3,600 tokens, then\r\n * rounded up.\r\n */\r\nexport const PROMPT_OVERHEAD_TOKENS = 5_000;\r\n\r\n/** A deliberately high estimate of what `text` costs in tokens. Counts code points, not UTF-16 units. */\r\nexport function estimateTokens(text: string): number {\r\n let alpha = 0;\r\n let digit = 0;\r\n let space = 0;\r\n let punct = 0;\r\n let nonAscii = 0;\r\n for (const ch of text) {\r\n const code = ch.codePointAt(0)!;\r\n if (code >= 128) nonAscii++;\r\n else if ((code >= 65 && code <= 90) || (code >= 97 && code <= 122)) alpha++;\r\n else if (code >= 48 && code <= 57) digit++;\r\n else if (code === 32 || code === 9 || code === 13 || code === 10) space++;\r\n else punct++;\r\n }\r\n return Math.ceil(\r\n alpha * TOKENS_PER_ALPHA_CHAR +\r\n digit * TOKENS_PER_DIGIT_CHAR +\r\n space * TOKENS_PER_SPACE_CHAR +\r\n punct * TOKENS_PER_PUNCTUATION_CHAR +\r\n nonAscii * TOKENS_PER_NON_ASCII_CHAR,\r\n );\r\n}\r\n\r\n/**\r\n * The estimated size of the model request one loop turn becomes: the prompt overhead plus the context as\r\n * the runtime renders it (indent 2, non-ASCII kept \u2014 never escaped, which would turn every non-ASCII\r\n * character into six ASCII ones and flatter the count).\r\n */\r\nexport function estimateRequestTokens(contextData: unknown): number {\r\n return PROMPT_OVERHEAD_TOKENS + estimateTokens(JSON.stringify(contextData ?? {}, null, 2));\r\n}\r\n", "import { checkHardFailure, unwrapExecute } from \"./envelope\";\r\nimport { RuntimeReplyError } from \"./runtimeReplyError\";\r\nimport { TargetingHttpError } from \"./targetingErrors\";\r\nimport { buildVisibleListing } from \"./targetingPaths\";\r\nimport {\r\n DEFAULT_LIMITS,\r\n createNodeToolFs,\r\n executeToolCall,\r\n newLedger,\r\n type ReadRecord,\r\n type ToolEnv,\r\n type ToolFs,\r\n type ToolLimits,\r\n type ToolResult,\r\n} from \"./targetingTools\";\r\nimport { estimateRequestTokens } from \"./tokenEstimate\";\r\n\r\n/**\r\n * QUIKTR-1458 \u2014 the read-only targeting loop.\r\n *\r\n * Instead of one call answered from the file listing alone, the runner and the AI Runtime talk in\r\n * turns. Each turn the runner POSTs to the same `/ai/execute`, carrying everything said so far (the\r\n * runtime keeps no state); the runtime answers either \"run these read-only tools\" or the final\r\n * targeting answer, in exactly the shape the single call returns. The runner runs the tools locally,\r\n * on the checkout, and sends the results with the next turn.\r\n *\r\n * The loop is built so it cannot run away and cannot go quiet:\r\n * - it ends with a final answer or a `LoopFailure`; the last turn is always one where the AI is told\r\n * to answer now, and a runtime that still asks for tools then is a failure, not a hang;\r\n * - every limit and every refusal is reported to the AI as a tool RESULT, not an exception;\r\n * - nothing it logs contains file content, a search text or the AI's reasoning.\r\n *\r\n * A `LoopFailure` is an EXPECTED way for this to not work (an older runtime, a timeout, a malformed\r\n * reply), and the caller falls back to the single call. A `SafetyRefusalError` is not: it means the\r\n * runtime refused the run itself (spend cap, credential), and a second call would only be refused or\r\n * paid for again.\r\n *\r\n * The wire shape here is a proposal until the AI Runtime side is built to match it; it is isolated in\r\n * this file so it can change in one place.\r\n */\r\n\r\nexport const LOOP_CONTRACT_VERSION = \"targeting-loop-1\";\r\n\r\nexport type LoopFinalReason = \"max_turns\" | \"tool_budget\" | \"read_budget\" | \"no_progress\";\r\n\r\nexport type LoopStopReason =\r\n | \"model_final\"\r\n | \"forced_max_turns\"\r\n | \"forced_tool_budget\"\r\n | \"forced_read_budget\"\r\n | \"forced_no_progress\"\r\n | \"fallback\";\r\n\r\nexport type FallbackReason =\r\n | \"contract_rejected\"\r\n | \"semantic_mismatch\"\r\n | \"http_error\"\r\n | \"transport\"\r\n | \"turn_timeout\"\r\n | \"loop_deadline\"\r\n | \"runtime_failed\"\r\n | \"bad_reply\"\r\n | \"duplicate_call_ids\"\r\n | \"final_not_produced\"\r\n | \"final_invalid\"\r\n | \"token_ceiling\"\r\n | \"executor_error\"\r\n | \"internal_error\";\r\n\r\nexport interface LoopSummary {\r\n turns: number;\r\n toolCalls: number;\r\n readChars: number;\r\n refused: number;\r\n stopReason: LoopStopReason;\r\n fellBack?: true;\r\n fallbackReason?: FallbackReason;\r\n reads: ReadRecord[];\r\n}\r\n\r\nexport class LoopFailure extends Error {\r\n readonly reason: FallbackReason;\r\n readonly runtimeCode?: string;\r\n /** What the loop had done when it failed, so reads made before the failure are not lost. */\r\n summary?: LoopSummary;\r\n constructor(reason: FallbackReason, runtimeCode?: string, cause?: unknown) {\r\n super(`pilot.targeting loop failed: ${reason}${runtimeCode ? ` (${runtimeCode})` : \"\"}`);\r\n this.name = \"LoopFailure\";\r\n this.reason = reason;\r\n this.runtimeCode = runtimeCode;\r\n if (cause !== undefined) (this as { cause?: unknown }).cause = cause;\r\n }\r\n}\r\n\r\n/** The runtime refused the RUN (not just this turn). Never answered by falling back. */\r\nexport class SafetyRefusalError extends RuntimeReplyError {\r\n constructor(message: string, summary: string) {\r\n super(message, summary);\r\n this.name = \"SafetyRefusalError\";\r\n }\r\n}\r\n\r\n/**\r\n * Runtime error codes that mean the run itself was refused: out of money, or the run credential does\r\n * not cover this. The single call would be refused too, or paid for twice.\r\n */\r\nexport const NO_FALLBACK_CODES: ReadonlySet<string> = new Set([\"RUN_BUDGET_EXCEEDED\", \"RUN_CREDENTIAL_SCOPE\"]);\r\n\r\nexport interface LoopDeps {\r\n /** One POST of `pilot.targeting`; resolves to the RAW `/ai/execute` envelope. */\r\n post(contextData: Record<string, unknown>, signal: AbortSignal): Promise<unknown>;\r\n fs?: ToolFs;\r\n limits?: Partial<ToolLimits>;\r\n now?: () => number;\r\n log?: (event: Record<string, unknown>) => void;\r\n turnTimeoutMs?: number;\r\n deadlineMs?: number;\r\n}\r\n\r\nexport interface LoopArgs {\r\n /** Exactly today's contextData for the single call. */\r\n baseContext: Record<string, unknown>;\r\n listing: string[];\r\n deniedPaths: string[];\r\n}\r\n\r\nconst TOOL_NAMES = new Set([\"list_files\", \"read_file\", \"grep\"]);\r\nconst MAX_ID_CHARS = 64;\r\nconst MAX_CALLS_IN_A_REPLY = 50;\r\nconst MAX_ARGS_JSON_CHARS = 1_000;\r\n\r\nfunction isPlainObject(x: unknown): x is Record<string, unknown> {\r\n return typeof x === \"object\" && x !== null && !Array.isArray(x);\r\n}\r\n\r\nfunction safeArgs(args: unknown): unknown {\r\n try {\r\n return JSON.stringify(args).length <= MAX_ARGS_JSON_CHARS ? args : { _omitted: \"too large\" };\r\n } catch {\r\n return { _omitted: \"unreadable\" };\r\n }\r\n}\r\n\r\nfunction classifyTransport(err: unknown): LoopFailure {\r\n if (err instanceof TargetingHttpError) return new LoopFailure(\"http_error\", undefined, err);\r\n const name = (err as { name?: unknown })?.name;\r\n if (name === \"TimeoutError\" || name === \"AbortError\") return new LoopFailure(\"turn_timeout\", undefined, err);\r\n return new LoopFailure(\"transport\", undefined, err);\r\n}\r\n\r\nexport async function runTargetingLoop(args: LoopArgs, deps: LoopDeps): Promise<{ body: unknown; summary: LoopSummary }> {\r\n const limits: ToolLimits = { ...DEFAULT_LIMITS, ...deps.limits };\r\n const now = deps.now ?? Date.now;\r\n const log = deps.log ?? ((e: Record<string, unknown>) => console.log(JSON.stringify(e)));\r\n const turnTimeoutMs = deps.turnTimeoutMs ?? 180_000;\r\n const deadlineMs = deps.deadlineMs ?? 600_000;\r\n\r\n const env: ToolEnv = {\r\n listing: new Set(args.listing),\r\n visible: buildVisibleListing(args.listing, args.deniedPaths),\r\n deniedPaths: args.deniedPaths,\r\n fs: deps.fs ?? createNodeToolFs(),\r\n limits,\r\n };\r\n const ledger = newLedger();\r\n const reads: ReadRecord[] = [];\r\n const transcript: Record<string, unknown>[] = [];\r\n const toolResults: ToolResult[] = [];\r\n const usedIds = new Set<string>();\r\n\r\n let turns = 0;\r\n let noProgressStreak = 0;\r\n let forced: LoopFinalReason | null = null;\r\n const started = now();\r\n\r\n // Spread then override: `contractVersion` keeps the position it has in today's request.\r\n const buildContext = (turn: number, isFinal: boolean, finalReason: LoopFinalReason): Record<string, unknown> => ({\r\n ...args.baseContext,\r\n contractVersion: LOOP_CONTRACT_VERSION,\r\n loop: {\r\n turn,\r\n maxTurns: limits.maxTurns,\r\n final: isFinal,\r\n ...(isFinal ? { finalReason } : {}),\r\n remaining: {\r\n toolCalls: Math.max(0, limits.maxToolCalls - ledger.toolCalls),\r\n readChars: Math.max(0, limits.readCharsTotal - ledger.readChars),\r\n },\r\n transcript,\r\n toolResults,\r\n },\r\n });\r\n\r\n const snapshot = (stopReason: LoopStopReason): LoopSummary => ({\r\n turns,\r\n toolCalls: ledger.toolCalls,\r\n readChars: ledger.readChars,\r\n refused: ledger.refused,\r\n stopReason,\r\n reads: [...reads],\r\n });\r\n\r\n log({ event: \"targeting.loop_start\", mode: \"loop\", maxTurns: limits.maxTurns, maxToolCalls: limits.maxToolCalls, listingFiles: args.listing.length });\r\n\r\n try {\r\n for (let turn = 1; turn <= limits.maxTurns; turn++) {\r\n turns = turn;\r\n if (now() - started > deadlineMs) throw new LoopFailure(\"loop_deadline\");\r\n\r\n const isFinal = forced !== null || turn === limits.maxTurns;\r\n const finalReason: LoopFinalReason = forced ?? \"max_turns\";\r\n const contextData = buildContext(turn, isFinal, finalReason);\r\n const requestChars = JSON.stringify(contextData).length;\r\n // The ceiling is enforced HERE because nothing else does: the runtime has no pre-dispatch size check\r\n // for targeting, and an oversized turn does not refuse cleanly \u2014 it fails at the provider.\r\n const requestTokens = estimateRequestTokens(contextData);\r\n if (requestTokens > limits.maxRequestTokens) {\r\n log({ event: \"targeting.loop_ceiling\", turn, action: \"not_sent\", projectedTokens: requestTokens, ceiling: limits.maxRequestTokens });\r\n throw new LoopFailure(\"token_ceiling\");\r\n }\r\n\r\n const turnStarted = now();\r\n let envelope: unknown;\r\n try {\r\n envelope = await deps.post(contextData, AbortSignal.timeout(turnTimeoutMs));\r\n } catch (err) {\r\n throw classifyTransport(err);\r\n }\r\n\r\n const code = (envelope as { errorCode?: unknown } | null)?.errorCode;\r\n try {\r\n checkHardFailure(envelope, \"pilot.targeting\");\r\n } catch (err) {\r\n throw new LoopFailure(code === \"CONTRACT_REJECTED\" ? \"contract_rejected\" : \"semantic_mismatch\", String(code), err);\r\n }\r\n if ((envelope as { success?: unknown } | null)?.success === false) {\r\n const runtimeCode = typeof code === \"string\" ? code : undefined;\r\n if (runtimeCode && NO_FALLBACK_CODES.has(runtimeCode)) {\r\n let inner: RuntimeReplyError | undefined;\r\n try {\r\n unwrapExecute(envelope, \"pilot.targeting\");\r\n } catch (e) {\r\n inner = e instanceof RuntimeReplyError ? e : undefined;\r\n }\r\n const fallbackText = `pilot.targeting failed: ${runtimeCode}`;\r\n throw new SafetyRefusalError(inner?.message ?? fallbackText, inner?.summary ?? fallbackText);\r\n }\r\n throw new LoopFailure(\"runtime_failed\", runtimeCode);\r\n }\r\n\r\n let body: Record<string, unknown>;\r\n try {\r\n body = unwrapExecute<Record<string, unknown>>(envelope, \"pilot.targeting\");\r\n } catch (err) {\r\n throw new LoopFailure(\"bad_reply\", undefined, err);\r\n }\r\n\r\n if (body.outcome === \"TARGETED\" || body.outcome === \"NO_TARGET\") {\r\n log({ event: \"targeting.loop_turn\", turn, outcome: \"final\", requestChars, requestTokens, elapsedMs: now() - turnStarted, calls: [] });\r\n const stopReason: LoopStopReason = isFinal ? (`forced_${finalReason}` as LoopStopReason) : \"model_final\";\r\n log({ event: \"targeting.loop_done\", turns, toolCalls: ledger.toolCalls, readChars: ledger.readChars, refused: ledger.refused, stopReason });\r\n return { body, summary: snapshot(stopReason) };\r\n }\r\n if (body.outcome !== \"TOOL_CALLS\") throw new LoopFailure(\"bad_reply\");\r\n if (isFinal) throw new LoopFailure(\"final_not_produced\");\r\n\r\n const rawCalls = body.toolCalls;\r\n if (!Array.isArray(rawCalls) || rawCalls.length === 0 || rawCalls.length > MAX_CALLS_IN_A_REPLY) {\r\n throw new LoopFailure(\"bad_reply\");\r\n }\r\n const calls: { id: string; name: string; args: unknown }[] = [];\r\n for (const c of rawCalls) {\r\n if (!isPlainObject(c) || typeof c.id !== \"string\" || c.id.length === 0 || c.id.length > MAX_ID_CHARS || typeof c.name !== \"string\") {\r\n throw new LoopFailure(\"bad_reply\");\r\n }\r\n if (usedIds.has(c.id) || calls.some((x) => x.id === c.id)) throw new LoopFailure(\"duplicate_call_ids\");\r\n calls.push({ id: c.id, name: c.name, args: c.args });\r\n }\r\n for (const c of calls) usedIds.add(c.id);\r\n\r\n const results: ToolResult[] = [];\r\n const logged: Record<string, unknown>[] = [];\r\n const turnReads: (ReadRecord | undefined)[] = [];\r\n calls.forEach((call, index) => {\r\n let result: ToolResult;\r\n let read: ReadRecord | undefined;\r\n if (index >= limits.maxCallsPerTurn) {\r\n result = {\r\n id: call.id,\r\n name: call.name,\r\n status: \"budget_exhausted\",\r\n reason: \"too_many_calls\",\r\n message: \"Too many calls in one turn; this one was not run.\",\r\n };\r\n } else {\r\n try {\r\n ({ result, read } = executeToolCall(call, env, ledger));\r\n } catch (err) {\r\n throw new LoopFailure(\"executor_error\", undefined, err);\r\n }\r\n }\r\n results.push(result);\r\n turnReads[index] = read;\r\n if (read) reads.push(read);\r\n const tool = TOOL_NAMES.has(call.name) ? call.name : \"unknown\";\r\n const path = read && read.path !== \"(invalid path)\" ? { path: read.path } : {};\r\n logged.push({ tool, status: result.status, ...(result.reason && result.status !== \"duplicate\" ? { reason: result.reason } : {}), ...path });\r\n if (result.status === \"refused\") {\r\n log({ event: \"targeting.loop_refused\", turn, tool, reason: result.reason, ...path });\r\n }\r\n });\r\n\r\n const reasoning = typeof body.reasoning === \"string\" ? body.reasoning.slice(0, limits.maxReasoningChars) : undefined;\r\n transcript.push({\r\n turn,\r\n ...(reasoning ? { reasoning } : {}),\r\n toolCalls: calls.map((c) => ({ id: c.id, name: c.name, args: safeArgs(c.args) })),\r\n });\r\n toolResults.push(...results);\r\n\r\n noProgressStreak = results.every((r) => r.status === \"duplicate\") ? noProgressStreak + 1 : 0;\r\n if (noProgressStreak >= 2) forced = \"no_progress\";\r\n else if (ledger.toolCalls >= limits.maxToolCalls) forced = \"tool_budget\";\r\n else if (ledger.readChars >= limits.readCharsTotal || ledger.resultChars >= limits.resultCharsTotal) forced = \"read_budget\";\r\n\r\n // Would the NEXT request still fit? A loop accumulates, so it is this, not a total, that can break.\r\n // If not: do not deliver what this turn found, tell the AI so (a result it already understands:\r\n // `budget_exhausted`), and make the next turn its last. If even that cannot fit, give up to the\r\n // single call rather than send something the provider will fail on.\r\n const nextTurn = turn + 1;\r\n if (nextTurn <= limits.maxTurns) {\r\n const nextFinal = forced !== null || nextTurn === limits.maxTurns;\r\n const projected = estimateRequestTokens(buildContext(nextTurn, nextFinal, forced ?? \"max_turns\"));\r\n if (projected > limits.maxRequestTokens) {\r\n results.forEach((r, idx) => {\r\n if (r.status !== \"ok\") return;\r\n toolResults[toolResults.indexOf(r)] = {\r\n id: r.id,\r\n name: r.name,\r\n status: \"budget_exhausted\",\r\n reason: \"token_ceiling\",\r\n message: \"Too large to include; answer from what you have.\",\r\n };\r\n const dropped = turnReads[idx];\r\n if (dropped) {\r\n const at = reads.indexOf(dropped);\r\n if (at >= 0) reads.splice(at, 1);\r\n }\r\n logged[idx].status = \"budget_exhausted\";\r\n logged[idx].reason = \"token_ceiling\";\r\n });\r\n forced = \"read_budget\";\r\n const trimmed = estimateRequestTokens(buildContext(nextTurn, true, \"read_budget\"));\r\n const fits = trimmed <= limits.maxRequestTokens;\r\n log({\r\n event: \"targeting.loop_ceiling\",\r\n turn,\r\n action: fits ? \"dropped_results\" : \"fallback\",\r\n projectedTokens: projected,\r\n ceiling: limits.maxRequestTokens,\r\n });\r\n if (!fits) throw new LoopFailure(\"token_ceiling\");\r\n }\r\n }\r\n log({ event: \"targeting.loop_turn\", turn, outcome: \"tool_calls\", requestChars, requestTokens, elapsedMs: now() - turnStarted, calls: logged });\r\n }\r\n throw new LoopFailure(\"final_not_produced\");\r\n } catch (err) {\r\n if (err instanceof SafetyRefusalError) throw err;\r\n const failure = err instanceof LoopFailure ? err : new LoopFailure(\"internal_error\", undefined, err);\r\n failure.summary ??= snapshot(\"fallback\");\r\n throw failure;\r\n }\r\n}\r\n", "import { looksLikeTruncatedRewrite, type CodegenFileResult } from \"./codegen\";\r\nimport { createCodegenWorkspace, type CodegenLimits } from \"./codegenTools\";\r\nimport { describeSyntaxProblem } from \"./syntaxCheck\";\r\nimport { checkHardFailure, unwrapExecute } from \"./envelope\";\r\nimport { RuntimeReplyError } from \"./runtimeReplyError\";\r\nimport { NO_FALLBACK_CODES, SafetyRefusalError } from \"./targetingLoop\";\r\nimport { TargetingHttpError } from \"./targetingErrors\";\r\nimport type { PilotTarget } from \"./targeting\";\r\nimport { executeToolCall, type ReadRecord, type ToolResult } from \"./targetingTools\";\r\nimport { estimateRequestTokens } from \"./tokenEstimate\";\r\nimport type { WriteFs } from \"./workspaceOverlay\";\r\n\r\n/**\r\n * QUIKTR-1458 \u00A724 \u2014 the code-writing loop (doc 62 Phase 2, first slice).\r\n *\r\n * Instead of one call per file, the runner and the AI Runtime talk in turns. Each turn the runner POSTs to `/ai/execute`\r\n * carrying everything said so far (the runtime keeps no state); the runtime answers with tool calls to run, or with `DONE`, or\r\n * with `CANNOT_COMPLETE`. The runner runs the tools on the checkout through an in-memory overlay (`codegenTools.ts`), so NOTHING is\r\n * written to disk, and what comes out is the same `{targetPath, newContent}` list the per-file path produces: every check after\r\n * codegen in `run.ts` is unchanged, and a loop that fails is thrown away without a trace so the caller can fall back.\r\n *\r\n * It is built, like the read-only targeting loop it grew from, so it cannot run away and cannot go quiet:\r\n * - it ends with a result or a `CodegenLoopFailure`; the last turn is always one where the AI is told to finish, and a runtime\r\n * that still asks for tools then is a failure, not a hang;\r\n * - every limit and every refusal reaches the AI as a tool RESULT, not an exception;\r\n * - nothing it logs contains file content, an anchor, a replacement, a search text or the AI's reasoning.\r\n *\r\n * Unlike the targeting loop it keeps the AI's own write arguments in the transcript in full (it has to see what it wrote), and\r\n * when a request grows past the ceiling it drops the OLDEST read outputs first (the AI can read again) before anything else.\r\n */\r\n\r\nexport const CODEGEN_LOOP_CONTRACT_VERSION = \"codegen-loop-1\";\r\n\r\nexport type CodegenFinalReason = \"max_turns\" | \"tool_budget\" | \"read_budget\" | \"write_budget\" | \"no_progress\";\r\n\r\nexport type CodegenStopReason =\r\n | \"model_done\"\r\n | \"forced_max_turns\"\r\n | \"forced_tool_budget\"\r\n | \"forced_read_budget\"\r\n | \"forced_write_budget\"\r\n | \"forced_no_progress\"\r\n | \"fallback\";\r\n\r\nexport type CodegenFallbackReason =\r\n | \"contract_rejected\"\r\n | \"semantic_mismatch\"\r\n | \"http_error\"\r\n | \"transport\"\r\n | \"turn_timeout\"\r\n | \"loop_deadline\"\r\n | \"runtime_failed\"\r\n | \"bad_reply\"\r\n | \"duplicate_call_ids\"\r\n | \"final_not_produced\"\r\n | \"token_ceiling\"\r\n | \"executor_error\"\r\n | \"internal_error\"\r\n | \"cannot_complete\"\r\n | \"no_writes\"\r\n | \"coverage_missing\"\r\n | \"truncation_guard\"\r\n | \"syntax_error\";\r\n\r\nexport interface CodegenLoopSummary {\r\n turns: number;\r\n toolCalls: number;\r\n refused: number;\r\n stopReason: CodegenStopReason;\r\n fellBack?: true;\r\n fallbackReason?: CodegenFallbackReason;\r\n /** Everything read, in order. Paths and sizes only. */\r\n reads: ReadRecord[];\r\n /** Successful edits per path. */\r\n edits: { path: string; count: number }[];\r\n /** Files created, with their size. */\r\n created: { path: string; chars: number }[];\r\n /** How many results of each status the AI was given. A closed vocabulary. */\r\n statusCounts: Record<string, number>;\r\n /** How many write results told the AI a file no longer parses (QUIKTR-1458), repaired or not. */\r\n syntaxWarnings: number;\r\n /** The AI's own one-or-two sentences per turn, so a reviewer can see why it went where it went. Model-written. */\r\n reasoning: { turn: number; text: string }[];\r\n}\r\n\r\nexport class CodegenLoopFailure extends Error {\r\n readonly reason: CodegenFallbackReason;\r\n readonly runtimeCode?: string;\r\n /** Short, runner-written (or, for CANNOT_COMPLETE, the AI's own summary cut to 300 characters). Never file content. */\r\n readonly detail?: string;\r\n summary?: CodegenLoopSummary;\r\n constructor(reason: CodegenFallbackReason, runtimeCode?: string, cause?: unknown, detail?: string) {\r\n super(`pilot.codegen loop failed: ${reason}${runtimeCode ? ` (${runtimeCode})` : \"\"}`);\r\n this.name = \"CodegenLoopFailure\";\r\n this.reason = reason;\r\n this.runtimeCode = runtimeCode;\r\n this.detail = detail;\r\n if (cause !== undefined) (this as { cause?: unknown }).cause = cause;\r\n }\r\n}\r\n\r\nexport interface CodegenLoopDeps {\r\n /** One POST of `pilot.codegen`; resolves to the RAW `/ai/execute` envelope. */\r\n post(contextData: Record<string, unknown>, signal: AbortSignal): Promise<unknown>;\r\n fs?: WriteFs;\r\n limits?: Partial<CodegenLimits>;\r\n now?: () => number;\r\n log?: (event: Record<string, unknown>) => void;\r\n turnTimeoutMs?: number;\r\n deadlineMs?: number;\r\n}\r\n\r\nexport interface CodegenLoopArgs {\r\n /** Everything the request carries besides `contractVersion` and `loop` (targets, requiredTests, workspaceListing, ...). */\r\n baseContext: Record<string, unknown>;\r\n /** The plan, for the truncated-rewrite guard (its plan text is the union of every target's steps). */\r\n targets: PilotTarget[];\r\n /** Every case that must end up bracketed in some written text; skipped cases are not in here. */\r\n requiredAutomationIds: string[];\r\n listing: string[];\r\n deniedPaths: string[];\r\n /** Existing test files: they accept only additions. */\r\n protectedTestPaths: string[];\r\n /** Existing files already shown to the AI before its first turn: evidence for the parse check that the project parses. */\r\n syntaxSeed?: { path: string; text: string }[];\r\n}\r\n\r\nconst MAX_ID_CHARS = 64;\r\nconst MAX_CALLS_IN_A_REPLY = 50;\r\nconst MAX_SUMMARY_CHARS = 300;\r\nconst READ_TOOLS = new Set([\"list_files\", \"read_file\", \"grep\"]);\r\nconst WRITE_TOOLS = new Set([\"edit_file\", \"write_file\"]);\r\nconst TOOL_NAMES = new Set([...READ_TOOLS, ...WRITE_TOOLS]);\r\n\r\nfunction isPlainObject(x: unknown): x is Record<string, unknown> {\r\n return typeof x === \"object\" && x !== null && !Array.isArray(x);\r\n}\r\n\r\nfunction classifyTransport(err: unknown): CodegenLoopFailure {\r\n if (err instanceof TargetingHttpError) return new CodegenLoopFailure(\"http_error\", undefined, err);\r\n const name = (err as { name?: unknown })?.name;\r\n if (name === \"TimeoutError\" || name === \"AbortError\") return new CodegenLoopFailure(\"turn_timeout\", undefined, err);\r\n return new CodegenLoopFailure(\"transport\", undefined, err);\r\n}\r\n\r\nconst DROPPED_OUTPUT = { dropped: true, note: \"Dropped to keep the request small. Read the file again if you need it.\" };\r\n\r\nexport async function runCodegenLoop(\r\n args: CodegenLoopArgs,\r\n deps: CodegenLoopDeps,\r\n): Promise<{ results: CodegenFileResult[]; summary: CodegenLoopSummary; doneSummary: string }> {\r\n const ws = createCodegenWorkspace({\r\n listing: args.listing,\r\n deniedPaths: args.deniedPaths,\r\n protectedTestPaths: args.protectedTestPaths,\r\n fs: deps.fs,\r\n limits: deps.limits,\r\n syntaxSeed: args.syntaxSeed,\r\n });\r\n const { env, ledger, overlay, limits } = ws;\r\n const now = deps.now ?? Date.now;\r\n const log = deps.log ?? ((e: Record<string, unknown>) => console.log(JSON.stringify(e)));\r\n const turnTimeoutMs = deps.turnTimeoutMs ?? 300_000;\r\n const deadlineMs = deps.deadlineMs ?? 1_500_000;\r\n\r\n const reads: ReadRecord[] = [];\r\n const reasoning: { turn: number; text: string }[] = [];\r\n const statusCounts: Record<string, number> = {};\r\n const transcript: { turn: number; reasoning?: string; toolCalls: { id: string; name: string; args: unknown }[] }[] = [];\r\n const toolResults: ToolResult[] = [];\r\n const usedIds = new Set<string>();\r\n\r\n let turns = 0;\r\n let noProgressStreak = 0;\r\n let forced: CodegenFinalReason | null = null;\r\n const started = now();\r\n\r\n const buildContext = (turn: number, isFinal: boolean, finalReason: CodegenFinalReason): Record<string, unknown> => ({\r\n ...args.baseContext,\r\n contractVersion: CODEGEN_LOOP_CONTRACT_VERSION,\r\n loop: {\r\n turn,\r\n maxTurns: limits.maxTurns,\r\n final: isFinal,\r\n ...(isFinal ? { finalReason } : {}),\r\n remaining: {\r\n toolCalls: Math.max(0, limits.maxToolCalls - ledger.toolCalls),\r\n readChars: Math.max(0, limits.readCharsTotal - ledger.readChars),\r\n writeChars: Math.max(0, limits.writeCharsTotal - ledger.writeChars),\r\n },\r\n transcript,\r\n toolResults,\r\n },\r\n });\r\n\r\n const snapshot = (stopReason: CodegenStopReason): CodegenLoopSummary => ({\r\n turns,\r\n toolCalls: ledger.toolCalls,\r\n refused: ledger.refused,\r\n stopReason,\r\n reads: [...reads],\r\n edits: [...ws.edits.entries()].map(([path, count]) => ({ path, count })),\r\n created: [...ws.created.entries()].map(([path, chars]) => ({ path, chars })),\r\n statusCounts: { ...statusCounts },\r\n syntaxWarnings: ws.syntaxWarnings,\r\n reasoning: [...reasoning],\r\n });\r\n\r\n /** Make room: oldest read outputs first (the AI can read again), then the text of the oldest writes. Returns true if it fits. */\r\n const makeRoom = (nextTurn: number, nextFinal: boolean, finalReason: CodegenFinalReason): boolean => {\r\n const fits = (): boolean => estimateRequestTokens(buildContext(nextTurn, nextFinal, finalReason)) <= limits.maxRequestTokens;\r\n if (fits()) return true;\r\n for (let i = 0; i < toolResults.length && !fits(); i++) {\r\n const r = toolResults[i]!;\r\n if (READ_TOOLS.has(r.name) && r.status === \"ok\" && r.output !== DROPPED_OUTPUT) toolResults[i] = { ...r, output: DROPPED_OUTPUT };\r\n }\r\n for (const key of [...ledger.seen.keys()]) {\r\n if (key.startsWith(\"read_file:\") || key.startsWith(\"grep:\") || key.startsWith(\"list_files:\")) ledger.seen.delete(key);\r\n }\r\n for (const entry of transcript) {\r\n if (fits()) break;\r\n entry.toolCalls = entry.toolCalls.map((c) => {\r\n if (!WRITE_TOOLS.has(c.name) || !isPlainObject(c.args) || \"_omitted\" in c.args) return c;\r\n const path = typeof c.args.path === \"string\" ? { path: c.args.path } : {};\r\n return { ...c, args: { ...path, _omitted: \"written earlier; read the file to see it\" } };\r\n });\r\n }\r\n return fits();\r\n };\r\n\r\n log({ event: \"codegen.loop_start\", maxTurns: limits.maxTurns, maxToolCalls: limits.maxToolCalls, listingFiles: args.listing.length });\r\n\r\n try {\r\n for (let turn = 1; turn <= limits.maxTurns; turn++) {\r\n turns = turn;\r\n if (now() - started > deadlineMs) throw new CodegenLoopFailure(\"loop_deadline\");\r\n\r\n const isFinal = forced !== null || turn === limits.maxTurns;\r\n const finalReason: CodegenFinalReason = forced ?? \"max_turns\";\r\n const contextData = buildContext(turn, isFinal, finalReason);\r\n const requestTokens = estimateRequestTokens(contextData);\r\n if (requestTokens > limits.maxRequestTokens) {\r\n log({ event: \"codegen.loop_ceiling\", turn, action: \"not_sent\", projectedTokens: requestTokens, ceiling: limits.maxRequestTokens });\r\n throw new CodegenLoopFailure(\"token_ceiling\");\r\n }\r\n\r\n const turnStarted = now();\r\n let envelope: unknown;\r\n try {\r\n envelope = await deps.post(contextData, AbortSignal.timeout(turnTimeoutMs));\r\n } catch (err) {\r\n throw classifyTransport(err);\r\n }\r\n\r\n const code = (envelope as { errorCode?: unknown } | null)?.errorCode;\r\n try {\r\n checkHardFailure(envelope, \"pilot.codegen\");\r\n } catch (err) {\r\n throw new CodegenLoopFailure(code === \"CONTRACT_REJECTED\" ? \"contract_rejected\" : \"semantic_mismatch\", String(code), err);\r\n }\r\n if ((envelope as { success?: unknown } | null)?.success === false) {\r\n const runtimeCode = typeof code === \"string\" ? code : undefined;\r\n if (runtimeCode && NO_FALLBACK_CODES.has(runtimeCode)) {\r\n let inner: RuntimeReplyError | undefined;\r\n try {\r\n unwrapExecute(envelope, \"pilot.codegen\");\r\n } catch (e) {\r\n inner = e instanceof RuntimeReplyError ? e : undefined;\r\n }\r\n const fallbackText = `pilot.codegen failed: ${runtimeCode}`;\r\n throw new SafetyRefusalError(inner?.message ?? fallbackText, inner?.summary ?? fallbackText);\r\n }\r\n throw new CodegenLoopFailure(\"runtime_failed\", runtimeCode);\r\n }\r\n\r\n let body: Record<string, unknown>;\r\n try {\r\n body = unwrapExecute<Record<string, unknown>>(envelope, \"pilot.codegen\");\r\n } catch (err) {\r\n throw new CodegenLoopFailure(\"bad_reply\", undefined, err);\r\n }\r\n\r\n const reasonText = typeof body.reasoning === \"string\" ? body.reasoning.slice(0, limits.maxReasoningChars) : undefined;\r\n\r\n if (body.outcome === \"CANNOT_COMPLETE\") {\r\n log({ event: \"codegen.loop_turn\", turn, outcome: \"cannot_complete\", requestTokens, elapsedMs: now() - turnStarted, calls: [] });\r\n const said = typeof body.summary === \"string\" ? body.summary.slice(0, MAX_SUMMARY_CHARS) : undefined;\r\n throw new CodegenLoopFailure(\"cannot_complete\", undefined, undefined, said);\r\n }\r\n\r\n if (body.outcome === \"DONE\") {\r\n log({ event: \"codegen.loop_turn\", turn, outcome: \"done\", requestTokens, elapsedMs: now() - turnStarted, calls: [] });\r\n const changed = overlay.changedPaths();\r\n if (changed.length === 0) throw new CodegenLoopFailure(\"no_writes\");\r\n const texts = changed.map((p) => overlay.get(p)?.lf ?? \"\");\r\n const missing = args.requiredAutomationIds.filter((id) => !texts.some((t) => t.includes(`[${id}]`)));\r\n if (missing.length > 0) {\r\n log({ event: \"codegen.loop_refused\", turn, reason: \"coverage_missing\", missing: missing.length });\r\n throw new CodegenLoopFailure(\"coverage_missing\", undefined, undefined, `${missing.length} required test case(s) not written`);\r\n }\r\n const planSteps = args.targets.flatMap((t) => t.planStepsImplemented);\r\n for (const path of changed) {\r\n const entry = overlay.get(path);\r\n if (!entry || entry.created || entry.originalLf === null) continue;\r\n const pseudo: PilotTarget = { path, kind: \"EXISTING\", planStepsImplemented: planSteps };\r\n const suspect = looksLikeTruncatedRewrite(pseudo, entry.originalLf, entry.lf);\r\n if (suspect) {\r\n log({ event: \"codegen.loop_refused\", turn, reason: \"truncation_guard\", path });\r\n throw new CodegenLoopFailure(\"truncation_guard\", undefined, undefined, `${path}: ${suspect}`);\r\n }\r\n }\r\n // A file that no longer parses would only fail lint after the run (QUIKTR-1458: both rc.6 failures were this). The AI was told in\r\n // the result of the edit that broke it; if it still ended with the file broken, the loop's work is not used.\r\n const broken = ws.syntaxProblems()[0];\r\n if (broken) {\r\n log({ event: \"codegen.loop_refused\", turn, reason: \"syntax_error\", path: broken.path, kind: broken.problem.kind, line: broken.problem.line });\r\n throw new CodegenLoopFailure(\"syntax_error\", undefined, undefined, `${broken.path}: ${describeSyntaxProblem(broken.problem)}`);\r\n }\r\n const stopReason: CodegenStopReason = isFinal ? (`forced_${finalReason}` as CodegenStopReason) : \"model_done\";\r\n const doneSummary = typeof body.summary === \"string\" ? body.summary.slice(0, MAX_SUMMARY_CHARS) : \"\";\r\n log({ event: \"codegen.loop_done\", turns, toolCalls: ledger.toolCalls, edits: ws.edits.size, created: ws.created.size, stopReason });\r\n return { results: overlay.results(), summary: snapshot(stopReason), doneSummary };\r\n }\r\n\r\n if (body.outcome !== \"TOOL_CALLS\") throw new CodegenLoopFailure(\"bad_reply\");\r\n if (isFinal) throw new CodegenLoopFailure(\"final_not_produced\");\r\n\r\n const rawCalls = body.toolCalls;\r\n if (!Array.isArray(rawCalls) || rawCalls.length === 0 || rawCalls.length > MAX_CALLS_IN_A_REPLY) throw new CodegenLoopFailure(\"bad_reply\");\r\n const calls: { id: string; name: string; args: unknown }[] = [];\r\n for (const c of rawCalls) {\r\n if (!isPlainObject(c) || typeof c.id !== \"string\" || c.id.length === 0 || c.id.length > MAX_ID_CHARS || typeof c.name !== \"string\") {\r\n throw new CodegenLoopFailure(\"bad_reply\");\r\n }\r\n if (usedIds.has(c.id) || calls.some((x) => x.id === c.id)) throw new CodegenLoopFailure(\"duplicate_call_ids\");\r\n calls.push({ id: c.id, name: c.name, args: c.args });\r\n }\r\n for (const c of calls) usedIds.add(c.id);\r\n\r\n const results: ToolResult[] = [];\r\n const logged: Record<string, unknown>[] = [];\r\n calls.forEach((call, index) => {\r\n let result: ToolResult;\r\n let read: ReadRecord | undefined;\r\n if (index >= limits.maxCallsPerTurn) {\r\n result = { id: call.id, name: call.name, status: \"budget_exhausted\", reason: \"too_many_calls\", message: \"Too many calls in one turn; this one was not run.\" };\r\n } else {\r\n try {\r\n ({ result, read } = executeToolCall(call, env, ledger));\r\n } catch (err) {\r\n throw new CodegenLoopFailure(\"executor_error\", undefined, err);\r\n }\r\n }\r\n results.push(result);\r\n if (read) reads.push(read);\r\n statusCounts[result.status] = (statusCounts[result.status] ?? 0) + 1;\r\n const tool = TOOL_NAMES.has(call.name) ? call.name : \"unknown\";\r\n const pathArg = isPlainObject(call.args) && typeof call.args.path === \"string\" && result.status !== \"refused\" ? { path: call.args.path } : {};\r\n logged.push({ tool, status: result.status, ...(result.reason && result.status !== \"duplicate\" ? { reason: result.reason } : {}), ...pathArg });\r\n if (result.status === \"refused\" || result.status === \"protected\") {\r\n log({ event: \"codegen.loop_refused\", turn, tool, status: result.status, reason: result.reason });\r\n }\r\n });\r\n\r\n if (reasonText) reasoning.push({ turn, text: reasonText });\r\n transcript.push({ turn, ...(reasonText ? { reasoning: reasonText } : {}), toolCalls: calls.map((c) => ({ id: c.id, name: c.name, args: c.args })) });\r\n toolResults.push(...results);\r\n\r\n noProgressStreak = results.every((r) => r.status === \"duplicate\") ? noProgressStreak + 1 : 0;\r\n if (noProgressStreak >= 2) forced = \"no_progress\";\r\n else if (ledger.toolCalls >= limits.maxToolCalls) forced = \"tool_budget\";\r\n else if (ledger.writeChars >= limits.writeCharsTotal) forced = \"write_budget\";\r\n else if (ledger.readChars >= limits.readCharsTotal || ledger.resultChars >= limits.resultCharsTotal) forced = \"read_budget\";\r\n\r\n const nextTurn = turn + 1;\r\n if (nextTurn <= limits.maxTurns) {\r\n const nextFinal = forced !== null || nextTurn === limits.maxTurns;\r\n if (!makeRoom(nextTurn, nextFinal, forced ?? \"max_turns\")) {\r\n // Even with the oldest reads and writes dropped it does not fit: make the next turn the last, and if that cannot\r\n // fit either, give up to the per-file path rather than send something the provider will fail on.\r\n forced = forced ?? \"read_budget\";\r\n const fits = makeRoom(nextTurn, true, forced);\r\n log({ event: \"codegen.loop_ceiling\", turn, action: fits ? \"forced_final\" : \"fallback\", ceiling: limits.maxRequestTokens });\r\n if (!fits) throw new CodegenLoopFailure(\"token_ceiling\");\r\n }\r\n }\r\n log({ event: \"codegen.loop_turn\", turn, outcome: \"tool_calls\", requestTokens, elapsedMs: now() - turnStarted, calls: logged });\r\n }\r\n throw new CodegenLoopFailure(\"final_not_produced\");\r\n } catch (err) {\r\n if (err instanceof SafetyRefusalError) throw err;\r\n const failure = err instanceof CodegenLoopFailure ? err : new CodegenLoopFailure(\"internal_error\", undefined, err);\r\n failure.summary ??= snapshot(\"fallback\");\r\n throw failure;\r\n }\r\n}\r\n", "import { runCodegen, type CodegenFileResult, type JudgedByCase } from \"./codegen\";\r\nimport { buildCodegenLoopRecord, type CodegenLoopRecord } from \"./codegenLoopRecord\";\r\nimport { collectLoopContext, type LoopContext } from \"./codegenLoopContext\";\r\nimport { CodegenLoopFailure, runCodegenLoop, type CodegenLoopArgs, type CodegenLoopDeps, type CodegenLoopSummary } from \"./codegenLoop\";\r\nimport type { CodegenMode } from \"./codegenMode\";\r\nimport { isTestTarget } from \"./overlapCheck\";\r\nimport type { PilotPacket } from \"./packet\";\r\nimport { fetchWithRetry } from \"./retryFetch\";\r\nimport type { PilotTarget, SkippedCase } from \"./targeting\";\r\nimport { TargetingHttpError } from \"./targetingErrors\";\r\nimport { SafetyRefusalError } from \"./targetingLoop\";\r\nimport type { CodegenContextRecord } from \"./targetingRecord\";\r\n\r\n/**\r\n * QUIKTR-1458 \u00A724 \u2014 the one place that decides HOW the code is written: the loop, or the per-file calls it replaces.\r\n *\r\n * With the loop switched on (`codegenMode.ts`) it tries the loop first. If the loop cannot finish for an ordinary reason it\r\n * is thrown away (it wrote nothing to disk) and the files are written one at a time, exactly as before, with a warning that\r\n * says so out loud: a run that quietly stopped using the loop would make every comparison between the two ways meaningless.\r\n * It NEVER falls back when the runtime refused the run itself (spend cap, credential): a second attempt would be refused again,\r\n * or paid for twice.\r\n */\r\n\r\nexport interface CodegenStepParams {\r\n mode: CodegenMode;\r\n gateway: PilotPacket[\"gateway\"];\r\n targets: PilotTarget[];\r\n workspaceListing: string[];\r\n requiredTests: PilotPacket[\"requiredTests\"];\r\n deniedPaths: string[];\r\n judgedByPool: JudgedByCase[];\r\n warnings: string[];\r\n contextLog: CodegenContextRecord[];\r\n outOfScope: string[];\r\n testDiscovery: PilotPacket[\"testDiscovery\"];\r\n skippedCases: SkippedCase[];\r\n /** Filled when the loop ran or was tried: what it did, for the run's record. */\r\n out: { loop?: CodegenLoopRecord };\r\n /** For tests: replace the network, the file system or the limits. */\r\n deps?: Partial<CodegenLoopDeps>;\r\n /** For tests: how a context file is read (default: from the checkout). */\r\n readFile?: (path: string) => string;\r\n}\r\n\r\n/** The cap on how many protected test paths go on the wire; the runner enforces the full list itself. */\r\nconst MAX_PROTECTED_PATHS_ON_WIRE = 300;\r\n\r\nexport async function postCodegenTurn(\r\n gateway: PilotPacket[\"gateway\"],\r\n contextData: Record<string, unknown>,\r\n signal?: AbortSignal,\r\n): Promise<unknown> {\r\n const res = await fetchWithRetry(`${gateway.baseUrl}/ai/execute`, {\r\n method: \"POST\",\r\n headers: { \"content-type\": \"application/json\", \"x-run-token\": gateway.token },\r\n body: JSON.stringify({\r\n appId: \"quiktrack\",\r\n useCase: \"pilot.codegen\",\r\n expectedOutputType: \"json\",\r\n userPrompt: \"\",\r\n contextData,\r\n }),\r\n ...(signal ? { signal } : {}),\r\n });\r\n if (!res.ok) throw new TargetingHttpError(res.status, res.statusText);\r\n return res.json();\r\n}\r\n\r\n/** Existing test files: the ones that look like tests by path, and the ones the last test report says the runner discovers. */\r\nexport function protectedTestFiles(listing: string[], testDiscovery: PilotPacket[\"testDiscovery\"]): string[] {\r\n const inListing = new Set(listing);\r\n const found = new Set<string>(listing.filter((p) => isTestTarget(p)));\r\n if (testDiscovery.report === \"PRESENT\") {\r\n for (const p of testDiscovery.discoveredTestFiles) if (inListing.has(p)) found.add(p);\r\n }\r\n return [...found].sort();\r\n}\r\n\r\nexport function buildCodegenLoopArgs(\r\n p: CodegenStepParams,\r\n context: LoopContext = collectLoopContext({ targets: p.targets, listing: p.workspaceListing, deniedPaths: p.deniedPaths, ...(p.readFile ? { readFile: p.readFile } : {}) }),\r\n): CodegenLoopArgs {\r\n const skipped = new Set(p.skippedCases.map((s) => s.automationId));\r\n const claimed = new Set<string>();\r\n for (const t of p.targets) for (const id of t.automationIds ?? []) if (!skipped.has(id)) claimed.add(id);\r\n const requiredTests = p.requiredTests.filter((tc) => claimed.has(tc.automationId));\r\n const protectedTestPaths = protectedTestFiles(p.workspaceListing, p.testDiscovery);\r\n\r\n const baseContext: Record<string, unknown> = {\r\n targets: p.targets.map((t) => ({\r\n path: t.path,\r\n kind: t.kind,\r\n role: (t.automationIds?.length ?? 0) > 0 || isTestTarget(t.path) ? \"test\" : \"code\",\r\n planSteps: t.planStepsImplemented,\r\n automationIds: t.automationIds ?? [],\r\n })),\r\n requiredTests,\r\n workspaceListing: p.workspaceListing,\r\n };\r\n // The files the plan named and the files the changed files import, shown before the first turn (`codegenLoopContext.ts`).\r\n if (context.entries.length > 0) baseContext.contextContents = context.entries;\r\n if (p.deniedPaths.length > 0) baseContext.deniedPaths = p.deniedPaths;\r\n if (protectedTestPaths.length > 0) baseContext.protectedTestPaths = protectedTestPaths.slice(0, MAX_PROTECTED_PATHS_ON_WIRE);\r\n if (p.outOfScope.length > 0) baseContext.outOfScope = p.outOfScope;\r\n\r\n return {\r\n baseContext,\r\n targets: p.targets,\r\n requiredAutomationIds: requiredTests.map((tc) => tc.automationId),\r\n listing: p.workspaceListing,\r\n deniedPaths: p.deniedPaths,\r\n protectedTestPaths,\r\n // The files already shown are evidence for the parse check that the project parses (`syntaxCheck.ts`).\r\n syntaxSeed: context.entries.map((e) => ({ path: e.path, text: e.content })),\r\n };\r\n}\r\n\r\nconst NO_SUMMARY: CodegenLoopSummary = {\r\n turns: 0,\r\n toolCalls: 0,\r\n refused: 0,\r\n stopReason: \"fallback\",\r\n reads: [],\r\n edits: [],\r\n created: [],\r\n statusCounts: {},\r\n syntaxWarnings: 0,\r\n reasoning: [],\r\n};\r\n\r\nfunction perFile(p: CodegenStepParams): Promise<CodegenFileResult[]> {\r\n return runCodegen(\r\n p.gateway,\r\n p.targets,\r\n p.workspaceListing,\r\n p.requiredTests,\r\n p.deniedPaths,\r\n p.judgedByPool,\r\n p.warnings,\r\n p.contextLog,\r\n p.outOfScope,\r\n );\r\n}\r\n\r\nexport async function runCodegenStep(p: CodegenStepParams): Promise<CodegenFileResult[]> {\r\n if (p.mode !== \"loop\") return perFile(p);\r\n\r\n const context = collectLoopContext({ targets: p.targets, listing: p.workspaceListing, deniedPaths: p.deniedPaths, ...(p.readFile ? { readFile: p.readFile } : {}) });\r\n // Same record the one-file path writes, so the run's record and the log say what was in front of the AI. Paths and counts only.\r\n p.contextLog.push(...context.records);\r\n console.log(\r\n JSON.stringify({\r\n event: \"codegen.loop_context\",\r\n files: context.entries.length,\r\n chars: context.entries.reduce((n, e) => n + e.content.length, 0),\r\n paths: context.entries.map((e) => e.path),\r\n existingTests: context.testPaths,\r\n }),\r\n );\r\n try {\r\n const { results, summary } = await runCodegenLoop(buildCodegenLoopArgs(p, context), {\r\n post: (contextData, signal) => postCodegenTurn(p.gateway, contextData, signal),\r\n ...p.deps,\r\n });\r\n p.out.loop = buildCodegenLoopRecord(summary);\r\n // The loop may touch a file the plan did not name. That is allowed (the checks after it still apply), but it is said\r\n // out loud: a reviewer reading the plan should not be surprised by a file it never mentioned.\r\n const planned = new Set(p.targets.map((t) => t.path));\r\n for (const r of results) {\r\n if (!planned.has(r.targetPath)) {\r\n const w = `QuikPilot changed ${r.targetPath}, which the plan did not name.`;\r\n p.warnings.push(w);\r\n console.warn(`QuikPilot codegen warning (not blocking): ${w}`);\r\n }\r\n }\r\n return results;\r\n } catch (err) {\r\n if (err instanceof SafetyRefusalError) throw err;\r\n const failure = err instanceof CodegenLoopFailure ? err : new CodegenLoopFailure(\"internal_error\", undefined, err);\r\n p.out.loop = buildCodegenLoopRecord({\r\n ...(failure.summary ?? NO_SUMMARY),\r\n stopReason: \"fallback\",\r\n fellBack: true,\r\n fallbackReason: failure.reason,\r\n });\r\n const said = failure.detail ? `: ${failure.detail}` : \"\";\r\n const w = `The code-writing loop could not finish (${failure.reason}${said}), so the files were written one at a time instead.`;\r\n p.warnings.push(w);\r\n console.warn(`QuikPilot codegen warning (not blocking): ${w}`);\r\n return perFile(p);\r\n }\r\n}\r\n", "import { readFileSync } from \"node:fs\";\r\nimport { resolve, join } from \"node:path\";\r\nimport type { CodegenFileResult } from \"./codegen\";\r\n\r\n/**\r\n * QUIKTR-1045 \u2014 codegen importing a package the repository doesn't have currently fails safely\r\n * (setup already ran, so the package genuinely isn't installed, and the regression check catches\r\n * the resulting test failure) but with the WRONG diagnosis: it reads as \"the generated logic is\r\n * broken\" when the real problem is a fabricated import. This names that failure correctly instead.\r\n *\r\n * Only a minimal regex import-scanner \u2014 not a real JS/TS parser. Same reasoning\r\n * `regressionCheck.ts` already states for its own hand-rolled JUnit scanner: this package is\r\n * dependency-free on purpose (published outside the monorepo, bundled into a single CLI file with\r\n * no externals \u2014 see build.mjs), so a real parser is off the table, not merely unused.\r\n *\r\n * Explicitly scoped to JS/TS: it only acts when a `package.json` is found. A repo in another\r\n * language has none, `readDeclaredDependencies` returns null, and the check no-ops \u2014 this is what\r\n * keeps it from looking like a general \"detect the repo's language\" mechanism, which it isn't.\r\n */\r\nexport interface DependencyViolation {\r\n file: string;\r\n packages: string[];\r\n}\r\n\r\nexport interface DependencyCheck {\r\n blocked: boolean;\r\n violations: DependencyViolation[];\r\n}\r\n\r\nconst SCANNABLE_EXTENSIONS = [\".ts\", \".tsx\", \".js\", \".jsx\", \".mjs\", \".cjs\", \".mts\", \".cts\"];\r\n\r\n// import ... from \"x\" / import \"x\" / export ... from \"x\" / require(\"x\") / import(\"x\")\r\nconst IMPORT_RE = /(?:\\bimport\\b[^'\"]*?\\bfrom\\s*|\\bimport\\s*\\(\\s*|\\bexport\\b[^'\"]*?\\bfrom\\s*|\\brequire\\s*\\(\\s*|\\bimport\\s+)(['\"])([^'\"]+)\\1/g;\r\n\r\n// Not exhaustive \u2014 same \"minimal, not exhaustive\" treatment regressionCheck.ts's own scanner uses.\r\nconst NODE_BUILTINS = new Set([\r\n \"assert\", \"buffer\", \"child_process\", \"cluster\", \"crypto\", \"dgram\", \"dns\", \"domain\", \"events\",\r\n \"fs\", \"http\", \"http2\", \"https\", \"net\", \"os\", \"path\", \"perf_hooks\", \"process\", \"punycode\",\r\n \"querystring\", \"readline\", \"repl\", \"stream\", \"string_decoder\", \"sys\", \"timers\", \"tls\", \"tty\",\r\n \"url\", \"util\", \"v8\", \"vm\", \"worker_threads\", \"zlib\", \"inspector\", \"async_hooks\",\r\n]);\r\n\r\n// QUIKTR-1063 \u2014 the two path-alias conventions common enough to assume even\r\n// when a repo's tsconfig can't be read or parsed: \"@/...\" (QuikTrack,\r\n// QuikChat, and most of this monorepo's own apps) and \"~/...\". Without this,\r\n// \"@/lib/x\" was parsed as the scoped package \"@/lib\" \u2014 a real package.json\r\n// entry it could never actually match \u2014 and every aliased import in a repo\r\n// using either convention was reported as an invented dependency.\r\n//\r\n// QUIKTR-1068 \u2014 this is now a FLOOR, not the whole answer: `resolveAliasPrefixes`\r\n// below adds whatever a real tsconfig.json/jsconfig.json actually declares in\r\n// `compilerOptions.paths`, for repos using some other convention entirely.\r\n// Always unioned in regardless of what a config says, so a repo with no\r\n// config (or an unparseable one) keeps exactly today's behavior.\r\nconst DEFAULT_ALIAS_PREFIXES = [\"@/\", \"~/\"];\r\n\r\nfunction packageNameFromSpecifier(specifier: string, aliasPrefixes: string[] = DEFAULT_ALIAS_PREFIXES): string | null {\r\n if (specifier.startsWith(\".\") || specifier.startsWith(\"/\")) return null; // relative/absolute\r\n if (specifier.startsWith(\"node:\")) return null; // explicit builtin\r\n if (aliasPrefixes.some((prefix) => specifier.startsWith(prefix))) return null; // path alias\r\n const segments = specifier.split(\"/\");\r\n const name = specifier.startsWith(\"@\") ? segments.slice(0, 2).join(\"/\") : segments[0];\r\n if (NODE_BUILTINS.has(name)) return null;\r\n return name;\r\n}\r\n\r\nfunction scanImports(source: string, aliasPrefixes: string[] = DEFAULT_ALIAS_PREFIXES): string[] {\r\n const found = new Set<string>();\r\n let match: RegExpExecArray | null;\r\n IMPORT_RE.lastIndex = 0;\r\n while ((match = IMPORT_RE.exec(source))) {\r\n const name = packageNameFromSpecifier(match[2], aliasPrefixes);\r\n if (name) found.add(name);\r\n }\r\n return [...found];\r\n}\r\n\r\n/** Pure \u2014 no fs, trivially unit-testable. `declaredDependencies === null` means \"couldn't tell\r\n * what this repo declares\" (no package.json, or unparseable) \u2014 the check no-ops rather than\r\n * blocking on a question it can't actually answer. `aliasPrefixes` defaults to the floor above;\r\n * callers with a real tsconfig read (see `resolveAliasPrefixes`) pass the fuller list. */\r\nexport function checkImportDependencies(\r\n results: CodegenFileResult[],\r\n declaredDependencies: Set<string> | null,\r\n aliasPrefixes: string[] = DEFAULT_ALIAS_PREFIXES,\r\n): DependencyCheck {\r\n if (!declaredDependencies) return { blocked: false, violations: [] };\r\n\r\n const violations: DependencyViolation[] = [];\r\n for (const { targetPath, newContent } of results) {\r\n if (!SCANNABLE_EXTENSIONS.some((ext) => targetPath.endsWith(ext))) continue;\r\n const invented = scanImports(newContent, aliasPrefixes).filter((pkg) => !declaredDependencies.has(pkg));\r\n if (invented.length > 0) violations.push({ file: targetPath, packages: invented });\r\n }\r\n return { blocked: violations.length > 0, violations };\r\n}\r\n\r\ninterface PackageJson {\r\n dependencies?: Record<string, string>;\r\n devDependencies?: Record<string, string>;\r\n peerDependencies?: Record<string, string>;\r\n}\r\n\r\nfunction dependencyNames(pkg: PackageJson): Set<string> {\r\n // devDependencies included deliberately \u2014 a generated test file may legitimately import one.\r\n return new Set([\r\n ...Object.keys(pkg.dependencies ?? {}),\r\n ...Object.keys(pkg.devDependencies ?? {}),\r\n ...Object.keys(pkg.peerDependencies ?? {}),\r\n ]);\r\n}\r\n\r\n/**\r\n * Reads the target repo's declared dependencies. Checks `results` FIRST for a generated\r\n * `package.json` \u2014 codegen may have legitimately added the very dependency it's about to import,\r\n * and reading the pre-generation file on disk would false-flag that. Falls back to the on-disk\r\n * file, and to `null` (\u2192 the check no-ops) when neither exists or parses.\r\n */\r\nexport function readDeclaredDependencies(\r\n results: CodegenFileResult[],\r\n workspaceRoot: string | null,\r\n): Set<string> | null {\r\n const packageJsonPath = join(resolve(workspaceRoot ?? \".\"), \"package.json\");\r\n const generated = results.find((r) => resolve(r.targetPath) === packageJsonPath);\r\n\r\n let raw: string | null;\r\n if (generated) {\r\n raw = generated.newContent;\r\n } else {\r\n try {\r\n raw = readFileSync(packageJsonPath, \"utf8\");\r\n } catch {\r\n raw = null;\r\n }\r\n }\r\n if (raw === null) return null;\r\n\r\n try {\r\n return dependencyNames(JSON.parse(raw) as PackageJson);\r\n } catch {\r\n return null;\r\n }\r\n}\r\n\r\n/**\r\n * QUIKTR-1068 \u2014 strips line and block comments plus trailing commas from a JSON(C) string, best\r\n * effort. Not a real JSONC parser: a character scanner rather than a regex replace (a regex would\r\n * corrupt a string VALUE containing `//`, e.g. a URL), but anything it can't cleanly handle just\r\n * fails `JSON.parse` afterward \u2014 `resolveAliasPrefixes` below treats that the same as no config at\r\n * all and falls back to the floor. Never throws itself.\r\n */\r\nfunction stripJsonComments(text: string): string {\r\n let out = \"\";\r\n let inString = false;\r\n let inLineComment = false;\r\n let inBlockComment = false;\r\n for (let i = 0; i < text.length; i++) {\r\n const c = text[i];\r\n const next = text[i + 1];\r\n if (inLineComment) {\r\n if (c === \"\\n\") {\r\n inLineComment = false;\r\n out += c;\r\n }\r\n continue;\r\n }\r\n if (inBlockComment) {\r\n if (c === \"*\" && next === \"/\") {\r\n inBlockComment = false;\r\n i++;\r\n }\r\n continue;\r\n }\r\n if (inString) {\r\n out += c;\r\n if (c === \"\\\\\") {\r\n out += next;\r\n i++;\r\n continue;\r\n }\r\n if (c === '\"') inString = false;\r\n continue;\r\n }\r\n if (c === '\"') {\r\n inString = true;\r\n out += c;\r\n continue;\r\n }\r\n if (c === \"/\" && next === \"/\") {\r\n inLineComment = true;\r\n i++;\r\n continue;\r\n }\r\n if (c === \"/\" && next === \"*\") {\r\n inBlockComment = true;\r\n i++;\r\n continue;\r\n }\r\n out += c;\r\n }\r\n return out.replace(/,(\\s*[}\\]])/g, \"$1\");\r\n}\r\n\r\ninterface TsOrJsConfig {\r\n compilerOptions?: { paths?: Record<string, unknown> };\r\n}\r\n\r\n/**\r\n * QUIKTR-1068 \u2014 `DEFAULT_ALIAS_PREFIXES` is a floor, not the whole answer: a repo may declare its\r\n * own alias conventions in `compilerOptions.paths`. Tries `tsconfig.json` then `jsconfig.json` at\r\n * the workspace root (same results-first-then-disk precedence as `readDeclaredDependencies` \u2014 a\r\n * generated config this run legitimately wrote should win over a stale on-disk one), unions any\r\n * `paths` keys (wildcard stripped: `\"@/*\"` \u2192 `\"@/\"`) with the floor, and dedupes. Never throws and\r\n * never returns fewer than the floor \u2014 an unreadable or malformed config is exactly the same as no\r\n * config, not a reason to block a run that could otherwise pass.\r\n *\r\n * Does NOT follow `extends` \u2014 only the root config's own `paths`, same \"minimal, not exhaustive\"\r\n * boundary this file already draws elsewhere (see the module docblock).\r\n */\r\nexport function resolveAliasPrefixes(\r\n results: CodegenFileResult[],\r\n workspaceRoot: string | null,\r\n): string[] {\r\n const root = resolve(workspaceRoot ?? \".\");\r\n\r\n for (const filename of [\"tsconfig.json\", \"jsconfig.json\"]) {\r\n const configPath = join(root, filename);\r\n const generated = results.find((r) => resolve(r.targetPath) === configPath);\r\n\r\n let raw: string | null;\r\n if (generated) {\r\n raw = generated.newContent;\r\n } else {\r\n try {\r\n raw = readFileSync(configPath, \"utf8\");\r\n } catch {\r\n raw = null;\r\n }\r\n }\r\n if (raw === null) continue;\r\n\r\n try {\r\n const parsed = JSON.parse(stripJsonComments(raw)) as TsOrJsConfig;\r\n const paths = parsed.compilerOptions?.paths;\r\n const fromConfig =\r\n paths && typeof paths === \"object\"\r\n ? Object.keys(paths).map((k) => (k.endsWith(\"*\") ? k.slice(0, -1) : k))\r\n : [];\r\n return [...new Set([...DEFAULT_ALIAS_PREFIXES, ...fromConfig])];\r\n } catch {\r\n continue; // malformed \u2014 try the next config file, or fall through to the floor\r\n }\r\n }\r\n\r\n return DEFAULT_ALIAS_PREFIXES;\r\n}\r\n\r\n/** Regressions and new failures named separately elsewhere in this package for the same reason\r\n * this exists at all: conflating diagnoses wastes someone's morning. */\r\nexport function describeDependencyViolations(check: DependencyCheck): string {\r\n return check.violations\r\n .map((v) => `${v.file} imports ${v.packages.join(\", \")}, not a dependency of this repository`)\r\n .join(\"; \");\r\n}\r\n", "import { addAll, diffCachedNamesMatching } from \"./git\";\r\n\r\n/** Stages everything, then refuses to proceed if any staged file matches a denied-path glob.\r\n * Public and inspectable on purpose (Suyash, 2026-09-10): moving this into a published package\r\n * doesn't hide the enforcement \u2014 it's the same check, just no longer duplicated per customer repo. */\r\nexport function checkGuardrail(deniedPaths: string[]): void {\r\n addAll();\r\n const violations = deniedPaths.flatMap((pattern) => diffCachedNamesMatching(pattern));\r\n if (violations.length > 0) {\r\n throw new Error(`QuikPilot touched denied paths:\\n${violations.join(\"\\n\")}`);\r\n }\r\n}\r\n", "import { describeQuikTrackFailure } from \"./quiktrackError\";\r\n\r\ninterface InstallationTokenResponse {\r\n success: boolean;\r\n data: { token: string; expiresAt: string };\r\n}\r\n\r\n/** Exchange the QuikPilot run token for a repo-scoped GitHub installation token (QUIKTR-804) \u2014\r\n * mirrors `tokenExchange.ts`'s `exchangeForRunToken` shape: bearer auth, `{success,data}`\r\n * envelope, same error-message style. */\r\nexport async function exchangeForInstallationToken(\r\n installationTokenUrl: string,\r\n runToken: string,\r\n): Promise<string> {\r\n const res = await fetch(installationTokenUrl, {\r\n method: \"POST\",\r\n headers: { Authorization: `Bearer ${runToken}` },\r\n });\r\n if (!res.ok) {\r\n throw new Error(`Exchange installation token failed: ${await describeQuikTrackFailure(res)}`);\r\n }\r\n const body = (await res.json()) as InstallationTokenResponse;\r\n if (body.success !== true) {\r\n throw new Error(\"Exchange installation token failed: response did not carry success:true\");\r\n }\r\n return body.data.token;\r\n}\r\n", "import { required } from \"./env\";\r\n\r\n/** Must equal `apps/quiktrack/lib/services/github/oidc.ts`'s own copy of this literal \u2014 that app\r\n * verifies the token this package requests. Duplicated because this package is published outside\r\n * the monorepo and cannot import from the app; same reasoning `packet.ts`'s header gives for\r\n * duplicating `PilotPacket`'s shape. */\r\nconst QUIKPILOT_OIDC_AUDIENCE = \"quiktrack-quikpilot\";\r\n\r\ninterface OidcTokenResponse {\r\n value: string;\r\n}\r\n\r\n/** Request a GitHub Actions OIDC ID token \u2014 the runner's proof of identity, exchanged at\r\n * `TOKEN_URL` for a QuikPilot run token (QUIKTR-805). `ACTIONS_ID_TOKEN_REQUEST_URL` and\r\n * `ACTIONS_ID_TOKEN_REQUEST_TOKEN` are ambient GitHub Actions env vars, present only because the\r\n * generated workflow declares `permissions: id-token: write` \u2014 no dispatch input carries them. */\r\nexport async function fetchGithubOidcToken(\r\n env: NodeJS.ProcessEnv = process.env,\r\n): Promise<string> {\r\n const requestUrl = required(\r\n \"ACTIONS_ID_TOKEN_REQUEST_URL\",\r\n env.ACTIONS_ID_TOKEN_REQUEST_URL,\r\n );\r\n const requestToken = required(\r\n \"ACTIONS_ID_TOKEN_REQUEST_TOKEN\",\r\n env.ACTIONS_ID_TOKEN_REQUEST_TOKEN,\r\n );\r\n const separator = requestUrl.includes(\"?\") ? \"&\" : \"?\";\r\n const url = `${requestUrl}${separator}audience=${encodeURIComponent(QUIKPILOT_OIDC_AUDIENCE)}`;\r\n const res = await fetch(url, {\r\n headers: { Authorization: `Bearer ${requestToken}` },\r\n });\r\n if (!res.ok) {\r\n throw new Error(`Fetch GitHub OIDC token failed: ${res.status} ${res.statusText}`);\r\n }\r\n const body = (await res.json()) as OidcTokenResponse;\r\n if (!body.value) {\r\n throw new Error(\"GitHub OIDC token response carried no value\");\r\n }\r\n return body.value;\r\n}\r\n", "import { describeQuikTrackFailure } from \"./quiktrackError\";\r\n\r\n/** Mirrors `apps/quiktrack/lib/services/pilot/packet.ts`'s `PilotPacket` shape. Duplicated rather\r\n * than imported \u2014 this package is published outside the monorepo and cannot depend on the app. */\r\nexport interface PilotPacket {\r\n runId: string;\r\n issueKey: string | null;\r\n /** QUIKTR-1067 \u2014 same nullability as issueKey, for the same reason: the commit message needs\r\n * both to say what actually changed instead of the hardcoded \"Phase 0 skeleton\" placeholder. */\r\n issueTitle: string | null;\r\n branch: string | null;\r\n targetBranch: string | null;\r\n /** QUIKTR-1033 \u2014 the subtree targeting (QUIKTR-1035) lists files under. Null means the\r\n * repository root, as null \u2014 never normalised to \".\". */\r\n workspaceRoot: string | null;\r\n commands: {\r\n setup: string | null;\r\n test: string | null;\r\n e2e: string | null;\r\n lint: string | null;\r\n /** QUIKTR-1045 \u2014 run after codegen flushes, before lint. Soft failure. */\r\n format: string | null;\r\n /** QUIKTR-1402 \u2014 runs ONE test file (path appended, or substituted for `{file}`) against the untouched\r\n * code, for the baseline check. Optional: an older QuikTrack omits it. Null/absent turns the check off. */\r\n testFile?: string | null;\r\n };\r\n guardrails: {\r\n deniedPaths: string[];\r\n maxHealIterations: number;\r\n maxWallClockMinutes: number;\r\n // No maxRunUsd \u2014 it travels as a claim on gateway.token instead (QUIKTR-823).\r\n };\r\n /** Where to call for AI codegen, and the credential that authorizes it. */\r\n gateway: {\r\n baseUrl: string;\r\n token: string;\r\n };\r\n /** The pilot.design technical design, as context for codegen. No file paths \u2014 see the app's\r\n * spec-contract.ts. Null only in theory (dispatch requires a design to already exist). */\r\n design: {\r\n rootCause: string;\r\n approach: string;\r\n /** Mirrors `apps/quiktrack/lib/services/pilot/spec-contract.ts`'s `PilotApiChange`. */\r\n apiChanges: { surface: string; change: string; reason: string }[];\r\n riskLevel: \"LOW\" | \"MEDIUM\" | \"HIGH\";\r\n riskRationale: string;\r\n } | null;\r\n quikTest: { testRunId: string; resultsUrl: string } | null;\r\n /** QUIKTR-1065 \u2014 the approved test cases codegen still owes real test code for. Sent to\r\n * pilot.targeting so it can propose a test-file target naming which cases it covers; today\r\n * nothing reads this field yet (the AI Runtime side isn't built), so it always arrives as `[]`\r\n * or is silently unused once wired up here. */\r\n requiredTests: {\r\n automationId: string;\r\n title: string;\r\n covers: string[];\r\n given: string | null;\r\n when: string | null;\r\n then: string | null;\r\n }[];\r\n /** QUIKTR-1402 \u2014 automationId -> the case's current type (FUNCTIONAL, NEGATIVE, REGRESSION, \u2026), only for\r\n * cases whose AI-assigned label QuikTrack recorded. Optional: an older QuikTrack omits it. A case that is\r\n * absent here is UNKNOWN and is never checked; REGRESSION is exempt. DELIBERATELY not a field of\r\n * `requiredTests`: those objects are forwarded to the AI Runtime as-is, and an unknown key on the\r\n * versioned path is refused CONTRACT_REJECTED. Nothing in this map may ever be sent to the runtime. */\r\n requiredTestTypes?: Record<string, string>;\r\n /** QUIKTR-1401 \u2014 the reviewer's approved \"things QuikPilot must not change\" list. Optional: a\r\n * QuikTrack that predates the field omits it. Forwarded to pilot.targeting and pilot.codegen (\u00A720,\r\n * deployed by the AI Runtime 2026-10-01) when non-empty, never to pilot.design. Free text, so unlike\r\n * `deniedPaths` it can only be told to the model, not checked. */\r\n outOfScope?: string[];\r\n /** QUIKTR-1315, \u00A719 of the AI Runtime contract (AGREED, final tagged shape) \u2014 the repo-relative\r\n * files the last DONE run's own ingested JUnit report named, sourced from stored QuikTest data,\r\n * not a live baseline capture here. Always present (never undefined) \u2014 \u00A719.12: a project with no\r\n * prior DONE run's report is `{ report: \"ABSENT\" }`, not an omitted field. `{ report: \"PRESENT\" }`\r\n * with an empty `discoveredTestFiles` is a different, real fact: a report was ingested but\r\n * nothing in it was path-shaped. See targeting.ts for how this is forwarded. */\r\n testDiscovery:\r\n | { report: \"PRESENT\"; discoveredTestFiles: string[]; unmappedEntries: number }\r\n | { report: \"ABSENT\" };\r\n}\r\n\r\ninterface PacketResponse {\r\n success: boolean;\r\n data: PilotPacket;\r\n}\r\n\r\n/** GET the run's work packet. Bearer auth via the run token, matching the header curl sent on\r\n * stdin (`--config -`) so it never showed up in `ps` \u2014 an HTTP client's header option is already\r\n * invisible to `ps`, so no equivalent trick is needed here. */\r\nexport async function fetchPacket(\r\n packetUrl: string,\r\n runToken: string,\r\n githubRunId: string,\r\n): Promise<PilotPacket> {\r\n const url = `${packetUrl}?githubRunId=${encodeURIComponent(githubRunId)}`;\r\n const res = await fetch(url, {\r\n headers: { Authorization: `Bearer ${runToken}` },\r\n });\r\n if (!res.ok) {\r\n throw new Error(`Fetch work packet failed: ${await describeQuikTrackFailure(res)}`);\r\n }\r\n const body = (await res.json()) as PacketResponse;\r\n if (body.success !== true) {\r\n throw new Error(\"Fetch work packet failed: response did not carry success:true\");\r\n }\r\n return body.data;\r\n}\r\n", "import { appendFileSync, mkdirSync } from \"node:fs\";\r\n\r\n/** Phase 0 has no agent. This proves the loop end to end without touching real source, which would\r\n * risk breaking the build for a reason nobody would connect back to QuikPilot. Verbatim carry-over\r\n * from the inlined workflow \u2014 real codegen is separate, not-yet-built work. */\r\nexport function writePhase0Marker(runId: string): void {\r\n mkdirSync(\".quikpilot\", { recursive: true });\r\n appendFileSync(\".quikpilot/phase0-marker.txt\", `QuikPilot Phase 0 skeleton marker for run ${runId}\\n`);\r\n}\r\n", "import { readFileSync, readdirSync, rmSync, statSync } from \"node:fs\";\r\nimport { join } from \"node:path\";\r\n\r\nconst SKIP_DIRS = new Set([\"node_modules\", \".git\"]);\r\n\r\nfunction walkForJUnitByName(dir: string): string | null {\r\n let entries: string[];\r\n try {\r\n entries = readdirSync(dir);\r\n } catch {\r\n return null;\r\n }\r\n for (const entry of entries) {\r\n if (SKIP_DIRS.has(entry)) continue;\r\n const full = join(dir, entry);\r\n let stat;\r\n try {\r\n stat = statSync(full);\r\n } catch {\r\n continue;\r\n }\r\n if (stat.isDirectory()) {\r\n const found = walkForJUnitByName(full);\r\n if (found) return found;\r\n } else if (/^junit.*\\.xml$/.test(entry)) {\r\n return full;\r\n }\r\n }\r\n return null;\r\n}\r\n\r\nfunction firstXmlIn(dir: string, namePattern: RegExp): string | null {\r\n let entries: string[];\r\n try {\r\n entries = readdirSync(dir);\r\n } catch {\r\n return null;\r\n }\r\n const match = entries.find((e) => namePattern.test(e));\r\n return match ? join(dir, match) : null;\r\n}\r\n\r\n/** The test report as bytes, or null when there is none or it cannot be read. QUIKTR-1447 takes a copy for a failed\r\n * run BEFORE `reportToQuikTest` sends and deletes it. */\r\nexport function readTestReportBytes(cwd = process.cwd()): Buffer | null {\r\n try {\r\n const report = findJUnitReport(cwd);\r\n return report ? readFileSync(report) : null;\r\n } catch {\r\n return null;\r\n }\r\n}\r\n\r\n/** QtPilotConfig has no column for the report path, so this is a convention over a short list of\r\n * common locations rather than a configurable setting. A project that writes its report elsewhere\r\n * reports nothing and finds out from the log \u2014 a missing artefact must not fail the run. Checked\r\n * in the same priority the original `find` clause listed them, though exact traversal order was\r\n * never guaranteed there either. */\r\nexport function findJUnitReport(cwd = process.cwd()): string | null {\r\n return (\r\n walkForJUnitByName(cwd) ??\r\n firstXmlIn(join(cwd, \"test-results\"), /\\.xml$/) ??\r\n firstXmlIn(join(cwd, \"reports\"), /^junit.*\\.xml$/) ??\r\n firstXmlIn(join(cwd, \"target\", \"surefire-reports\"), /\\.xml$/)\r\n );\r\n}\r\n\r\nfunction buildCiUrl(serverUrl: string, repository: string, githubRunId: string): string {\r\n return `${serverUrl}/${repository}/actions/runs/${githubRunId}`;\r\n}\r\n\r\n/** The ingest route's summary of automationIds present in the JUnit report that matched no\r\n * `QtTestCase` \u2014 computed and returned by QuikTrack's own ingest today (`IngestSummary.unmatched`\r\n * in `apps/quiktrack/lib/services/testIngest.ts`), but silently discarded here until QUIKTR-1374:\r\n * a bracket/format mismatch (or any other ingest failure) produced zero matches on every run with\r\n * nothing on screen to say why. */\r\nexport interface ReportToQuikTestResult {\r\n unmatched: Array<{ automationId: string; count: number }>;\r\n}\r\n\r\n/** One warning naming every unmatched id and its count \u2014 `null` when there's nothing to report,\r\n * so the caller can push straight into `warnings` without an extra length check. */\r\nexport function describeUnmatchedAutomationIds(unmatched: ReportToQuikTestResult[\"unmatched\"]): string | null {\r\n if (unmatched.length === 0) return null;\r\n const named = unmatched.map((u) => `${u.automationId} (\u00D7${u.count})`).join(\", \");\r\n return `${unmatched.length} generated test result(s) did not match any test case: ${named} \u2014 check the automationId format.`;\r\n}\r\n\r\n/** Best-effort \u2014 every branch here is designed to never throw, matching the bash step's own\r\n * `if: always()` + internally tolerant logic (null resultsUrl and \"no report found\" are both the\r\n * common path in Phase 0, not edge cases \u2014 D19). Deletes the report after a successful POST so the\r\n * guardrail's `git add -A` never commits a CI artefact into the customer's pull request. Returns\r\n * `null` whenever nothing was actually reported (no results URL, no report found, or the POST\r\n * itself failed) \u2014 the caller folds a non-null `unmatched` array into the run's warnings. */\r\nexport async function reportToQuikTest(params: {\r\n resultsUrl: string | null | undefined;\r\n runToken: string;\r\n githubServerUrl: string;\r\n githubRepository: string;\r\n githubRunId: string;\r\n /** QUIKTR-1333 \u2014 the files QuikPilot actually generated or edited this run. Scopes QuikTrack's\r\n * unmatched-automationId warning to just these, so a repository's own pre-existing tests (which\r\n * can never carry a QuikPilot id) stop being reported as unmatched on every single run.\r\n * `undefined` = no scoping information (the server keeps its unfiltered behavior). An EMPTY\r\n * array is a real answer \u2014 codegen produced nothing (it failed, or there was no target) \u2014 and is\r\n * sent as an empty parameter so the server scopes to nothing instead of falling back. */\r\n generatedFiles?: string[];\r\n cwd?: string;\r\n}): Promise<ReportToQuikTestResult | null> {\r\n const { resultsUrl, runToken, githubServerUrl, githubRepository, githubRunId, generatedFiles, cwd } = params;\r\n if (!resultsUrl) {\r\n console.log(\"packet.quikTest is null \u2014 this run has no QuikTest run to report into.\");\r\n return null;\r\n }\r\n const report = findJUnitReport(cwd);\r\n if (!report) {\r\n console.warn(\"::warning::QuikPilot found no JUnit report \u2014 no results reported to QuikTest.\");\r\n return null;\r\n }\r\n try {\r\n console.log(`reporting ${report}`);\r\n const ciUrl = buildCiUrl(githubServerUrl, githubRepository, githubRunId);\r\n const { readFileSync } = await import(\"node:fs\");\r\n const body = readFileSync(report);\r\n // QUIKTR-1082 \u2014 this runner is the only caller QuikPilot controls; requesting \"bracket\"\r\n // explicitly here changes nothing for any other QuikTest customer's own ingestion.\r\n let url = `${resultsUrl}?ciUrl=${encodeURIComponent(ciUrl)}&automationIdFormat=bracket`;\r\n // QUIKTR-1333 \u2014 optional: an old runner or a human's manual upload (the sibling route) never\r\n // sends this, and the server falls back to today's unfiltered behavior either way. Sent even\r\n // when empty: \"generated nothing\" must not be mistaken for \"no information\".\r\n if (generatedFiles) {\r\n url += `&generatedFiles=${encodeURIComponent(generatedFiles.join(\",\"))}`;\r\n }\r\n const res = await fetch(url, {\r\n method: \"POST\",\r\n headers: { Authorization: `Bearer ${runToken}`, \"Content-Type\": \"text/xml\" },\r\n body,\r\n });\r\n if (!res.ok) {\r\n throw new Error(`QuikTest report POST failed: ${res.status} ${res.statusText}`);\r\n }\r\n rmSync(report, { force: true });\r\n // QUIKTR-1374 \u2014 read the ingest summary instead of discarding it. Best-effort: the POST\r\n // itself already succeeded (res.ok), so a body that isn't the expected JSON shape must never\r\n // turn a working report into a failure \u2014 it just means no warning can be derived from it.\r\n let unmatched: ReportToQuikTestResult[\"unmatched\"] = [];\r\n try {\r\n const json = (await res.json()) as { data?: { unmatched?: ReportToQuikTestResult[\"unmatched\"] } };\r\n unmatched = json.data?.unmatched ?? [];\r\n } catch {\r\n // Not JSON, or not the expected shape \u2014 leave unmatched empty.\r\n }\r\n return { unmatched };\r\n } catch (err) {\r\n console.warn(`::warning::QuikPilot failed to report results to QuikTest: ${err instanceof Error ? err.message : String(err)}`);\r\n return null;\r\n }\r\n}\r\n", "import { execFileSync } from \"node:child_process\";\r\nimport { existsSync, mkdirSync, readFileSync, rmSync, rmdirSync, statSync, writeFileSync } from \"node:fs\";\r\nimport { dirname, isAbsolute, relative, resolve } from \"node:path\";\r\nimport type { CodegenFileResult } from \"./codegen\";\r\nimport { runCommandWithTimeout, type TimedRunOutcome } from \"./commands\";\r\nimport { findJUnitReport } from \"./quiktest\";\r\nimport { readAutomationIdResults } from \"./regressionCheck\";\r\nimport type { PilotTarget } from \"./targeting\";\r\n\r\n/**\r\n * QUIKTR-1402 \u2014 the baseline check.\r\n *\r\n * A spec can contain a case that asserts something ALREADY TRUE before any change (\"the server route\r\n * remains unchanged\"); no test can satisfy it, and a phrase list cannot catch the next phrasing. What every\r\n * such case shares is not wording but behaviour: its generated test PASSES on the unmodified code. So,\r\n * after codegen and before anything is written for real, this writes ONLY the generated test files, runs\r\n * each one alone against the untouched code, flags a non-Regression case whose test passed, and puts\r\n * everything back. A Regression case is meant to pass there, so it is exempt.\r\n *\r\n * It FLAGS and never blocks: a no-op change is legitimate, and an unsatisfiable case is a spec problem a\r\n * person should see rather than a run that dies. Every uncertain outcome therefore means \"no flag\", and\r\n * every one of them is said out loud (a silent timeout would look exactly like a check that found nothing).\r\n *\r\n * Unknown is never flagged: only a case whose label QuikTrack recorded (`requiredTestTypes`) is checked,\r\n * so anything approved before the label was kept, and any label we did not recognise, is left alone.\r\n */\r\n\r\n/**\r\n * How long one single-file run may take before it is stopped. A constant, not a setting (Suyash): one more\r\n * knob is one more thing to get wrong, and nobody has the information to tune it. Measured on QuikTrack and\r\n * QuikChat, one file takes 2 to 5 seconds warm and up to ~14 seconds on a cold start; two minutes is far\r\n * outside that and only ever reached by a command that hangs, which produces no error and would otherwise\r\n * hold the run until the job's own limit while looking like QuikPilot being slow.\r\n */\r\nexport const BASELINE_CHECK_TIMEOUT_MS = 120_000;\r\n\r\nexport interface BaselineFindings {\r\n /** ALREADY_TRUE: the change altered the code but the case still passed before it. NO_OP: every file the\r\n * change edited came out unchanged. The check cannot tell the two apart for certain; the wording hedges. */\r\n cause: \"ALREADY_TRUE\" | \"NO_OP\";\r\n /** Case ids only \u2014 QuikTrack looks the titles up itself, so case text never travels. */\r\n automationIds: string[];\r\n}\r\n\r\nexport interface BaselineCheckResult {\r\n findings: BaselineFindings | null;\r\n /** Run-record sentences: a finding, or a reason the check could not give an answer. */\r\n warnings: string[];\r\n}\r\n\r\nexport interface BaselineCheckParams {\r\n targets: PilotTarget[];\r\n results: CodegenFileResult[];\r\n testFileCmd: string | null | undefined;\r\n /** automationId -> the case's current type, only for cases whose label is known. */\r\n requiredTestTypes: Record<string, string> | undefined;\r\n cwd?: string;\r\n /** Test seam: the real one spawns bash with a hard time limit. */\r\n runFile?: (command: string, timeoutMs: number) => Promise<TimedRunOutcome>;\r\n}\r\n\r\n/** POSIX single-quoting: the path is chosen by the model, so it must never be able to inject a command. */\r\nexport function shellQuote(value: string): string {\r\n return `'${value.split(\"'\").join(\"'\\\\''\")}'`;\r\n}\r\n\r\n/** `{file}` is replaced wherever it appears; with no placeholder the path is appended as the last argument. */\r\nexport function buildSingleFileCommand(command: string, path: string): string {\r\n const quoted = shellQuote(path);\r\n return command.includes(\"{file}\") ? command.split(\"{file}\").join(quoted) : `${command} ${quoted}`;\r\n}\r\n\r\nconst isTestTarget = (t: PilotTarget): boolean => (t.automationIds?.length ?? 0) > 0;\r\n\r\n/** A case is checked only if its label is KNOWN and is not Regression (which is supposed to pass). */\r\nfunction checkableIds(ids: string[], types: Record<string, string> | undefined): string[] {\r\n if (!types) return [];\r\n return ids.filter((id) => {\r\n if (!Object.prototype.hasOwnProperty.call(types, id)) return false;\r\n const type = types[id];\r\n return typeof type === \"string\" && type.trim() !== \"\" && type.trim().toUpperCase() !== \"REGRESSION\";\r\n });\r\n}\r\n\r\n/** Absolute path inside the checkout, or null when the target would land outside it. */\r\nfunction insideCheckout(cwd: string, path: string): string | null {\r\n const abs = resolve(cwd, path);\r\n const rel = relative(cwd, abs);\r\n return rel === \"\" || rel.startsWith(\"..\") || isAbsolute(rel) ? null : abs;\r\n}\r\n\r\ninterface WrittenFile {\r\n abs: string;\r\n /** null when the file did not exist before. */\r\n original: Buffer | null;\r\n /** Directories this check had to create, outermost first. */\r\n createdDirs: string[];\r\n}\r\n\r\nfunction writeForCheck(abs: string, content: string): WrittenFile {\r\n const original = existsSync(abs) ? readFileSync(abs) : null;\r\n const createdDirs: string[] = [];\r\n if (original === null) {\r\n const missing: string[] = [];\r\n for (let d = dirname(abs); !existsSync(d); d = dirname(d)) missing.push(d);\r\n for (const d of missing.reverse()) {\r\n mkdirSync(d);\r\n createdDirs.push(d);\r\n }\r\n }\r\n writeFileSync(abs, content);\r\n return { abs, original, createdDirs };\r\n}\r\n\r\nfunction restore(written: WrittenFile[]): void {\r\n for (const file of [...written].reverse()) {\r\n try {\r\n if (file.original !== null) writeFileSync(file.abs, file.original);\r\n else rmSync(file.abs, { force: true });\r\n for (const d of [...file.createdDirs].reverse()) {\r\n try {\r\n rmdirSync(d);\r\n } catch {\r\n // not empty or already gone \u2014 leave it\r\n }\r\n }\r\n } catch (err) {\r\n console.error(`Baseline check could not restore ${file.abs}: ${err instanceof Error ? err.message : String(err)}`);\r\n }\r\n }\r\n}\r\n\r\n/** Untracked, non-ignored files \u2014 exactly what the guardrail's `git add -A` would commit. `null` when git\r\n * cannot say, in which case nothing is cleaned up rather than guessing. */\r\nfunction untrackedFiles(cwd: string): Set<string> | null {\r\n try {\r\n const out = execFileSync(\"git\", [\"ls-files\", \"--others\", \"--exclude-standard\", \"-z\"], {\r\n cwd,\r\n encoding: \"utf8\",\r\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\r\n maxBuffer: 64 * 1024 * 1024,\r\n });\r\n return new Set(out.split(\"\\0\").filter(Boolean));\r\n } catch {\r\n return null;\r\n }\r\n}\r\n\r\nconst mtimeOf = (path: string): number | null => {\r\n try {\r\n return statSync(path).mtimeMs;\r\n } catch {\r\n return null;\r\n }\r\n};\r\n\r\n/** NO_OP only when there is code to compare and every file the change edits came out exactly as it was. */\r\nfunction decideCause(targets: PilotTarget[], results: Map<string, string>, cwd: string): BaselineFindings[\"cause\"] {\r\n const codeTargets = targets.filter((t) => !isTestTarget(t));\r\n if (codeTargets.length === 0) return \"ALREADY_TRUE\";\r\n for (const t of codeTargets) {\r\n if (t.kind === \"NEW_FILE\") return \"ALREADY_TRUE\";\r\n const next = results.get(t.path);\r\n const abs = insideCheckout(cwd, t.path);\r\n if (next === undefined || abs === null) return \"ALREADY_TRUE\";\r\n try {\r\n if (readFileSync(abs, \"utf8\") !== next) return \"ALREADY_TRUE\";\r\n } catch {\r\n return \"ALREADY_TRUE\";\r\n }\r\n }\r\n return \"NO_OP\";\r\n}\r\n\r\nexport async function runBaselineCheck(params: BaselineCheckParams): Promise<BaselineCheckResult> {\r\n const { targets, results, testFileCmd, requiredTestTypes } = params;\r\n const cwd = params.cwd ?? process.cwd();\r\n const runFile = params.runFile ?? runCommandWithTimeout;\r\n const nothing: BaselineCheckResult = { findings: null, warnings: [] };\r\n\r\n if (!testFileCmd || testFileCmd.trim() === \"\") return nothing;\r\n const testTargets = targets.filter(isTestTarget);\r\n const toCheck = testTargets\r\n .map((target) => ({ target, ids: checkableIds(target.automationIds ?? [], requiredTestTypes) }))\r\n .filter((entry) => entry.ids.length > 0);\r\n if (toCheck.length === 0) {\r\n console.log(\"Baseline check: no case with a known, non-Regression label \u2014 nothing to check.\");\r\n return nothing;\r\n }\r\n\r\n const warnings: string[] = [];\r\n const flagged: string[] = [];\r\n const written: WrittenFile[] = [];\r\n const unsafe = new Set<string>();\r\n const skip = (path: string, why: string) => {\r\n const message = `Baseline check skipped for ${path}: ${why}`;\r\n console.warn(`::warning::${message}`);\r\n warnings.push(message);\r\n };\r\n\r\n try {\r\n const contentByPath = new Map(results.map((r) => [r.targetPath, r.newContent]));\r\n const cause = decideCause(targets, contentByPath, cwd);\r\n\r\n // Only the generated TEST files are written; the code under test stays exactly as it is.\r\n for (const target of testTargets) {\r\n const content = contentByPath.get(target.path);\r\n if (content === undefined) continue;\r\n const abs = insideCheckout(cwd, target.path);\r\n if (abs === null) {\r\n unsafe.add(target.path);\r\n continue;\r\n }\r\n written.push(writeForCheck(abs, content));\r\n }\r\n\r\n for (const { target, ids } of toCheck) {\r\n if (unsafe.has(target.path)) {\r\n skip(target.path, \"the path is outside the checkout, so the file was not written or run.\");\r\n continue;\r\n }\r\n if (!contentByPath.has(target.path)) continue;\r\n\r\n const reportBefore = findJUnitReport(cwd);\r\n const mtimeBefore = reportBefore ? mtimeOf(reportBefore) : null;\r\n const untrackedBefore = untrackedFiles(cwd);\r\n\r\n const outcome = await runFile(buildSingleFileCommand(testFileCmd, target.path), BASELINE_CHECK_TIMEOUT_MS);\r\n\r\n if (outcome === \"timeout\") {\r\n skip(\r\n target.path,\r\n `the single-file command did not finish within ${BASELINE_CHECK_TIMEOUT_MS / 1000} seconds and was stopped. ` +\r\n \"No test case from this file was flagged.\",\r\n );\r\n } else if (outcome === \"error\") {\r\n skip(target.path, \"the single-file command could not be started. No test case from this file was flagged.\");\r\n } else {\r\n const reportAfter = findJUnitReport(cwd);\r\n const fresh = reportAfter !== null && (reportAfter !== reportBefore || mtimeOf(reportAfter) !== mtimeBefore);\r\n if (!fresh) {\r\n skip(\r\n target.path,\r\n \"the single-file command wrote no new JUnit report (it must write the same JUnit report as the test \" +\r\n \"command), so nothing could be checked.\",\r\n );\r\n } else {\r\n const byId = readAutomationIdResults(cwd);\r\n for (const id of ids) if (byId?.get(id) === \"pass\") flagged.push(id);\r\n }\r\n }\r\n\r\n // The report has been read; now remove whatever this run left behind that the guardrail would commit\r\n // (a snapshot file written against the OLD behaviour would make the real run fail). Never anything\r\n // that existed before this run.\r\n const untrackedAfter = untrackedFiles(cwd);\r\n if (untrackedBefore && untrackedAfter) {\r\n for (const file of untrackedAfter) {\r\n if (untrackedBefore.has(file)) continue;\r\n const abs = insideCheckout(cwd, file);\r\n if (abs) rmSync(abs, { force: true });\r\n }\r\n }\r\n }\r\n\r\n if (flagged.length === 0) return { findings: null, warnings };\r\n\r\n const automationIds = [...new Set(flagged)].slice(0, 200);\r\n const list = automationIds.join(\", \");\r\n warnings.push(\r\n cause === \"NO_OP\"\r\n ? `Baseline check: ${automationIds.length} test case(s) passed against the unmodified code, and every file the ` +\r\n `generated change edited came out unchanged, so the change itself may have been a no-op: ${list}.`\r\n : `Baseline check: ${automationIds.length} test case(s) passed against the unmodified code, so they may assert ` +\r\n `something already true: ${list}. This check cannot tell that from a change that did nothing.`,\r\n );\r\n return { findings: { cause, automationIds }, warnings };\r\n } catch (err) {\r\n const message = `Baseline check could not run: ${err instanceof Error ? err.message : String(err)}`;\r\n console.warn(`::warning::${message}`);\r\n return { findings: null, warnings: [...warnings, message] };\r\n } finally {\r\n restore(written);\r\n }\r\n}\r\n", "import { readFileSync } from \"node:fs\";\r\nimport { runTestCommand, runTestCommandAsync, type TestOutcome } from \"./commands\";\r\nimport { findJUnitReport } from \"./quiktest\";\r\n\r\n/**\r\n * QUIKTR-1036 \u2014 once codegen writes real code, a failing test after it probably means the\r\n * generated code (or a generated test) is wrong. Blocking unconditionally would break any repo\r\n * with pre-existing failures, so a run captures a \"before\" snapshot (the baseline, run against the\r\n * untouched tree) and an \"after\" snapshot (post-codegen), and diffs them per test:\r\n * passed before, fails now -> regression, block\r\n * absent before, fails now -> new failure, block (codegen writing test files makes this the\r\n * common case, not an edge case \u2014 a different diagnosis from a\r\n * regression, so it's reported separately)\r\n * failed before, fails now -> not ours, stays soft (the case the soft-fail existed for)\r\n *\r\n * Only a minimal <testcase> scanner \u2014 not a full XML parser like\r\n * apps/quiktrack/lib/test/resultParser.ts, which extracts failure messages/stack traces across\r\n * multiple formats for QuikTest's ingest API and can't be imported here anyway (this package is\r\n * published outside the monorepo \u2014 same reason packet.ts duplicates its types instead of sharing\r\n * them). classname::name (or bare name with no classname) is an internal-only identity, used only\r\n * to match a test between two local runs \u2014 it never needs to match QuikTest's own configurable\r\n * automationIdFormat.\r\n */\r\nexport interface TestSnapshot {\r\n outcome: TestOutcome;\r\n /** testId -> passed. null when no JUnit report was found or it couldn't be parsed \u2014 the\r\n * fallback used when either snapshot lacks this is to stay soft, same as today, since blocking\r\n * with no way to name what broke would contradict the whole point of the classification. */\r\n results: Map<string, boolean> | null;\r\n /**\r\n * QUIKTR-1029 self-heal prerequisite 1 (Suyash, 2026-09-22 \u2014 \"buildable now and useful on its\r\n * own: today a regression blocks the push without saying why the test failed\"). testId -> a\r\n * bounded failure message, only for tests that failed IN THIS SNAPSHOT. Deliberately a second,\r\n * optional map rather than widening `results`'s value type: `checkForRegressions`'s diffing\r\n * logic (and every existing test constructing a `TestSnapshot` fixture directly) stays untouched\r\n * \u2014 this is additive context, not a new signal the diff itself reasons about.\r\n */\r\n failureText?: Map<string, string>;\r\n /**\r\n * QUIKTR-1315 \u2014 the file paths the test runner itself discovered, read from each `<testsuite>`'s\r\n * `file` attribute and each `<testcase>`'s `file`/`classname` attributes, verbatim (backslashes\r\n * normalised to forward slashes only). `null` when no report was found \u2014 same \"can't tell, don't\r\n * block\" posture as `results`. An empty (non-null) set means a report existed but carried no\r\n * file-shaped attribution at all \u2014 also treated as \"can't tell\" by `testPlacementCheck.ts`, not as\r\n * \"nothing was discovered.\" Best-effort only: `classname` is a real file path for Vitest and\r\n * derivable for pytest, but not guaranteed for Jest (depends on `jest-junit` config) or Go\r\n * (typically package-, not file-, scoped) \u2014 see `testPlacementCheck.ts`'s own docblock for how\r\n * this is matched loosely rather than exactly for that reason.\r\n */\r\n discoveredFiles?: Set<string> | null;\r\n /**\r\n * QUIKTR-1315 \u2014 every `[<automationId>]` leading-bracket token found in a `<testcase>` name,\r\n * duplicating `apps/quiktrack/lib/test/resultParser.ts`'s `LEADING_BRACKET_RE` convention (this\r\n * package can't import that file \u2014 published outside the monorepo). `null` when no report was\r\n * found, same as `discoveredFiles`.\r\n */\r\n discoveredAutomationIds?: Set<string> | null;\r\n}\r\n\r\nconst TESTCASE_RE = /<testcase\\b([^>]*?)(?:\\/>|>([\\s\\S]*?)<\\/testcase>)/g;\r\nconst NAME_ATTR_RE = /\\bname=\"([^\"]*)\"/;\r\nconst CLASSNAME_ATTR_RE = /\\bclassname=\"([^\"]*)\"/;\r\nconst FAILURE_CHILD_RE = /<failure\\b|<error\\b/;\r\nconst SKIPPED_CHILD_RE = /<skipped\\b/;\r\n\r\n// QUIKTR-1315 \u2014 `<testsuite>` open tags only (not self-closed the way an empty `<testcase/>` can\r\n// be): a suite always wraps at least its own attributes even with zero testcases inside.\r\nconst TESTSUITE_OPEN_RE = /<testsuite\\b([^>]*?)>/g;\r\nconst FILE_ATTR_RE = /\\bfile=\"([^\"]*)\"/;\r\n// QUIKTR-1082/1374's convention, duplicated \u2014 see this file's module docblock and\r\n// `TestSnapshot`'s `discoveredAutomationIds` field for why this can't just import\r\n// resultParser.ts instead. Matches QuikPilot's own token shape (QP-<PROJECT-KEY>-<issue>-<n>)\r\n// anywhere in the name rather than requiring it at the start \u2014 a bare \"[Smoke]\"-style tag can\r\n// never satisfy this shape, so QUIKTR-1082's \"don't match an unrelated bracketed tag\" safety\r\n// property holds without depending on position, which Vitest's JUnit reporter doesn't preserve.\r\nconst QP_TOKEN_BRACKET_RE = /\\[(QP-[A-Z][A-Z0-9]*-\\d+-\\d+)\\]/;\r\n\r\nfunction normalizeSlashes(path: string): string {\r\n return path.replace(/\\\\/g, \"/\");\r\n}\r\n\r\n/** The `<failure>`/`<error>` child itself, within one `<testcase>`'s already-isolated body. */\r\nconst FAILURE_TAG_RE = /<(?:failure|error)\\b([^>]*?)(?:\\/>|>([\\s\\S]*?)<\\/(?:failure|error)>)/;\r\nconst FAILURE_MESSAGE_ATTR_RE = /\\bmessage=\"([^\"]*)\"/;\r\n\r\n/** Console/PR-message budget, not a data-integrity bound \u2014 this is display text, never re-parsed. */\r\nconst MAX_FAILURE_TEXT = 500;\r\n\r\n/** The five entities the JUnit writers in real use (Vitest, Jest, pytest, go-junit-report) all\r\n * produce \u2014 not a general XML-unescape, same \"minimal scanner, not a parser\" posture as the rest\r\n * of this file. Literal `"`/`&` reaching a console log or a PR body reads as broken. */\r\nfunction unescapeXmlEntities(s: string): string {\r\n return s.replace(/</g, \"<\").replace(/>/g, \">\").replace(/"/g, '\"').replace(/'/g, \"'\").replace(/&/g, \"&\");\r\n}\r\n\r\n/** A file Vite cannot parse is reported with one generic message whatever the file or the syntax error;\r\n * only a `File: <path>:<line>[:<col>]` line in the body says which file and where (Vitest 4.1.11). */\r\nconst FAILURE_FILE_LINE_RE = /^[ \\t]*File:[ \\t]*(\\S[^\\r\\n]*?:\\d+(?::\\d+)?)[ \\t]*$/m;\r\nconst MAX_FAILURE_LOCATION = 300;\r\n\r\nfunction parseFailureLocation(body: string): string | null {\r\n const found = FAILURE_FILE_LINE_RE.exec(unescapeXmlEntities(body));\r\n if (!found) return null;\r\n const path = normalizeSlashes(found[1]);\r\n const root = `${normalizeSlashes(process.cwd()).replace(/\\/+$/, \"\")}/`;\r\n const shown = path.startsWith(root) ? path.slice(root.length) : path;\r\n return shown.length > MAX_FAILURE_LOCATION ? `${shown.slice(0, MAX_FAILURE_LOCATION)}\u2026` : shown;\r\n}\r\n\r\n/** `message=\"...\"` when present (short, what every framework puts the assertion diff in);\r\n * otherwise the tag's own body text (stack trace), truncated \u2014 never both, never neither if\r\n * either exists. `null` when the testcase body has no `<failure>`/`<error>` at all, or the tag\r\n * carries no text either way (both attrs and body empty \u2014 seen from at least one Go harness).\r\n *\r\n * Exception: when the message attribute is used and the body names a file and position (a file that\r\n * failed to parse), that location is appended, because the message alone cannot say which file. */\r\nfunction extractFailureText(testcaseBody: string): string | null {\r\n const tag = FAILURE_TAG_RE.exec(testcaseBody);\r\n if (!tag) return null;\r\n const [, attrs = \"\", inner = \"\"] = tag;\r\n const messageAttr = FAILURE_MESSAGE_ATTR_RE.exec(attrs)?.[1];\r\n const raw = (messageAttr ?? inner).trim();\r\n if (!raw) return null;\r\n const text = unescapeXmlEntities(raw);\r\n const shortened = text.length > MAX_FAILURE_TEXT ? `${text.slice(0, MAX_FAILURE_TEXT)}\u2026` : text;\r\n const location = messageAttr === undefined ? null : parseFailureLocation(inner);\r\n return location ? `${shortened} [at ${location}]` : shortened;\r\n}\r\n\r\n/** QUIKTR-1402 \u2014 one QuikPilot case's result in a report. `skipped` is its own answer, NOT a pass: a test\r\n * that did not run shows nothing about the case, and the baseline check must never read it as \"passed\". */\r\nexport type AutomationIdResult = \"pass\" | \"fail\" | \"skipped\";\r\n\r\n/** When several tests carry one case's id, the worst answer wins: fail > skipped > pass. */\r\nconst RESULT_RANK: Record<AutomationIdResult, number> = { pass: 0, skipped: 1, fail: 2 };\r\n\r\ninterface JUnitParseResult {\r\n outcomes: Map<string, boolean>;\r\n automationIdResults: Map<string, AutomationIdResult>;\r\n failureText: Map<string, string>;\r\n discoveredFiles: Set<string>;\r\n discoveredAutomationIds: Set<string>;\r\n}\r\n\r\nfunction parseJUnitOutcomes(xml: string): JUnitParseResult {\r\n const outcomes = new Map<string, boolean>();\r\n const automationIdResults = new Map<string, AutomationIdResult>();\r\n const failureText = new Map<string, string>();\r\n const discoveredFiles = new Set<string>();\r\n const discoveredAutomationIds = new Set<string>();\r\n\r\n TESTSUITE_OPEN_RE.lastIndex = 0;\r\n let suiteMatch: RegExpExecArray | null;\r\n while ((suiteMatch = TESTSUITE_OPEN_RE.exec(xml))) {\r\n const file = FILE_ATTR_RE.exec(suiteMatch[1])?.[1];\r\n if (file) discoveredFiles.add(normalizeSlashes(file));\r\n }\r\n\r\n let match: RegExpExecArray | null;\r\n TESTCASE_RE.lastIndex = 0;\r\n while ((match = TESTCASE_RE.exec(xml))) {\r\n const [, attrs, body = \"\"] = match;\r\n // A test's identity is its title as a person reads it. JUnit writers escape it (\"describe > test\" arrives as\r\n // \"describe > test\"), and the identity is what a failed run's reason names, so it is unescaped here once.\r\n const rawName = NAME_ATTR_RE.exec(attrs)?.[1];\r\n if (!rawName) continue;\r\n const name = unescapeXmlEntities(rawName);\r\n const rawClassname = CLASSNAME_ATTR_RE.exec(attrs)?.[1];\r\n const classname = rawClassname === undefined ? undefined : unescapeXmlEntities(rawClassname);\r\n const id = classname ? `${classname}::${name}` : name;\r\n const failed = FAILURE_CHILD_RE.test(body);\r\n outcomes.set(id, !failed);\r\n if (failed) {\r\n const text = extractFailureText(body);\r\n if (text) failureText.set(id, text);\r\n }\r\n const file = FILE_ATTR_RE.exec(attrs)?.[1];\r\n if (file) discoveredFiles.add(normalizeSlashes(file));\r\n if (classname) discoveredFiles.add(normalizeSlashes(classname));\r\n const bracket = QP_TOKEN_BRACKET_RE.exec(name)?.[1];\r\n if (bracket) {\r\n discoveredAutomationIds.add(bracket);\r\n const result: AutomationIdResult = failed ? \"fail\" : SKIPPED_CHILD_RE.test(body) ? \"skipped\" : \"pass\";\r\n const seen = automationIdResults.get(bracket);\r\n if (!seen || RESULT_RANK[result] > RESULT_RANK[seen]) automationIdResults.set(bracket, result);\r\n }\r\n }\r\n return { outcomes, automationIdResults, failureText, discoveredFiles, discoveredAutomationIds };\r\n}\r\n\r\nfunction readJUnitOutcomes(cwd: string): JUnitParseResult | null {\r\n const report = findJUnitReport(cwd);\r\n if (!report) return null;\r\n try {\r\n return parseJUnitOutcomes(readFileSync(report, \"utf8\"));\r\n } catch {\r\n return null;\r\n }\r\n}\r\n\r\n/** QUIKTR-1402 \u2014 per-case results from whatever JUnit report is on disk now; `null` when none is found or\r\n * it cannot be parsed (\"could not tell\", which the baseline check must treat differently from \"nothing\r\n * passed\"). Deliberately not part of TestSnapshot: only the baseline check reads it. */\r\nexport function readAutomationIdResults(cwd = process.cwd()): Map<string, AutomationIdResult> | null {\r\n return readJUnitOutcomes(cwd)?.automationIdResults ?? null;\r\n}\r\n\r\nexport function captureTestSnapshot(command: string | null, cwd = process.cwd()): TestSnapshot {\r\n const outcome = runTestCommand(command);\r\n const parsed = readJUnitOutcomes(cwd);\r\n return {\r\n outcome,\r\n results: parsed?.outcomes ?? null,\r\n failureText: parsed?.failureText,\r\n discoveredFiles: parsed?.discoveredFiles ?? null,\r\n discoveredAutomationIds: parsed?.discoveredAutomationIds ?? null,\r\n };\r\n}\r\n\r\nexport async function captureBaselineSnapshot(\r\n command: string | null,\r\n cwd = process.cwd(),\r\n): Promise<TestSnapshot> {\r\n const outcome = await runTestCommandAsync(command);\r\n const parsed = readJUnitOutcomes(cwd);\r\n return {\r\n outcome,\r\n results: parsed?.outcomes ?? null,\r\n failureText: parsed?.failureText,\r\n discoveredFiles: parsed?.discoveredFiles ?? null,\r\n discoveredAutomationIds: parsed?.discoveredAutomationIds ?? null,\r\n };\r\n}\r\n\r\nexport interface RegressionCheck {\r\n blocked: boolean;\r\n regressions: string[];\r\n newFailures: string[];\r\n preExisting: string[];\r\n /** testId -> bounded failure text, for whichever `regressions`/`newFailures` entries had one in\r\n * the AFTER snapshot (the failure that actually blocks the push \u2014 the baseline's own failure\r\n * text, if any, is irrelevant here). Always present, possibly empty \u2014 never omitted, so a\r\n * caller never has to guard its absence the way `results` itself still requires. */\r\n failureText: Map<string, string>;\r\n}\r\n\r\nexport function checkForRegressions(baseline: TestSnapshot, after: TestSnapshot): RegressionCheck {\r\n if (!baseline.results || !after.results) {\r\n return { blocked: false, regressions: [], newFailures: [], preExisting: [], failureText: new Map() };\r\n }\r\n\r\n const regressions: string[] = [];\r\n const newFailures: string[] = [];\r\n const preExisting: string[] = [];\r\n const failureText = new Map<string, string>();\r\n const afterFailureText = after.failureText;\r\n\r\n for (const [testId, passed] of after.results) {\r\n if (passed) continue;\r\n const before = baseline.results.get(testId);\r\n if (before === true) {\r\n regressions.push(testId);\r\n const text = afterFailureText?.get(testId);\r\n if (text) failureText.set(testId, text);\r\n } else if (before === false) {\r\n preExisting.push(testId);\r\n } else {\r\n newFailures.push(testId);\r\n const text = afterFailureText?.get(testId);\r\n if (text) failureText.set(testId, text);\r\n }\r\n }\r\n\r\n return { blocked: regressions.length > 0 || newFailures.length > 0, regressions, newFailures, preExisting, failureText };\r\n}\r\n\r\n/** Regressions and new failures named separately \u2014 conflating them is the thing that wastes\r\n * someone's morning (they're different diagnoses: one means the generated code broke something\r\n * that worked, the other means a generated test doesn't pass yet). Pre-existing failures are\r\n * noted, not hidden, so the message doesn't read as if they were silently dropped.\r\n *\r\n * QUIKTR-1029 self-heal prerequisite 1 \u2014 each named test now carries its failure text inline\r\n * when one was captured, so a run that blocks says WHY, not only WHAT. */\r\nexport function describeRegressions(check: RegressionCheck): string {\r\n const withText = (id: string) => {\r\n const text = check.failureText.get(id);\r\n return text ? `${id} (${text})` : id;\r\n };\r\n const parts: string[] = [];\r\n if (check.regressions.length > 0) {\r\n parts.push(\r\n `${check.regressions.length} regression(s) (passed before, now fail): ${check.regressions.map(withText).join(\", \")}`,\r\n );\r\n }\r\n if (check.newFailures.length > 0) {\r\n parts.push(\r\n `${check.newFailures.length} new failure(s) (did not exist before): ${check.newFailures.map(withText).join(\", \")}`,\r\n );\r\n }\r\n if (check.preExisting.length > 0) {\r\n parts.push(`${check.preExisting.length} pre-existing failure(s), unrelated to this change, not blocking`);\r\n }\r\n return parts.join(\"; \");\r\n}\r\n", "import { existsSync, mkdirSync, rmSync, writeFileSync } from \"node:fs\";\r\nimport { dirname, isAbsolute, join, relative, resolve } from \"node:path\";\r\nimport { scrubSecrets } from \"./failureReason\";\r\n\r\n/**\r\n * QUIKTR-1447 \u2014 what a failed run leaves behind for a person: the files QuikPilot wrote, the last test report and a short\r\n * manifest, in a folder the workflow uploads as an Actions artifact (kept 7 days, readable by whoever can see the repo's\r\n * Actions). Nothing goes to a branch or a pull request, and QuikTrack stores none of it.\r\n *\r\n * Written only after code generation finished, and never able to change how the run ends: the caller wraps it, and it\r\n * reports `written: false` instead of throwing.\r\n */\r\n\r\n/** Relative to the checkout root, which is where the workflow's upload step looks. */\r\nexport const FAILURE_ARTIFACT_DIR = \"quikpilot-failure\";\r\n\r\n/** Not named `junit*.xml`: the runner's own report finder walks the checkout for that pattern and would pick the copy up. */\r\nconst REPORT_COPY = \"final-test-report.xml\";\r\nconst MAX_REPORT_BYTES = 5 * 1024 * 1024;\r\nconst MAX_FILES = 200;\r\n\r\n// Replaced at build time (build.mjs); absent under vitest.\r\ndeclare const __RUNNER_VERSION__: string | undefined;\r\nconst RUNNER_VERSION = typeof __RUNNER_VERSION__ === \"string\" ? __RUNNER_VERSION__ : \"dev\";\r\n\r\nexport interface FailureArtifactInput {\r\n cwd: string;\r\n runId: string;\r\n issueKey: string | null;\r\n targets: ReadonlyArray<{ path: string; kind: string; automationIds?: string[] }>;\r\n results: ReadonlyArray<{ targetPath: string; newContent: string }>;\r\n /** The test report from the run after code generation, or null if no such run happened. A report from before\r\n * generation (the baseline) must never be passed. */\r\n testReport: Buffer | null;\r\n /** Already scrubbed and cut by the caller; scrubbed again here as the manifest is written. */\r\n failureReasons: readonly string[];\r\n /** Values that must not appear anywhere in the manifest, such as the run token. */\r\n secrets: readonly string[];\r\n}\r\n\r\n/** A path from the model must resolve inside the folder: absolute and parent-directory paths are refused. */\r\nfunction safeDestination(base: string, repoPath: string): string | null {\r\n if (!repoPath || isAbsolute(repoPath)) return null;\r\n const destination = resolve(base, repoPath);\r\n const rel = relative(base, destination);\r\n if (!rel || rel.startsWith(\"..\") || isAbsolute(rel)) return null;\r\n return destination;\r\n}\r\n\r\nexport function writeFailureArtifact(input: FailureArtifactInput): { written: boolean } {\r\n if (input.results.length === 0) return { written: false };\r\n try {\r\n const base = resolve(input.cwd, FAILURE_ARTIFACT_DIR);\r\n // A folder from an earlier call must not mix with this one.\r\n rmSync(base, { recursive: true, force: true });\r\n mkdirSync(base, { recursive: true });\r\n\r\n const files: Array<{ path: string; bytes: number }> = [];\r\n const skipped: string[] = [];\r\n for (const result of input.results) {\r\n const destination = files.length < MAX_FILES ? safeDestination(base, result.targetPath) : null;\r\n if (!destination) {\r\n skipped.push(result.targetPath);\r\n continue;\r\n }\r\n mkdirSync(dirname(destination), { recursive: true });\r\n writeFileSync(destination, result.newContent);\r\n files.push({ path: result.targetPath, bytes: Buffer.byteLength(result.newContent) });\r\n }\r\n\r\n let testReport: \"included\" | \"none\" | \"too-large\" = \"none\";\r\n if (input.testReport) {\r\n if (input.testReport.byteLength > MAX_REPORT_BYTES) {\r\n testReport = \"too-large\";\r\n } else {\r\n writeFileSync(join(base, REPORT_COPY), input.testReport);\r\n testReport = \"included\";\r\n }\r\n }\r\n\r\n const manifest = {\r\n runId: input.runId,\r\n issueKey: input.issueKey,\r\n runnerVersion: RUNNER_VERSION,\r\n generatedAt: new Date().toISOString(),\r\n targets: input.targets.map((t) => ({\r\n path: t.path,\r\n kind: t.kind,\r\n ...(t.automationIds && t.automationIds.length > 0 ? { automationIds: t.automationIds } : {}),\r\n })),\r\n files,\r\n skipped,\r\n testReport,\r\n failureReasons: input.failureReasons,\r\n };\r\n // Every string is scrubbed as the manifest is written, so a token that reached any field is taken out.\r\n const text = JSON.stringify(manifest, (_key, value) => (typeof value === \"string\" ? scrubSecrets(value, input.secrets) : value), 2);\r\n writeFileSync(join(base, \"manifest.json\"), text);\r\n return { written: existsSync(join(base, \"manifest.json\")) };\r\n } catch (err: unknown) {\r\n console.warn(`::warning::Could not keep the failed run's files: ${err instanceof Error ? err.message : String(err)}`);\r\n return { written: false };\r\n }\r\n}\r\n", "import { RuntimeReplyError } from \"./runtimeReplyError\";\r\n\r\n/** What a failed run tells QuikTrack about why. The message a hard failure threw used to go to the CI job log and\r\n * nowhere else; it is now sent, so it is written on one line, cut to a safe length, and has anything that looks like\r\n * a credential taken out first (an error from a failed push or request can carry one). */\r\nexport const MAX_FAILURE_REASON = 1000;\r\n\r\n/** Anything shorter than this is not treated as a secret to search for: replacing a three-letter \"token\" would wreck\r\n * every word that contains it. */\r\nconst MIN_SECRET_LENGTH = 8;\r\n\r\nconst CREDENTIAL_PATTERNS: RegExp[] = [\r\n /\\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}/g,\r\n /\\bgithub_pat_[A-Za-z0-9_]{20,}/g,\r\n /x-access-token:[^@\\s'\"]+/gi,\r\n // Only the header form (\"Authorization: basic <token>\"), or a bearer value that contains a digit: a bare\r\n // \"basic authentication\" or \"bearer of the news\" is prose, not a credential.\r\n /\\bauthorization:\\s*(?:basic|bearer|token)\\s+[^\\s'\"]{8,}/gi,\r\n /\\bbearer\\s+(?=[A-Za-z0-9._~+/=-]*\\d)[A-Za-z0-9._~+/=-]{12,}/gi,\r\n // A signed JWT is three dot-separated segments; QuikPilot's own run token is an encrypted JWT (alg dir) of five, the\r\n // second one empty. The run token is also matched by exact value, but one that has expired or rotated is not the\r\n // current value, so its shape has to catch it.\r\n /\\beyJ[A-Za-z0-9_-]{8,}(?:\\.[A-Za-z0-9_-]*){2,4}/g,\r\n];\r\n\r\n/** What may leave the job for a thrown error: the summary when the error quotes the AI Runtime's reply, otherwise its\r\n * message. The full message is still printed to the job log by the caller. */\r\nexport function failureSummary(err: unknown): string {\r\n if (err instanceof RuntimeReplyError) return err.summary;\r\n return err instanceof Error ? err.message : String(err);\r\n}\r\n\r\n/** Takes known secrets (by value) and anything shaped like a credential out of a piece of text. Does not change the\r\n * text otherwise: no line folding, no cutting. */\r\nexport function scrubSecrets(message: string, secrets: readonly string[] = []): string {\r\n let text = message;\r\n for (const secret of secrets) {\r\n if (secret.length >= MIN_SECRET_LENGTH) text = text.split(secret).join(\"***\");\r\n }\r\n for (const pattern of CREDENTIAL_PATTERNS) text = text.replace(pattern, \"***\");\r\n return text;\r\n}\r\n\r\nexport function describeFailureReason(message: string, secrets: readonly string[] = []): string {\r\n let text = scrubSecrets(message, secrets);\r\n text = text.replace(/\\s*\\n\\s*/g, \" | \").trim();\r\n return text.length > MAX_FAILURE_REASON ? `${text.slice(0, MAX_FAILURE_REASON)}\u2026` : text;\r\n}\r\n", "import { readFileSync } from \"node:fs\";\r\nimport type { CodegenFileResult } from \"./codegen\";\r\nimport type { PilotTarget } from \"./targeting\";\r\n\r\n/**\r\n * QUIKTR-1081 \u2014 QUIKSPL-5's PR #22 fixed the reported bug in src/validation.js and also silently\r\n * added an undeclared PUT endpoint to src/server.js that returned success while updating nothing.\r\n * Tests passed, the dependency check passed, and nothing compared what codegen actually added\r\n * against the design's own declared `apiChanges` \u2014 because nothing did.\r\n *\r\n * Same \"minimal, not exhaustive\" standard as dependencyCheck.ts's import scanner and\r\n * regressionCheck.ts's JUnit scanner, for the same reason: this package is dependency-free,\r\n * bundled into a single CLI file with no externals, published outside the monorepo, and the\r\n * target repository is arbitrary \u2014 no real per-framework route parser is on the table. This is a\r\n * same-line METHOD+PATH text heuristic, a tripwire against the ticket's own incident (method and\r\n * path both named on the documenting comment's line), not a route parser for every framework a\r\n * customer repo might use. It will not catch a Next.js-style `export function PUT(...)` whose path\r\n * comes from file location rather than an in-file string \u2014 ROUTE_EXPORT_RE below covers that one\r\n * export shape specifically, matched by method presence alone since it has no in-file path to\r\n * compare.\r\n *\r\n * \"Exported symbols\" (the ticket's own words) is deliberately narrowed to route-handler-shaped\r\n * exports here, not any new exported symbol: an arbitrary new exported helper is routine,\r\n * legitimate refactoring, and checking every export against free-text `apiChanges` would produce\r\n * exactly the kind of false-positive noise this package's checks otherwise avoid.\r\n */\r\nexport interface ScopeViolation {\r\n file: string;\r\n method: string;\r\n path: string;\r\n}\r\n\r\nexport interface ScopeCheck {\r\n blocked: boolean;\r\n violations: ScopeViolation[];\r\n}\r\n\r\ninterface RouteMention {\r\n method: string;\r\n path: string;\r\n}\r\n\r\nconst ROUTE_METHOD_RE = /\\b(GET|POST|PUT|PATCH|DELETE)\\b/i;\r\nconst ROUTE_PATH_RE = /\\/[A-Za-z0-9_\\-{}[\\]]+(?:\\/[A-Za-z0-9_\\-:{}[\\]]+)+/;\r\nconst ROUTE_EXPORT_RE = /\\bexport\\s+(?:async\\s+)?function\\s+(GET|POST|PUT|PATCH|DELETE)\\s*\\(/;\r\n\r\n/** No in-file path \u2014 a Next.js-style route handler's path comes from where the file lives, not a\r\n * string in it. Matched against `apiChanges` by method presence alone (see `surfaceCovers`). */\r\nconst NO_PATH = \"(this file's route)\";\r\n\r\nfunction detectMentions(text: string): RouteMention[] {\r\n const found: RouteMention[] = [];\r\n for (const line of text.split(\"\\n\")) {\r\n const methodMatch = ROUTE_METHOD_RE.exec(line);\r\n const pathMatch = ROUTE_PATH_RE.exec(line);\r\n if (methodMatch && pathMatch) {\r\n found.push({ method: methodMatch[1].toUpperCase(), path: pathMatch[0] });\r\n }\r\n const exportMatch = ROUTE_EXPORT_RE.exec(line);\r\n if (exportMatch) {\r\n found.push({ method: exportMatch[1].toUpperCase(), path: NO_PATH });\r\n }\r\n }\r\n return found;\r\n}\r\n\r\n/** `:id`, `{id}`, `[id]` all become `*` so a declared surface and a detected mention compare equal\r\n * regardless of the exact param name either side happens to use. */\r\nfunction normalizePath(path: string): string {\r\n return path.replace(/:[A-Za-z0-9_]+|\\{[^}]+\\}|\\[[^\\]]+\\]/g, \"*\");\r\n}\r\n\r\nfunction surfaceCovers(surface: string, mention: RouteMention): boolean {\r\n if (!new RegExp(`\\\\b${mention.method}\\\\b`, \"i\").test(surface)) return false;\r\n if (mention.path === NO_PATH) return true; // method presence is all a route-export mention has\r\n const declaredPath = normalizePath(surface);\r\n const mentionPath = normalizePath(mention.path);\r\n return declaredPath.includes(mentionPath) || mentionPath.includes(declaredPath);\r\n}\r\n\r\n/** Lines present in `after` but not in `before` \u2014 a set difference, not a positional diff (code\r\n * can shift line numbers around an addition). Good enough to separate \"genuinely new this run\"\r\n * from \"was already there\" without a real diff algorithm, same spirit as this package's other\r\n * scanners. */\r\nfunction addedLines(before: string, after: string): string {\r\n const beforeLines = new Set(before.split(\"\\n\"));\r\n return after\r\n .split(\"\\n\")\r\n .filter((line) => !beforeLines.has(line))\r\n .join(\"\\n\");\r\n}\r\n\r\n/** A test names and calls routes constantly (`describe(\"POST /api/x\", \u2026)`) but cannot define one,\r\n * so scanning it can only produce false positives. Common conventions only, in the same spirit as\r\n * the rest of this file \u2014 not an exhaustive per-framework list. */\r\nconst TEST_FILE_RES = [\r\n /(^|\\/)(__tests__|__mocks__|tests?|specs?)\\//i,\r\n /\\.(test|spec)\\.[^/.]+$/i,\r\n /(^|\\/)test_[^/]+\\.py$/i,\r\n /_test\\.(py|go)$/i,\r\n /Tests?\\.(java|kt|cs)$/,\r\n];\r\n\r\nfunction isTestFile(path: string): boolean {\r\n return TEST_FILE_RES.some((re) => re.test(path));\r\n}\r\n\r\nexport function checkApiScope(\r\n results: CodegenFileResult[],\r\n targets: PilotTarget[],\r\n apiChanges: { surface: string; change: string; reason: string }[],\r\n): ScopeCheck {\r\n const targetsByPath = new Map(targets.map((t) => [t.path, t]));\r\n const violations: ScopeViolation[] = [];\r\n\r\n for (const { targetPath, newContent } of results) {\r\n if (isTestFile(targetPath)) continue;\r\n const target = targetsByPath.get(targetPath);\r\n const isNewFile = target?.kind === \"NEW_FILE\";\r\n\r\n let scanned: string;\r\n if (isNewFile) {\r\n scanned = newContent;\r\n } else {\r\n let currentContent: string;\r\n try {\r\n currentContent = readFileSync(targetPath, \"utf8\");\r\n } catch {\r\n currentContent = \"\";\r\n }\r\n scanned = addedLines(currentContent, newContent);\r\n }\r\n\r\n for (const mention of detectMentions(scanned)) {\r\n if (!apiChanges.some((c) => surfaceCovers(c.surface, mention))) {\r\n violations.push({ file: targetPath, method: mention.method, path: mention.path });\r\n }\r\n }\r\n }\r\n\r\n return { blocked: violations.length > 0, violations };\r\n}\r\n\r\nexport function describeScopeViolations(check: ScopeCheck): string {\r\n return check.violations\r\n .map((v) => `${v.file} adds ${v.method} ${v.path}, not declared in the design's API changes`)\r\n .join(\"; \");\r\n}\r\n", "import { resolve, relative, isAbsolute } from \"node:path\";\r\nimport { findDeniedContextPath, matchesDeniedPath } from \"./deniedPaths\";\r\nimport { listFiles } from \"./git\";\r\nimport { checkHardFailure, unwrapExecute } from \"./envelope\";\r\nimport { RuntimeReplyError } from \"./runtimeReplyError\";\r\nimport type { PilotPacket } from \"./packet\";\r\nimport { fetchWithRetry } from \"./retryFetch\";\r\nimport { DeniedPathError, TargetingHttpError } from \"./targetingErrors\";\r\nimport { resolveTargetingMode, type TargetingMode } from \"./targetingMode\";\r\nimport {\r\n LoopFailure,\r\n SafetyRefusalError,\r\n runTargetingLoop,\r\n type FallbackReason,\r\n type LoopDeps,\r\n type LoopSummary,\r\n} from \"./targetingLoop\";\r\n\r\nexport { DeniedPathError, TargetingHttpError };\r\n\r\n/**\r\n * QUIKTR-1035 \u2014 `pilot.targeting`: turns the design plus a file listing into real per-file\r\n * instructions, replacing codegen.ts's old planStepsFromDesign entirely. Proven live by the AI\r\n * Runtime against a real 624-file QuikChat listing before this was wired in.\r\n *\r\n * QUIKTR-1083 (\u00A715) \u2014 the versioned test-target contract. `contractVersion: \"test-targets-1\"` is\r\n * sent unconditionally: per \u00A715.6 the unversioned path is only \"exactly today's behaviour\" for a\r\n * caller that never asks for the new shape, and this runner always wants it once it ships.\r\n */\r\nconst CONTRACT_VERSION = \"test-targets-1\";\r\n\r\nexport type TargetKind = \"EXISTING\" | \"NEW_FILE\";\r\n\r\nexport interface PilotTarget {\r\n path: string;\r\n kind: TargetKind;\r\n planStepsImplemented: string[];\r\n // Context contract change \u2014 pilot.targeting now names, per target, which other files\r\n // pilot.codegen should read before writing this one (\"to write this file, read these\").\r\n // codegen.ts validates and reads these; absent/empty means no context, no fallback.\r\n contextPaths?: string[];\r\n /** \u00A715.3 \u2014 present only on a test target: the automation IDs (not database ids \u2014 see\r\n * \u00A715.3's own naming rationale) this target's generated file must cover. codegen.ts forwards\r\n * only the matching `requiredTests` subset for a target carrying this. */\r\n automationIds?: string[];\r\n}\r\n\r\n/** \u00A715.3 amendment 1 \u2014 a case with no behaviour (given/when/then all null) is named here instead\r\n * of silently dropped; the model has no discretion over which cases land here vs. in a target's\r\n * `automationIds` (completeness is enforced on the runtime side). Informational on this side \u2014\r\n * folded into `run.ts`'s `warnings`, never blocking. */\r\nexport interface SkippedCase {\r\n automationId: string;\r\n reason: \"NO_BEHAVIOUR\";\r\n}\r\n\r\nexport type TargetingResult = (\r\n | {\r\n outcome: \"TARGETED\";\r\n targets: PilotTarget[];\r\n skippedCases: SkippedCase[];\r\n /** Paths targeting called NEW_FILE although they are already in the checkout; they come back as EXISTING. */\r\n correctedKinds?: string[];\r\n }\r\n | { outcome: \"NO_TARGET\"; reason: string | null }\r\n) & {\r\n /** QUIKTR-1458 \u2014 present only when the read-only loop ran (or was tried): what it did. */\r\n loop?: LoopSummary;\r\n /** Non-blocking notes for the run's warnings list (today: only \"the loop fell back\"). */\r\n warnings?: string[];\r\n};\r\n\r\nexport interface TargetingResponse {\r\n outcome?: \"TARGETED\" | \"NO_TARGET\";\r\n targets?: {\r\n path: string;\r\n kind: string;\r\n planStepsImplemented: string[];\r\n contextPaths?: string[];\r\n automationIds?: string[];\r\n }[];\r\n skippedCases?: SkippedCase[];\r\n noTargetReason?: string;\r\n}\r\n\r\n/**\r\n * Tracked files under the packet's workspace root, or the whole checkout when it's null\r\n * (QUIKTR-1033) \u2014 never normalised to \".\" at the packet layer itself, only here where a concrete\r\n * pathspec is actually needed. An unscoped listing on a large monorepo is ~210k tokens, which fits\r\n * one provider and breaks the fallback chain \u2014 see workspaceRoot's own doc comment on PilotPacket.\r\n */\r\nexport function listWorkspaceFiles(workspaceRoot: string | null): string[] {\r\n return listFiles(workspaceRoot ?? \".\");\r\n}\r\n\r\n/**\r\n * VALIDATION IS OURS \u2014 the AI Runtime's schema doesn't guarantee a path is actually safe to write.\r\n * An EXISTING target must already be in the checkout; a NEW_FILE target must resolve inside the\r\n * workspace root. Either failure throws \u2014 a dropped target is a plan half-executed, and run.ts's\r\n * existing top-level try/catch already turns this into the same hard failure any other pre-setup\r\n * step gets.\r\n */\r\nfunction validateTarget(\r\n target: { path: string; kind: string; contextPaths?: string[] },\r\n workspaceRoot: string | null,\r\n workspaceListing: Set<string>,\r\n deniedPaths: string[],\r\n): void {\r\n // QUIKTR-1083 (\u00A715.3) \u2014 layer 2 of three: checked here, before any codegen spend, regardless of\r\n // kind. Layer 1 (the runtime's own targeting validator) should already exclude a denied path;\r\n // this does not trust that and re-checks independently.\r\n const denied = matchesDeniedPath(target.path, deniedPaths);\r\n if (denied) {\r\n throw new DeniedPathError(\r\n `pilot.targeting proposed a target matching a denied path (${denied}): ${target.path}`,\r\n );\r\n }\r\n // QUIKTR-1420 \u2014 the same list applies to what the target cites as CONTEXT, which the runner reads and\r\n // sends to the model provider. Checked before anything else, and before any codegen spend.\r\n const deniedContext = findDeniedContextPath(target.contextPaths ?? [], deniedPaths);\r\n if (deniedContext) {\r\n throw new DeniedPathError(\r\n `pilot.targeting cited a denied path as context (${deniedContext.pattern}): ${deniedContext.path} (target ${target.path})`,\r\n );\r\n }\r\n if (target.kind !== \"EXISTING\" && target.kind !== \"NEW_FILE\") {\r\n throw new Error(`pilot.targeting returned an unknown kind \"${target.kind}\" for ${target.path}`);\r\n }\r\n if (target.kind === \"EXISTING\") {\r\n if (!workspaceListing.has(target.path)) {\r\n throw new Error(\r\n `pilot.targeting named an EXISTING file not found in the checkout: ${target.path}`,\r\n );\r\n }\r\n return;\r\n }\r\n const root = resolve(workspaceRoot ?? \".\");\r\n const rel = relative(root, resolve(target.path));\r\n if (rel.startsWith(\"..\") || isAbsolute(rel)) {\r\n throw new Error(\r\n `pilot.targeting named a NEW_FILE path that escapes the workspace root: ${target.path}`,\r\n );\r\n }\r\n}\r\n\r\n/**\r\n * The request body for the single-call `pilot.targeting`. Key ORDER is part of the contract with the\r\n * AI Runtime's versioned path and is pinned by targeting.characterisation.test.ts.\r\n */\r\nexport function buildContextData(\r\n design: PilotPacket[\"design\"],\r\n workspaceListing: string[],\r\n requiredTests: PilotPacket[\"requiredTests\"],\r\n deniedPaths: string[],\r\n testDiscovery: PilotPacket[\"testDiscovery\"],\r\n outOfScope: string[],\r\n): Record<string, unknown> {\r\n const contextData: Record<string, unknown> = {\r\n // NESTED, NOT FLATTENED \u2014 a second vocabulary for the design shape is exactly what\r\n // QUIKTR-1034 cost.\r\n workspaceListing,\r\n design,\r\n // QUIKTR-1065/1083 \u2014 requiredTests carried through so targeting can propose a test-file\r\n // target naming which cases it covers (\u00A715.1's Case shape, unchanged).\r\n requiredTests,\r\n // QUIKTR-1083 (\u00A715.6) \u2014 required on the versioned path.\r\n contractVersion: CONTRACT_VERSION,\r\n };\r\n // QUIKTR-1083 (\u00A715.3) \u2014 optional on the wire; omitted rather than sent empty, matching\r\n // codegen.ts's identical treatment.\r\n if (deniedPaths.length > 0) {\r\n contextData.deniedPaths = deniedPaths;\r\n }\r\n // QUIKTR-1401, \u00A720 of the AI Runtime contract (deployed and confirmed 2026-10-01) \u2014 an optional declared key\r\n // under the versioned contract, sent only when non-empty: an empty list would make the prompt mention\r\n // constraints that are not there. Free text, so unlike deniedPaths it can only be TOLD to the model, never\r\n // checked. Never sent to pilot.design.\r\n if (outOfScope.length > 0) {\r\n contextData.outOfScope = outOfScope;\r\n }\r\n // QUIKTR-1315, \u00A719 of the AI Runtime contract \u2014 AGREED (2026-09-28), confirmed deployed and\r\n // live (2026-09-29). ALWAYS sent, never omitted \u2014 \u00A719's whole point is the tagged\r\n // `{ report: \"PRESENT\" | \"ABSENT\" }` shape replacing an absent-vs-empty key distinction, so this\r\n // must not fall back to \"omit when nothing to say\" the way `deniedPaths` does above. The packet\r\n // already resolves this to a real value in every case (never undefined) \u2014 see packet.ts.\r\n contextData.testDiscovery = testDiscovery;\r\n return contextData;\r\n}\r\n\r\n/**\r\n * One POST of `pilot.targeting`, returning the RAW `/ai/execute` envelope. Shared by the single call\r\n * and by every turn of the read-only loop. QUIKTR-1069 \u2014 retryFetch retries a transport-level failure\r\n * only (502/503/504, a dropped connection); a real refusal always arrives as a 200 with the refusal\r\n * inside the envelope. `signal` is for loop turns only; the single call never had a timeout and\r\n * keeps behaving exactly as before.\r\n */\r\nexport async function postTargeting(\r\n gateway: PilotPacket[\"gateway\"],\r\n contextData: Record<string, unknown>,\r\n signal?: AbortSignal,\r\n): Promise<unknown> {\r\n const res = await fetchWithRetry(`${gateway.baseUrl}/ai/execute`, {\r\n method: \"POST\",\r\n headers: { \"content-type\": \"application/json\", \"x-run-token\": gateway.token },\r\n body: JSON.stringify({\r\n appId: \"quiktrack\",\r\n useCase: \"pilot.targeting\",\r\n expectedOutputType: \"json\",\r\n userPrompt: \"\",\r\n contextData,\r\n }),\r\n ...(signal ? { signal } : {}),\r\n });\r\n\r\n if (!res.ok) {\r\n throw new TargetingHttpError(res.status, res.statusText);\r\n }\r\n return res.json();\r\n}\r\n\r\n/**\r\n * Everything that happens to a targeting ANSWER, whichever way it was obtained: the shape check, our\r\n * own validation of every target, and the NEW_FILE correction. The single call and the read-only loop\r\n * both end here, so a target is judged by exactly the same rules either way.\r\n */\r\nexport function finalizeTargeting(\r\n body: TargetingResponse,\r\n workspaceRoot: string | null,\r\n workspaceListing: string[],\r\n deniedPaths: string[],\r\n): TargetingResult {\r\n if (body.outcome === \"NO_TARGET\") {\r\n return { outcome: \"NO_TARGET\", reason: body.noTargetReason ?? null };\r\n }\r\n if (body.outcome !== \"TARGETED\" || !Array.isArray(body.targets)) {\r\n throw new RuntimeReplyError(\r\n `pilot.targeting returned an unexpected shape: ${JSON.stringify(body)}`,\r\n \"pilot.targeting returned an unexpected shape\",\r\n );\r\n }\r\n\r\n const listing = new Set(workspaceListing);\r\n for (const target of body.targets) {\r\n validateTarget(target, workspaceRoot, listing, deniedPaths);\r\n }\r\n\r\n // A NEW_FILE target is sent to codegen with no current content, so a file that already exists would be\r\n // overwritten blind (QUIKTR-1448). The checkout listing says which it is, so the label is corrected here\r\n // rather than failing a run over a mistake with an obvious answer.\r\n const correctedKinds: string[] = [];\r\n const targets = (body.targets as PilotTarget[]).map((target) => {\r\n if (target.kind === \"NEW_FILE\" && listing.has(target.path)) {\r\n correctedKinds.push(target.path);\r\n return { ...target, kind: \"EXISTING\" as const };\r\n }\r\n return target;\r\n });\r\n\r\n return {\r\n outcome: \"TARGETED\",\r\n targets,\r\n skippedCases: body.skippedCases ?? [],\r\n ...(correctedKinds.length > 0 ? { correctedKinds } : {}),\r\n };\r\n}\r\n\r\n/** Today's behaviour: one call, answered from the file listing alone. */\r\nexport async function runSingleShot(\r\n gateway: PilotPacket[\"gateway\"],\r\n design: PilotPacket[\"design\"],\r\n workspaceRoot: string | null,\r\n workspaceListing: string[],\r\n requiredTests: PilotPacket[\"requiredTests\"],\r\n deniedPaths: string[],\r\n testDiscovery: PilotPacket[\"testDiscovery\"],\r\n outOfScope: string[] = [],\r\n): Promise<TargetingResult> {\r\n const contextData = buildContextData(design, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope);\r\n // /ai/execute wraps every result in an envelope \u2014 the use-case result lives at\r\n // structuredJson, and a failure can arrive as success:false in an HTTP 200 (see envelope.ts).\r\n // QUIKTR-1083 \u2014 SEMANTIC_MISMATCH/CONTRACT_REJECTED are checked on the raw envelope, before\r\n // unwrapping, same reason codegen.ts's pre-existing CODEGEN_* checks do: unwrapping first would\r\n // throw unwrapExecute's generic success:false error and lose the distinction.\r\n const envelope = await postTargeting(gateway, contextData);\r\n checkHardFailure(envelope, \"pilot.targeting\");\r\n const body = unwrapExecute<TargetingResponse>(envelope, \"pilot.targeting\");\r\n return finalizeTargeting(body, workspaceRoot, workspaceListing, deniedPaths);\r\n}\r\n\r\nexport interface RunTargetingOptions {\r\n /** Overrides the environment switch. Tests, and (one day) a QuikTrack setting, pass this. */\r\n mode?: TargetingMode;\r\n /** Test seam: a fake filesystem, tighter limits, a fake clock or log for the loop. */\r\n loopDeps?: Partial<Omit<LoopDeps, \"post\">>;\r\n}\r\n\r\nconst CODE_LIKE = /^[A-Z0-9_]{1,40}$/;\r\n\r\n/**\r\n * `pilot.targeting`: which files to change. By default one call answered from the file listing alone.\r\n * With the read-only loop switched on (QUIKTR-1458: `QUIKPILOT_TARGETING_MODE=loop`) the AI may look\r\n * at the code first; if the loop cannot finish for an ordinary reason, the run falls back to the\r\n * single call and says so. A refusal never falls back (see targetingLoop.ts).\r\n */\r\nexport async function runTargeting(\r\n gateway: PilotPacket[\"gateway\"],\r\n design: PilotPacket[\"design\"],\r\n workspaceRoot: string | null,\r\n workspaceListing: string[],\r\n requiredTests: PilotPacket[\"requiredTests\"],\r\n deniedPaths: string[],\r\n testDiscovery: PilotPacket[\"testDiscovery\"],\r\n /** QUIKTR-1401 (\u00A720) \u2014 what the reviewer approved the change must NOT touch. Optional and last: every\r\n * existing caller is unchanged. */\r\n outOfScope: string[] = [],\r\n options: RunTargetingOptions = {},\r\n): Promise<TargetingResult> {\r\n const mode = options.mode ?? resolveTargetingMode();\r\n if (mode !== \"loop\") {\r\n return runSingleShot(gateway, design, workspaceRoot, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope);\r\n }\r\n\r\n const baseContext = buildContextData(design, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope);\r\n let summary: LoopSummary | undefined;\r\n let runtimeCode: string | undefined;\r\n let reason: FallbackReason;\r\n try {\r\n const looped = await runTargetingLoop(\r\n { baseContext, listing: workspaceListing, deniedPaths },\r\n { ...options.loopDeps, post: (contextData, signal) => postTargeting(gateway, contextData, signal) },\r\n );\r\n summary = looped.summary;\r\n const result = finalizeTargeting(looped.body as TargetingResponse, workspaceRoot, workspaceListing, deniedPaths);\r\n return { ...result, loop: summary };\r\n } catch (err) {\r\n // A refusal is never answered by trying again another way.\r\n if (err instanceof DeniedPathError || err instanceof SafetyRefusalError) throw err;\r\n if (err instanceof LoopFailure) {\r\n reason = err.reason;\r\n runtimeCode = err.runtimeCode;\r\n summary = err.summary ?? summary;\r\n } else {\r\n // Only finalizeTargeting can end up here: the loop got an answer, but it is not usable.\r\n reason = \"final_invalid\";\r\n }\r\n }\r\n\r\n const fellBack: LoopSummary = {\r\n turns: summary?.turns ?? 0,\r\n toolCalls: summary?.toolCalls ?? 0,\r\n readChars: summary?.readChars ?? 0,\r\n refused: summary?.refused ?? 0,\r\n reads: summary?.reads ?? [],\r\n stopReason: \"fallback\",\r\n fellBack: true,\r\n fallbackReason: reason,\r\n };\r\n const log = options.loopDeps?.log ?? ((e: Record<string, unknown>) => console.log(JSON.stringify(e)));\r\n log({\r\n event: \"targeting.loop_fallback\",\r\n reason,\r\n turn: fellBack.turns,\r\n toolCalls: fellBack.toolCalls,\r\n ...(runtimeCode && CODE_LIKE.test(runtimeCode) ? { runtimeCode } : {}),\r\n });\r\n\r\n // If this fails too, it fails the run exactly as it would have without the loop.\r\n const single = await runSingleShot(gateway, design, workspaceRoot, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope);\r\n return {\r\n ...single,\r\n loop: fellBack,\r\n warnings: [`QuikPilot's read-only targeting could not complete (${reason}); standard targeting was used instead.`],\r\n };\r\n}\r\n", "/**\r\n * QUIKTR-1458 \u2014 which way `pilot.targeting` runs.\r\n *\r\n * `single` is today's behaviour: one call, the model answers from the file listing alone. `loop` lets\r\n * the model look at the code first, through read-only tools (targetingLoop.ts). It is OFF unless\r\n * asked for, and only the exact word `loop` asks.\r\n *\r\n * Today the switch is an environment variable in the workflow file, set by hand. The long-term home\r\n * is a per-project QuikTrack setting carried in the run packet; `packetSetting` is that seam, so the\r\n * day it exists it is one argument at one call site and this precedence (setting, then environment,\r\n * then off) is already settled and tested. Nothing passes it yet.\r\n */\r\nexport type TargetingMode = \"single\" | \"loop\";\r\n\r\nexport const TARGETING_MODE_ENV = \"QUIKPILOT_TARGETING_MODE\";\r\n\r\nfunction parse(value: string | null | undefined): TargetingMode | null {\r\n if (typeof value !== \"string\") return null;\r\n const v = value.trim().toLowerCase();\r\n if (v === \"loop\") return \"loop\";\r\n if (v === \"single\") return \"single\";\r\n return null;\r\n}\r\n\r\nexport function resolveTargetingMode(\r\n env: NodeJS.ProcessEnv = process.env,\r\n packetSetting?: string | null,\r\n): TargetingMode {\r\n const fromSetting = parse(packetSetting);\r\n if (fromSetting) return fromSetting;\r\n return parse(env[TARGETING_MODE_ENV]) ?? \"single\";\r\n}\r\n", "import type { TargetKind, TargetingResult } from \"./targeting\";\r\nimport type { LoopStopReason, LoopSummary } from \"./targetingLoop\";\r\n\r\n/**\r\n * QUIKTR-1421 \u2014 a record of what pilot.targeting decided, reported to QuikTrack in the run's final callback so\r\n * \"which contextPaths did targeting list for the test?\" can be answered after the fact. Twice it could not\r\n * (QUIKSPL-16, then run 25): the AI Runtime's logs carry counts only, deliberately, and QuikTrack's run trail\r\n * stores a payload hash, so neither side kept what was actually DECIDED.\r\n *\r\n * PATHS AND CASE IDS ONLY (Suyash). Never case text, never `planStepsImplemented` (model-written prose about\r\n * the customer's code), never file content. The one free-text field is the NO_TARGET reason, cut to 300\r\n * characters with a flag saying so.\r\n *\r\n * Every cap below matches QuikTrack's `targetingRecordSchema`. That is not tidiness: a record QuikTrack finds\r\n * invalid is dropped, so a record over the caps is a record lost. Anything cut sets `truncated`.\r\n */\r\nconst MAX_TARGETS = 25;\r\nconst MAX_IDS_PER_TARGET = 50;\r\nconst MAX_CONTEXT_PATHS = 20;\r\nconst MAX_ADDED_PATHS = 20;\r\nconst MAX_SKIPPED_CONTEXT = 20;\r\nconst MAX_SKIPPED_CASES = 200;\r\nconst MAX_CONTEXT_RECORDS = 25;\r\nconst MAX_PATH_CHARS = 300;\r\nconst MAX_ID_CHARS = 100;\r\nconst MAX_REASON_CHARS = 300;\r\n// QUIKTR-1458 \u2014 the read-only loop's part of the record. These must match QuikTrack's schema when it adds the field.\r\nconst MAX_LOOP_READS = 50;\r\nconst MAX_FALLBACK_REASON_CHARS = 40;\r\n\r\n/** One `runCodegen` call: what targeting named as context, what the runner ADDED (QUIKTR-1419), and what it\r\n * skipped. `runCodegen` fills a caller-owned array of these, so the entries survive a later throw. */\r\nexport interface CodegenContextRecord {\r\n targetPath: string;\r\n contextPaths: string[];\r\n addedPaths: string[];\r\n skipped: { path: string; reason: string }[];\r\n /** QUIKTR-1454 \u2014 the part of `addedPaths` that came from the target's own imports. Log line only: QuikTrack's\r\n * record keeps `addedPaths` (which includes them) and strips fields it does not know. Omitted when empty. */\r\n importedPaths?: string[];\r\n /** QUIKTR-1454 \u2014 path-alias imports (`@/x`) seen and not followed. Counted, not listed. Omitted when zero. */\r\n aliasImports?: number;\r\n /** The runtime refused the context as too large and the call was retried WITHOUT the added files, so\r\n * `addedPaths` is empty even though files were offered first. */\r\n retriedWithoutAdded?: true;\r\n}\r\n\r\n/**\r\n * QUIKTR-1458 \u2014 what the read-only targeting loop looked at. PATHS AND COUNTS ONLY: never file content, a\r\n * search text or the AI's reasoning. Present only when the loop ran (or was tried and fell back); an older\r\n * QuikTrack strips the key it does not know. It is how a reviewer can see what the AI read, which is why\r\n * refused reads are listed too.\r\n */\r\nexport interface LoopRecord {\r\n turns: number;\r\n toolCalls: number;\r\n refused: number;\r\n stopReason: LoopStopReason;\r\n fellBack?: true;\r\n fallbackReason?: string;\r\n reads: { path: string; startLine?: number; endLine?: number; chars: number; refused?: true }[];\r\n truncated?: true;\r\n}\r\n\r\nexport interface TargetingRecord {\r\n outcome: \"TARGETED\" | \"NO_TARGET\";\r\n noTargetReason?: string;\r\n noTargetReasonTruncated?: true;\r\n targets: { path: string; kind: TargetKind; contextPaths: string[]; automationIds: string[] }[];\r\n skippedCaseIds: string[];\r\n codegenContext: CodegenContextRecord[];\r\n truncated?: true;\r\n /** QUIKTR-1458 \u2014 see LoopRecord. */\r\n loop?: LoopRecord;\r\n}\r\n\r\n/** Keeps at most `max` non-empty entries no longer than `maxChars`, telling the caller if anything was cut. A\r\n * too-long value is DROPPED, not shortened: a cut-off path is a wrong path. */\r\nfunction clampList(values: string[] | undefined, max: number, maxChars: number): { kept: string[]; cut: boolean } {\r\n let cut = false;\r\n const kept: string[] = [];\r\n for (const raw of values ?? []) {\r\n const v = typeof raw === \"string\" ? raw.trim() : \"\";\r\n if (v.length === 0) continue;\r\n if (v.length > maxChars || kept.length >= max) {\r\n cut = true;\r\n continue;\r\n }\r\n kept.push(v);\r\n }\r\n return { kept, cut };\r\n}\r\n\r\nfunction wholeNumber(n: unknown): number {\r\n return typeof n === \"number\" && Number.isInteger(n) && n >= 0 ? n : 0;\r\n}\r\n\r\n/** A too-long path is DROPPED, not shortened (a cut-off path is a wrong path), and the cut is flagged. */\r\nfunction clampLoop(loop: LoopSummary): LoopRecord {\r\n let cut = false;\r\n const reads: LoopRecord[\"reads\"] = [];\r\n for (const r of loop.reads ?? []) {\r\n if (reads.length >= MAX_LOOP_READS) {\r\n cut = true;\r\n break;\r\n }\r\n const path = typeof r.path === \"string\" ? r.path.trim() : \"\";\r\n if (path.length === 0 || path.length > MAX_PATH_CHARS) {\r\n cut = true;\r\n continue;\r\n }\r\n reads.push({\r\n path,\r\n ...(Number.isInteger(r.startLine) ? { startLine: r.startLine } : {}),\r\n ...(Number.isInteger(r.endLine) ? { endLine: r.endLine } : {}),\r\n chars: wholeNumber(r.chars),\r\n ...(r.refused ? { refused: true as const } : {}),\r\n });\r\n }\r\n return {\r\n turns: wholeNumber(loop.turns),\r\n toolCalls: wholeNumber(loop.toolCalls),\r\n refused: wholeNumber(loop.refused),\r\n stopReason: loop.stopReason,\r\n ...(loop.fellBack ? { fellBack: true as const } : {}),\r\n ...(loop.fallbackReason ? { fallbackReason: String(loop.fallbackReason).slice(0, MAX_FALLBACK_REASON_CHARS) } : {}),\r\n reads,\r\n ...(cut ? { truncated: true as const } : {}),\r\n };\r\n}\r\n\r\nexport function buildTargetingRecord(targeting: TargetingResult, contextLog: CodegenContextRecord[]): TargetingRecord {\r\n let truncated = false;\r\n const note = (cut: boolean) => {\r\n if (cut) truncated = true;\r\n };\r\n\r\n if (targeting.outcome === \"NO_TARGET\") {\r\n const record: TargetingRecord = { outcome: \"NO_TARGET\", targets: [], skippedCaseIds: [], codegenContext: [] };\r\n const reason = (targeting.reason ?? \"\").trim();\r\n if (reason.length > 0) {\r\n record.noTargetReason = reason.slice(0, MAX_REASON_CHARS);\r\n if (reason.length > MAX_REASON_CHARS) record.noTargetReasonTruncated = true;\r\n }\r\n if (targeting.loop) record.loop = clampLoop(targeting.loop);\r\n return record;\r\n }\r\n\r\n const targets: TargetingRecord[\"targets\"] = [];\r\n for (const t of targeting.targets) {\r\n if (targets.length >= MAX_TARGETS) {\r\n truncated = true;\r\n break;\r\n }\r\n const path = typeof t.path === \"string\" ? t.path.trim() : \"\";\r\n if (path.length === 0 || path.length > MAX_PATH_CHARS) {\r\n truncated = true;\r\n continue;\r\n }\r\n const contextPaths = clampList(t.contextPaths, MAX_CONTEXT_PATHS, MAX_PATH_CHARS);\r\n const automationIds = clampList(t.automationIds, MAX_IDS_PER_TARGET, MAX_ID_CHARS);\r\n note(contextPaths.cut);\r\n note(automationIds.cut);\r\n targets.push({ path, kind: t.kind, contextPaths: contextPaths.kept, automationIds: automationIds.kept });\r\n }\r\n\r\n const skipped = clampList(\r\n (targeting.skippedCases ?? []).map((c) => c.automationId),\r\n MAX_SKIPPED_CASES,\r\n MAX_ID_CHARS,\r\n );\r\n note(skipped.cut);\r\n\r\n const codegenContext: CodegenContextRecord[] = [];\r\n for (const entry of contextLog) {\r\n if (codegenContext.length >= MAX_CONTEXT_RECORDS) {\r\n truncated = true;\r\n break;\r\n }\r\n const targetPath = typeof entry.targetPath === \"string\" ? entry.targetPath.trim() : \"\";\r\n if (targetPath.length === 0 || targetPath.length > MAX_PATH_CHARS) {\r\n truncated = true;\r\n continue;\r\n }\r\n const contextPaths = clampList(entry.contextPaths, MAX_CONTEXT_PATHS, MAX_PATH_CHARS);\r\n const addedPaths = clampList(entry.addedPaths, MAX_ADDED_PATHS, MAX_PATH_CHARS);\r\n const skippedPaths = clampList(\r\n (entry.skipped ?? []).map((s) => s.path),\r\n MAX_SKIPPED_CONTEXT,\r\n MAX_PATH_CHARS,\r\n );\r\n note(contextPaths.cut);\r\n note(addedPaths.cut);\r\n note(skippedPaths.cut);\r\n const reasonByPath = new Map((entry.skipped ?? []).map((s) => [s.path.trim(), s.reason]));\r\n codegenContext.push({\r\n targetPath,\r\n contextPaths: contextPaths.kept,\r\n addedPaths: addedPaths.kept,\r\n skipped: skippedPaths.kept.map((path) => ({ path, reason: String(reasonByPath.get(path) ?? \"skipped\").slice(0, 40) })),\r\n ...(entry.retriedWithoutAdded ? { retriedWithoutAdded: true as const } : {}),\r\n });\r\n }\r\n\r\n const record: TargetingRecord = {\r\n outcome: \"TARGETED\",\r\n targets,\r\n skippedCaseIds: skipped.kept,\r\n codegenContext,\r\n };\r\n if (truncated) record.truncated = true;\r\n if (targeting.loop) record.loop = clampLoop(targeting.loop);\r\n return record;\r\n}\r\n", "import type { PilotTarget } from \"./targeting\";\r\n\r\n/**\r\n * QUIKTR-1315 \u2014 targeting can claim a test case's `automationId` against a SOURCE-file target while\r\n * proposing a separate, empty test-file target alongside it (no plan steps, no automationIds).\r\n * Verified against a real captured AI Runtime sample (`targeting-versioned.json`): the model wrote\r\n * `tests/auth/login.test.ts` with `automationIds: []` and claimed all three cases on\r\n * `src/auth/middleware.ts`/`src/auth/login.ts` instead. When that happens, the generated test lands\r\n * inside a source file the repository's test runner never discovers \u2014 the case has zero real\r\n * coverage even though its id is present in the generated text, and \u00A715's own completeness rule\r\n * (every case appears exactly once) is satisfied regardless.\r\n *\r\n * Two detectors, both using the repository's OWN JUnit report as ground truth for \"which files the\r\n * test runner actually looks at\" \u2014 no naming convention, derived by running the repo's own tooling,\r\n * language-neutral by construction:\r\n *\r\n * `checkTestPlacement` \u2014 BEFORE the write, against the BASELINE report (pre-codegen).\r\n * Scoped to EXISTING targets only: a NEW_FILE test target is never\r\n * in the baseline set because it does not exist yet, so this check\r\n * must never run on one \u2014 a legitimate first test file would be\r\n * indistinguishable from the suspicious case.\r\n * `checkAutomationIdCoverage` \u2014 AFTER the change, against the AFTER report (post-codegen). The\r\n * stronger of the two: catches inverted placement regardless of\r\n * why it happened, including whatever the first check's loose\r\n * file-matching missed.\r\n *\r\n * Both are TRIPWIRES, not proofs \u2014 same posture as this package's other `*Check.ts` scanners\r\n * (`dependencyCheck.ts`, `scopeCheck.ts`): a minimal heuristic against an arbitrary target repo,\r\n * deliberately erring toward under-flagging (fewer false positives blocking a real run) rather than\r\n * over-flagging, since both are hard-failing checks.\r\n */\r\nexport interface TestPlacementViolation {\r\n file: string;\r\n automationIds: string[];\r\n}\r\n\r\nexport interface TestPlacementCheck {\r\n blocked: boolean;\r\n violations: TestPlacementViolation[];\r\n}\r\n\r\n/** A target's path counts as \"discovered\" if it exactly equals, is a suffix of, or has as a suffix,\r\n * any candidate string the JUnit report produced. Loose on purpose: `classname` is a real file path\r\n * for Vitest and derivable for pytest, but not guaranteed for Jest or Go \u2014 see this file's module\r\n * docblock. A tighter, exact-only match would false-positive on every repo where the report's path\r\n * is relative to a different root than the target's own path. */\r\nfunction isDiscovered(targetPath: string, discoveredFiles: Set<string>): boolean {\r\n const normalized = targetPath.replace(/\\\\/g, \"/\");\r\n for (const candidate of discoveredFiles) {\r\n if (candidate === normalized) return true;\r\n if (candidate.endsWith(normalized) || normalized.endsWith(candidate)) return true;\r\n }\r\n return false;\r\n}\r\n\r\n/**\r\n * `discoveredFiles` is the BASELINE run's `TestSnapshot.discoveredFiles` \u2014 `undefined`/`null`/empty\r\n * all mean \"can't tell,\" and the check no-ops rather than blocking on a question it can't answer\r\n * (no baseline report at all, or one with no file-shaped attribution). A repository producing no\r\n * JUnit report gets no detector \u2014 not a gap here, `readiness-panel`'s existing dry-run warning\r\n * (QUIKTR-1084) is what tells the user to fix that.\r\n */\r\nexport function checkTestPlacement(\r\n targets: PilotTarget[],\r\n discoveredFiles: Set<string> | null | undefined,\r\n): TestPlacementCheck {\r\n if (!discoveredFiles || discoveredFiles.size === 0) return { blocked: false, violations: [] };\r\n\r\n const violations: TestPlacementViolation[] = [];\r\n for (const target of targets) {\r\n if (target.kind !== \"EXISTING\") continue;\r\n if (!target.automationIds || target.automationIds.length === 0) continue;\r\n if (!isDiscovered(target.path, discoveredFiles)) {\r\n violations.push({ file: target.path, automationIds: target.automationIds });\r\n }\r\n }\r\n return { blocked: violations.length > 0, violations };\r\n}\r\n\r\nexport function describeTestPlacementViolations(check: TestPlacementCheck): string {\r\n return check.violations\r\n .map(\r\n (v) =>\r\n `${v.file} claims test case(s) ${v.automationIds.join(\", \")} but the repository's own test runner never discovered this file`,\r\n )\r\n .join(\"; \");\r\n}\r\n\r\nexport interface AutomationCoverageCheck {\r\n blocked: boolean;\r\n missing: string[];\r\n}\r\n\r\n/**\r\n * `discoveredAutomationIds` is the AFTER run's `TestSnapshot.discoveredAutomationIds` \u2014\r\n * `undefined`/`null` means \"can't tell\" (no post-codegen report at all), same no-op posture as\r\n * `checkTestPlacement`. An EMPTY (present) set is different and deliberate: it means a report\r\n * existed but nothing in it carried a bracketed id at all, which \u2014 if this run claimed any\r\n * `automationIds` \u2014 is exactly the failure this check exists to catch, so it blocks.\r\n */\r\nexport function checkAutomationIdCoverage(\r\n targets: PilotTarget[],\r\n discoveredAutomationIds: Set<string> | null | undefined,\r\n): AutomationCoverageCheck {\r\n if (discoveredAutomationIds === null || discoveredAutomationIds === undefined) {\r\n return { blocked: false, missing: [] };\r\n }\r\n\r\n const claimed = new Set<string>();\r\n for (const target of targets) {\r\n for (const id of target.automationIds ?? []) claimed.add(id);\r\n }\r\n const missing = [...claimed].filter((id) => !discoveredAutomationIds.has(id));\r\n return { blocked: missing.length > 0, missing };\r\n}\r\n\r\nexport function describeAutomationCoverageViolations(check: AutomationCoverageCheck): string {\r\n return `test case(s) ${check.missing.join(\", \")} have no matching test discovered in the test run \u2014 generated, but never executed`;\r\n}\r\n", "import { describeQuikTrackFailure } from \"./quiktrackError\";\r\n\r\ninterface TokenExchangeResponse {\r\n success: boolean;\r\n data: { runToken: string; expiresAt: string };\r\n}\r\n\r\n/** Exchange a GitHub OIDC ID token for a QuikPilot run token (QUIKTR-805) \u2014 mirrors `packet.ts`'s\r\n * `fetchPacket` shape: bearer auth, `{success,data}` envelope, same error-message style. */\r\nexport async function exchangeForRunToken(tokenUrl: string, oidcToken: string): Promise<string> {\r\n const res = await fetch(tokenUrl, {\r\n method: \"POST\",\r\n headers: { Authorization: `Bearer ${oidcToken}` },\r\n });\r\n if (!res.ok) {\r\n throw new Error(`Exchange run token failed: ${await describeQuikTrackFailure(res)}`);\r\n }\r\n const body = (await res.json()) as TokenExchangeResponse;\r\n if (body.success !== true) {\r\n throw new Error(\"Exchange run token failed: response did not carry success:true\");\r\n }\r\n return body.data.runToken;\r\n}\r\n", "import type { TestSnapshot } from \"./regressionCheck\";\r\n\r\n/**\r\n * QUIKTR-1448 \u2014 a test that ran before the change and is missing from the final report. The regression gate\r\n * only looks at tests present AFTER, so a rewritten test file that drops tests passes it (QuikSplit PR #4\r\n * lost 9 tests this way). Warn-only: the fix may mean to remove or rename a test, and a user has no way yet\r\n * to approve that, so nothing here blocks a run.\r\n */\r\nexport interface VanishedTests {\r\n /** Test ids (`classname::name`), at most MAX_VANISHED_NAMES. */\r\n names: string[];\r\n /** How many went missing, including any names cut by the cap. */\r\n total: number;\r\n}\r\n\r\n/** Bounds the callback body and the pull request description. */\r\nexport const MAX_VANISHED_NAMES = 50;\r\n\r\n/** Null when nothing is missing, or when either run produced no report (cannot tell \u2014 same posture as\r\n * `checkForRegressions`, which also stays quiet then). A test that still exists and now fails is a\r\n * regression, not a missing test, so it is not named here. */\r\nexport function findVanishedTests(baseline: TestSnapshot, after: TestSnapshot): VanishedTests | null {\r\n if (!baseline.results || !after.results) return null;\r\n const missing = [...baseline.results.keys()].filter((id) => !after.results!.has(id));\r\n if (missing.length === 0) return null;\r\n return { names: missing.slice(0, MAX_VANISHED_NAMES), total: missing.length };\r\n}\r\n\r\n/** The run-event warning. A COUNT only: test titles are the customer's text and the event reason is stored by\r\n * QuikTrack; the titles go to the pull request description instead. */\r\nexport function describeVanishedTests(vanished: VanishedTests): string {\r\n const noun = vanished.total === 1 ? \"1 test\" : `${vanished.total} tests`;\r\n return `${noun} that ran before this change ${vanished.total === 1 ? \"is\" : \"are\"} missing from the final test report; the pull request lists ${vanished.total === 1 ? \"it\" : \"them\"}.`;\r\n}\r\n", "import { reportBack } from \"./callback\";\r\nimport { runCommand, runTestCommand } from \"./commands\";\r\nimport { commitAndPush } from \"./commit\";\r\nimport { buildJudgedByPool, flushCodegenResults, type CodegenFileResult } from \"./codegen\";\r\nimport { resolveCodegenMode } from \"./codegenMode\";\r\nimport type { CodegenLoopRecord } from \"./codegenLoopRecord\";\r\nimport { runCodegenStep } from \"./codegenStep\";\r\nimport {\r\n checkImportDependencies,\r\n describeDependencyViolations,\r\n readDeclaredDependencies,\r\n resolveAliasPrefixes,\r\n} from \"./dependencyCheck\";\r\nimport type { PilotRunEnv } from \"./env\";\r\nimport { checkGuardrail } from \"./guardrail\";\r\nimport { checkoutTargetBranch } from \"./git\";\r\nimport { exchangeForInstallationToken } from \"./installationToken\";\r\nimport { fetchGithubOidcToken } from \"./oidc\";\r\nimport { describeOverlapWarnings, findOverlappingSteps } from \"./overlapCheck\";\r\nimport { fetchPacket, type PilotPacket } from \"./packet\";\r\nimport { writePhase0Marker } from \"./phase0\";\r\nimport { describeUnmatchedAutomationIds, readTestReportBytes, reportToQuikTest } from \"./quiktest\";\r\nimport { runBaselineCheck, type BaselineFindings } from \"./baselineCheck\";\r\nimport { writeFailureArtifact } from \"./failureArtifact\";\r\nimport { describeFailureReason, failureSummary } from \"./failureReason\";\r\nimport { captureBaselineSnapshot, captureTestSnapshot, checkForRegressions, describeRegressions } from \"./regressionCheck\";\r\nimport { checkApiScope, describeScopeViolations } from \"./scopeCheck\";\r\nimport { listWorkspaceFiles, runTargeting, type TargetingResult } from \"./targeting\";\r\nimport { buildTargetingRecord, type CodegenContextRecord } from \"./targetingRecord\";\r\nimport {\r\n checkAutomationIdCoverage,\r\n checkTestPlacement,\r\n describeAutomationCoverageViolations,\r\n describeTestPlacementViolations,\r\n} from \"./testPlacementCheck\";\r\nimport { exchangeForRunToken } from \"./tokenExchange\";\r\nimport { describeVanishedTests, findVanishedTests, type VanishedTests } from \"./vanishedTests\";\r\n\r\n/**\r\n * QUIKTR-572 \u2014 the run sequence, preserving the original inlined workflow's error semantics exactly:\r\n * Fetch packet / Checkout branch / Setup / Lint / Guardrail are hard failures that skip everything\r\n * remaining except the QuikTest report and the final callback (both ran under `if: always()`\r\n * before). Test alone is soft \u2014 its failure never blocks Guardrail/Commit/Push and never flips the\r\n * final callback to `failed` (QuikTest owns per-test outcomes; captured here only for the log).\r\n *\r\n * QUIKTR-1045 \u2014 Format is soft, same reasoning as Test: a formatting hiccup must not block a\r\n * correct fix. Caught locally at its own call site (not a new commands.ts function) and logged;\r\n * never sets hardFailure, never blocks the Lint/regression-check/Guardrail/Commit/Push that follow.\r\n *\r\n * QUIKTR-805 \u2014 the very first thing the run does is exchange a GitHub OIDC ID token for a run\r\n * token (no QuikPilot credential exists before this). It is folded into the same top-level try as\r\n * every other hard failure, with one deliberate exception: if THIS step fails, there is no run\r\n * token to report failure with either, so reportToQuikTest/reportBack are skipped rather than\r\n * called with nothing to authenticate \u2014 the job's own log is the only record, and the run's\r\n * existing DISPATCHING-expiry sweep is what notices it (same accepted fallback dispatch.ts's own\r\n * docblock documents for its \"RESIDUAL WINDOW\" crash case).\r\n *\r\n * QUIKTR-804 \u2014 immediately before pushing, the run token (already in hand by this point) is\r\n * exchanged for a repo-scoped GitHub installation token, which authenticates the push itself\r\n * instead of the ambient `github.token`. Folded into the EXISTING Guardrail/Commit/Push try block\r\n * below rather than given its own \u2014 a failure here is just another commit/push hard failure, with\r\n * no new edge case: unlike the OIDC exchange above, the run token already exists, so\r\n * reportToQuikTest/reportBack fire normally either way.\r\n */\r\n/** Caller narrows `RunnerEnv` to `PilotRunEnv` first \u2014 `index.ts` branches on `mode` before either\r\n * this or `readinessCheck.ts`'s `runReadinessCheck` is invoked. No default parameter: the old\r\n * `readRunnerEnv()` default returned this shape unconditionally, which is no longer true now\r\n * that `RunnerEnv` is a union (QUIKTR-1084). */\r\nexport async function run(env: PilotRunEnv): Promise<{ hardFailure: boolean }> {\r\n let hardFailure = false;\r\n let packet: PilotPacket | undefined;\r\n let branch: string | undefined;\r\n let runToken: string | undefined;\r\n const warnings: string[] = [];\r\n // Why the run failed, for the final callback. The message used to be printed to the job log and lost to\r\n // QuikTrack, which then knew only \"failed\". Scrubbed of credentials and cut before it is kept.\r\n const failureReasons: string[] = [];\r\n const recordFailure = (err: unknown) => {\r\n const message = err instanceof Error ? err.message : String(err);\r\n console.error(message);\r\n // The job log gets the full message; what is reported is the summary when the error quotes the AI Runtime's reply.\r\n const reason = describeFailureReason(failureSummary(err), runToken ? [runToken] : []);\r\n if (reason) failureReasons.push(reason);\r\n };\r\n // QUIKTR-1067 \u2014 hoisted out of the try block's TARGETED branch: commitAndPush\r\n // needs it later, outside that scope, to build a real commit message instead\r\n // of the \"Phase 0 skeleton\" placeholder. Defaults false \u2014 correct for\r\n // NO_TARGET and for any early hard failure, both of which skip commitAndPush\r\n // or must fall back to the marker message anyway.\r\n let targeted = false;\r\n // QUIKTR-1333 \u2014 same hoisting reason as `targeted` above: reportToQuikTest is\r\n // called later, outside the TARGETED branch's scope where `results` lives.\r\n // Empty for NO_TARGET and any early failure \u2014 correct, since nothing was\r\n // written either way.\r\n let generatedFilePaths: string[] = [];\r\n // QUIKTR-1447 \u2014 hoisted for the same reason, so a run that fails AFTER code generation can keep what was generated.\r\n // Held in memory because the dependency, scope and placement checks fail before the files are flushed. The final\r\n // test report is read right after the post-generation test run and nowhere else: a report on disk before that is\r\n // the baseline's, and reportToQuikTest deletes it once sent.\r\n let generatedResults: CodegenFileResult[] = [];\r\n let finalTestReport: Buffer | null = null;\r\n // QUIKTR-1421 \u2014 hoisted for the same reason: the record is built at the end, outside the try, so a run that\r\n // dies in codegen still reports what targeting decided and which context codegen had already assembled.\r\n let targetingResult: TargetingResult | undefined;\r\n // QUIKTR-1402 \u2014 hoisted for the same reason: reported at the end, outside the try. Undefined when the check\r\n // did not run or flagged nothing.\r\n let baselineFindings: BaselineFindings | undefined;\r\n // QUIKTR-1448 \u2014 hoisted for the same reason: reported at the end, and it must survive a run that then fails on a\r\n // regression. Undefined when no test went missing or a report was not available.\r\n let vanishedTests: VanishedTests | undefined;\r\n const contextLog: CodegenContextRecord[] = [];\r\n // QUIKTR-1458 \u00A724 \u2014 what the code-writing loop did, when it ran or was tried. Hoisted so it is reported even when the run then fails.\r\n const codegenOut: { loop?: CodegenLoopRecord } = {};\r\n\r\n try {\r\n runToken = await exchangeForRunToken(env.tokenUrl, await fetchGithubOidcToken());\r\n packet = await fetchPacket(env.packetUrl, runToken, env.githubRunId);\r\n checkoutTargetBranch(packet.targetBranch);\r\n\r\n const workspaceListing = listWorkspaceFiles(packet.workspaceRoot);\r\n // QUIKTR-1401 (\u00A720) \u2014 the reviewer's approved \"must not change\" list, with blank entries dropped. A QuikTrack\r\n // that predates the field sends none, which is the same as an empty list.\r\n const outOfScope = (packet.outOfScope ?? []).map((entry) => entry.trim()).filter((entry) => entry.length > 0);\r\n const targeting = await runTargeting(\r\n packet.gateway,\r\n packet.design,\r\n packet.workspaceRoot,\r\n workspaceListing,\r\n packet.requiredTests,\r\n packet.guardrails.deniedPaths,\r\n packet.testDiscovery,\r\n outOfScope,\r\n );\r\n targetingResult = targeting;\r\n // QUIKTR-1458 \u2014 the read-only loop could not finish and the single call was used instead. Not blocking, but\r\n // said out loud: it changes what the AI was shown, and a run that quietly stopped using the loop would make\r\n // every comparison between the two modes meaningless.\r\n for (const w of targeting.warnings ?? []) {\r\n warnings.push(w);\r\n console.warn(`QuikPilot targeting warning (not blocking): ${w}`);\r\n }\r\n // QUIKTR-1448 \u2014 targeting called an existing file a new one; runTargeting already treated it as existing, so the\r\n // model saw its content. Said out loud because it is a mistake in the plan, not something to hide.\r\n if (targeting.outcome === \"TARGETED\") {\r\n for (const path of targeting.correctedKinds ?? []) {\r\n const w = `QuikPilot named ${path} as a new file, but it already exists in the repository. It was treated as an existing file so its current content was kept in view.`;\r\n warnings.push(w);\r\n console.warn(`QuikPilot targeting warning (not blocking): ${w}`);\r\n console.log(JSON.stringify({ event: \"targeting.kind_corrected\", path }));\r\n }\r\n }\r\n if (targeting.outcome === \"NO_TARGET\") {\r\n // Nothing to write \u2014 a marker commit is more honest than an empty one. Nothing was\r\n // generated, so there's nothing to regress against \u2014 Test stays soft, unchanged.\r\n writePhase0Marker(env.runId);\r\n runCommand(packet.commands.setup, \"Setup\");\r\n runCommand(packet.commands.lint, \"Lint\");\r\n runTestCommand(packet.commands.test);\r\n } else {\r\n targeted = true;\r\n // QUIKTR-1083 (\u00A715.3) \u2014 informational, never blocking: a case with no given/when/then has\r\n // nothing to test, and the runtime already enforces every requiredTests case lands in\r\n // exactly one of a target's automationIds or here, never both, never neither. Folded into\r\n // the same warnings array the overlap-check below already populates and reportBack sends.\r\n if (targeting.skippedCases?.length) {\r\n for (const skipped of targeting.skippedCases) {\r\n const w = `Test case ${skipped.automationId} has no given/when/then \u2014 skipped, no test was written for it.`;\r\n warnings.push(w);\r\n console.warn(`QuikPilot targeting warning (not blocking): ${w}`);\r\n }\r\n }\r\n // QUIKTR-1064 \u2014 cheap: two targets whose planStepsImplemented describe the same rule (the\r\n // real fix is pilot.targeting's prompt, an AI Runtime change, not this package's \u2014 see\r\n // overlapCheck.ts). QUIKTR-1081 \u2014 a literal identical instruction now blocks outright: two\r\n // legitimate halves of one change never share the exact same instruction, and PR #23 merged\r\n // 28 seconds after opening on exactly this signal. A near-identical, reworded pair stays a\r\n // non-blocking warning, logged and reported back, same as before.\r\n const overlaps = findOverlappingSteps(targeting.targets);\r\n const blockingOverlaps = overlaps.filter((o) => o.severity === \"identical\");\r\n const softOverlaps = overlaps.filter((o) => o.severity === \"similar\");\r\n if (softOverlaps.length > 0) {\r\n const overlapWarnings = describeOverlapWarnings(softOverlaps);\r\n warnings.push(...overlapWarnings);\r\n for (const w of overlapWarnings) {\r\n console.warn(`QuikPilot targeting warning (not blocking): ${w}`);\r\n }\r\n }\r\n if (blockingOverlaps.length > 0) {\r\n throw new Error(\r\n `QuikPilot's generated plan gives two files identical instructions \u2014 ${describeOverlapWarnings(blockingOverlaps).join(\"; \")}`,\r\n );\r\n }\r\n\r\n // QUIKTR-1036 \u2014 Setup moves here (was after codegen/flush): the baseline test needs\r\n // dependencies installed, but has to run against the PRE-codegen tree. Installing\r\n // dependencies doesn't depend on which application source files exist, so this is safe, and\r\n // running Setup a second time later would undercut \"the baseline costs almost no wall-clock.\"\r\n runCommand(packet.commands.setup, \"Setup\");\r\n\r\n // \u00A718 \u2014 built once, from every case claimed by any target in the run, minus the\r\n // NO_BEHAVIOUR skips above. Sent only to code targets (codegen.ts's own else-branch);\r\n // targeting.skippedCases is the same list already folded into warnings just above.\r\n const judgedByPool = buildJudgedByPool(\r\n packet.requiredTests,\r\n targeting.targets,\r\n targeting.skippedCases ?? [],\r\n );\r\n\r\n // Baseline runs concurrently with codegen's network-bound calls \u2014 codegen writes nothing\r\n // until flushCodegenResults, so there's nothing for the baseline to race against.\r\n const [baseline, results] = await Promise.all([\r\n captureBaselineSnapshot(packet.commands.test),\r\n runCodegenStep({\r\n mode: resolveCodegenMode(),\r\n gateway: packet.gateway,\r\n targets: targeting.targets,\r\n workspaceListing,\r\n requiredTests: packet.requiredTests,\r\n deniedPaths: packet.guardrails.deniedPaths,\r\n judgedByPool,\r\n warnings,\r\n contextLog,\r\n outOfScope,\r\n testDiscovery: packet.testDiscovery,\r\n skippedCases: targeting.skippedCases ?? [],\r\n out: codegenOut,\r\n }),\r\n ]);\r\n\r\n generatedResults = results;\r\n\r\n // QUIKTR-1045 \u2014 checked on the in-memory results, BEFORE anything is\r\n // written: an invented import is never written to disk at all, matching\r\n // the same all-or-nothing treatment every other codegen failure already\r\n // gets here. Hard failure \u2014 a generation that imports a package this\r\n // repository doesn't have can't be trusted.\r\n const depCheck = checkImportDependencies(\r\n results,\r\n readDeclaredDependencies(results, packet.workspaceRoot),\r\n resolveAliasPrefixes(results, packet.workspaceRoot),\r\n );\r\n if (depCheck.blocked) {\r\n throw new Error(\r\n `QuikPilot's generated code imports packages this repository doesn't have \u2014 ${describeDependencyViolations(depCheck)}`,\r\n );\r\n }\r\n\r\n // QUIKTR-1081 \u2014 QUIKSPL-5's PR #22: codegen added an undeclared PUT endpoint alongside the\r\n // fix nobody asked for. Checked here for the same reason as the dependency check above \u2014\r\n // in-memory, before anything is written \u2014 against the design's own declared apiChanges.\r\n const scopeCheck = checkApiScope(results, targeting.targets, packet.design?.apiChanges ?? []);\r\n if (scopeCheck.blocked) {\r\n throw new Error(\r\n `QuikPilot's generated code exceeds the approved design \u2014 ${describeScopeViolations(scopeCheck)}`,\r\n );\r\n }\r\n\r\n // QUIKTR-1315 \u2014 same \"in-memory results, before anything is written\" point as the two checks\r\n // above: a test case claimed against a source-file target instead of the real test file has\r\n // zero coverage even though its id is present, and nothing else here catches that. Uses the\r\n // BASELINE run's JUnit report (already captured above) as the ground truth for which files\r\n // the test runner actually discovers \u2014 never the workspace listing, which includes files the\r\n // runner never looks at.\r\n const placementCheck = checkTestPlacement(targeting.targets, baseline.discoveredFiles);\r\n if (placementCheck.blocked) {\r\n throw new Error(\r\n `QuikPilot's generated tests are not where the test runner will find them \u2014 ${describeTestPlacementViolations(placementCheck)}`,\r\n );\r\n }\r\n\r\n // QUIKTR-1402 \u2014 run the generated tests alone on the still-untouched tree and flag a non-Regression\r\n // case that already passes there. After the in-memory checks above (no point spending the time on a\r\n // run that is about to fail) and before the flush (the code files are still the originals). Flag-only:\r\n // it never throws out of here, and a surprise from it must not cost the run.\r\n try {\r\n const baselineCheck = await runBaselineCheck({\r\n targets: targeting.targets,\r\n results,\r\n testFileCmd: packet.commands.testFile,\r\n requiredTestTypes: packet.requiredTestTypes,\r\n });\r\n warnings.push(...baselineCheck.warnings);\r\n baselineFindings = baselineCheck.findings ?? undefined;\r\n } catch (err) {\r\n const message = `Baseline check could not run: ${err instanceof Error ? err.message : String(err)}`;\r\n console.error(message);\r\n warnings.push(message);\r\n }\r\n\r\n // QUIKTR-1333 \u2014 the files QuikPilot actually generated or edited this run, exactly what\r\n // reportToQuikTest's generatedFiles param needs to scope the unmatched-id warning. runCodegen\r\n // is all-or-nothing, so by this point `results` is the complete, successful set \u2014 nothing\r\n // extra needed from targeting.targets.\r\n generatedFilePaths = results.map((r) => r.targetPath);\r\n\r\n flushCodegenResults(results);\r\n try {\r\n runCommand(packet.commands.format, \"Format\");\r\n } catch (err) {\r\n // QUIKTR-1045 \u2014 soft, like Test: see the file docblock.\r\n console.error(`Format failed (not blocking): ${err instanceof Error ? err.message : String(err)}`);\r\n }\r\n runCommand(packet.commands.lint, \"Lint\");\r\n\r\n const after = captureTestSnapshot(packet.commands.test);\r\n finalTestReport = readTestReportBytes();\r\n // QUIKTR-1448 \u2014 before the regression throw below, so a run that then fails still reports it. Warn-only.\r\n vanishedTests = findVanishedTests(baseline, after) ?? undefined;\r\n if (vanishedTests) {\r\n const w = describeVanishedTests(vanishedTests);\r\n warnings.push(w);\r\n console.warn(`QuikPilot test warning (not blocking): ${w}`);\r\n }\r\n const check = checkForRegressions(baseline, after);\r\n if (check.blocked) {\r\n throw new Error(\r\n `QuikPilot's generated code introduced test failures \u2014 ${describeRegressions(check)}`,\r\n );\r\n }\r\n\r\n // QUIKTR-1315 \u2014 the stronger of the two placement checks: run against the REAL, post-codegen\r\n // JUnit report, so it catches inverted placement regardless of why it happened, including\r\n // whatever checkTestPlacement's baseline-only, loose file-matching missed above.\r\n const coverageCheck = checkAutomationIdCoverage(targeting.targets, after.discoveredAutomationIds);\r\n if (coverageCheck.blocked) {\r\n throw new Error(\r\n `QuikPilot's generated tests were not executed \u2014 ${describeAutomationCoverageViolations(coverageCheck)}`,\r\n );\r\n }\r\n }\r\n } catch (err) {\r\n hardFailure = true;\r\n recordFailure(err);\r\n }\r\n\r\n if (!runToken) {\r\n console.error(\"No run token \u2014 the OIDC exchange failed before QuikTrack could be reached.\");\r\n return { hardFailure: true };\r\n }\r\n\r\n const quikTestReport = await reportToQuikTest({\r\n resultsUrl: packet?.quikTest?.resultsUrl,\r\n runToken,\r\n githubServerUrl: env.githubServerUrl,\r\n githubRepository: env.githubRepository,\r\n githubRunId: env.githubRunId,\r\n generatedFiles: generatedFilePaths,\r\n });\r\n // QUIKTR-1374 \u2014 the ingest response already knows which generated automationIds matched no\r\n // test case; read it and surface it here instead of letting it disappear once reportToQuikTest\r\n // returns. Reuses the same warnings -> reportBack path QUIKTR-1064's overlap detection already\r\n // uses, which QuikTrack folds into the run's own event timeline \u2014 no new plumbing.\r\n const unmatchedWarning = quikTestReport ? describeUnmatchedAutomationIds(quikTestReport.unmatched) : null;\r\n if (unmatchedWarning) {\r\n warnings.push(unmatchedWarning);\r\n console.warn(`QuikPilot ingest warning (not blocking): ${unmatchedWarning}`);\r\n }\r\n\r\n if (!hardFailure && packet) {\r\n try {\r\n checkGuardrail(packet.guardrails.deniedPaths);\r\n const installationToken = await exchangeForInstallationToken(\r\n env.installationTokenUrl,\r\n runToken,\r\n );\r\n const result = commitAndPush(\r\n packet.branch,\r\n env.runId,\r\n installationToken,\r\n targeted,\r\n packet.issueKey,\r\n packet.issueTitle,\r\n );\r\n branch = result.branch;\r\n } catch (err) {\r\n hardFailure = true;\r\n recordFailure(err);\r\n }\r\n }\r\n\r\n // QUIKTR-1447 \u2014 before the callback, so it exists whether or not the callback succeeds. Only for a run that got as far\r\n // as generating files, and never allowed to change how the run ends.\r\n if (hardFailure && generatedResults.length > 0) {\r\n try {\r\n writeFailureArtifact({\r\n cwd: process.cwd(),\r\n runId: env.runId,\r\n issueKey: packet?.issueKey ?? null,\r\n targets: targetingResult?.outcome === \"TARGETED\" ? targetingResult.targets : [],\r\n results: generatedResults,\r\n testReport: finalTestReport,\r\n failureReasons,\r\n secrets: runToken ? [runToken] : [],\r\n });\r\n } catch (err: unknown) {\r\n console.warn(`::warning::Could not keep the failed run's files: ${err instanceof Error ? err.message : String(err)}`);\r\n }\r\n }\r\n\r\n await reportBack({\r\n callbackUrl: env.callbackUrl,\r\n runToken,\r\n status: hardFailure ? \"failed\" : \"completed\",\r\n branch,\r\n warnings,\r\n // Omitted when targeting itself never produced a result (nothing exists to record).\r\n targeting: targetingResult ? buildTargetingRecord(targetingResult, contextLog) : undefined,\r\n baselineFindings,\r\n vanishedTests,\r\n codegenLoop: codegenOut.loop,\r\n unresolved: failureReasons.length > 0 ? failureReasons : undefined,\r\n });\r\n\r\n return { hardFailure };\r\n}\r\n", "import type { ReadinessCheckEnv } from \"./env\";\r\nimport { runCommand, runTestCommand } from \"./commands\";\r\nimport { findJUnitReport } from \"./quiktest\";\r\nimport { describeQuikTrackFailure } from \"./quiktrackError\";\r\n\r\n/**\r\n * QUIKTR-1084 \u2014 readiness's \"later session\": actually run the customer's `setupCmd`/`testCmd` and\r\n * report whether the run produced a JUnit report the pilot-run path (`quiktest.ts`) will ever\r\n * find. Checked out onto the default branch already by the workflow's own `actions/checkout` step\r\n * \u2014 no packet, no design, no codegen, no commit, no push.\r\n *\r\n * Both command failures are soft here, deliberately unlike `run.ts`'s hard-fails-on-Setup: a\r\n * repo's setup or test suite failing is not what this check is FOR \u2014 it exists purely to answer\r\n * \"if a real run happened, would QuikTest hear about it,\" which only needs the report to exist,\r\n * not the tests to pass.\r\n */\r\nexport interface ReadinessCheckResult {\r\n setupOk: boolean;\r\n testOk: boolean;\r\n junitFound: boolean;\r\n junitPath: string | null;\r\n}\r\n\r\nexport async function runReadinessCheck(env: ReadinessCheckEnv): Promise<void> {\r\n let setupOk = true;\r\n try {\r\n runCommand(env.setupCmd || null, \"Setup\");\r\n } catch (err) {\r\n setupOk = false;\r\n console.error(err instanceof Error ? err.message : String(err));\r\n }\r\n\r\n const testOutcome = runTestCommand(env.testCmd);\r\n const testOk = testOutcome === \"success\";\r\n\r\n const junitPath = findJUnitReport();\r\n const result: ReadinessCheckResult = {\r\n setupOk,\r\n testOk,\r\n junitFound: junitPath !== null,\r\n junitPath,\r\n };\r\n\r\n try {\r\n const res = await fetch(env.readinessCallbackUrl, {\r\n method: \"POST\",\r\n headers: { Authorization: `Bearer ${env.readinessToken}`, \"Content-Type\": \"application/json\" },\r\n body: JSON.stringify(result),\r\n });\r\n if (!res.ok) {\r\n throw new Error(`Readiness callback POST failed: ${await describeQuikTrackFailure(res)}`);\r\n }\r\n } catch (err) {\r\n // Same \"never throws\" posture as reportToQuikTest/reportBack \u2014 the job's own log is the\r\n // fallback record if even this fails. The expiry sweep readiness.ts will need (mirroring\r\n // dispatch.ts's DISPATCHING-expiry sweep) is what notices a dry run stuck in RUNNING.\r\n console.warn(\r\n `::warning::QuikPilot readiness check failed to report its result: ${err instanceof Error ? err.message : String(err)}`,\r\n );\r\n }\r\n}\r\n", "import { readRunnerEnv } from \"./env\";\r\nimport { run } from \"./run\";\r\nimport { runReadinessCheck } from \"./readinessCheck\";\r\n\r\nconst env = readRunnerEnv();\r\n\r\n// QUIKTR-1084 \u2014 narrows the RunnerEnv union before either branch runs; run()/runReadinessCheck()\r\n// each take only their own variant, not the union, so this `if` is what makes that safe.\r\nconst task =\r\n env.mode === \"readiness_check\"\r\n ? runReadinessCheck(env).then(() => ({ hardFailure: false }))\r\n : run(env);\r\n\r\ntask\r\n .then(({ hardFailure }) => {\r\n process.exitCode = hardFailure ? 1 : 0;\r\n })\r\n .catch((err) => {\r\n // reportBack/the readiness callback itself throwing is the one failure mode neither branch can\r\n // recover from internally \u2014 still exit non-zero so the raw Actions UI shows the run as failed.\r\n console.error(err instanceof Error ? err.message : String(err));\r\n process.exitCode = 1;\r\n });\r\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,gDAAAA,UAAA;AA2BA,KAAC,SAAS,MAAMA,UAAS;AACrB;AAEA,UAAIC,SACA,eACA,aACA,OACA,MACA;AAEJ,eAAS,SAAS,KAAK;AACnB,YAAI,MAAM,CAAC,GAAG,KAAK;AACnB,aAAK,OAAO,KAAK;AACb,cAAI,IAAI,eAAe,GAAG,GAAG;AACzB,kBAAM,IAAI,GAAG;AACb,gBAAI,OAAO,QAAQ,YAAY,QAAQ,MAAM;AACzC,kBAAI,GAAG,IAAI,SAAS,GAAG;AAAA,YAC3B,OAAO;AACH,kBAAI,GAAG,IAAI;AAAA,YACf;AAAA,UACJ;AAAA,QACJ;AACA,eAAO;AAAA,MACX;AAKA,eAAS,WAAW,OAAO,MAAM;AAC7B,YAAI,MAAM,KAAKC,IAAGC;AAElB,cAAM,MAAM;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,OAAO;AAAA,EAC1C,SAAS,KAAK;AACZ,cAAU;AACV,YAAQ,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,EAChE;AAEA,QAAM,cAAc,eAAeA,KAAI,OAAO;AAC9C,QAAM,SAAS,gBAAgB;AAE/B,QAAM,YAAY,gBAAgB;AAClC,QAAM,SAA+B;AAAA,IACnC;AAAA,IACA;AAAA,IACA,YAAY,cAAc;AAAA,IAC1B;AAAA,EACF;AAEA,MAAI;AACF,UAAM,MAAM,MAAM,MAAMA,KAAI,sBAAsB;AAAA,MAChD,QAAQ;AAAA,MACR,SAAS,EAAE,eAAe,UAAUA,KAAI,cAAc,IAAI,gBAAgB,mBAAmB;AAAA,MAC7F,MAAM,KAAK,UAAU,MAAM;AAAA,IAC7B,CAAC;AACD,QAAI,CAAC,IAAI,IAAI;AACX,YAAM,IAAI,MAAM,mCAAmC,MAAM,yBAAyB,GAAG,CAAC,EAAE;AAAA,IAC1F;AAAA,EACF,SAAS,KAAK;AAIZ,YAAQ;AAAA,MACN,qEAAqE,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,IACvH;AAAA,EACF;AACF;;;ACxDA,IAAM,MAAM,cAAc;AAI1B,IAAM,OACJ,IAAI,SAAS,oBACT,kBAAkB,GAAG,EAAE,KAAK,OAAO,EAAE,aAAa,MAAM,EAAE,IAC1D,IAAI,GAAG;AAEb,KACG,KAAK,CAAC,EAAE,YAAY,MAAM;AACzB,UAAQ,WAAW,cAAc,IAAI;AACvC,CAAC,EACA,MAAM,CAAC,QAAQ;AAGd,UAAQ,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAC9D,UAAQ,WAAW;AACrB,CAAC;",
|
|
6
|
+
"names": ["exports", "Syntax", "i", "current", "Reference", "replace", "ref", "result", "path", "traverse", "current2", "element", "key", "comment", "exports", "module", "exports", "estraverse", "i", "env", "resolve", "import_node_child_process", "import_node_path", "i", "i", "relative", "sibling", "path", "attempt", "path", "whole", "env", "import_node_fs", "i", "i", "join", "i", "i", "TokenType", "Position", "SourceLocation", "offset", "Parser", "parse", "ref", "DestructuringErrors", "list", "ecmaVersion", "TokContext", "Scope", "Node", "BranchID", "RegExpValidationState", "current", "Token", "parse", "import_assert", "estraverse", "i", "Scope", "ref", "current", "assert", "import_assert", "i", "assert", "import_estraverse", "import_esrecurse", "import_estraverse", "Syntax", "estraverse", "esrecurse", "i", "import_assert", "Syntax", "estraverse", "esrecurse", "i", "assert", "defaultOptions", "assert", "estraverse", "i", "offset", "ref", "at", "i", "import_node_path", "i", "import_node_fs", "import_node_path", "i", "env", "at", "import_node_fs", "import_node_path", "current", "hasNul", "i", "bad", "env", "i", "isPlainObject", "env", "at", "MAX_ID_CHARS", "MAX_CALLS_IN_A_REPLY", "TOOL_NAMES", "isPlainObject", "classifyTransport", "env", "i", "import_node_fs", "import_node_path", "i", "env", "import_node_fs", "import_node_fs", "import_node_path", "readFileSync", "import_node_child_process", "import_node_fs", "import_node_path", "import_node_fs", "isTestTarget", "types", "list", "import_node_fs", "import_node_path", "import_node_fs", "import_node_path", "parse", "env", "CONTRACT_VERSION", "MAX_PATH_CHARS", "MAX_ID_CHARS", "record", "env", "env"]
|
|
7
7
|
}
|