Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
117 commits
Select commit Hold shift + click to select a range
2b6a00d
fix: scope codegraph batch complexity targets to file paths
carlos-alm Jul 5, 2026
b28051a
fix: exclude parameters and interface/type members from dead-role cla…
carlos-alm Jul 5, 2026
17fbcba
fix: credit import-type usages as exports consumers
carlos-alm Jul 5, 2026
26918bb
fix: prevent fn-impact/query crash when -f/--file is passed
carlos-alm Jul 5, 2026
be6432c
fix: correct exported-symbol detection for literal and object-literal…
carlos-alm Jul 5, 2026
4ead840
fix: exclude primitive type keywords from ast --kind string matching
carlos-alm Jul 5, 2026
f6326bf
fix: resolve call edges through renamed import specifiers
carlos-alm Jul 5, 2026
590f560
fix: couple file_hashes updates with edge regeneration in incremental…
carlos-alm Jul 5, 2026
d3ea4a4
fix: compare signature-change diffs using new-file line ranges
carlos-alm Jul 5, 2026
c306812
feat: add environment doctor check for stale native binary and missin…
carlos-alm Jul 5, 2026
8bb5893
fix: eliminate non-deterministic ordering in community detection
carlos-alm Jul 6, 2026
46037b1
fix: sync update-graph.sh hook extension allowlist with EXTENSIONS
carlos-alm Jul 6, 2026
6a84cf9
fix: recompute directory structure metrics for affected directories o…
carlos-alm Jul 6, 2026
8d936d1
refactor: register hardcoded execFileSync/execSync maxBuffer values i…
carlos-alm Jul 6, 2026
11c84be
fix: gate blast-radius check on newly introduced risk, not pre-existi…
carlos-alm Jul 6, 2026
963301a
fix: gate identifier-argument dynamic call edges on callback-acceptin…
carlos-alm Jul 6, 2026
3e8035d
fix: gate Array.from's callback arg by position, not just callee name
carlos-alm Jul 6, 2026
879635e
fix: scope reexportedSymbols to actually-named re-export specifiers
carlos-alm Jul 6, 2026
0fe9fc3
fix: stop CFG block/edge count from overriding AST-derived cyclomatic…
carlos-alm Jul 6, 2026
ccf3c19
fix: backfill edges.technique for incrementally-inserted calls edges
carlos-alm Jul 6, 2026
d5b1162
fix: wrap remote embedding JSON parse failure in EngineError
carlos-alm Jul 6, 2026
8971017
refactor: extract shared platform-default-path helper in config.ts
carlos-alm Jul 6, 2026
056c5e4
refactor: decompose loadConfig and related high-effort functions in c…
carlos-alm Jul 6, 2026
0738171
refactor: decompose findDbPath and openRepo in db/connection.ts (docs…
carlos-alm Jul 6, 2026
6f2423c
refactor: dedupe busy/locked error detection into isBusyOrLockedError
carlos-alm Jul 6, 2026
4c02378
fix: log statSync failures in findDbPath instead of silently swallowi…
carlos-alm Jul 6, 2026
0698e16
test: add direct unit coverage for closeDbPair/closeDbPairDeferred/cl…
carlos-alm Jul 6, 2026
4ac3b99
fix: correct blast-radius/fn-impact computation for line-shifted decl…
carlos-alm Jul 6, 2026
6767f09
feat: wire points-to solver max-iterations cap through DEFAULTS.analy…
carlos-alm Jul 6, 2026
5f6f30a
refactor: route console.log calls in domain/search through logger
carlos-alm Jul 6, 2026
b479318
refactor: reduce cyclomatic complexity of computeDeltaModularityDirected
carlos-alm Jul 6, 2026
c39ac40
refactor: unify impact-level rendering format between audit and fn-im…
carlos-alm Jul 6, 2026
067674f
refactor: dedupe computeSavings via pct helper and persist partial to…
carlos-alm Jul 6, 2026
f6807b4
fix: add main.rs driver to rust dynamic tracer fixture
carlos-alm Jul 6, 2026
1c07a54
fix: scope diff file-header detection to between-hunk positions
carlos-alm Jul 6, 2026
bf82aa2
fix: update titan-grind's dead-symbol script for current roles --json…
carlos-alm Jul 6, 2026
cd02d27
fix: thread configured busyTimeoutMs through remaining read-only quer…
carlos-alm Jul 6, 2026
980b5dc
fix: resolve computed string-literal keys in object-literal extractio…
carlos-alm Jul 6, 2026
4a873a3
fix: add same-class bare-call fallback to incremental rebuild path (d…
carlos-alm Jul 6, 2026
8f3348a
fix: unify Object.defineProperty accessor fallback kind-filtering bet…
carlos-alm Jul 6, 2026
acf804c
refactor: share chunked statement-cache primitive between builder and…
carlos-alm Jul 6, 2026
986c851
refactor: cache prepared statements in applyEdgeTechniquesAfterNative…
carlos-alm Jul 6, 2026
71e9174
fix: replace fixed-depth directory-proximity check with symmetric dis…
carlos-alm Jul 6, 2026
d2935cc
refactor: remove unreachable Partition delta-computation interface me…
carlos-alm Jul 6, 2026
6515186
fix: emit reference edges for function identifiers used as object-lit…
carlos-alm Jul 6, 2026
30c491a
refactor: unify call-ref and tests rendering format between audit and…
carlos-alm Jul 6, 2026
9db911b
fix: classify destructured bindings as constant, not function (docs c…
carlos-alm Jul 6, 2026
70559fc
refactor: adopt timeMedian in remaining benchmark timing loops
carlos-alm Jul 6, 2026
822e0eb
refactor: decompose runPerfBenchmarks in token-benchmark.ts
carlos-alm Jul 6, 2026
fcdfe7d
fix: attribute liveness to Lua functions assigned to global/builtin i…
carlos-alm Jul 6, 2026
ee6362c
refactor: extract shared sedi() helper for tracer scripts
carlos-alm Jul 6, 2026
d4e6212
fix: restore reflection dynamicKind for .call/.apply/.bind (docs chec…
carlos-alm Jul 6, 2026
aec5d2b
fix: restrict entry-role classification to function/method-kind symbo…
carlos-alm Jul 6, 2026
d250f8d
fix: credit destructured dynamic import() bindings as exports consumers
carlos-alm Jul 6, 2026
75978e2
fix: recognize Lua function nodes in complexity metrics computation (…
carlos-alm Jul 6, 2026
af17b6d
fix: scope global call-resolution fallback to same-language candidate…
carlos-alm Jul 6, 2026
dd447bc
fix: credit instanceof ClassName checks as exports consumers
carlos-alm Jul 6, 2026
a79a8a1
fix: update automated-review workflow to use current claude-code-acti…
carlos-alm Jul 6, 2026
d84f6b5
refactor: widen outputResult signature, remove redundant casts at cal…
carlos-alm Jul 6, 2026
e7a2255
fix: port Leiden algorithm to native Rust for cross-engine community-…
carlos-alm Jul 7, 2026
b54972a
feat: detect exported-symbol loss from full file deletion in checkNoS…
carlos-alm Jul 7, 2026
1821a8b
fix(complexity): scope summary stats to file/target/kind filters
carlos-alm Jul 7, 2026
d45aba7
fix(extractors): label property_signature interface/type members as k…
carlos-alm Jul 7, 2026
69d8a6f
fix(roles): exclude genuine class/struct properties from dead-role cl…
carlos-alm Jul 7, 2026
db08219
fix(resolver): scope extends/implements edges to same-file/import/lan…
carlos-alm Jul 7, 2026
79cd761
fix: track inline per-specifier type-only import modifier
carlos-alm Jul 7, 2026
cbfa954
fix(native): widen NativeRepository file filters to accept string[]
carlos-alm Jul 7, 2026
c0e7eae
fix(native): remove unused source param from get_first_call_arg
carlos-alm Jul 7, 2026
2dabe21
fix(extractors): align native/WASM definitions order for object-liter…
carlos-alm Jul 7, 2026
b1eb9af
fix(extractors): capture top-level const definitions regardless of in…
carlos-alm Jul 7, 2026
4a1e279
fix: exclude PHP scalar type-hint/cast keywords from ast --kind string
carlos-alm Jul 7, 2026
40b5e24
fix: track barrel re-export renames (export { X as Y } from ...)
carlos-alm Jul 7, 2026
1506896
fix: record local alias for dynamic import() destructuring renames
carlos-alm Jul 7, 2026
2dfd6bc
fix: resolve renamed-import receiver calls in qualified-method lookup
carlos-alm Jul 7, 2026
ccea0cb
fix(native): propagate edge/node write failures out of run_pipeline
carlos-alm Jul 7, 2026
93ccfa3
fix(exports): discriminate file-level from symbol-level consumer entries
carlos-alm Jul 7, 2026
e105c26
docs: refresh CONTRIBUTING.md for TypeScript architecture and current…
carlos-alm Jul 7, 2026
5d99bf0
fix(exports): credit plain imports of TypeScript interfaces/type aliases
carlos-alm Jul 7, 2026
e0ab9dc
fix(hooks): point update-graph.sh fallback build path at dist/cli.js
carlos-alm Jul 7, 2026
730b49b
fix(hooks): resolve track-edits.sh's PROJECT_DIR from the edited file…
carlos-alm Jul 7, 2026
0d7e8e6
fix: capture removed files' cross-directory neighbors before purge
carlos-alm Jul 7, 2026
c5b9a34
docs: fix stale codegraph check flag names in recommended-practices.md
carlos-alm Jul 7, 2026
2de6550
fix(cycles): classify cycles whose only closing edges are speculative
carlos-alm Jul 7, 2026
e5fe754
fix(resolver): recognize identifier args to user-defined higher-order…
carlos-alm Jul 8, 2026
4eef28e
fix(native): scope barrel-only import skipping to transient barrel re…
carlos-alm Jul 8, 2026
4090355
refactor(ast-analysis): extract shared CFG/complexity result-merging …
carlos-alm Jul 8, 2026
bf8e969
fix(incremental): port CHA/RTA dispatch, points-to, and dynamic-sink …
carlos-alm Jul 8, 2026
51b9e23
fix(config): derive ENV_LLM_KEYS from ENV_LLM_MAP to prevent drift
carlos-alm Jul 8, 2026
a62bab7
fix(resolver): resolveByGlobal picks the single best match, not every…
carlos-alm Jul 8, 2026
8f52d28
fix(embed): resolve default DB path from positional dir, not cwd
carlos-alm Jul 8, 2026
59220a5
refactor(leiden): extract makePartition's inline getters to cut cyclo…
carlos-alm Jul 8, 2026
2e1aa11
docs: regenerate stale audit/diff-impact example output blocks
carlos-alm Jul 8, 2026
3d436ca
fix(rust): resolve self.field, unit-struct, and constructor-typed locals
carlos-alm Jul 8, 2026
668451c
docs: add missing titan-grind mirror to claude-code-skills examples
carlos-alm Jul 8, 2026
4bccd4b
fix(scripts): migrate ts-resolve-loader.js off deprecated module.regi…
carlos-alm Jul 8, 2026
25ba42f
fix(native): recover renamed import names in the FFI hybrid import-ed…
carlos-alm Jul 8, 2026
431c0e5
fix: reconnect reverse-dep edges correctly when a sibling group's siz…
carlos-alm Jul 8, 2026
ab6a685
fix: derive loadConfig() rootDir from --db path in read-only query fu…
carlos-alm Jul 8, 2026
17e265b
fix(native): thread config.db.busyTimeoutMs into NativeDatabase open …
carlos-alm Jul 8, 2026
fdedff8
fix(extractors): unwrap computed string-literal keys in typeMap/proto…
carlos-alm Jul 8, 2026
6ef1731
fix(native): add Object.defineProperty accessor dispatch post-pass to…
carlos-alm Jul 8, 2026
afca17f
fix(resolver): kind-filter same-file bare-name lookup for receiver-be…
carlos-alm Jul 8, 2026
801d290
fix(resolver): attribute new ClassName() calls to the constructor method
carlos-alm Jul 8, 2026
a45e74d
fix(extractors): attribute same-file ES6 getter/setter property reads…
carlos-alm Jul 8, 2026
453a768
fix(resolver): require invocation evidence for object-literal value-r…
carlos-alm Jul 8, 2026
1d957a4
fix(extractors): resolve inline object-literal dispatch tables on WASM
carlos-alm Jul 8, 2026
438f2da
fix(extractors): emit per-element definitions for array-pattern destr…
carlos-alm Jul 8, 2026
0a07066
fix(scripts): resolve benchmark hub targets to a single, kind-filtere…
carlos-alm Jul 8, 2026
5933236
refactor(scripts): decompose runSession in token-benchmark.ts
carlos-alm Jul 8, 2026
771a64c
fix(scripts): resolve token-benchmark.ts --perf imports to real neste…
carlos-alm Jul 8, 2026
2810b4c
fix(lua): port eval/computed-key dynamic-call detection to WASM extra…
carlos-alm Jul 8, 2026
b63a700
docs(roles): correct hasActiveFileSiblings JSDoc to match population …
carlos-alm Jul 8, 2026
8e3d353
fix(tracer): fix BSD-incompatible sed injection at remaining jvm/nati…
carlos-alm Jul 8, 2026
af58002
fix: resolve merge conflicts with main (docs check acknowledged)
carlos-alm Jul 11, 2026
f978eb0
fix: correct sedi_insert_before docstring to say every match, not fir…
carlos-alm Jul 11, 2026
3dabba5
test: document why tracer-common.sh is excluded from the sed-injectio…
carlos-alm Jul 11, 2026
def6c68
fix(tracer): avoid GNU sed -i cross-device rename failure on Windows CI
carlos-alm Jul 11, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 16 additions & 26 deletions tests/benchmarks/resolution/tracer/jvm-tracer.sh
Original file line number Diff line number Diff line change
Expand Up @@ -142,17 +142,13 @@ case "$LANG" in
# Match lines like: public void method(...) {
# The first sed pass matches all method/constructor opening braces,
# so a second pass is unnecessary (it would double-inject traceCall).
sedi -E '/\)\s*\{$/{
/class |interface /!{
a\ CallTracer.traceCall();
}
}' "$javafile"
sedi_append_unless '/\)[[:space:]]*\{$/' '/class |interface /' \
' CallTracer.traceCall();' "$javafile"
done

# Add dump call at end of main
sedi '/public static void main/,/\}/ {
/^\s*\}/ i\ CallTracer.dump();
}' "$TMP_DIR/Main.java" 2>/dev/null || true
sedi_insert_before_end '/public static void main/' '/\}/' '/^[[:space:]]*\}/' \
' CallTracer.dump();' "$TMP_DIR/Main.java" 2>/dev/null || true

# Compile and run
cd "$TMP_DIR"
Expand All @@ -171,15 +167,13 @@ case "$LANG" in

# Inject CallTracer.traceCall() into every function body
for ktfile in "$TMP_DIR"/*.kt; do
sedi -E '/fun [a-zA-Z].*\{[[:space:]]*$/{
/class |interface |object /!a\ CallTracer.traceCall();
}' "$ktfile"
sedi_append_unless '/fun [a-zA-Z].*\{[[:space:]]*$/' '/class |interface |object /' \
' CallTracer.traceCall();' "$ktfile"
done

# Inject dump call before main's closing brace
sedi '/^fun main/,/^\}/ {
/^\}/ i\ CallTracer.dump()
}' "$TMP_DIR/Main.kt"
sedi_insert_before_end '/^fun main/' '/^\}/' '/^\}/' \
' CallTracer.dump()' "$TMP_DIR/Main.kt"

# Suppress println to keep stdout clean for JSON
for ktfile in "$TMP_DIR"/*.kt; do
Expand All @@ -198,15 +192,13 @@ case "$LANG" in
# Inject CallTracer.traceCall() into every def body
for scfile in "$TMP_DIR"/*.scala; do
base="$(basename "$scfile")"
sedi -E '/def [a-zA-Z].*\{[[:space:]]*$/{
/class |trait |object .*extends/!a\ CallTracer.traceCall();
}' "$scfile"
sedi_append_unless '/def [a-zA-Z].*\{[[:space:]]*$/' '/class |trait |object .*extends/' \
' CallTracer.traceCall();' "$scfile"
done

# Inject dump call before main's closing brace
sedi '/def main/,/^\s*\}/ {
/^\s*\}/ i\ CallTracer.dump()
}' "$TMP_DIR/Main.scala"
sedi_insert_before_end '/def main/' '/^[[:space:]]*\}/' '/^[[:space:]]*\}/' \
' CallTracer.dump()' "$TMP_DIR/Main.scala"

# Suppress println to keep stdout clean for JSON
for scfile in "$TMP_DIR"/*.scala; do
Expand All @@ -231,15 +223,13 @@ case "$LANG" in

# Inject CallTracer.traceCall() into every method body
for grfile in "$TMP_DIR"/*.groovy; do
sedi -E '/\)\s*\{[[:space:]]*$/{
/class |interface /!a\ CallTracer.traceCall();
}' "$grfile"
sedi_append_unless '/\)[[:space:]]*\{[[:space:]]*$/' '/class |interface /' \
' CallTracer.traceCall();' "$grfile"
done

# Inject dump call before main's closing brace
sedi '/static void main/,/^\s*\}/ {
/^\s*\}/ i\ CallTracer.dump()
}' "$TMP_DIR/Main.groovy"
sedi_insert_before_end '/static void main/' '/^[[:space:]]*\}/' '/^[[:space:]]*\}/' \
' CallTracer.dump()' "$TMP_DIR/Main.groovy"

# Suppress println to keep stdout clean for JSON
for grfile in "$TMP_DIR"/*.groovy; do
Expand Down
23 changes: 10 additions & 13 deletions tests/benchmarks/resolution/tracer/native-tracer.sh
Original file line number Diff line number Diff line change
Expand Up @@ -598,12 +598,12 @@ CSTRACE
done

# Inject Dump at end of Main
sedi '/public static void Main/,/^\s*\}/ {
/^\s*\}/ i\ CallTracer.Dump();
}' "$TMP_DIR/Program.cs" 2>/dev/null || true
sedi_insert_before_end '/public static void Main/' '/^[[:space:]]*\}/' '/^[[:space:]]*\}/' \
' CallTracer.Dump();' "$TMP_DIR/Program.cs" 2>/dev/null || true

# Also call RunWithValidation if it exists
sedi '/CallTracer.Dump/i\ RunWithValidation();' "$TMP_DIR/Program.cs" 2>/dev/null || true
sedi_insert_before '/CallTracer.Dump/' ' RunWithValidation();' \
"$TMP_DIR/Program.cs" 2>/dev/null || true

# Redirect Console.WriteLine in fixture code to stderr
for csfile in "$TMP_DIR"/*.cs; do
Expand Down Expand Up @@ -702,9 +702,8 @@ SWTRACE

# Inject dump at end of main (top-level code or main function)
if grep -q 'func main' "$TMP_DIR/main.swift" 2>/dev/null; then
sedi '/^func main/,/^\}/ {
/^\}/ i\ CallTracer.shared.dump()
}' "$TMP_DIR/main.swift"
sedi_insert_before_end '/^func main/' '/^\}/' '/^\}/' \
' CallTracer.shared.dump()' "$TMP_DIR/main.swift"
else
echo 'CallTracer.shared.dump()' >> "$TMP_DIR/main.swift"
fi
Expand Down Expand Up @@ -800,9 +799,8 @@ DARTTRACE
' } finally { CallTracer.instance.traceReturn(); }'

# Inject dump at end of main
sedi '/^void main/,/^\}/ {
/^\}/ i\ CallTracer.instance.dump();
}' "$TMP_DIR/main.dart" 2>/dev/null || true
sedi_insert_before_end '/^void main/' '/^\}/' '/^\}/' \
' CallTracer.instance.dump();' "$TMP_DIR/main.dart" 2>/dev/null || true

# Redirect print to stderr in fixture files (trace_support.dart excluded
# because its dump() must write JSON to stdout; main.dart is NOT excluded
Expand Down Expand Up @@ -912,9 +910,8 @@ ZIGTRACE
' trace_support.traceCall("%s", "%s"); defer trace_support.traceReturn();'

# Inject dump at end of main
sedi '/^pub fn main/,/^\}/ {
/^\}/ i\ trace_support.dumpTrace();
}' "$TMP_DIR/main.zig" 2>/dev/null || true
sedi_insert_before_end '/^pub fn main/' '/^\}/' '/^\}/' \
' trace_support.dumpTrace();' "$TMP_DIR/main.zig" 2>/dev/null || true

cd "$TMP_DIR"
if zig build-exe main.zig 2>/dev/null; then
Expand Down
71 changes: 67 additions & 4 deletions tests/benchmarks/resolution/tracer/tracer-common.sh
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,74 @@
#
# source "$(dirname "${BASH_SOURCE[0]}")/tracer-common.sh"

# Portable sed -i (GNU vs BSD)
# Portable in-place sed. Deliberately does NOT delegate to sed's own `-i`:
# GNU sed's `-i` places its scratch file by looking for the last "/" in the
# target path and creating the scratch file alongside it, falling back to the
# current working directory when no "/" is found. A native Windows path (as
# produced by Node's path.join/os.tmpdir on win32, e.g.
# `C:\Users\...\Program.cs`) has no "/" at all, so on Windows/Git-Bash/MSYS2
# CI runners sed's scratch file lands in the CWD (typically the repo
# checkout) instead of next to the target — and when the target lives on a
# different drive than the CWD (as it does for os.tmpdir() vs. a `D:`-drive
# checkout on GitHub's windows-2022 runners), the final rename fails with
# "Invalid cross-device link" (#1913 follow-up). Normalizing to forward
# slashes first and doing our own same-directory scratch-file swap sidesteps
# both the path-parsing bug and the cross-device rename, and — since it never
# uses `-i` — works identically on GNU sed, BSD sed, and MSYS's bundled GNU
# sed without needing to detect which flavor is present.
sedi() {
if sed --version 2>/dev/null | grep -q GNU; then
sed -i "$@"
local n=$#
local file="${!n}"
file="${file//\\//}"
local dir
dir="$(dirname "$file")"
local tmp
tmp="$(mktemp "$dir/tracer-sed.XXXXXX")" || return 1
local status=0
sed "${@:1:$((n - 1))}" "$file" >"$tmp" || status=$?
if [ "$status" -eq 0 ]; then
mv "$tmp" "$file"
else
sed -i '' "$@"
rm -f "$tmp"
fi
return "$status"
}

# GNU sed accepts the single-line "i\text" / "a\text" shortcut for its insert
# and append commands; BSD sed (macOS) rejects it and requires the text on
# the line *after* the backslash (see #1759). The three helpers below build
# that portable multi-line form internally so call sites never hand-roll the
# GNU-only shortcut (see #1913).

# Insert TEXT on the line immediately before every line matching PATTERN.
sedi_insert_before() {
local pattern="$1" text="$2" file="$3"
sedi "${pattern} i\\
${text}" "$file"
}

# Insert TEXT immediately before the first line matching INSERT_PATTERN,
# scoped to the START_PATTERN,END_PATTERN address range. Used to splice a
# dump()-style call just before a function's closing brace without touching
# unrelated braces elsewhere in the file. INSERT_PATTERN is taken separately
# from END_PATTERN because some callers close the range on a looser match
# (e.g. any line containing `}`) than the line they actually inject before.
sedi_insert_before_end() {
local start_pattern="$1" end_pattern="$2" insert_pattern="$3" text="$4" file="$5"
sedi "${start_pattern},${end_pattern} {
${insert_pattern} i\\
${text}
}" "$file"
}

# Append TEXT after every line matching OUTER_PATTERN, except lines that also
# match NEGATE_PATTERN (used to skip class/interface/object declaration lines
# that share the same brace-opening shape as method signatures). Runs with
# extended regex (-E) since every current caller relies on ERE alternation.
sedi_append_unless() {
local outer_pattern="$1" negate_pattern="$2" text="$3" file="$4"
sedi -E "${outer_pattern}{
${negate_pattern}!a\\
${text}
}" "$file"
}
169 changes: 169 additions & 0 deletions tests/benchmarks/resolution/tracer/tracer-common.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
/**
* Regression coverage for #1913: the sed-injection helpers in
* tracer-common.sh must produce output that is byte-identical on GNU sed
* (Linux CI) and BSD sed (macOS dev boxes), which — unlike GNU — rejects the
* single-line `a\text` / `i\text` shortcut and requires the text on the line
* after the backslash.
*
* These tests exercise the shared helpers directly with bash + sed (whatever
* sed the host provides), independent of any per-language compiler toolchain
* (javac/kotlinc/scalac/groovyc/dotnet/dart/zig), so they run identically in
* every environment regardless of which toolchains happen to be installed.
*/
import { execFileSync } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const TRACER_DIR = __dirname;
const TRACER_COMMON = path.join(TRACER_DIR, 'tracer-common.sh');

function runHelper(fnCall: string, file: string): string {
execFileSync('bash', ['-c', `source "${TRACER_COMMON}"; ${fnCall}`]);
return fs.readFileSync(file, 'utf8');
}

describe('tracer-common.sh sed-injection helpers (#1913)', () => {
let tmpDir: string;

beforeEach(() => {
tmpDir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'tracer-common-test-')));
});

afterEach(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});

