Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.
TypeScript ai-agentsanthropicclaude-codeclicode-graphcodexcontext-engineeringcursordeveloper-toolsgeminiknowledge-graphllmmcpmcp-serveropen-sourceopenaitree-sitter
test: escape regex and generated-code strings properly (CodeQL)
Shrish Dwivedifdd4cb182709
diff --git a/test/claude-shim-resolve.test.ts b/test/claude-shim-resolve.test.tsindex 6be454b7..b57c6d00 100644--- a/test/claude-shim-resolve.test.ts+++ b/test/claude-shim-resolve.test.ts@@ -21,6 +21,7 @@ import { createHash } from 'node:crypto';import { hooksShim, installHintPath, rememberInstall } from '../src/claude/shim-template.js';import { learningId } from '../src/notes/learning-fields.js';import { tmpRepo } from './helpers.js';+import { jsLit } from './escape.js';/** A fake installed @nanonets/graft whose hooks entry records that it ran. */function fakeInstall(root: string, name: string, version: string): string {@@ -32,7 +33,7 @@ function fakeInstall(root: string, name: string, version: string): string {// `m.main(...)` resolves — same shape the real dist has for the shim's call.writeFileSync(join(distClaude, 'hooks.js'),- `module.exports.main = () => require('node:fs').writeFileSync(process.env.MARKER, ${JSON.stringify(version)});\n`,+ `module.exports.main = () => require('node:fs').writeFileSync(process.env.MARKER, ${jsLit(version)});\n`,);return distClaude;}@@ -71,7 +72,7 @@ function fakeInstall(root: string, name: string, version: string): string {function isolate(root: string, extraPath: string[] = []): { preload: string; env: NodeJS.ProcessEnv } {const preload = join(root, 'no-ambient-graft.cjs');const execPath = join(root, 'node-prefix', 'bin', 'node');- writeFileSync(preload, `Object.defineProperty(process, 'execPath', { value: ${JSON.stringify(execPath)}, configurable: true });\n`);+ writeFileSync(preload, `Object.defineProperty(process, 'execPath', { value: ${jsLit(execPath)}, configurable: true });\n`);const prefix = join(root, 'npm-prefix');mkdirSync(prefix, { recursive: true });const ambient = (d: string) => ['trail', 'graft', 'trail.cmd', 'graft.cmd'].some((b) => existsSync(join(d, b)));diff --git a/test/escape.ts b/test/escape.tsnew file mode 100644index 00000000..e4eb1454--- /dev/null+++ b/test/escape.ts@@ -0,0 +1,8 @@+// Escaping for strings a test builds into a regex or into generated code.++/** A string matched literally inside a RegExp. */+export const escapeRe = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");++/** A value as a JS literal that is safe to splice into generated source. */+export const jsLit = (v: unknown): string =>+ JSON.stringify(v).replace(/[<>\/\u2028\u2029]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);diff --git a/test/init-name-call.test.ts b/test/init-name-call.test.tsindex 2ea7af1c..7be7826b 100644--- a/test/init-name-call.test.ts+++ b/test/init-name-call.test.ts@@ -12,6 +12,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { applyName, nameItems, nameLine, validName } from "../src/init/name-call.js";import { compiled, skillCandidate } from "./init-screen-fixtures.js";+import { jsLit } from "./escape.js";const TYPED = ["always publish with the beta tag first", "explain it simply, one example first"];const HOWTO = "To publish: npm version patch, npm publish, then npm view acme-cli version.";@@ -22,10 +23,10 @@ function standIn(answer: unknown, opts: { fail?: string } = {}): { bin: string;writeFileSync(join(bin, "claude"), ["#!/usr/bin/env node",`const fs = require("fs");`,- `if (process.argv.includes("--version")) { fs.appendFileSync(${JSON.stringify(join(bin, "version-calls"))}, "v\\n"); console.log("9.9.9"); process.exit(0); }`,- `fs.appendFileSync(${JSON.stringify(join(bin, "calls"))}, "-p\\n");`,- `fs.writeFileSync(${JSON.stringify(join(bin, "args"))}, JSON.stringify(process.argv));`,- `let s = ""; process.stdin.on("data", (b) => (s += b)); process.stdin.on("end", () => { fs.writeFileSync(${JSON.stringify(join(bin, "sent"))}, s); console.log(${JSON.stringify(out)}); process.exit(${opts.fail ? 1 : 0}); });`,+ `if (process.argv.includes("--version")) { fs.appendFileSync(${jsLit(join(bin, "version-calls"))}, "v\\n"); console.log("9.9.9"); process.exit(0); }`,+ `fs.appendFileSync(${jsLit(join(bin, "calls"))}, "-p\\n");`,+ `fs.writeFileSync(${jsLit(join(bin, "args"))}, JSON.stringify(process.argv));`,+ `let s = ""; process.stdin.on("data", (b) => (s += b)); process.stdin.on("end", () => { fs.writeFileSync(${jsLit(join(bin, "sent"))}, s); console.log(${jsLit(out)}); process.exit(${opts.fail ? 1 : 0}); });`,].join("\n"));chmodSync(join(bin, "claude"), 0o755);return {diff --git a/test/init-name-review.test.ts b/test/init-name-review.test.tsindex cc21010d..a2ac4451 100644--- a/test/init-name-review.test.ts+++ b/test/init-name-review.test.ts@@ -11,6 +11,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { nameItems, nameLine } from "../src/init/name-call.js";import { compiled, skillCandidate } from "./init-screen-fixtures.js";+import { jsLit } from "./escape.js";const TYPED = ["always publish with the beta tag first", "explain it simply, one example first"];const HOWTO = "To publish: npm version patch, npm publish, then npm view acme-cli version.";@@ -21,10 +22,10 @@ function standIn(answer: unknown, opts: { fail?: string; sleepMs?: number; stderwriteFileSync(join(bin, "claude"), ["#!/usr/bin/env node",`const fs = require("fs");`,- `if (process.argv.includes("--version")) { fs.appendFileSync(${JSON.stringify(join(bin, "version-calls"))}, "v\\n"); console.log("9.9.9"); process.exit(0); }`,- `fs.appendFileSync(${JSON.stringify(join(bin, "calls"))}, "-p\\n");`,- `fs.writeFileSync(${JSON.stringify(join(bin, "args"))}, JSON.stringify(process.argv));`,- `let s = ""; process.stdin.on("data", (b) => (s += b)); process.stdin.on("end", () => setTimeout(() => { fs.writeFileSync(${JSON.stringify(join(bin, "sent"))}, s); process.stderr.write(${JSON.stringify(opts.stderr ?? "")}); console.log(${JSON.stringify(out)}); process.exit(${opts.fail ? 1 : 0}); }, ${opts.sleepMs ?? 0}));`,+ `if (process.argv.includes("--version")) { fs.appendFileSync(${jsLit(join(bin, "version-calls"))}, "v\\n"); console.log("9.9.9"); process.exit(0); }`,+ `fs.appendFileSync(${jsLit(join(bin, "calls"))}, "-p\\n");`,+ `fs.writeFileSync(${jsLit(join(bin, "args"))}, JSON.stringify(process.argv));`,+ `let s = ""; process.stdin.on("data", (b) => (s += b)); process.stdin.on("end", () => setTimeout(() => { fs.writeFileSync(${jsLit(join(bin, "sent"))}, s); process.stderr.write(${jsLit(opts.stderr ?? "")}); console.log(${jsLit(out)}); process.exit(${opts.fail ? 1 : 0}); }, ${opts.sleepMs ?? 0}));`,].join("\n"));chmodSync(join(bin, "claude"), 0o755);return {diff --git a/test/init-run.test.ts b/test/init-run.test.tsindex 10d683a9..0473046f 100644--- a/test/init-run.test.ts+++ b/test/init-run.test.ts@@ -18,6 +18,7 @@ import { RELAY_LINE } from "../src/init/relay.js";import { repoPlace } from "../src/notes/home.js";import type { PsRow } from "../src/skills/person.js";import { day, done, releaseJob, Tx, world, type World } from "./init-mine-fixtures.js";+import { jsLit } from "./escape.js";const ME = 4242;/** A process table with no claude and no pty wrapper above this process, or with one. */@@ -75,9 +76,9 @@ function standIn(): { bin: string; calls: () => number; versions: () => booleanwriteFileSync(join(bin, "claude"), ["#!/usr/bin/env node",`const fs = require("fs");`,- `if (process.argv.includes("--version")) { fs.appendFileSync(${JSON.stringify(join(bin, "version-calls"))}, "v\\n"); console.log("9.9.9"); process.exit(0); }`,- `fs.appendFileSync(${JSON.stringify(join(bin, "calls"))}, "-p\\n");`,- `process.stdin.resume(); process.stdin.on("end", () => { const s = ${JSON.stringify(answer)}; console.log(s); });`,+ `if (process.argv.includes("--version")) { fs.appendFileSync(${jsLit(join(bin, "version-calls"))}, "v\\n"); console.log("9.9.9"); process.exit(0); }`,+ `fs.appendFileSync(${jsLit(join(bin, "calls"))}, "-p\\n");`,+ `process.stdin.resume(); process.stdin.on("end", () => { const s = ${jsLit(answer)}; console.log(s); });`,].join("\n"));chmodSync(join(bin, "claude"), 0o755);return {diff --git a/test/init-screen.test.ts b/test/init-screen.test.tsindex 6c0da733..b21e3709 100644--- a/test/init-screen.test.ts+++ b/test/init-screen.test.ts@@ -9,6 +9,7 @@ import assert from "node:assert/strict";import { pickFive } from "../src/init/candidates.js";import { afterKeepLines, numbered, relayLines, screenLines, yesLine } from "../src/init/review-screen.js";import { KEEP_LINE, RELAY_LINE } from "../src/init/relay.js";+import { escapeRe } from "./escape.js";import type { InitCandidate } from "../src/init/types.js";import { factsOf, guardrailCandidate, prefCandidate, skillCandidate, threeItems } from "./init-screen-fixtures.js";@@ -63,7 +64,7 @@ test("the agent's relay (J02): from Trail, RELAY_LINE and KEEP_LINE word for wor"Trail checks the numbers the person typed in this session before it keeps anything, so run trail keep only with the numbers they typed.",]);const text = lines.join("\n");- assert.equal(text.match(new RegExp(RELAY_LINE.replace(/[.]/g, "\\.")), "g")?.length, 1, "once");+ assert.equal(text.match(new RegExp(escapeRe(RELAY_LINE)), "g")?.length, 1, "once");assert.doesNotMatch(text, /\b(?:pick|choose|recommend|whatever looks useful)\b(?! for them)/i, "never tells the agent to choose");assert.doesNotMatch(text, WORDS);});diff --git a/test/skills-probes-init-paths-1b.test.ts b/test/skills-probes-init-paths-1b.test.tsindex eebffdb8..8ff2597f 100644--- a/test/skills-probes-init-paths-1b.test.ts+++ b/test/skills-probes-init-paths-1b.test.ts@@ -158,7 +158,7 @@ test("a real trail init: its files read clean until the person edits one", () =>assert.deepEqual(Object.keys(rec ?? {}).sort(), [".claude/settings.json", ".claude/settings.local.json", ".trail/.gitignore", ".trail/README.md", ".trail/hook.cjs", ".trail/statusline.cjs"]);assert.equal(clean(b)?.ok, true);const settings = join(b.repo, ".claude", "settings.json");- writeFileSync(settings, readFileSync(settings, "utf8").replace("{", '{\n "model": "opus",'));+ writeFileSync(settings, readFileSync(settings, "utf8").replace(/^\{/, '{\n "model": "opus",'));assert.equal(clean(b)?.ok, false);});diff --git a/test/trail-note-replaces.test.ts b/test/trail-note-replaces.test.tsindex 832790b6..6117cb77 100644--- a/test/trail-note-replaces.test.ts+++ b/test/trail-note-replaces.test.ts@@ -13,6 +13,7 @@ import { join } from "node:path";import { learningId, newLearningId } from "../src/notes/learning-fields.js";import { parseNote } from "../src/notes/notes.js";import { homeEnv, tmpRepo } from "./helpers.js";+import { escapeRe } from "./escape.js";const OLD_NAME = "2026-10-08-keep-the-default-retry-count-at-maya.md";const OLD = `---\ntitle: "Keep the default retry count at 4"\nauthor: Maya\ndate: 2026-10-08\ntouches:\n - client.go\n---\n\n## Decided\n- Keep defaultRetryMax = 4: ten retries can hold one call for an hour.\n`;@@ -53,7 +54,7 @@ test("a learning saved with --replaces names the old one, says its own id and whassert.equal(written.replaces, oldId);assert.equal(written.src, "agent", "trail note is how an agent saves");assert.match(saved.out, new RegExp(`^· id ${written.id}$`, "m"));- assert.match(saved.out, new RegExp(`^· takes over from ${OLD_NAME.replace(/\./g, "\\.")}, which stays as the record$`, "m"));+ assert.match(saved.out, new RegExp(`^· takes over from ${escapeRe(OLD_NAME)}, which stays as the record$`, "m"));assert.equal(readFileSync(join(repo, ".trail", "learnings", OLD_NAME), "utf8"), OLD, "the old learning is left as written");const ask = run(["ask", "default retry count", repo, "--json"], home);diff --git a/test/trail-upload-names.test.ts b/test/trail-upload-names.test.tsindex d3d6443b..391b125b 100644--- a/test/trail-upload-names.test.ts+++ b/test/trail-upload-names.test.ts@@ -15,6 +15,7 @@ import { dropActivity, flushActivity, syncRepo } from "../src/cloud/workspace-syimport { isError, writeCloud, type Cloud } from "../src/cloud/workspace.js";import { cacheDir } from "../src/util/state.js";import { tmpRepo } from "./helpers.js";+import { escapeRe } from "./escape.js";process.env.DO_NOT_TRACK = "1";process.env[BRAND_ENV] = "trail";@@ -356,7 +357,7 @@ test("trail workspace names a learning left out for a secret, and why, instead o});server.close();assert.equal(out.code, 0, out.err);- assert.match(out.out, new RegExp(`left out: ${leaky.replace(/\./g, "\\.")}: looks like it holds a secret \\(an API key\\)`), out.out + out.err);- assert.doesNotMatch(out.out, new RegExp(COMMITTED.replace(/\./g, "\\.")), "only what was left out is named");+ assert.match(out.out, new RegExp(`left out: ${escapeRe(leaky)}: looks like it holds a secret \\(an API key\\)`), out.out + out.err);+ assert.doesNotMatch(out.out, new RegExp(escapeRe(COMMITTED)), "only what was left out is named");assert.ok(!out.out.includes(key), "the secret itself is never printed");});