it('sedi_insert_before inserts text directly before the matching line (native-tracer.sh csharp RunWithValidation site)', () => {
const file = path.join(tmpDir, 'Program.cs');
fs.writeFileSync(
file,
[
'class Program {',
' public static void Main() {',
' CallTracer.Dump();',
' }',
'}',
'',
].join('\n'),
);

const out = runHelper(
`sedi_insert_before '/CallTracer.Dump/' ' RunWithValidation();' "${file}"`,
file,
);

expect(out).toContain(' RunWithValidation();\n CallTracer.Dump();');
});

it('sedi_insert_before_end inserts before the matching brace within a range (jvm/native dump-injection sites)', () => {
const file = path.join(tmpDir, 'main.dart');
fs.writeFileSync(file, ['void main() {', ' print(1);', '}', ''].join('\n'));

const out = runHelper(
`sedi_insert_before_end '/^void main/' '/^\\}/' '/^\\}/' ' CallTracer.instance.dump();' "${file}"`,
file,
);

expect(out.split('\n')).toEqual([
'void main() {',
' print(1);',
' CallTracer.instance.dump();',
'}',
'',
]);
});

it('sedi_insert_before_end honors distinct range-end and insert-line patterns (jvm-tracer.sh java dump site)', () => {
// java's dump site scopes the range with a loose /\}/ end-address but
// only inserts before a line that is *purely* a closing brace, so the
// range and insertion patterns must be tracked independently.
const file = path.join(tmpDir, 'Main.java');
fs.writeFileSync(
file,
[
'public class Main {',
' public static void main(String[] args) {',
' foo();',
' }',
'}',
'',
].join('\n'),
);

const out = runHelper(
`sedi_insert_before_end '/public static void main/' '/\\}/' '/^[[:space:]]*\\}/' ' CallTracer.dump();' "${file}"`,
file,
);

expect(out).toContain(' foo();\n CallTracer.dump();\n }\n}');
});

it('sedi_append_unless appends after matching lines except negated ones, including a space before the brace (jvm-tracer.sh java/groovy per-method sites)', () => {
const file = path.join(tmpDir, 'BaseService.java');
fs.writeFileSync(
file,
[
'public abstract class BaseService {',
'',
' protected void log(String message) {',
' System.out.println(message);',
' }',
'}',
'',
].join('\n'),
);

const out = runHelper(
`sedi_append_unless '/\\)[[:space:]]*\\{$/' '/class |interface /' ' CallTracer.traceCall();' "${file}"`,
file,
);

// The method signature line (ending in ") {") gets the call appended...
expect(out).toContain(
' protected void log(String message) {\n CallTracer.traceCall();',
);
// ...but the class declaration line (also ending in "{") is excluded.
expect(out.split('\n')[0]).toBe('public abstract class BaseService {');
});

it('rejects a regression back to the GNU-only single-line a\\/i\\ shortcut in the tracer scripts', () => {
// Every dump()/traceCall() injection now goes through the shared helpers
// above, so the raw sed scripts embedded directly in the language
// tracers should contain zero remaining single-line "i\text"/"a\text"
// occurrences (the exact defect #1913 fixed) — this guards against
// future injection sites reintroducing the GNU-only shortcut.
//
// tracer-common.sh itself is deliberately NOT in this list: its helpers
// build the sed script inside double-quoted bash strings, so a literal
// backslash is written as "i\\" (escaped for the enclosing quotes)
// immediately followed by a newline. That raw "\\" trips the /[ai]\\\S/
// pattern below as a false positive — the second backslash satisfies \S
// — even though it's the correct portable multi-line form, not the
// banned single-line shortcut. Trade-off: a future helper mistakenly
// written with the real GNU-only form directly inside tracer-common.sh
// would go undetected by this guard.
const guardedFiles = ['jvm-tracer.sh', 'native-tracer.sh', 'go-tracer.sh'];

for (const name of guardedFiles) {
const code = fs
.readFileSync(path.join(TRACER_DIR, name), 'utf8')
.split('\n')
// Drop comment lines so prose that *describes* the banned form (as
// this very fix's changelog comments do) isn't mistaken for it.
.filter((line) => !line.trim().startsWith('#'))
.join('\n');
// \S excludes the newline that must immediately follow a portable
// "i\" / "a\" — so this only matches the banned single-line form
// where real text follows the backslash on the same line.
const offender = code.match(/[ai]\\\S/);
expect(
offender,
`${name} contains a GNU-only single-line a\\/i\\ form: ${offender}`,
).toBeNull();
}
});
});
Comment on lines +149 to +169

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Regression guard omits tracer-common.sh itself

The guard intentionally skips tracer-common.sh to avoid false-positives from the i\\ in the helpers' own portable implementation (the JS regex /[ai]\\\S/ would match the second backslash in i\\<newline>text). That's the right trade-off, but it means a new injection helper mistakenly written with the GNU-only form directly inside tracer-common.sh would go undetected. A comment in the test recording why the file is excluded would make this intentional gap visible to the next contributor.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Fix in Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a comment at the guardedFiles declaration documenting the exclusion (commit 3dabba5) — records that tracer-common.sh's own helpers embed a literal i\\ (escaped for the enclosing double-quoted bash string) immediately followed by a newline, which trips the /[ai]\\\S/ pattern as a false positive since the second backslash satisfies \S, and notes the resulting trade-off explicitly: a real GNU-only shortcut added directly inside tracer-common.sh would go undetected by this guard.

Loading