Skip to content

Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.

WIP: strict linting + RAM-first pipeline (lint fixes pending)

Martin Vogel7fa3acd0c6af
diff --git a/.clang-tidy b/.clang-tidy
index d8119da24..cf4bc3b1b 100644
--- a/.clang-tidy
+++ b/.clang-tidy
@@ -3,31 +3,8 @@
# ALL checks enabled. WarningsAsErrors: '*'.
# Check thresholds configured for idiomatic C11 (not C++).
#
-# Globally disabled checks must have an upstream bug reference or
-# architectural justification. Re-evaluate on LLVM upgrades.
-#
-# Documented LLVM false positives:
-# bugprone-multi-level-implicit-pointer-conversion — LLVM #93959, relaxed in LLVM 19
-# clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling — LLVM #64027
-# clang-analyzer-optin.portability.UnixAPI — malloc(0) behavior, guarded in code
-#
-# Architectural:
-# bugprone-command-processor — popen required for git, inputs validated
-# cert-env33-c — popen/system needed for git commands, inputs validated
-#
-# Pending fix (phases 4-6):
-# bugprone-easily-swappable-parameters — Phase 5: struct params
-# concurrency-mt-unsafe — Phase 4: thread-safe wrappers
-# cert-err33-c — Phase 4: check fwrite/fseek return values
-# performance-no-int-to-ptr — Phase 4: union type-punning
-# bugprone-branch-clone — Phase 6
-# readability-avoid-nested-conditional-operator — Phase 6
-# readability-redundant-casting — Phase 6
-# bugprone-implicit-widening-of-multiplication-result — Phase 6
-# bugprone-unchecked-string-to-number-conversion — Phase 6
-# clang-analyzer-core.CallAndMessage — Phase 6
-# clang-analyzer-core.NullPointerArithm — Phase 6
-# clang-analyzer-security.insecureAPI.strcpy — Phase 6
+# Only C++ idiom checks and confirmed LLVM false positives are disabled.
+# Everything else must be fixed in code.
Checks: >
-*,
@@ -41,41 +18,20 @@ Checks: >
portability-*,
readability-*,
clang-analyzer-*,
- -misc-no-recursion,
- -readability-implicit-bool-conversion,
-bugprone-multi-level-implicit-pointer-conversion,
+ -readability-implicit-bool-conversion,
-clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling,
- -clang-analyzer-optin.portability.UnixAPI,
-clang-analyzer-security.ArrayBound,
- -clang-analyzer-unix.Malloc,
- -misc-include-cleaner,
- -bugprone-command-processor,
- -bugprone-suspicious-include,
- -cert-env33-c,
- -bugprone-easily-swappable-parameters,
- -concurrency-mt-unsafe,
- -cert-err33-c,
- -performance-no-int-to-ptr,
- -bugprone-branch-clone,
- -readability-avoid-nested-conditional-operator,
- -readability-redundant-casting,
- -bugprone-implicit-widening-of-multiplication-result,
- -bugprone-unchecked-string-to-number-conversion,
- -clang-analyzer-core.CallAndMessage,
- -clang-analyzer-core.NullPointerArithm,
- -clang-analyzer-security.insecureAPI.strcpy,
WarningsAsErrors: '*'
CheckOptions:
- bugprone-implicit-widening-of-multiplication-result.UseCXXStaticCastsInCppSources: false
readability-identifier-length.MinimumVariableNameLength: 1
readability-identifier-length.MinimumParameterNameLength: 1
readability-identifier-length.MinimumLoopCounterNameLength: 1
- readability-implicit-bool-conversion.AllowIntegerConditions: true
- readability-implicit-bool-conversion.AllowPointerConditions: true
- readability-magic-numbers.IgnoredIntegerValues: "1;2;3;4;5;6;7;8;9;10;11;12;14;15;16;20;24;32;48;64;100;128;200;256;493;512;755;1000;1024;1040;2048;4096;8192;16384;32768;65536;500000;1000000;1000000000"
- readability-magic-numbers.IgnoredFloatingPointValues: "0.0;0.25;0.5;0.7;0.75;0.8;0.85;0.9;0.95;1.0;2.0;100.0;1e308"
+ readability-magic-numbers.IgnoredIntegerValues: ""
+ readability-magic-numbers.IgnoredFloatingPointValues: ""
+ bugprone-easily-swappable-parameters.MinimumLength: 3
readability-function-cognitive-complexity.Threshold: 25
readability-function-size.StatementThreshold: 200
readability-function-size.LineThreshold: 400
diff --git a/.github/workflows/dry-run.yml b/.github/workflows/dry-run.yml
index 054af7533..62ea7e37f 100644
--- a/.github/workflows/dry-run.yml
+++ b/.github/workflows/dry-run.yml
@@ -30,7 +30,7 @@ jobs:
if: ${{ inputs.skip_lint != true }}
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- name: Install build deps
run: sudo apt-get update && sudo apt-get install -y zlib1g-dev cmake
@@ -42,7 +42,7 @@ jobs:
sudo apt-get update
sudo apt-get install -y clang-format-20
- - uses: actions/cache@668228422ae6a00e4ad889ee87cd7109ec5666a7 # v5.0.4
+ - uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4
id: cppcheck-cache
with:
path: /opt/cppcheck
@@ -69,7 +69,7 @@ jobs:
if: ${{ inputs.skip_lint != true }}
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- name: "Layer 1: Static allow-list audit"
run: scripts/security-audit.sh
@@ -182,7 +182,7 @@ jobs:
cxx: c++
runs-on: ${{ matrix.os }}
steps:
- - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- name: Install deps (Ubuntu)
if: startsWith(matrix.os, 'ubuntu')
@@ -196,7 +196,7 @@ jobs:
needs: [lint]
runs-on: windows-latest
steps:
- - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- uses: msys2/setup-msys2@4f806de0a5a7294ffabaff804b38a9b435a73bda # v2
with:
@@ -241,7 +241,7 @@ jobs:
cxx: c++
runs-on: ${{ matrix.os }}
steps:
- - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- name: Install deps (Ubuntu)
if: startsWith(matrix.os, 'ubuntu')
@@ -281,17 +281,65 @@ jobs:
tar -czf codebase-memory-mcp-ui-${{ matrix.goos }}-${{ matrix.goarch }}.tar.gz \
-C build/c codebase-memory-mcp LICENSE
- - uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
+ - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: binaries-${{ matrix.goos }}-${{ matrix.goarch }}
path: "*.tar.gz"
+ # ── Step 3b: Build portable Linux binaries (musl static) ────
+ build-linux-portable:
+ if: ${{ inputs.skip_builds != true && always() && (needs.test-unix.result == 'success' || needs.test-unix.result == 'skipped') && (needs.test-windows.result == 'success' || needs.test-windows.result == 'skipped') }}
+ needs: [test-unix, test-windows]
+ strategy:
+ matrix:
+ include:
+ - arch: amd64
+ runner: ubuntu-latest
+ - arch: arm64
+ runner: ubuntu-24.04-arm
+ runs-on: ${{ matrix.runner }}
+ container:
+ image: alpine:3.21
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+
+ - name: Install musl build deps
+ run: apk add --no-cache build-base linux-headers zlib-dev zlib-static nodejs npm
+
+ - name: Build standard binary (static)
+ run: scripts/build.sh CC=gcc CXX=g++ STATIC=1
+
+ - name: Verify static linking
+ run: |
+ file build/c/codebase-memory-mcp | grep -q "statically linked"
+ echo "=== Confirmed: fully static binary ==="
+
+ - name: Archive standard binary
+ run: |
+ cp LICENSE build/c/
+ tar -czf codebase-memory-mcp-linux-${{ matrix.arch }}-portable.tar.gz \
+ -C build/c codebase-memory-mcp LICENSE
+
+ - name: Build UI binary (static)
+ run: scripts/build.sh --with-ui CC=gcc CXX=g++ STATIC=1
+
+ - name: Archive UI binary
+ run: |
+ cp LICENSE build/c/
+ tar -czf codebase-memory-mcp-ui-linux-${{ matrix.arch }}-portable.tar.gz \
+ -C build/c codebase-memory-mcp LICENSE
+
+ - uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
+ with:
+ name: binaries-linux-${{ matrix.arch }}-portable
+ path: "*.tar.gz"
+
build-windows:
if: ${{ inputs.skip_builds != true && always() && (needs.test-unix.result == 'success' || needs.test-unix.result == 'skipped') && (needs.test-windows.result == 'success' || needs.test-windows.result == 'skipped') }}
needs: [test-unix, test-windows]
runs-on: windows-latest
steps:
- - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- uses: msys2/setup-msys2@4f806de0a5a7294ffabaff804b38a9b435a73bda # v2
with:
@@ -331,7 +379,7 @@ jobs:
cp "$BIN" codebase-memory-mcp-ui.exe
zip codebase-memory-mcp-ui-windows-amd64.zip codebase-memory-mcp-ui.exe LICENSE
- - uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
+ - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: binaries-windows-amd64
path: "*.zip"
@@ -359,7 +407,7 @@ jobs:
variant: [standard, ui]
runs-on: ${{ matrix.os }}
steps:
- - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with:
@@ -450,7 +498,7 @@ jobs:
variant: [standard, ui]
runs-on: windows-latest
steps:
- - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- uses: msys2/setup-msys2@4f806de0a5a7294ffabaff804b38a9b435a73bda # v2
with:
@@ -518,6 +566,81 @@ jobs:
}
Write-Host "=== Windows Defender: clean ==="
+ # ── Step 4b: Smoke test portable Linux binaries ──────────────
+ smoke-linux-portable:
+ if: ${{ !cancelled() && inputs.skip_builds != true }}
+ needs: [build-linux-portable]
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - os: ubuntu-latest
+ arch: amd64
+ - os: ubuntu-24.04-arm
+ arch: arm64
+ variant: [standard, ui]
+ runs-on: ${{ matrix.os }}
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+
+ - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
+ with:
+ name: binaries-linux-${{ matrix.arch }}-portable
+
+ - name: Extract binary
+ run: |
+ SUFFIX=${{ matrix.variant == 'ui' && '-ui' || '' }}
+ tar -xzf codebase-memory-mcp${SUFFIX}-linux-${{ matrix.arch }}-portable.tar.gz
+ chmod +x codebase-memory-mcp
+
+ - name: Start artifact server for E2E smoke tests
+ run: |
+ mkdir -p /tmp/smoke-server
+ cp codebase-memory-mcp /tmp/smoke-server/
+ ARCH=${{ matrix.arch }}
+ SUFFIX=${{ matrix.variant == 'ui' && '-ui' || '' }}
+ tar -czf "/tmp/smoke-server/codebase-memory-mcp${SUFFIX}-linux-${ARCH}-portable.tar.gz" \
+ -C /tmp/smoke-server codebase-memory-mcp
+ # Also serve under standard name so install.sh + update --standard work
+ cp "/tmp/smoke-server/codebase-memory-mcp${SUFFIX}-linux-${ARCH}-portable.tar.gz" \
+ "/tmp/smoke-server/codebase-memory-mcp-linux-${ARCH}.tar.gz"
+ if [ -n "$SUFFIX" ]; then
+ cp "/tmp/smoke-server/codebase-memory-mcp${SUFFIX}-linux-${ARCH}-portable.tar.gz" \
+ "/tmp/smoke-server/codebase-memory-mcp${SUFFIX}-linux-${ARCH}.tar.gz"
+ fi
+ cd /tmp/smoke-server
+ sha256sum *.tar.gz > checksums.txt 2>/dev/null || shasum -a 256 *.tar.gz > checksums.txt
+ python3 -m http.server 18080 -d /tmp/smoke-server &
+
+ - name: Smoke test (portable ${{ matrix.variant }}, linux-${{ matrix.arch }})
+ run: scripts/smoke-test.sh ./codebase-memory-mcp
+ env:
+ SMOKE_DOWNLOAD_URL: http://localhost:18080
+
+ - name: Binary string audit (portable linux-${{ matrix.arch }})
+ if: matrix.variant == 'standard'
+ run: scripts/security-strings.sh ./codebase-memory-mcp
+
+ - name: Install output audit (portable linux-${{ matrix.arch }})
+ if: matrix.variant == 'standard'
+ run: scripts/security-install.sh ./codebase-memory-mcp
+
+ - name: Network egress test (portable linux-${{ matrix.arch }})
+ if: matrix.variant == 'standard'
+ run: scripts/security-network.sh ./codebase-memory-mcp
+
+ - name: ClamAV scan (portable Linux)
+ if: matrix.variant == 'standard'
+ run: |
+ sudo apt-get update -qq && sudo apt-get install -y -qq clamav > /dev/null 2>&1
+ sudo sed -i 's/^Example/#Example/' /etc/clamav/freshclam.conf 2>/dev/null || true
+ grep -q "DatabaseMirror" /etc/clamav/freshclam.conf 2>/dev/null || \
+ echo "DatabaseMirror database.clamav.net" | sudo tee -a /etc/clamav/freshclam.conf > /dev/null
+ sudo freshclam --quiet
+ echo "=== ClamAV scan (portable) ==="
+ clamscan --no-summary ./codebase-memory-mcp
+ echo "=== ClamAV: clean ==="
+
# ── Step 6: Soak tests (after smoke, per-platform) ──────────
soak-quick:
if: ${{ !cancelled() && inputs.soak_level != 'none' && inputs.skip_builds != true }}
@@ -549,7 +672,7 @@ jobs:
cc: cc
cxx: c++
steps:
- - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v4
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
- name: Install deps (Linux)
if: startsWith(matrix.os, 'ubuntu')
@@ -563,7 +686,7 @@ jobs:
- name: Upload soak metrics
if: always()
- uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: soak-quick-${{ matrix.goos }}-${{ matrix.goarch }}
path: soak-results/
@@ -575,7 +698,7 @@ jobs:
runs-on: windows-latest
timeout-minutes: 30
steps:
- - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v4
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
- uses: msys2/setup-msys2@4f806de0a5a7294ffabaff804b38a9b435a73bda # v2
with:
@@ -602,7 +725,7 @@ jobs:
- name: Upload soak metrics
if: always()
- uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: soak-quick-windows-amd64
path: soak-results/
@@ -638,7 +761,7 @@ jobs:
cc: cc
cxx: c++
steps:
- - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v4
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
- name: Install deps (Linux)
if: startsWith(matrix.os, 'ubuntu')
@@ -656,7 +779,7 @@ jobs:
- name: Upload ASan soak metrics
if: always()
- uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: soak-asan-${{ matrix.goos }}-${{ matrix.goarch }}
path: soak-results/
@@ -668,7 +791,7 @@ jobs:
runs-on: windows-latest
timeout-minutes: 45
steps:
- - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v4
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
- uses: msys2/setup-msys2@4f806de0a5a7294ffabaff804b38a9b435a73bda # v2
with:
msystem: CLANG64
@@ -695,8 +818,84 @@ jobs:
scripts/soak-test.sh "$BIN" 15
- name: Upload ASan soak metrics
if: always()
- uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: soak-asan-windows-amd64
path: soak-results/
retention-days: 14
+
+ # ── Step 6c: Quick soak (portable Linux, musl static) ──────────
+ soak-quick-linux-portable:
+ if: ${{ !cancelled() && inputs.soak_level != 'none' && inputs.skip_builds != true }}
+ needs: [build-linux-portable]
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - arch: amd64
+ runner: ubuntu-latest
+ - arch: arm64
+ runner: ubuntu-24.04-arm
+ runs-on: ${{ matrix.runner }}
+ container:
+ image: alpine:3.21
+ timeout-minutes: 30
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+
+ - name: Install musl build deps
+ run: apk add --no-cache build-base linux-headers zlib-dev zlib-static python3 git nodejs npm
+
+ - name: Build (release mode, static)
+ run: scripts/build.sh CC=gcc CXX=g++ STATIC=1
+
+ - name: Quick soak (10 min)
+ run: scripts/soak-test.sh build/c/codebase-memory-mcp 10
+
+ - name: Upload soak metrics
+ if: always()
+ uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
+ with:
+ name: soak-quick-linux-${{ matrix.arch }}-portable
+ path: soak-results/
+ retention-days: 14
+
+ # ── Step 6d: ASan soak (portable Linux, musl static) ──────────
+ soak-asan-linux-portable:
+ if: ${{ !cancelled() && inputs.soak_level == 'full' && inputs.skip_builds != true }}
+ needs: [build-linux-portable]
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - arch: amd64
+ runner: ubuntu-latest
+ - arch: arm64
+ runner: ubuntu-24.04-arm
+ runs-on: ${{ matrix.runner }}
+ container:
+ image: alpine:3.21
+ timeout-minutes: 45
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+
+ - name: Install musl build deps
+ run: apk add --no-cache build-base linux-headers zlib-dev zlib-static python3 git nodejs npm
+
+ - name: Build (ASan + LeakSanitizer, static)
+ run: |
+ SANITIZE="-fsanitize=address,undefined -fno-omit-frame-pointer"
+ scripts/build.sh CC=gcc CXX=g++ STATIC=1 EXTRA_CFLAGS="$SANITIZE" EXTRA_LDFLAGS="$SANITIZE"
+
+ - name: ASan soak (15 min)
+ env:
+ ASAN_OPTIONS: "detect_leaks=1:halt_on_error=0:log_path=soak-results/asan"
+ run: scripts/soak-test.sh build/c/codebase-memory-mcp 15
+
+ - name: Upload ASan soak metrics
+ if: always()
+ uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
+ with:
+ name: soak-asan-linux-${{ matrix.arch }}-portable
+ path: soak-results/
+ retention-days: 14
diff --git a/.github/workflows/nightly-soak.yml b/.github/workflows/nightly-soak.yml
index 10231db1b..1618406b6 100644
--- a/.github/workflows/nightly-soak.yml
+++ b/.github/workflows/nightly-soak.yml
@@ -51,7 +51,7 @@ jobs:
echo "Skipping ${{ matrix.goos }}-${{ matrix.goarch }} (filter: ${{ inputs.platforms }})"
exit 0
- - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v4
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
- name: Install deps (Linux)
if: startsWith(matrix.os, 'ubuntu')
@@ -65,7 +65,7 @@ jobs:
- name: Upload soak metrics
if: always()
- uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: nightly-soak-${{ matrix.goos }}-${{ matrix.goarch }}
path: soak-results/
@@ -95,7 +95,7 @@ jobs:
if: ${{ !contains(matrix.filter, inputs.platforms || 'all') }}
run: exit 0
- - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v4
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
- name: Install deps
run: sudo apt-get update && sudo apt-get install -y zlib1g-dev python3 git
@@ -112,8 +112,91 @@ jobs:
- name: Upload ASan soak metrics
if: always()
- uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: nightly-asan-${{ matrix.goos }}-${{ matrix.goarch }}
path: soak-results/
retention-days: 30
+
+ # ── Nightly soak: portable Linux (musl static) ──────────────
+ soak-nightly-portable:
+ runs-on: ${{ matrix.runner }}
+ container:
+ image: alpine:3.21
+ timeout-minutes: 330
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - runner: ubuntu-latest
+ arch: amd64
+ filter: all linux-only
+ - runner: ubuntu-24.04-arm
+ arch: arm64
+ filter: all linux-only
+ steps:
+ - name: Check platform filter
+ if: ${{ !contains(matrix.filter, inputs.platforms || 'all') }}
+ run: exit 0
+
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+
+ - name: Install musl build deps
+ run: apk add --no-cache build-base linux-headers zlib-dev zlib-static python3 git nodejs npm
+
+ - name: Build (release mode, static)
+ run: scripts/build.sh CC=gcc CXX=g++ STATIC=1
+
+ - name: Nightly soak (${{ inputs.duration_minutes || 240 }} min, portable)
+ run: scripts/soak-test.sh build/c/codebase-memory-mcp ${{ inputs.duration_minutes || 240 }}
+
+ - name: Upload soak metrics
+ if: always()
+ uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
+ with:
+ name: nightly-soak-linux-${{ matrix.arch }}-portable
+ path: soak-results/
+ retention-days: 30
+
+ soak-nightly-asan-portable:
+ runs-on: ${{ matrix.runner }}
+ container:
+ image: alpine:3.21
+ timeout-minutes: 120
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - runner: ubuntu-latest
+ arch: amd64
+ filter: all linux-only
+ - runner: ubuntu-24.04-arm
+ arch: arm64
+ filter: all linux-only
+ steps:
+ - name: Check platform filter
+ if: ${{ !contains(matrix.filter, inputs.platforms || 'all') }}
+ run: exit 0
+
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+
+ - name: Install musl build deps
+ run: apk add --no-cache build-base linux-headers zlib-dev zlib-static python3 git nodejs npm
+
+ - name: Build (ASan + LeakSanitizer, static)
+ run: |
+ SANITIZE="-fsanitize=address,undefined -fno-omit-frame-pointer"
+ scripts/build.sh CC=gcc CXX=g++ STATIC=1 EXTRA_CFLAGS="$SANITIZE" EXTRA_LDFLAGS="$SANITIZE"
+
+ - name: ASan soak (60 min, portable)
+ env:
+ ASAN_OPTIONS: "detect_leaks=1:halt_on_error=0:log_path=soak-results/asan"
+ run: scripts/soak-test.sh build/c/codebase-memory-mcp 60
+
+ - name: Upload ASan soak metrics
+ if: always()
+ uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
+ with:
+ name: nightly-asan-linux-${{ matrix.arch }}-portable
+ path: soak-results/
+ retention-days: 30
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index fef431b55..30ae203ca 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -334,6 +334,102 @@ jobs:
name: binaries-windows-amd64
path: "*.zip"
+ # ── Step 3b: Build portable Linux binaries (musl static) ────
+ build-linux-portable:
+ needs: [test-unix, test-windows]
+ strategy:
+ matrix:
+ include:
+ - arch: amd64
+ runner: ubuntu-latest
+ - arch: arm64
+ runner: ubuntu-24.04-arm
+ runs-on: ${{ matrix.runner }}
+ container:
+ image: alpine:3.21
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+
+ - name: Install musl build deps
+ run: apk add --no-cache build-base linux-headers zlib-dev zlib-static nodejs npm
+
+ - name: Build standard binary (static)
+ run: scripts/build.sh --version ${{ inputs.version }} CC=gcc CXX=g++ STATIC=1
+
+ - name: Verify static linking
+ run: |
+ file build/c/codebase-memory-mcp | grep -q "statically linked"
+ echo "=== Confirmed: fully static binary ==="
+
+ - name: Archive standard binary
+ run: |
+ cp LICENSE install.sh build/c/
+ tar -czf codebase-memory-mcp-linux-${{ matrix.arch }}-portable.tar.gz \
+ -C build/c codebase-memory-mcp LICENSE install.sh
+
+ - name: Build UI binary (static)
+ run: scripts/build.sh --with-ui --version ${{ inputs.version }} CC=gcc CXX=g++ STATIC=1
+
+ - name: Archive UI binary
+ run: |
+ cp LICENSE install.sh build/c/
+ tar -czf codebase-memory-mcp-ui-linux-${{ matrix.arch }}-portable.tar.gz \
+ -C build/c codebase-memory-mcp LICENSE install.sh
+
+ - uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
+ with:
+ name: binaries-linux-${{ matrix.arch }}-portable
+ path: "*.tar.gz"
+
+ build-windows:
+ needs: [test-unix, test-windows]
+ runs-on: windows-latest
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+
+ - uses: msys2/setup-msys2@4f806de0a5a7294ffabaff804b38a9b435a73bda # v2
+ with:
+ msystem: CLANG64
+ path-type: inherit
+ install: >-
+ mingw-w64-clang-x86_64-clang
+ mingw-w64-clang-x86_64-zlib
+ make
+ zip
+
+ - uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0
+ with:
+ node-version: "22"
+
+ - name: Build standard binary
+ shell: msys2 {0}
+ run: scripts/build.sh --version ${{ inputs.version }} CC=clang CXX=clang++
+
+ - name: Archive standard binary
+ shell: msys2 {0}
+ run: |
+ BIN=build/c/codebase-memory-mcp
+ [ -f "${BIN}.exe" ] && BIN="${BIN}.exe"
+ cp "$BIN" codebase-memory-mcp.exe
+ zip codebase-memory-mcp-windows-amd64.zip codebase-memory-mcp.exe LICENSE install.ps1
+
+ - name: Build UI binary
+ shell: msys2 {0}
+ run: scripts/build.sh --with-ui --version ${{ inputs.version }} CC=clang CXX=clang++
+
+ - name: Archive UI binary
+ shell: msys2 {0}
+ run: |
+ BIN=build/c/codebase-memory-mcp
+ [ -f "${BIN}.exe" ] && BIN="${BIN}.exe"
+ cp "$BIN" codebase-memory-mcp.exe
+ zip codebase-memory-mcp-ui-windows-amd64.zip codebase-memory-mcp.exe LICENSE install.ps1
+
+ - uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
+ with:
+ name: binaries-windows-amd64
+ path: "*.zip"
+
# ── Step 4: Smoke test every binary ─────────────────────────
smoke-unix:
needs: [build-unix]
diff --git a/.gitignore b/.gitignore
index e11b2be7c..7a7666e0f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -50,3 +50,6 @@ graph-ui/dist/
BENCHMARK_REPORT.md
TEST_PLAN.md
CHANGELOG.md
+
+# Soak test output
+soak-results/
diff --git a/Makefile.cbm b/Makefile.cbm
index eeb2b9c00..c4c8e6dc0 100644
--- a/Makefile.cbm
+++ b/Makefile.cbm
@@ -172,7 +172,6 @@ PIPELINE_SRCS = \
src/pipeline/pass_semantic.c \
src/pipeline/pass_tests.c \
src/pipeline/pass_githistory.c \
- src/pipeline/pass_httplinks.c \
src/pipeline/pass_gitdiff.c \
src/pipeline/pass_configures.c \
src/pipeline/pass_configlink.c \
@@ -182,7 +181,6 @@ PIPELINE_SRCS = \
src/pipeline/pass_compile_commands.c \
src/pipeline/pass_infrascan.c \
src/pipeline/pass_k8s.c \
- src/pipeline/httplink.c
# Traces module (new)
TRACES_SRCS = src/traces/traces.c
@@ -287,7 +285,6 @@ TEST_INTEGRATION_SRCS = tests/test_integration.c tests/test_incremental.c
TEST_TRACES_SRCS = tests/test_traces.c
-TEST_HTTPLINK_SRCS = tests/test_httplink.c
TEST_CLI_SRCS = tests/test_cli.c
@@ -299,7 +296,8 @@ TEST_SECURITY_SRCS = tests/test_security.c
TEST_YAML_SRCS = tests/test_yaml.c
-ALL_TEST_SRCS = $(TEST_FOUNDATION_SRCS) $(TEST_EXTRACTION_SRCS) $(TEST_STORE_SRCS) $(TEST_CYPHER_SRCS) $(TEST_MCP_SRCS) $(TEST_DISCOVER_SRCS) $(TEST_GRAPH_BUFFER_SRCS) $(TEST_PIPELINE_SRCS) $(TEST_WATCHER_SRCS) $(TEST_LZ4_SRCS) $(TEST_SQLITE_WRITER_SRCS) $(TEST_GO_LSP_SRCS) $(TEST_C_LSP_SRCS) $(TEST_TRACES_SRCS) $(TEST_HTTPLINK_SRCS) $(TEST_CLI_SRCS) $(TEST_MEM_SRCS) $(TEST_UI_SRCS) $(TEST_SECURITY_SRCS) $(TEST_YAML_SRCS) $(TEST_INTEGRATION_SRCS)
+ALL_TEST_SRCS = $(TEST_FOUNDATION_SRCS) $(TEST_EXTRACTION_SRCS) $(TEST_STORE_SRCS) $(TEST_CYPHER_SRCS) $(TEST_MCP_SRCS) $(TEST_DISCOVER_SRCS) $(TEST_GRAPH_BUFFER_SRCS) $(TEST_PIPELINE_SRCS) $(TEST_WATCHER_SRCS) $(TEST_LZ4_SRCS) $(TEST_SQLITE_WRITER_SRCS) $(TEST_GO_LSP_SRCS) $(TEST_C_LSP_SRCS) $(TEST_TRACES_SRCS) $(TEST_CLI_SRCS) $(TEST_MEM_SRCS) $(TEST_UI_SRCS) $(TEST_SECURITY_SRCS) $(TEST_YAML_SRCS) $(TEST_INTEGRATION_SRCS)
+
# ── Build directories ────────────────────────────────────────────
@@ -395,7 +393,14 @@ $(BUILD_DIR)/prod_tre.o: $(TRE_SRC) | $(BUILD_DIR)
$(CC) $(TRE_CFLAGS) -O2 -c -o $@ $<
endif
-OBJS_VENDORED_TEST = $(MIMALLOC_OBJ_TEST) $(SQLITE3_OBJ_TEST) $(TRE_OBJ_TEST) $(GRAMMAR_OBJS_TEST) $(TS_RUNTIME_OBJ_TEST) $(LSP_OBJ_TEST) $(PP_OBJ_TEST) $(MONGOOSE_OBJ_TEST)
+# Vendored LZ4 (test build)
+LZ4_OBJ_TEST = $(BUILD_DIR)/test_lz4.o $(BUILD_DIR)/test_lz4hc.o
+$(BUILD_DIR)/test_lz4.o: $(CBM_DIR)/vendored/lz4/lz4.c | $(BUILD_DIR)
+ $(CC) -std=c11 -D_DEFAULT_SOURCE -g -O1 $(SANITIZE) -w -I$(CBM_DIR) -c -o $@ $<
+$(BUILD_DIR)/test_lz4hc.o: $(CBM_DIR)/vendored/lz4/lz4hc.c | $(BUILD_DIR)
+ $(CC) -std=c11 -D_DEFAULT_SOURCE -g -O1 $(SANITIZE) -w -I$(CBM_DIR)/vendored/lz4 -c -o $@ $<
+
+OBJS_VENDORED_TEST = $(MIMALLOC_OBJ_TEST) $(SQLITE3_OBJ_TEST) $(TRE_OBJ_TEST) $(GRAMMAR_OBJS_TEST) $(TS_RUNTIME_OBJ_TEST) $(LSP_OBJ_TEST) $(PP_OBJ_TEST) $(MONGOOSE_OBJ_TEST) $(LZ4_OBJ_TEST)
$(BUILD_DIR)/test-runner: $(ALL_TEST_SRCS) $(PROD_SRCS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(SQLITE_WRITER_SRC) $(OBJS_VENDORED_TEST) | $(BUILD_DIR)
$(CC) $(CFLAGS_TEST) -o $@ \
@@ -432,7 +437,14 @@ $(BUILD_DIR)/prod_lsp_all.o: $(CBM_DIR)/lsp_all.c | $(BUILD_DIR)
$(BUILD_DIR)/prod_preprocessor.o: $(CBM_DIR)/preprocessor.cpp | $(BUILD_DIR)
$(CXX) $(CXXFLAGS_PROD) -w -I$(CBM_DIR)/vendored -c -o $@ $<
-OBJS_VENDORED_PROD = $(MIMALLOC_OBJ_PROD) $(SQLITE3_OBJ_PROD) $(TRE_OBJ_PROD) $(GRAMMAR_OBJS_PROD) $(TS_RUNTIME_OBJ_PROD) $(LSP_OBJ_PROD) $(PP_OBJ_PROD) $(MONGOOSE_OBJ_PROD)
+# Vendored LZ4 (compiled separately, not unity-built via lz4_store.c)
+LZ4_OBJ_PROD = $(BUILD_DIR)/prod_lz4.o $(BUILD_DIR)/prod_lz4hc.o
+$(BUILD_DIR)/prod_lz4.o: $(CBM_DIR)/vendored/lz4/lz4.c | $(BUILD_DIR)
+ $(CC) -std=c11 -D_DEFAULT_SOURCE -O2 -w -I$(CBM_DIR) -c -o $@ $<
+$(BUILD_DIR)/prod_lz4hc.o: $(CBM_DIR)/vendored/lz4/lz4hc.c | $(BUILD_DIR)
+ $(CC) -std=c11 -D_DEFAULT_SOURCE -O2 -w -I$(CBM_DIR)/vendored/lz4 -c -o $@ $<
+
+OBJS_VENDORED_PROD = $(MIMALLOC_OBJ_PROD) $(SQLITE3_OBJ_PROD) $(TRE_OBJ_PROD) $(GRAMMAR_OBJS_PROD) $(TS_RUNTIME_OBJ_PROD) $(LSP_OBJ_PROD) $(PP_OBJ_PROD) $(MONGOOSE_OBJ_PROD) $(LZ4_OBJ_PROD)
MAIN_SRC = src/main.c
@@ -524,14 +536,23 @@ lint-format:
@echo "=== clang-format ==="
@$(CLANG_FORMAT) --dry-run --Werror $(LINT_SRCS) $(LINT_HDRS)
-# Ban NOLINTNEXTLINE in our code (vendored code exempt)
+# Ban ALL NOLINT variants EXCEPT whitelisted NOLINT(misc-no-recursion).
+# The whitelist is in src/foundation/recursion_whitelist.h with documented reasoning.
+# Rule: NOLINT(misc-no-recursion) is allowed ONLY on function definitions that are
+# listed in recursion_whitelist.h. All other NOLINT forms are banned.
lint-no-suppress:
- @echo "=== NOLINTNEXTLINE check ==="
- @if grep -rn 'NOLINTNEXTLINE\|NOLINTBEGIN\|NOLINTEND' src/ internal/cbm/*.c 2>/dev/null | grep -v vendored; then \
- echo "ERROR: NOLINTNEXTLINE/NOLINTBEGIN/NOLINTEND found in source code."; \
- echo "Fix the underlying issue instead of suppressing the linter."; \
+ @echo "=== NOLINT check ==="
+ @if grep -rn 'NOLINT' src/ internal/cbm/*.c internal/cbm/*.h 2>/dev/null \
+ | grep -v vendored \
+ | grep -v 'NOLINT(misc-no-recursion)' \
+ | grep -v 'recursion_whitelist.h'; then \
+ echo "ERROR: Banned NOLINT comment found in source code."; \
+ echo "Only NOLINT(misc-no-recursion) is allowed, and only for whitelisted functions."; \
+ echo "See src/foundation/recursion_whitelist.h for the whitelist."; \
exit 1; \
fi
+ @echo " Checking NOLINT(misc-no-recursion) against whitelist..."
+ @scripts/check-nolint-whitelist.sh
# All linters (run with make -j3 lint for parallel execution)
lint: lint-tidy lint-cppcheck lint-format lint-no-suppress
diff --git a/internal/cbm/ac.c b/internal/cbm/ac.c
index 69b29729e..f693d709b 100644
--- a/internal/cbm/ac.c
+++ b/internal/cbm/ac.c
@@ -21,18 +21,25 @@
// Maximum pattern count for bitmask mode.
#define CBM_AC_MAX_BITMASK 64
+#define CBM_AC_BYTE_RANGE 256
+#define CBM_AC_NO_STATE (-1)
+#define CBM_AC_ROOT_STATES 1
+#define CBM_AC_ALLOC_ONE 1
+#define CBM_AC_PATTERN_BIT(p) (1ULL << (p))
+#define CBM_AC_CLEAR_LOW_BIT(b) ((b) & ((b) - 1ULL))
+
// Decompression buffer alignment mask (round up to 64KB chunks).
#define DECOMP_BUF_ALIGN_MASK 0xFFFF
struct CBMAutomaton {
int num_states;
int num_patterns;
- int alpha_size; // 256 for raw byte, or smaller for mapped alphabet
- uint8_t alpha_map[256]; // byte → mapped index (identity if alpha_size==256)
- int *go_table; // [num_states * alpha_size] — pre-computed transitions
- uint64_t *output; // [num_states] — bitmask of matching pattern IDs
- int *output_list; // [num_states] — linked list: pattern ID or -1
- int *output_next; // [num_states] — next pointer for output_list chain
+ int alpha_size; // 256 for raw byte, or smaller for mapped alphabet
+ uint8_t alpha_map[CBM_AC_BYTE_RANGE]; // byte → mapped index (identity if alpha_size==256)
+ int *go_table; // [num_states * alpha_size] — pre-computed transitions
+ uint64_t *output; // [num_states] — bitmask of matching pattern IDs
+ int *output_list; // [num_states] — linked list: pattern ID or -1
+ int *output_next; // [num_states] — next pointer for output_list chain
};
// ─── Build ─────────────────────────────────────────────────────────────────
@@ -64,27 +71,27 @@ static void queue_free(Queue *q) {
// Phase 1: Build trie (goto function) from patterns. Returns state count.
static int ac_build_trie(CBMAutomaton *ac, const char **patterns, const int *lengths, int count) {
int alpha_size = ac->alpha_size;
- int num_states = 1; // state 0 = root
+ int num_states = CBM_AC_ROOT_STATES; // state 0 = root
for (int p = 0; p < count; p++) {
int state = 0;
for (int j = 0; j < lengths[p]; j++) {
int c = ac->alpha_map[(unsigned char)patterns[p][j]];
int idx = (state * alpha_size) + c;
- if (ac->go_table[idx] == -1) {
+ if (ac->go_table[idx] == CBM_AC_NO_STATE) {
ac->go_table[idx] = num_states++;
}
state = ac->go_table[idx];
}
if (p < CBM_AC_MAX_BITMASK) {
- ac->output[state] |= (1ULL << p);
+ ac->output[state] |= CBM_AC_PATTERN_BIT(p);
}
ac->output_list[state] = p;
}
// Root self-loops for unmatched bytes.
for (int c = 0; c < alpha_size; c++) {
- if (ac->go_table[c] == -1) {
+ if (ac->go_table[c] == CBM_AC_NO_STATE) {
ac->go_table[c] = 0;
}
}
@@ -112,10 +119,11 @@ static void ac_build_failure(CBMAutomaton *ac, int num_states) {
for (int c = 0; c < alpha_size; c++) {
int idx = (r * alpha_size) + c;
int s = ac->go_table[idx];
- if (s != -1) {
+ if (s != CBM_AC_NO_STATE) {
fail[s] = ac->go_table[(fail[r] * alpha_size) + c];
ac->output[s] |= ac->output[fail[s]];
- if (ac->output_next[s] == -1 && ac->output_list[fail[s]] != -1) {
+ if (ac->output_next[s] == CBM_AC_NO_STATE &&
+ ac->output_list[fail[s]] != CBM_AC_NO_STATE) {
ac->output_next[s] = fail[s];
}
queue_push(&q, s);
@@ -171,34 +179,34 @@ CBMAutomaton *cbm_ac_build(const char **patterns, const int *lengths, int count,
return NULL;
}
if (alpha_size <= 0) {
- alpha_size = 256;
+ alpha_size = CBM_AC_BYTE_RANGE;
}
- int max_states = 1;
+ int max_states = CBM_AC_ROOT_STATES;
for (int i = 0; i < count; i++) {
max_states += lengths[i];
}
- CBMAutomaton *ac = (CBMAutomaton *)calloc(1, sizeof(CBMAutomaton));
+ CBMAutomaton *ac = (CBMAutomaton *)calloc(CBM_AC_ALLOC_ONE, sizeof(CBMAutomaton));
ac->alpha_size = alpha_size;
ac->num_patterns = count;
if (alpha_map) {
- memcpy(ac->alpha_map, alpha_map, 256);
+ memcpy(ac->alpha_map, alpha_map, CBM_AC_BYTE_RANGE);
} else {
- for (int i = 0; i < 256; i++) {
+ for (int i = 0; i < CBM_AC_BYTE_RANGE; i++) {
ac->alpha_map[i] = (uint8_t)i;
}
}
ac->go_table = (int *)malloc((size_t)max_states * alpha_size * sizeof(int));
- memset(ac->go_table, -1, (size_t)max_states * alpha_size * sizeof(int));
+ memset(ac->go_table, CBM_AC_NO_STATE, (size_t)max_states * alpha_size * sizeof(int));
ac->output = (uint64_t *)calloc(max_states, sizeof(uint64_t));
ac->output_list = (int *)malloc(max_states * sizeof(int));
ac->output_next = (int *)malloc(max_states * sizeof(int));
for (int i = 0; i < max_states; i++) {
- ac->output_list[i] = -1;
- ac->output_next[i] = -1;
+ ac->output_list[i] = CBM_AC_NO_STATE;
+ ac->output_next[i] = CBM_AC_NO_STATE;
}
int num_states = ac_build_trie(ac, patterns, lengths, count);
@@ -252,7 +260,7 @@ static char *get_decomp_buf(int needed) {
free(tls_decomp_buf);
// Round up to 64KB chunks for reuse.
int cap = (needed + DECOMP_BUF_ALIGN_MASK) & ~DECOMP_BUF_ALIGN_MASK;
- tls_decomp_buf = (char *)malloc((size_t)cap);
+ tls_decomp_buf = (cap > 0) ? (char *)malloc((size_t)cap) : NULL;
tls_decomp_cap = cap;
}
return tls_decomp_buf;
@@ -385,13 +393,13 @@ int cbm_ac_scan_batch(const CBMAutomaton *ac, const char *names_buf, const int *
out_matches[total].name_index = n;
out_matches[total].pattern_id = pid;
total++;
- seen |= (1ULL << pid);
- bits &= bits - 1; // clear lowest set bit
+ seen |= CBM_AC_PATTERN_BIT(pid);
+ bits = CBM_AC_CLEAR_LOW_BIT(bits);
}
// Follow output_next for patterns beyond bitmask range.
int next_state = ac->output_next[s];
- if (next_state == -1 || next_state == s) {
+ if (next_state == CBM_AC_NO_STATE || next_state == s) {
break;
}
s = next_state;
diff --git a/internal/cbm/arena.c b/internal/cbm/arena.c
index ca689aa24..7f268048f 100644
--- a/internal/cbm/arena.c
+++ b/internal/cbm/arena.c
@@ -9,7 +9,7 @@ void cbm_arena_init(CBMArena *a) {
a->block_size = CBM_ARENA_DEFAULT_BLOCK_SIZE;
a->blocks[0] = (char *)malloc(a->block_size);
if (a->blocks[0]) {
- a->nblocks = 1;
+ a->nblocks = SKIP_ONE;
}
}
@@ -17,7 +17,7 @@ static int arena_grow(CBMArena *a, size_t min_size) {
if (a->nblocks >= CBM_ARENA_MAX_BLOCKS) {
return 0;
}
- size_t new_size = a->block_size * 2;
+ size_t new_size = a->block_size * PAIR_LEN;
if (new_size < min_size) {
new_size = min_size;
}
@@ -49,7 +49,7 @@ void *cbm_arena_alloc(CBMArena *a, size_t n) {
}
}
- char *ptr = a->blocks[a->nblocks - 1] + a->used;
+ char *ptr = a->blocks[a->nblocks - SKIP_ONE] + a->used;
a->used += n;
return ptr;
}
@@ -58,9 +58,9 @@ char *cbm_arena_strdup(CBMArena *a, const char *s) {
if (!s)
return NULL;
size_t len = strlen(s);
- char *dst = (char *)cbm_arena_alloc(a, len + 1);
+ char *dst = (char *)cbm_arena_alloc(a, len + SKIP_ONE);
if (dst) {
- memcpy(dst, s, len + 1);
+ memcpy(dst, s, len + SKIP_ONE);
}
return dst;
}
@@ -68,7 +68,7 @@ char *cbm_arena_strdup(CBMArena *a, const char *s) {
char *cbm_arena_strndup(CBMArena *a, const char *s, size_t len) {
if (!s)
return NULL;
- char *dst = (char *)cbm_arena_alloc(a, len + 1);
+ char *dst = (char *)cbm_arena_alloc(a, len + SKIP_ONE);
if (dst) {
memcpy(dst, s, len);
dst[len] = '\0';
@@ -87,13 +87,13 @@ char *cbm_arena_sprintf(CBMArena *a, const char *fmt, ...) {
return NULL;
}
- char *dst = (char *)cbm_arena_alloc(a, (size_t)needed + 1);
+ char *dst = (char *)cbm_arena_alloc(a, (size_t)needed + SKIP_ONE);
if (!dst) {
return NULL;
}
va_start(args, fmt);
- vsnprintf(dst, (size_t)needed + 1, fmt, args);
+ vsnprintf(dst, (size_t)needed + SKIP_ONE, fmt, args);
va_end(args);
return dst;
diff --git a/internal/cbm/cbm.c b/internal/cbm/cbm.c
index 086e8529d..3d5360a31 100644
--- a/internal/cbm/cbm.c
+++ b/internal/cbm/cbm.c
@@ -8,10 +8,11 @@
#include "preprocessor.h"
#include "foundation/compat.h"
#include "tree_sitter/api.h" // TSParser, TSNode, TSTree, TSInput, TSLanguage, TSPoint, TSParseOptions, TSParseState
+#include "foundation/constants.h"
#include <stdint.h> // uint32_t, uint64_t, int64_t
#include <stdlib.h>
#include <string.h>
-#include <time.h> // clock_gettime, CLOCK_MONOTONIC
+#include <time.h> // struct timespec, CLOCK_MONOTONIC
// Atomic counters for profiling parse vs extraction time (nanoseconds).
// Accessed from multiple threads; using _Atomic for safe accumulation.
@@ -24,18 +25,27 @@ static _Atomic uint64_t total_files_preprocessed = 0;
static _Atomic uint64_t total_files = 0;
#define NSEC_PER_SEC 1000000000ULL
+#define USEC_TO_NSEC 1000ULL
+/* Use compat.h's cbm_clock_gettime which accepts CLOCK_MONOTONIC (value
+ * varies by platform: 1 on Linux/Windows, 6 on macOS). We pass the
+ * platform value via the compat.h fallback. */
+#ifdef __APPLE__
+#define CBM_CLOCK_MONO 6
+#else
+#define CBM_CLOCK_MONO 1
+#endif
static uint64_t now_ns(void) {
struct timespec ts;
- cbm_clock_gettime(CLOCK_MONOTONIC, &ts);
+ cbm_clock_gettime(CBM_CLOCK_MONO, &ts);
return ((uint64_t)ts.tv_sec * NSEC_PER_SEC) + (uint64_t)ts.tv_nsec;
}
// cbm_get_profile returns accumulated parse/extract times and file count.
-void cbm_get_profile(uint64_t *parse_ns, uint64_t *extract_ns, uint64_t *files) {
- *parse_ns = atomic_load(&total_parse_ns);
- *extract_ns = atomic_load(&total_extract_ns);
- *files = atomic_load(&total_files);
+void cbm_get_profile(cbm_profile_out_t out) {
+ *out.parse_ns = atomic_load(&total_parse_ns);
+ *out.extract_ns = atomic_load(&total_extract_ns);
+ *out.files = atomic_load(&total_files);
}
uint64_t cbm_get_lsp_ns(void) {
@@ -65,7 +75,7 @@ void cbm_reset_profile(void) {
#define GROW_ARRAY(arr, arena) \
do { \
if ((arr)->count >= (arr)->cap) { \
- int new_cap = (arr)->cap == 0 ? 32 : (arr)->cap * 2; \
+ int new_cap = (arr)->cap == 0 ? CBM_SZ_32 : (arr)->cap * PAIR_LEN; \
void *new_items = cbm_arena_alloc((arena), (size_t)new_cap * sizeof(*(arr)->items)); \
if (!new_items) \
return; \
@@ -200,7 +210,8 @@ int cbm_init(void) {
if (cbm_initialized) {
return 0;
}
- cbm_initialized = 1;
+ enum { CBM_INIT_DONE = 1 };
+ cbm_initialized = CBM_INIT_DONE;
return 0;
}
@@ -235,7 +246,8 @@ CBMFileResult *cbm_extract_file(const char *source, int source_len, CBMLanguage
const char *project, const char *rel_path, int64_t timeout_micros,
const char **extra_defines, const char **include_paths) {
// Allocate result on heap (arena inside for all string data)
- CBMFileResult *result = (CBMFileResult *)calloc(1, sizeof(CBMFileResult));
+ enum { SINGLE = 1 };
+ CBMFileResult *result = (CBMFileResult *)calloc(SINGLE, sizeof(CBMFileResult));
if (!result) {
return NULL;
}
@@ -284,7 +296,7 @@ CBMFileResult *cbm_extract_file(const char *source, int source_len, CBMLanguage
TSParseOptions opts = {0};
uint64_t deadline_ns = 0; // cppcheck-suppress unreadVariable
if (timeout_micros > 0) {
- deadline_ns = t0 + ((uint64_t)timeout_micros * 1000ULL);
+ deadline_ns = t0 + ((uint64_t)timeout_micros * USEC_TO_NSEC);
opts.payload = &deadline_ns;
opts.progress_callback = cbm_timeout_cb;
}
diff --git a/internal/cbm/cbm.h b/internal/cbm/cbm.h
index c4fcb114d..56876a49e 100644
--- a/internal/cbm/cbm.h
+++ b/internal/cbm/cbm.h
@@ -390,7 +390,12 @@ void cbm_destroy_thread_parser(void);
void cbm_shutdown(void);
// Profiling: get accumulated parse/extraction times and file count.
-void cbm_get_profile(uint64_t *parse_ns, uint64_t *extract_ns, uint64_t *files);
+typedef struct {
+ uint64_t *parse_ns;
+ uint64_t *extract_ns;
+ uint64_t *files;
+} cbm_profile_out_t;
+void cbm_get_profile(cbm_profile_out_t out);
uint64_t cbm_get_lsp_ns(void);
uint64_t cbm_get_preprocess_ns(void);
uint64_t cbm_get_files_preprocessed(void);
diff --git a/internal/cbm/extract_calls.c b/internal/cbm/extract_calls.c
index 3195b1334..24b59c4a4 100644
--- a/internal/cbm/extract_calls.c
+++ b/internal/cbm/extract_calls.c
@@ -3,11 +3,25 @@
#include "helpers.h"
#include "lang_specs.h"
#include "extract_unified.h"
+#include "foundation/constants.h"
#include "tree_sitter/api.h" // TSNode, ts_node_*
#include <stdint.h> // uint32_t
#include <string.h>
#include <ctype.h>
+/* Max ancestor depth for Lean type-position check. */
+enum { LEAN_MAX_PARENT_DEPTH = 20 };
+/* Max positional args to scan for URL/string. */
+enum { MAX_POSITIONAL_SCAN = 3 };
+/* Max positional args to scan for handler ref. */
+enum { MAX_HANDLER_SCAN = 4 };
+/* Max string arg length before rejection. */
+enum { MAX_STRING_ARG_LEN = CBM_SZ_512 };
+/* Min printable ASCII (space). */
+enum { MIN_PRINTABLE = 0x20 };
+/* Handler arg scan start index (skip first positional). */
+enum { HANDLER_START_IDX = 1 };
+
/* Look up a module-level string constant by name. */
static const char *lookup_string_constant(const CBMExtractCtx *ctx, const char *name) {
if (!name || !name[0]) {
@@ -35,8 +49,8 @@ static const char *strip_quotes(CBMArena *a, const char *text) {
return NULL;
}
int len = (int)strlen(text);
- if (len >= 2 && (text[0] == '"' || text[0] == '\'')) {
- return cbm_arena_strndup(a, text + 1, (size_t)(len - 2));
+ if (len >= CBM_QUOTE_PAIR && (text[0] == '"' || text[0] == '\'')) {
+ return cbm_arena_strndup(a, text + CBM_QUOTE_OFFSET, (size_t)(len - CBM_QUOTE_PAIR));
}
return text;
}
@@ -53,7 +67,7 @@ static void extract_jsx_refs(CBMExtractCtx *ctx, TSNode node);
// only if it overlaps the body range of the enclosing declaration.
static bool lean_is_in_type_position(TSNode node) {
TSNode cur = ts_node_parent(node);
- for (int depth = 0; depth < 20; depth++) {
+ for (int depth = 0; depth < LEAN_MAX_PARENT_DEPTH; depth++) {
if (ts_node_is_null(cur)) {
return false;
}
@@ -70,7 +84,7 @@ static bool lean_is_in_type_position(TSNode node) {
// Check if apply comes after the type annotation.
// Strategy: if the node starts after the end of the "type" field, it's in value
// position. If there's no "type" field, allow the call (no annotation to filter).
- TSNode type_field = ts_node_child_by_field_name(cur, "type", 4);
+ TSNode type_field = ts_node_child_by_field_name(cur, TS_FIELD("type"));
if (ts_node_is_null(type_field)) {
return false; // no type annotation → allow call
}
@@ -90,7 +104,7 @@ static bool lean_is_in_type_position(TSNode node) {
// Try common field-based callee resolution (function, name, method fields).
static char *extract_callee_from_fields(CBMArena *a, TSNode node, const char *source) {
// Try "function" field
- TSNode func_node = ts_node_child_by_field_name(node, "function", 8);
+ TSNode func_node = ts_node_child_by_field_name(node, TS_FIELD("function"));
if (!ts_node_is_null(func_node)) {
const char *fk = ts_node_type(func_node);
if (strcmp(fk, "identifier") == 0 || strcmp(fk, "simple_identifier") == 0 ||
@@ -104,10 +118,10 @@ static char *extract_callee_from_fields(CBMArena *a, TSNode node, const char *so
}
// Try "name" field (Java method_invocation)
- TSNode name_node = ts_node_child_by_field_name(node, "name", 4);
+ TSNode name_node = ts_node_child_by_field_name(node, TS_FIELD("name"));
if (!ts_node_is_null(name_node)) {
char *name = cbm_node_text(a, name_node, source);
- TSNode obj = ts_node_child_by_field_name(node, "object", 6);
+ TSNode obj = ts_node_child_by_field_name(node, TS_FIELD("object"));
if (!ts_node_is_null(obj) && name) {
char *obj_text = cbm_node_text(a, obj, source);
if (obj_text && obj_text[0]) {
@@ -118,10 +132,10 @@ static char *extract_callee_from_fields(CBMArena *a, TSNode node, const char *so
}
// Ruby: "method" + "receiver" fields
- TSNode method_node = ts_node_child_by_field_name(node, "method", 6);
+ TSNode method_node = ts_node_child_by_field_name(node, TS_FIELD("method"));
if (!ts_node_is_null(method_node)) {
char *method = cbm_node_text(a, method_node, source);
- TSNode recv = ts_node_child_by_field_name(node, "receiver", 8);
+ TSNode recv = ts_node_child_by_field_name(node, TS_FIELD("receiver"));
if (!ts_node_is_null(recv) && method) {
char *recv_text = cbm_node_text(a, recv, source);
if (recv_text && recv_text[0]) {
@@ -147,12 +161,13 @@ static char *extract_fp_callee(CBMArena *a, TSNode node, const char *source, con
}
}
if (strcmp(nk, "infix") == 0 || strcmp(nk, "infix_expression") == 0) {
- TSNode op = ts_node_child_by_field_name(node, "operator", 8);
+ TSNode op = ts_node_child_by_field_name(node, TS_FIELD("operator"));
if (!ts_node_is_null(op)) {
return cbm_node_text(a, op, source);
}
- if (ts_node_child_count(node) >= 3) {
- return cbm_node_text(a, ts_node_child(node, 1), source);
+ enum { INFIX_MIN_CHILDREN = 3, INFIX_OP_IDX = 1 };
+ if (ts_node_child_count(node) >= INFIX_MIN_CHILDREN) {
+ return cbm_node_text(a, ts_node_child(node, INFIX_OP_IDX), source);
}
}
return NULL;
@@ -211,9 +226,9 @@ static char *extract_scripting_callee(CBMArena *a, TSNode node, const char *sour
return cbm_node_text(a, ts_node_child(node, 0), source);
}
if (lang == CBM_LANG_PHP) {
- TSNode func_node = ts_node_child_by_field_name(node, "function", 8);
+ TSNode func_node = ts_node_child_by_field_name(node, TS_FIELD("function"));
if (ts_node_is_null(func_node)) {
- func_node = ts_node_child_by_field_name(node, "name", 4);
+ func_node = ts_node_child_by_field_name(node, TS_FIELD("name"));
}
return ts_node_is_null(func_node) ? NULL : cbm_node_text(a, func_node, source);
}
@@ -231,7 +246,7 @@ static char *extract_objc_callee(CBMArena *a, TSNode node, const char *source, c
if (strcmp(nk, "message_expression") != 0) {
return NULL;
}
- TSNode selector = ts_node_child_by_field_name(node, "selector", 8);
+ TSNode selector = ts_node_child_by_field_name(node, TS_FIELD("selector"));
return ts_node_is_null(selector) ? NULL : cbm_node_text(a, selector, source);
}
@@ -304,15 +319,15 @@ static const char *strip_and_validate_string_arg(CBMArena *a, char *text) {
return NULL;
}
int len = (int)strlen(text);
- if (len >= 2 && (text[0] == '"' || text[0] == '\'')) {
- text = cbm_arena_strndup(a, text + 1, (size_t)(len - 2));
- len -= 2;
+ if (len >= CBM_QUOTE_PAIR && (text[0] == '"' || text[0] == '\'')) {
+ text = cbm_arena_strndup(a, text + CBM_QUOTE_OFFSET, (size_t)(len - CBM_QUOTE_PAIR));
+ len -= CBM_QUOTE_PAIR;
}
- if (!text || len <= 0 || len >= 512) {
+ if (!text || len <= 0 || len >= MAX_STRING_ARG_LEN) {
return NULL;
}
for (int vi = 0; vi < len; vi++) {
- if ((unsigned char)text[vi] < 0x20 && text[vi] != '\t') {
+ if ((unsigned char)text[vi] < MIN_PRINTABLE && text[vi] != '\t') {
return NULL;
}
}
@@ -322,7 +337,7 @@ static const char *strip_and_validate_string_arg(CBMArena *a, char *text) {
// Extract first string argument from a call's arguments node.
static const char *extract_first_string_arg(CBMExtractCtx *ctx, TSNode args) {
uint32_t nc = ts_node_named_child_count(args);
- for (uint32_t ai = 0; ai < nc && ai < 3; ai++) {
+ for (uint32_t ai = 0; ai < nc && ai < MAX_POSITIONAL_SCAN; ai++) {
TSNode arg = ts_node_named_child(args, ai);
const char *ak = ts_node_type(arg);
if (is_string_like(ak)) {
@@ -334,7 +349,7 @@ static const char *extract_first_string_arg(CBMExtractCtx *ctx, TSNode args) {
}
// Walk AST for call nodes (iterative)
-#define CALLS_STACK_CAP 512
+#define CALLS_STACK_CAP CBM_SZ_512
static void walk_calls(CBMExtractCtx *ctx, TSNode root, const CBMLangSpec *spec) {
TSNode stack[CALLS_STACK_CAP];
int top = 0;
@@ -351,7 +366,7 @@ static void walk_calls(CBMExtractCtx *ctx, TSNode root, const CBMLangSpec *spec)
call.callee_name = callee;
call.enclosing_func_qn = cbm_enclosing_func_qn_cached(ctx, node);
- TSNode args = ts_node_child_by_field_name(node, "arguments", 9);
+ TSNode args = ts_node_child_by_field_name(node, TS_FIELD("arguments"));
if (!ts_node_is_null(args)) {
call.first_string_arg = extract_first_string_arg(ctx, args);
}
@@ -367,7 +382,8 @@ static void walk_calls(CBMExtractCtx *ctx, TSNode root, const CBMLangSpec *spec)
}
uint32_t count = ts_node_child_count(node);
- for (int i = (int)count - 1; i >= 0 && top < CALLS_STACK_CAP; i--) {
+ enum { LAST_IDX_OFFSET = 1 };
+ for (int i = (int)(count - LAST_IDX_OFFSET); i >= 0 && top < CALLS_STACK_CAP; i--) {
stack[top++] = ts_node_child(node, (uint32_t)i);
}
}
@@ -375,7 +391,7 @@ static void walk_calls(CBMExtractCtx *ctx, TSNode root, const CBMLangSpec *spec)
// Extract JSX component references (uppercase = component, lowercase = HTML)
static void extract_jsx_refs(CBMExtractCtx *ctx, TSNode node) {
- TSNode name_node = ts_node_child_by_field_name(node, "name", 4);
+ TSNode name_node = ts_node_child_by_field_name(node, TS_FIELD("name"));
if (ts_node_is_null(name_node)) {
return;
}
@@ -409,10 +425,10 @@ void cbm_extract_calls(CBMExtractCtx *ctx) {
// Process a keyword argument (keyword_argument or pair node).
static void process_keyword_arg(CBMExtractCtx *ctx, TSNode arg_node, CBMCallArg *ca) {
- TSNode key_n = ts_node_child_by_field_name(arg_node, "name", 4);
- TSNode val_n = ts_node_child_by_field_name(arg_node, "value", 5);
+ TSNode key_n = ts_node_child_by_field_name(arg_node, TS_FIELD("name"));
+ TSNode val_n = ts_node_child_by_field_name(arg_node, TS_FIELD("value"));
if (ts_node_is_null(key_n)) {
- key_n = ts_node_child_by_field_name(arg_node, "key", 3);
+ key_n = ts_node_child_by_field_name(arg_node, TS_FIELD("key"));
}
if (!ts_node_is_null(key_n)) {
ca->keyword = cbm_node_text(ctx->arena, key_n, ctx->source);
@@ -496,10 +512,10 @@ static const char *extract_string_value(CBMExtractCtx *ctx, TSNode val_node) {
// Try to extract URL/topic from a keyword_argument or pair node.
static const char *extract_keyword_url(CBMExtractCtx *ctx, TSNode arg) {
- TSNode key_node = ts_node_child_by_field_name(arg, "name", 4);
- TSNode val_node = ts_node_child_by_field_name(arg, "value", 5);
+ TSNode key_node = ts_node_child_by_field_name(arg, TS_FIELD("name"));
+ TSNode val_node = ts_node_child_by_field_name(arg, TS_FIELD("value"));
if (ts_node_is_null(key_node)) {
- key_node = ts_node_child_by_field_name(arg, "key", 3);
+ key_node = ts_node_child_by_field_name(arg, TS_FIELD("key"));
}
if (ts_node_is_null(key_node) || ts_node_is_null(val_node)) {
return NULL;
@@ -544,7 +560,7 @@ static const char *extract_url_or_topic_arg(CBMExtractCtx *ctx, TSNode args) {
continue;
}
- if (ai < 3) {
+ if (ai < MAX_POSITIONAL_SCAN) {
const char *val = extract_positional_url(ctx, arg, ak);
if (val) {
return val;
@@ -557,7 +573,7 @@ static const char *extract_url_or_topic_arg(CBMExtractCtx *ctx, TSNode args) {
// Extract second argument name (handler ref for route registrations).
static const char *extract_handler_arg(CBMExtractCtx *ctx, TSNode args) {
uint32_t nc = ts_node_named_child_count(args);
- for (uint32_t ai = 1; ai < nc && ai < 4; ai++) {
+ for (uint32_t ai = HANDLER_START_IDX; ai < nc && ai < MAX_HANDLER_SCAN; ai++) {
TSNode arg2 = ts_node_named_child(args, ai);
const char *ak2 = ts_node_type(arg2);
if (strcmp(ak2, "identifier") == 0 || strcmp(ak2, "member_expression") == 0 ||
@@ -575,7 +591,7 @@ static void extract_jsx_component_ref(CBMExtractCtx *ctx, TSNode node, const cha
if (strcmp(kind, "jsx_self_closing_element") != 0 && strcmp(kind, "jsx_opening_element") != 0) {
return;
}
- TSNode name_node = ts_node_child_by_field_name(node, "name", 4);
+ TSNode name_node = ts_node_child_by_field_name(node, TS_FIELD("name"));
if (ts_node_is_null(name_node)) {
return;
}
@@ -600,7 +616,7 @@ void handle_calls(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec, Walk
call.callee_name = callee;
call.enclosing_func_qn = state->enclosing_func_qn;
- TSNode args = ts_node_child_by_field_name(node, "arguments", 9);
+ TSNode args = ts_node_child_by_field_name(node, TS_FIELD("arguments"));
if (!ts_node_is_null(args)) {
call.first_string_arg = extract_url_or_topic_arg(ctx, args);
if (call.first_string_arg && call.first_string_arg[0] == '/') {
diff --git a/internal/cbm/extract_defs.c b/internal/cbm/extract_defs.c
index a8c802849..96cc8b4a7 100644
--- a/internal/cbm/extract_defs.c
+++ b/internal/cbm/extract_defs.c
@@ -2,23 +2,48 @@
#include "arena.h" // CBMArena, cbm_arena_alloc/strdup/sprintf
#include "helpers.h"
#include "lang_specs.h"
+#include "foundation/constants.h"
#include "tree_sitter/api.h" // TSNode, ts_node_*
#include <stdint.h> // uint32_t
#include <string.h>
#include <ctype.h>
-// Field name lengths for ts_node_child_by_field_name() calls.
-#define FIELD_LEN_FUNCTION_NAME 13 // strlen("function_name")
-#define FIELD_LEN_FUNCTION_DECL_LEFT 22 // strlen("functionDeclarationLeft")
-
// Buffer sizes for local arrays (base classes, params, return types).
#define MAX_COMMENT_LEN 500
#define MAX_BASES 16
#define MAX_BASES_MINUS_1 15
-#define MAX_PARAMS 32
+#define MAX_PARAMS CBM_SZ_32
#define MAX_PARAMS_MINUS_1 31
+#define MAX_RETURN_TYPES 16
#define MAX_RETURN_TYPES_MINUS_1 15
+// Tree traversal limits.
+enum {
+ TEMPLATE_DEPTH_LIMIT = 4,
+ DECLARATOR_DEPTH_LIMIT = 8,
+ EXPORT_ANCESTOR_DEPTH = 4,
+ DECORATOR_SCAN_LIMIT = 3,
+ C_RETURN_WALK_DEPTH = 5,
+ VAR_RECURSION_LIMIT = 8,
+ NESTED_CLASS_STACK_CAP = 128,
+};
+
+// Tree-sitter row is 0-based; lines are 1-based.
+
+// Null-terminated array allocation: need count + 1 for terminator.
+enum { NULL_TERM = 1 };
+
+// String operations.
+enum {
+ SKIP_CHAR = 1, // skip one character (dot, quote, prefix)
+ PAIR_CHARS = 2, // pair of delimiters (quotes, parens)
+ SECOND_CHILD_IDX = 1, // index of second child
+ FIRST_LINE = 1, // first line number
+};
+
+// Return type pair array size.
+enum { RT_PAIR_SIZE = 2 };
+
// Forward declarations
static void extract_func_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec);
static void extract_class_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec);
@@ -36,7 +61,7 @@ static void extract_elixir_call(CBMExtractCtx *ctx, TSNode node, const CBMLangSp
// Get "name" field from a node
static TSNode func_name_node(TSNode node) {
- return ts_node_child_by_field_name(node, "name", 4);
+ return ts_node_child_by_field_name(node, TS_FIELD("name"));
}
// Lua: resolve anonymous function assignment name from parent assignment_statement.
@@ -49,7 +74,7 @@ static TSNode resolve_lua_func_name(TSNode node) {
TSNode null_node = {0};
return null_node;
}
- TSNode vars = ts_node_child_by_field_name(parent, "variables", 9);
+ TSNode vars = ts_node_child_by_field_name(parent, TS_FIELD("variables"));
if (ts_node_is_null(vars)) {
uint32_t n = ts_node_child_count(parent);
for (uint32_t i = 0; i < n; i++) {
@@ -70,7 +95,7 @@ static TSNode resolve_lua_func_name(TSNode node) {
// Julia: walk named children to find first identifier.
static TSNode resolve_julia_func_name(TSNode node) {
TSNode current = node;
- for (int depth = 0; depth < 4; depth++) {
+ for (int depth = 0; depth < TEMPLATE_DEPTH_LIMIT; depth++) {
if (ts_node_named_child_count(current) == 0) {
break;
}
@@ -89,7 +114,7 @@ static TSNode resolve_julia_func_name(TSNode node) {
static TSNode resolve_ocaml_func_name(TSNode node) {
TSNode binding = cbm_find_child_by_kind(node, "let_binding");
if (!ts_node_is_null(binding)) {
- TSNode pattern = ts_node_child_by_field_name(binding, "pattern", 7);
+ TSNode pattern = ts_node_child_by_field_name(binding, TS_FIELD("pattern"));
if (!ts_node_is_null(pattern)) {
return pattern;
}
@@ -163,7 +188,7 @@ static TSNode resolve_func_name_scripting(TSNode node, CBMLanguage lang, const c
// Lean: resolve function name from declId field.
static TSNode resolve_lean_func_name(TSNode node, TSNode name) {
- TSNode decl_id = ts_node_child_by_field_name(node, "declId", 6);
+ TSNode decl_id = ts_node_child_by_field_name(node, TS_FIELD("declId"));
if (!ts_node_is_null(decl_id)) {
TSNode id = cbm_find_child_by_kind(decl_id, "ident");
if (!ts_node_is_null(id)) {
@@ -202,7 +227,7 @@ static TSNode resolve_haskell_func_name(TSNode node) {
// CommonLisp: resolve defun name from function_name field or defun_header→sym_lit.
static TSNode resolve_commonlisp_func_name(TSNode node) {
- TSNode fn = ts_node_child_by_field_name(node, "function_name", FIELD_LEN_FUNCTION_NAME);
+ TSNode fn = ts_node_child_by_field_name(node, TS_FIELD("function_name"));
if (!ts_node_is_null(fn)) {
return fn;
}
@@ -225,8 +250,7 @@ static TSNode resolve_makefile_func_name(TSNode node) {
// Elm: resolve value_declaration name from functionDeclarationLeft field.
static TSNode resolve_elm_func_name(TSNode node) {
- TSNode fdl =
- ts_node_child_by_field_name(node, "functionDeclarationLeft", FIELD_LEN_FUNCTION_DECL_LEFT);
+ TSNode fdl = ts_node_child_by_field_name(node, TS_FIELD("functionDeclarationLeft"));
if (ts_node_is_null(fdl)) {
fdl = cbm_find_child_by_kind(node, "function_declaration_left");
}
@@ -314,8 +338,8 @@ static TSNode resolve_qualified_name(TSNode decl) {
// Resolve function name from C/C++/CUDA/GLSL declarator chain.
static TSNode resolve_c_declarator_name(TSNode node) {
- TSNode decl = ts_node_child_by_field_name(node, "declarator", 10);
- for (int depth = 0; depth < 8 && !ts_node_is_null(decl); depth++) {
+ TSNode decl = ts_node_child_by_field_name(node, TS_FIELD("declarator"));
+ for (int depth = 0; depth < DECLARATOR_DEPTH_LIMIT && !ts_node_is_null(decl); depth++) {
const char *dk = ts_node_type(decl);
if (is_c_terminal_name(dk)) {
return decl;
@@ -323,7 +347,7 @@ static TSNode resolve_c_declarator_name(TSNode node) {
if (strcmp(dk, "qualified_identifier") == 0 || strcmp(dk, "scoped_identifier") == 0) {
return resolve_qualified_name(decl);
}
- TSNode inner = ts_node_child_by_field_name(decl, "declarator", 10);
+ TSNode inner = ts_node_child_by_field_name(decl, TS_FIELD("declarator"));
if (ts_node_is_null(inner) && ts_node_named_child_count(decl) > 0) {
inner = ts_node_named_child(decl, 0);
}
@@ -340,9 +364,9 @@ static TSNode resolve_c_declarator_name(TSNode node) {
static TSNode resolve_r_func_name(TSNode node) {
TSNode parent = ts_node_parent(node);
if (!ts_node_is_null(parent) && strcmp(ts_node_type(parent), "binary_operator") == 0) {
- TSNode lhs = ts_node_child_by_field_name(parent, "left", 4);
+ TSNode lhs = ts_node_child_by_field_name(parent, TS_FIELD("left"));
if (ts_node_is_null(lhs)) {
- lhs = ts_node_child_by_field_name(parent, "lhs", 3);
+ lhs = ts_node_child_by_field_name(parent, TS_FIELD("lhs"));
}
if (ts_node_is_null(lhs) && ts_node_named_child_count(parent) > 0) {
lhs = ts_node_named_child(parent, 0);
@@ -356,87 +380,125 @@ static TSNode resolve_r_func_name(TSNode node) {
}
// Forward declaration for mutual recursion.
-static TSNode resolve_func_name(TSNode node, CBMLanguage lang, const char *source);
+static TSNode resolve_func_name(TSNode node, CBMLanguage lang);
-// C++/CUDA: resolve function name from template_declaration's inner function/declaration.
-static TSNode resolve_template_inner_func_name(TSNode node, CBMLanguage lang, const char *source) {
+// C++/CUDA: find inner function/declaration inside template_declaration.
+// Returns the inner node (not the resolved name) to break the recursive cycle.
+static TSNode resolve_template_inner_node(TSNode node) {
uint32_t nc = ts_node_named_child_count(node);
for (uint32_t i = 0; i < nc; i++) {
TSNode ch = ts_node_named_child(node, i);
const char *ck = ts_node_type(ch);
if (strcmp(ck, "function_definition") == 0 || strcmp(ck, "declaration") == 0) {
- return resolve_func_name(ch, lang, source);
+ return ch;
}
}
TSNode null_node = {0};
return null_node;
}
-// Resolve the name node for a function, handling language-specific quirks.
-static TSNode resolve_func_name(TSNode node, CBMLanguage lang, const char *source) {
- const char *kind = ts_node_type(node);
-
- if (lang == CBM_LANG_HASKELL && strcmp(kind, "signature") == 0) {
+// Try arrow_function name via parent variable_declarator (top-level resolution).
+static TSNode resolve_toplevel_arrow_name(TSNode node, const char *kind) {
+ if (strcmp(kind, "arrow_function") != 0) {
TSNode null_node = {0};
return null_node;
}
-
- TSNode name = func_name_node(node);
-
- if (lang == CBM_LANG_R && strcmp(kind, "function_definition") == 0) {
- return resolve_r_func_name(node);
+ TSNode parent = ts_node_parent(node);
+ if (!ts_node_is_null(parent) && strcmp(ts_node_type(parent), "variable_declarator") == 0) {
+ return ts_node_child_by_field_name(parent, TS_FIELD("name"));
}
+ TSNode null_node = {0};
+ return null_node;
+}
- if (!ts_node_is_null(name)) {
- return name;
+// Try C/C++/CUDA/GLSL function_definition declarator name or template unwrap.
+static TSNode resolve_func_name_c_family(TSNode *node_ptr, CBMLanguage lang, const char *kind) {
+ if ((lang == CBM_LANG_CPP || lang == CBM_LANG_CUDA) &&
+ strcmp(kind, "template_declaration") == 0) {
+ TSNode inner = resolve_template_inner_node(*node_ptr);
+ if (!ts_node_is_null(inner)) {
+ *node_ptr = inner; /* signal caller to retry */
+ }
+ TSNode null_node = {0};
+ return null_node;
+ }
+ if ((lang == CBM_LANG_C || lang == CBM_LANG_CPP || lang == CBM_LANG_CUDA ||
+ lang == CBM_LANG_GLSL) &&
+ strcmp(kind, "function_definition") == 0) {
+ return resolve_c_declarator_name(*node_ptr);
}
+ TSNode null_node = {0};
+ return null_node;
+}
- if (lang == CBM_LANG_SWIFT && strcmp(kind, "function_declaration") == 0) {
- TSNode si = cbm_find_child_by_kind(node, "simple_identifier");
- if (!ts_node_is_null(si)) {
- return si;
+// Resolve the name node for a function, handling language-specific quirks.
+// Uses a loop to handle template_declaration unwrapping (avoids recursion).
+static TSNode resolve_func_name(TSNode node, CBMLanguage lang) {
+ enum { MAX_TEMPLATE_DEPTH = 2 };
+ for (int tmpl_depth = 0; tmpl_depth < MAX_TEMPLATE_DEPTH; tmpl_depth++) {
+ const char *kind = ts_node_type(node);
+
+ if (lang == CBM_LANG_HASKELL && strcmp(kind, "signature") == 0) {
+ TSNode null_node = {0};
+ return null_node;
}
- }
- if (strcmp(kind, "arrow_function") == 0) {
- TSNode parent = ts_node_parent(node);
- if (!ts_node_is_null(parent) && strcmp(ts_node_type(parent), "variable_declarator") == 0) {
- return ts_node_child_by_field_name(parent, "name", 4);
+ TSNode name = func_name_node(node);
+
+ if (lang == CBM_LANG_R && strcmp(kind, "function_definition") == 0) {
+ return resolve_r_func_name(node);
}
- }
- {
- TSNode result = resolve_func_name_scripting(node, lang, kind);
- if (!ts_node_is_null(result)) {
- return result;
+ if (!ts_node_is_null(name)) {
+ return name;
}
- }
- {
- TSNode result = resolve_func_name_fp(node, lang, kind, name);
- if (!ts_node_is_null(result)) {
- return result;
+ if (lang == CBM_LANG_SWIFT && strcmp(kind, "function_declaration") == 0) {
+ TSNode si = cbm_find_child_by_kind(node, "simple_identifier");
+ if (!ts_node_is_null(si)) {
+ return si;
+ }
}
- }
- if ((lang == CBM_LANG_CPP || lang == CBM_LANG_CUDA) &&
- strcmp(kind, "template_declaration") == 0) {
- return resolve_template_inner_func_name(node, lang, source);
- }
+ {
+ TSNode r = resolve_toplevel_arrow_name(node, kind);
+ if (!ts_node_is_null(r)) {
+ return r;
+ }
+ }
+ {
+ TSNode r = resolve_func_name_scripting(node, lang, kind);
+ if (!ts_node_is_null(r)) {
+ return r;
+ }
+ }
+ {
+ TSNode r = resolve_func_name_fp(node, lang, kind, name);
+ if (!ts_node_is_null(r)) {
+ return r;
+ }
+ }
- if ((lang == CBM_LANG_C || lang == CBM_LANG_CPP || lang == CBM_LANG_CUDA ||
- lang == CBM_LANG_GLSL) &&
- strcmp(kind, "function_definition") == 0) {
- return resolve_c_declarator_name(node);
- }
+ {
+ TSNode prev = node;
+ TSNode r = resolve_func_name_c_family(&node, lang, kind);
+ if (!ts_node_is_null(r)) {
+ return r;
+ }
+ if (!ts_node_eq(prev, node)) {
+ continue; /* template unwrapped — retry */
+ }
+ }
+ break;
+ } /* end template depth loop */
TSNode null_node = {0};
return null_node;
}
// Check for export_statement ancestor (JS/TS/TSX)
static bool is_js_exported(TSNode node) {
- return cbm_has_ancestor_kind(node, "export_statement", 4);
+ return cbm_has_ancestor_kind(node, "export_statement", EXPORT_ANCESTOR_DEPTH);
}
// Check if a node is a comment node type.
@@ -473,7 +535,7 @@ static const char *extract_go_type_docstring(CBMArena *a, TSNode node, const cha
// Python-specific: docstring as first expression_statement -> string in function body.
static const char *extract_python_docstring(CBMArena *a, TSNode node, const char *source) {
- TSNode body = ts_node_child_by_field_name(node, "body", 4);
+ TSNode body = ts_node_child_by_field_name(node, TS_FIELD("body"));
if (ts_node_is_null(body) || ts_node_named_child_count(body) == 0) {
return NULL;
}
@@ -523,7 +585,7 @@ static const char *decorator_method_name(const char *attr_text) {
}
/* Match the last segment after the dot: "router.post" → "post" */
const char *dot = strrchr(attr_text, '.');
- const char *method = dot ? dot + 1 : attr_text;
+ const char *method = dot ? dot + SKIP_CHAR : attr_text;
if (strcmp(method, "get") == 0 || strcmp(method, "Get") == 0) {
return "GET";
}
@@ -554,7 +616,7 @@ static const char *decorator_method_name(const char *attr_text) {
* 2. The first string argument → route path */
// Find the arguments node for a decorator call node.
static TSNode find_decorator_args(TSNode call_node) {
- TSNode args = ts_node_child_by_field_name(call_node, "arguments", 9);
+ TSNode args = ts_node_child_by_field_name(call_node, TS_FIELD("arguments"));
if (ts_node_is_null(args)) {
for (uint32_t ai = 0; ai < ts_node_named_child_count(call_node); ai++) {
TSNode ac = ts_node_named_child(call_node, ai);
@@ -569,7 +631,7 @@ static TSNode find_decorator_args(TSNode call_node) {
// Extract route path from decorator arguments (first string that starts with /).
static const char *extract_route_path_from_args(CBMArena *a, TSNode args, const char *source) {
uint32_t nc = ts_node_named_child_count(args);
- for (uint32_t ai = 0; ai < nc && ai < 3; ai++) {
+ for (uint32_t ai = 0; ai < nc && ai < DECORATOR_SCAN_LIMIT; ai++) {
TSNode arg = ts_node_named_child(args, ai);
const char *ak = ts_node_type(arg);
if (strcmp(ak, "string") != 0 && strcmp(ak, "string_literal") != 0 &&
@@ -579,8 +641,8 @@ static const char *extract_route_path_from_args(CBMArena *a, TSNode args, const
char *path = cbm_node_text(a, arg, source);
if (path) {
int plen = (int)strlen(path);
- if (plen >= 2 && (path[0] == '"' || path[0] == '\'')) {
- path = cbm_arena_strndup(a, path + 1, (size_t)(plen - 2));
+ if (plen >= PAIR_CHARS && (path[0] == '"' || path[0] == '\'')) {
+ path = cbm_arena_strndup(a, path + SKIP_CHAR, (size_t)(plen - PAIR_CHARS));
}
if (path && path[0] == '/') {
return path;
@@ -594,7 +656,7 @@ static const char *extract_route_path_from_args(CBMArena *a, TSNode args, const
// Returns true if a route method was found (even with fallback path "/").
static bool try_route_from_decorator_call(CBMArena *a, TSNode dchild, const char *source,
const char **out_path, const char **out_method) {
- TSNode fn = ts_node_child_by_field_name(dchild, "function", 8);
+ TSNode fn = ts_node_child_by_field_name(dchild, TS_FIELD("function"));
if (ts_node_is_null(fn)) {
fn = ts_node_named_child(dchild, 0);
}
@@ -672,7 +734,7 @@ static TSNode find_jvm_modifiers(TSNode node, CBMLanguage lang) {
if (lang != CBM_LANG_JAVA && lang != CBM_LANG_KOTLIN && lang != CBM_LANG_CSHARP) {
return null_node;
}
- TSNode modifiers = ts_node_child_by_field_name(node, "modifiers", 9);
+ TSNode modifiers = ts_node_child_by_field_name(node, TS_FIELD("modifiers"));
if (ts_node_is_null(modifiers)) {
modifiers = cbm_find_child_by_kind(node, "modifiers");
}
@@ -724,7 +786,8 @@ static const char **extract_decorators(CBMArena *a, TSNode node, const char *sou
return NULL;
}
- const char **result = (const char **)cbm_arena_alloc(a, sizeof(const char *) * (total + 1));
+ const char **result =
+ (const char **)cbm_arena_alloc(a, sizeof(const char *) * (total + NULL_TERM));
if (!result) {
return NULL;
}
@@ -757,7 +820,7 @@ static char *extract_cpp_base_text(CBMArena *a, TSNode bc, const char *source) {
return cbm_node_text(a, bc, source);
}
if (strcmp(bk, "template_type") == 0) {
- TSNode tname = ts_node_child_by_field_name(bc, "name", 4);
+ TSNode tname = ts_node_child_by_field_name(bc, TS_FIELD("name"));
if (!ts_node_is_null(tname)) {
return cbm_node_text(a, tname, source);
}
@@ -767,7 +830,7 @@ static char *extract_cpp_base_text(CBMArena *a, TSNode bc, const char *source) {
// Extract base classes from a C++ base_class_clause node.
static const char **extract_cpp_base_classes(CBMArena *a, TSNode clause, const char *source) {
- const char *bases[16];
+ const char *bases[MAX_BASES];
int base_count = 0;
uint32_t bnc = ts_node_named_child_count(clause);
for (uint32_t bi = 0; bi < bnc && base_count < MAX_BASES_MINUS_1; bi++) {
@@ -778,7 +841,7 @@ static const char **extract_cpp_base_classes(CBMArena *a, TSNode clause, const c
}
if (base_count > 0) {
const char **result =
- (const char **)cbm_arena_alloc(a, (base_count + 1) * sizeof(const char *));
+ (const char **)cbm_arena_alloc(a, (base_count + NULL_TERM) * sizeof(const char *));
if (result) {
for (int j = 0; j < base_count; j++) {
result[j] = bases[j];
@@ -795,10 +858,10 @@ static const char **make_single_base(CBMArena *a, const char *text) {
if (!text || !text[0]) {
return NULL;
}
- const char **result = (const char **)cbm_arena_alloc(a, sizeof(const char *) * 2);
+ const char **result = (const char **)cbm_arena_alloc(a, sizeof(const char *) * RT_PAIR_SIZE);
if (result) {
result[0] = text;
- result[1] = NULL;
+ result[SKIP_CHAR] = NULL;
}
return result;
}
@@ -937,7 +1000,7 @@ static char *clean_type_name(CBMArena *a, const char *raw) {
if (len == 0) {
return NULL;
}
- char *result = cbm_arena_alloc(a, len + 1);
+ char *result = cbm_arena_alloc(a, len + NULL_TERM);
memcpy(result, s, len);
result[len] = '\0';
return result;
@@ -950,7 +1013,7 @@ static char *resolve_param_name(CBMArena *a, TSNode param, const char *source) {
const char *pk = ts_node_type(param);
if (strcmp(pk, "parameter_declaration") == 0) {
- TSNode nm = ts_node_child_by_field_name(param, "name", 4);
+ TSNode nm = ts_node_child_by_field_name(param, TS_FIELD("name"));
if (!ts_node_is_null(nm)) {
return cbm_node_text(a, nm, source);
}
@@ -963,9 +1026,9 @@ static char *resolve_param_name(CBMArena *a, TSNode param, const char *source) {
strcmp(pk, "required_parameter") == 0 || strcmp(pk, "optional_parameter") == 0 ||
strcmp(pk, "simple_parameter") == 0 || strcmp(pk, "typed_parameter") == 0 ||
strcmp(pk, "default_parameter") == 0 || strcmp(pk, "typed_default_parameter") == 0) {
- TSNode nm = ts_node_child_by_field_name(param, "name", 4);
+ TSNode nm = ts_node_child_by_field_name(param, TS_FIELD("name"));
if (ts_node_is_null(nm)) {
- nm = ts_node_child_by_field_name(param, "pattern", 7);
+ nm = ts_node_child_by_field_name(param, TS_FIELD("pattern"));
}
if (!ts_node_is_null(nm)) {
if (strcmp(ts_node_type(nm), "identifier") == 0 ||
@@ -984,7 +1047,7 @@ static const char **extract_param_names(CBMArena *a, TSNode params, const char *
return NULL;
}
- const char *names[32];
+ const char *names[MAX_PARAMS];
int count = 0;
uint32_t nc = ts_node_child_count(params);
@@ -1005,7 +1068,8 @@ static const char **extract_param_names(CBMArena *a, TSNode params, const char *
return NULL;
}
- const char **result = (const char **)cbm_arena_alloc(a, (count + 1) * sizeof(const char *));
+ const char **result =
+ (const char **)cbm_arena_alloc(a, (count + NULL_TERM) * sizeof(const char *));
for (int i = 0; i < count; i++) {
result[i] = names[i];
}
@@ -1037,7 +1101,7 @@ static void extract_go_multi_return(CBMArena *a, TSNode rt_node, const char *sou
continue;
}
if (strcmp(ts_node_type(child), "parameter_declaration") == 0) {
- TSNode tn = ts_node_child_by_field_name(child, "type", 4);
+ TSNode tn = ts_node_child_by_field_name(child, TS_FIELD("type"));
if (!ts_node_is_null(tn)) {
add_cleaned_type(a, types, count, cbm_node_text(a, tn, source));
}
@@ -1052,7 +1116,8 @@ static const char **build_type_array(CBMArena *a, const char **types, int count)
if (count == 0) {
return NULL;
}
- const char **result = (const char **)cbm_arena_alloc(a, (count + 1) * sizeof(const char *));
+ const char **result =
+ (const char **)cbm_arena_alloc(a, (count + NULL_TERM) * sizeof(const char *));
for (int i = 0; i < count; i++) {
result[i] = types[i];
}
@@ -1067,7 +1132,7 @@ static const char **extract_return_types(CBMArena *a, TSNode rt_node, const char
return NULL;
}
- const char *types[16];
+ const char *types[MAX_RETURN_TYPES];
int count = 0;
if (strcmp(ts_node_type(rt_node), "parameter_list") == 0) {
@@ -1117,7 +1182,7 @@ static char *resolve_jvm_param_type(CBMArena *a, TSNode param, const char *pk, c
return NULL;
}
if (lang == CBM_LANG_KOTLIN) {
- TSNode tn = ts_node_child_by_field_name(param, "type", 4);
+ TSNode tn = ts_node_child_by_field_name(param, TS_FIELD("type"));
if (!ts_node_is_null(tn)) {
return cbm_node_text(a, tn, source);
}
@@ -1129,13 +1194,13 @@ static char *resolve_jvm_param_type(CBMArena *a, TSNode param, const char *pk, c
return ts_node_is_null(tid) ? NULL : cbm_node_text(a, tid, source);
}
if (lang == CBM_LANG_GROOVY) {
- TSNode tn = ts_node_child_by_field_name(param, "type", 4);
+ TSNode tn = ts_node_child_by_field_name(param, TS_FIELD("type"));
return ts_node_is_null(tn) ? NULL : cbm_node_text(a, tn, source);
}
if (lang == CBM_LANG_OCAML) {
TSNode tp = cbm_find_child_by_kind(param, "typed_pattern");
if (!ts_node_is_null(tp)) {
- TSNode tn = ts_node_child_by_field_name(tp, "type", 4);
+ TSNode tn = ts_node_child_by_field_name(tp, TS_FIELD("type"));
if (!ts_node_is_null(tn)) {
return cbm_node_text(a, tn, source);
}
@@ -1164,7 +1229,7 @@ static char *resolve_param_type_text(CBMArena *a, TSNode param, const char *sour
// Generic: parameter-like nodes with "type" field
if (is_generic_param_kind(pk)) {
- TSNode tn = ts_node_child_by_field_name(param, "type", 4);
+ TSNode tn = ts_node_child_by_field_name(param, TS_FIELD("type"));
if (!ts_node_is_null(tn)) {
return cbm_node_text(a, tn, source);
}
@@ -1195,7 +1260,7 @@ static const char **extract_param_types(CBMArena *a, TSNode params, const char *
return NULL;
}
- const char *types[32];
+ const char *types[MAX_PARAMS];
int count = 0;
uint32_t nc = ts_node_child_count(params);
@@ -1211,7 +1276,8 @@ static const char **extract_param_types(CBMArena *a, TSNode params, const char *
return NULL;
}
- const char **result = (const char **)cbm_arena_alloc(a, (count + 1) * sizeof(const char *));
+ const char **result =
+ (const char **)cbm_arena_alloc(a, (count + NULL_TERM) * sizeof(const char *));
for (int i = 0; i < count; i++) {
result[i] = types[i];
}
@@ -1239,13 +1305,13 @@ static TSNode unwrap_template_inner(TSNode node, CBMLanguage lang) {
// C/C++/CUDA/GLSL: parameters live on function_declarator inside declarator chain.
static TSNode find_c_params(TSNode func_node) {
- TSNode decl = ts_node_child_by_field_name(func_node, "declarator", 10);
- for (int d = 0; d < 5 && !ts_node_is_null(decl); d++) {
- TSNode params = ts_node_child_by_field_name(decl, "parameters", 10);
+ TSNode decl = ts_node_child_by_field_name(func_node, TS_FIELD("declarator"));
+ for (int d = 0; d < C_RETURN_WALK_DEPTH && !ts_node_is_null(decl); d++) {
+ TSNode params = ts_node_child_by_field_name(decl, TS_FIELD("parameters"));
if (!ts_node_is_null(params)) {
return params;
}
- decl = ts_node_child_by_field_name(decl, "declarator", 10);
+ decl = ts_node_child_by_field_name(decl, TS_FIELD("declarator"));
}
TSNode null_node = {0};
return null_node;
@@ -1255,7 +1321,7 @@ static TSNode find_c_params(TSNode func_node) {
// Updates def->return_type and def->return_types if trailing type found.
static void resolve_cpp_trailing_return(CBMArena *a, TSNode func_node, const char *source,
CBMDefinition *def) {
- TSNode declarator = ts_node_child_by_field_name(func_node, "declarator", 10);
+ TSNode declarator = ts_node_child_by_field_name(func_node, TS_FIELD("declarator"));
if (ts_node_is_null(declarator)) {
return;
}
@@ -1266,10 +1332,11 @@ static void resolve_cpp_trailing_return(CBMArena *a, TSNode func_node, const cha
TSNode type_desc = ts_node_named_child_count(ch) > 0 ? ts_node_named_child(ch, 0) : ch;
def->return_type = cbm_node_text(a, type_desc, source);
if (def->return_type && def->return_type[0]) {
- const char **rt = (const char **)cbm_arena_alloc(a, 2 * sizeof(const char *));
+ const char **rt =
+ (const char **)cbm_arena_alloc(a, RT_PAIR_SIZE * sizeof(const char *));
if (rt) {
rt[0] = def->return_type;
- rt[1] = NULL;
+ rt[SKIP_CHAR] = NULL;
def->return_types = rt;
}
}
@@ -1281,7 +1348,7 @@ static void resolve_cpp_trailing_return(CBMArena *a, TSNode func_node, const cha
static void extract_func_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec) {
CBMArena *a = ctx->arena;
- TSNode name_node = resolve_func_name(node, ctx->language, ctx->source);
+ TSNode name_node = resolve_func_name(node, ctx->language);
if (ts_node_is_null(name_node)) {
return;
}
@@ -1300,13 +1367,13 @@ static void extract_func_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec
def.qualified_name = cbm_fqn_compute(a, ctx->project, ctx->rel_path, name);
def.label = "Function";
def.file_path = ctx->rel_path;
- def.start_line = ts_node_start_point(node).row + 1;
- def.end_line = ts_node_end_point(node).row + 1;
- def.lines = (int)(def.end_line - def.start_line + 1);
+ def.start_line = ts_node_start_point(node).row + TS_LINE_OFFSET;
+ def.end_line = ts_node_end_point(node).row + TS_LINE_OFFSET;
+ def.lines = (int)(def.end_line - def.start_line + TS_LINE_OFFSET);
def.is_exported = cbm_is_exported(name, ctx->language);
// Parameters — use func_node (inner function for templates)
- TSNode params = ts_node_child_by_field_name(func_node, "parameters", 10);
+ TSNode params = ts_node_child_by_field_name(func_node, TS_FIELD("parameters"));
if (ts_node_is_null(params) &&
(ctx->language == CBM_LANG_C || ctx->language == CBM_LANG_CPP ||
ctx->language == CBM_LANG_CUDA || ctx->language == CBM_LANG_GLSL)) {
@@ -1336,7 +1403,7 @@ static void extract_func_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec
}
// Receiver (Go methods)
- TSNode recv = ts_node_child_by_field_name(node, "receiver", 8);
+ TSNode recv = ts_node_child_by_field_name(node, TS_FIELD("receiver"));
if (!ts_node_is_null(recv)) {
def.receiver = cbm_node_text(a, recv, ctx->source);
def.label = "Method";
@@ -1381,8 +1448,8 @@ static void push_simple_class_def(CBMExtractCtx *ctx, TSNode node, char *name, c
def.qualified_name = cbm_fqn_compute(a, ctx->project, ctx->rel_path, name);
def.label = label;
def.file_path = ctx->rel_path;
- def.start_line = ts_node_start_point(node).row + 1;
- def.end_line = ts_node_end_point(node).row + 1;
+ def.start_line = ts_node_start_point(node).row + TS_LINE_OFFSET;
+ def.end_line = ts_node_end_point(node).row + TS_LINE_OFFSET;
def.is_exported = true;
cbm_defs_push(&ctx->result->defs, a, def);
}
@@ -1460,8 +1527,9 @@ static char *trim_heading_name(char *name) {
return NULL;
}
size_t len = strlen(name);
- while (len > 0 && (name[len - 1] == '\n' || name[len - 1] == '\r' || name[len - 1] == ' ')) {
- name[len - 1] = '\0';
+ while (len > 0 && (name[len - SKIP_CHAR] == '\n' || name[len - SKIP_CHAR] == '\r' ||
+ name[len - SKIP_CHAR] == ' ')) {
+ name[len - SKIP_CHAR] = '\0';
len--;
}
return (name[0]) ? name : NULL;
@@ -1539,7 +1607,7 @@ static void extract_class_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec
return;
}
- TSNode name_node = ts_node_child_by_field_name(node, "name", 4);
+ TSNode name_node = ts_node_child_by_field_name(node, TS_FIELD("name"));
// ObjC: class name is first identifier child
if (ts_node_is_null(name_node) && ctx->language == CBM_LANG_OBJC) {
name_node = cbm_find_child_by_kind(node, "identifier");
@@ -1568,7 +1636,7 @@ static void extract_class_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec
// Go type_spec: check inner type for interface/struct
if (strcmp(kind, "type_spec") == 0) {
- TSNode type_inner = ts_node_child_by_field_name(node, "type", 4);
+ TSNode type_inner = ts_node_child_by_field_name(node, TS_FIELD("type"));
if (!ts_node_is_null(type_inner)) {
const char *inner_kind = ts_node_type(type_inner);
if (strcmp(inner_kind, "interface_type") == 0) {
@@ -1585,8 +1653,8 @@ static void extract_class_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec
def.qualified_name = class_qn;
def.label = label;
def.file_path = ctx->rel_path;
- def.start_line = ts_node_start_point(node).row + 1;
- def.end_line = ts_node_end_point(node).row + 1;
+ def.start_line = ts_node_start_point(node).row + TS_LINE_OFFSET;
+ def.end_line = ts_node_end_point(node).row + TS_LINE_OFFSET;
def.is_exported = cbm_is_exported(name, ctx->language);
def.base_classes = extract_base_classes(a, node, ctx->source, ctx->language);
def.decorators = extract_decorators(a, node, ctx->source, ctx->language, spec);
@@ -1616,7 +1684,7 @@ static TSNode find_class_body(TSNode class_node, CBMLanguage lang) {
}
// Go: type_spec -> type field (interface_type or struct_type)
if (lang == CBM_LANG_GO) {
- TSNode type_inner = ts_node_child_by_field_name(class_node, "type", 4);
+ TSNode type_inner = ts_node_child_by_field_name(class_node, TS_FIELD("type"));
if (!ts_node_is_null(type_inner)) {
return type_inner;
}
@@ -1678,10 +1746,10 @@ static TSNode resolve_arrow_func_name(TSNode child) {
if (!ts_node_is_null(parent)) {
const char *pk = ts_node_type(parent);
if (strcmp(pk, "field_definition") == 0) {
- return ts_node_child_by_field_name(parent, "property", 8);
+ return ts_node_child_by_field_name(parent, TS_FIELD("property"));
}
if (strcmp(pk, "public_field_definition") == 0 || strcmp(pk, "variable_declarator") == 0) {
- return ts_node_child_by_field_name(parent, "name", 4);
+ return ts_node_child_by_field_name(parent, TS_FIELD("name"));
}
}
TSNode null_node = {0};
@@ -1700,11 +1768,11 @@ static TSNode resolve_method_name(TSNode child, CBMLanguage lang) {
if ((lang == CBM_LANG_C || lang == CBM_LANG_CPP || lang == CBM_LANG_CUDA ||
lang == CBM_LANG_GLSL) &&
strcmp(ck, "function_definition") == 0) {
- return resolve_func_name(child, lang, NULL);
+ return resolve_func_name(child, lang);
}
if (lang == CBM_LANG_GROOVY && strcmp(ck, "function_definition") == 0) {
- TSNode fn = ts_node_child_by_field_name(child, "function", 8);
+ TSNode fn = ts_node_child_by_field_name(child, TS_FIELD("function"));
if (!ts_node_is_null(fn)) {
return fn;
}
@@ -1750,12 +1818,12 @@ static void push_method_def(CBMExtractCtx *ctx, TSNode child, const char *class_
def.label = "Method";
def.file_path = ctx->rel_path;
def.parent_class = class_qn;
- def.start_line = ts_node_start_point(child).row + 1;
- def.end_line = ts_node_end_point(child).row + 1;
- def.lines = (int)(def.end_line - def.start_line + 1);
+ def.start_line = ts_node_start_point(child).row + TS_LINE_OFFSET;
+ def.end_line = ts_node_end_point(child).row + TS_LINE_OFFSET;
+ def.lines = (int)(def.end_line - def.start_line + TS_LINE_OFFSET);
def.is_exported = cbm_is_exported(name, ctx->language);
- TSNode params = ts_node_child_by_field_name(child, "parameters", 10);
+ TSNode params = ts_node_child_by_field_name(child, TS_FIELD("parameters"));
if (!ts_node_is_null(params)) {
def.signature = cbm_node_text(a, params, ctx->source);
def.param_types = extract_param_types(a, params, ctx->source, ctx->language);
@@ -1847,7 +1915,7 @@ static void extract_class_methods(CBMExtractCtx *ctx, TSNode class_node, const c
static void extract_rust_impl(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec) {
CBMArena *a = ctx->arena;
- TSNode type_node = ts_node_child_by_field_name(node, "type", 4);
+ TSNode type_node = ts_node_child_by_field_name(node, TS_FIELD("type"));
if (ts_node_is_null(type_node)) {
return;
}
@@ -1858,7 +1926,7 @@ static void extract_rust_impl(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec
}
// Check for "impl Trait for Struct" pattern
- TSNode trait_node = ts_node_child_by_field_name(node, "trait", 5);
+ TSNode trait_node = ts_node_child_by_field_name(node, TS_FIELD("trait"));
if (!ts_node_is_null(trait_node)) {
char *trait_name = cbm_node_text(a, trait_node, ctx->source);
if (trait_name && trait_name[0]) {
@@ -1872,7 +1940,7 @@ static void extract_rust_impl(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec
const char *type_qn = cbm_fqn_compute(a, ctx->project, ctx->rel_path, type_name);
// Extract methods inside impl body
- TSNode body = ts_node_child_by_field_name(node, "body", 4);
+ TSNode body = ts_node_child_by_field_name(node, TS_FIELD("body"));
if (ts_node_is_null(body)) {
return;
}
@@ -1906,11 +1974,11 @@ static void extract_rust_impl(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec
def.label = "Method";
def.file_path = ctx->rel_path;
def.parent_class = type_qn;
- def.start_line = ts_node_start_point(child).row + 1;
- def.end_line = ts_node_end_point(child).row + 1;
+ def.start_line = ts_node_start_point(child).row + TS_LINE_OFFSET;
+ def.end_line = ts_node_end_point(child).row + TS_LINE_OFFSET;
def.is_exported = cbm_is_exported(name, ctx->language);
- TSNode params = ts_node_child_by_field_name(child, "parameters", 10);
+ TSNode params = ts_node_child_by_field_name(child, TS_FIELD("parameters"));
if (!ts_node_is_null(params)) {
def.signature = cbm_node_text(a, params, ctx->source);
def.param_types = extract_param_types(a, params, ctx->source, ctx->language);
@@ -1928,9 +1996,9 @@ static void extract_rust_impl(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec
// Get the "arguments" node for an Elixir call, with fallback to second child.
static TSNode elixir_call_args(TSNode node) {
- TSNode args = ts_node_child_by_field_name(node, "arguments", 9);
- if (ts_node_is_null(args) && ts_node_child_count(node) > 1) {
- args = ts_node_child(node, 1);
+ TSNode args = ts_node_child_by_field_name(node, TS_FIELD("arguments"));
+ if (ts_node_is_null(args) && ts_node_child_count(node) > SECOND_CHILD_IDX) {
+ args = ts_node_child(node, SECOND_CHILD_IDX);
}
return args;
}
@@ -1965,73 +2033,81 @@ static void extract_elixir_func_def(CBMExtractCtx *ctx, TSNode node, const char
def.qualified_name = cbm_fqn_compute(a, ctx->project, ctx->rel_path, name);
def.label = "Function";
def.file_path = ctx->rel_path;
- def.start_line = ts_node_start_point(node).row + 1;
- def.end_line = ts_node_end_point(node).row + 1;
+ def.start_line = ts_node_start_point(node).row + TS_LINE_OFFSET;
+ def.end_line = ts_node_end_point(node).row + TS_LINE_OFFSET;
def.is_exported = (strcmp(macro, "def") == 0 || strcmp(macro, "defmacro") == 0);
cbm_defs_push(&ctx->result->defs, a, def);
}
-// Handle Elixir defmodule — extract class definition and recurse into do_block.
-static void extract_elixir_module_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec) {
+// Emit Class definition for an Elixir defmodule node. Returns do_block or null.
+static TSNode emit_elixir_module_class(CBMExtractCtx *ctx, TSNode cur) {
CBMArena *a = ctx->arena;
- TSNode args = elixir_call_args(node);
+ TSNode null_node = {0};
+ TSNode args = elixir_call_args(cur);
if (ts_node_is_null(args)) {
- return;
+ return null_node;
}
-
TSNode name_node = ts_node_child(args, 0);
if (ts_node_is_null(name_node)) {
- return;
+ return null_node;
}
-
char *name = cbm_node_text(a, name_node, ctx->source);
if (!name || !name[0]) {
- return;
+ return null_node;
}
-
CBMDefinition def;
memset(&def, 0, sizeof(def));
def.name = name;
def.qualified_name = cbm_fqn_compute(a, ctx->project, ctx->rel_path, name);
def.label = "Class";
def.file_path = ctx->rel_path;
- def.start_line = ts_node_start_point(node).row + 1;
- def.end_line = ts_node_end_point(node).row + 1;
+ def.start_line = ts_node_start_point(cur).row + TS_LINE_OFFSET;
+ def.end_line = ts_node_end_point(cur).row + TS_LINE_OFFSET;
def.is_exported = true;
cbm_defs_push(&ctx->result->defs, a, def);
-
- // Recurse into do_block for nested def/defp/defmacro
- TSNode do_block = cbm_find_child_by_kind(node, "do_block");
- if (!ts_node_is_null(do_block)) {
- uint32_t dbc = ts_node_child_count(do_block);
- for (uint32_t di = 0; di < dbc; di++) {
- TSNode dchild = ts_node_child(do_block, di);
- if (!ts_node_is_null(dchild) && strcmp(ts_node_type(dchild), "call") == 0) {
- extract_elixir_call(ctx, dchild, spec);
- }
- }
- }
+ return cbm_find_child_by_kind(cur, "do_block");
}
+// Process Elixir call nodes iteratively — handles defmodule/def/defp/defmacro
+// without recursion between extract_elixir_call ↔ extract_elixir_module_def.
+#define ELIXIR_STACK_CAP CBM_SZ_64
static void extract_elixir_call(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec) {
- CBMArena *a = ctx->arena;
+ (void)spec;
+ TSNode stack[ELIXIR_STACK_CAP];
+ int top = 0;
+ stack[top++] = node;
- if (ts_node_child_count(node) == 0) {
- return;
- }
- TSNode callee = ts_node_child(node, 0);
- if (ts_node_is_null(callee)) {
- return;
- }
- char *macro = cbm_node_text(a, callee, ctx->source);
- if (!macro) {
- return;
- }
+ while (top > 0) {
+ TSNode cur = stack[--top];
+ CBMArena *a = ctx->arena;
+
+ if (ts_node_child_count(cur) == 0) {
+ continue;
+ }
+ TSNode callee = ts_node_child(cur, 0);
+ if (ts_node_is_null(callee)) {
+ continue;
+ }
+ char *macro = cbm_node_text(a, callee, ctx->source);
+ if (!macro) {
+ continue;
+ }
- if (strcmp(macro, "def") == 0 || strcmp(macro, "defp") == 0 || strcmp(macro, "defmacro") == 0) {
- extract_elixir_func_def(ctx, node, macro);
- } else if (strcmp(macro, "defmodule") == 0) {
- extract_elixir_module_def(ctx, node, spec);
+ if (strcmp(macro, "def") == 0 || strcmp(macro, "defp") == 0 ||
+ strcmp(macro, "defmacro") == 0) {
+ extract_elixir_func_def(ctx, cur, macro);
+ } else if (strcmp(macro, "defmodule") == 0) {
+ TSNode do_block = emit_elixir_module_class(ctx, cur);
+ if (!ts_node_is_null(do_block)) {
+ uint32_t dbc = ts_node_child_count(do_block);
+ for (int di = (int)dbc - SKIP_CHAR; di >= 0 && top < ELIXIR_STACK_CAP; di--) {
+ TSNode dchild = ts_node_child(do_block, (uint32_t)di);
+ if (!ts_node_is_null(dchild) && strcmp(ts_node_type(dchild), "call") == 0) {
+ stack[top++] = dchild;
+ }
+ }
+ }
+ }
}
}
@@ -2049,8 +2125,8 @@ static void push_var_def(CBMExtractCtx *ctx, const char *name, TSNode node) {
def.qualified_name = cbm_fqn_compute(a, ctx->project, ctx->rel_path, name);
def.label = "Variable";
def.file_path = ctx->rel_path;
- def.start_line = ts_node_start_point(node).row + 1;
- def.end_line = ts_node_end_point(node).row + 1;
+ def.start_line = ts_node_start_point(node).row + TS_LINE_OFFSET;
+ def.end_line = ts_node_end_point(node).row + TS_LINE_OFFSET;
def.is_exported = cbm_is_exported(name, ctx->language);
cbm_defs_push(&ctx->result->defs, a, def);
}
@@ -2059,7 +2135,7 @@ static void push_var_def(CBMExtractCtx *ctx, const char *name, TSNode node) {
// declaration > init_declarator > declarator (may be pointer_declarator > identifier)
static const char *extract_c_declarator_name(CBMArena *a, TSNode decl, const char *source) {
// Try "declarator" field on the declaration
- TSNode declarator = ts_node_child_by_field_name(decl, "declarator", 10);
+ TSNode declarator = ts_node_child_by_field_name(decl, TS_FIELD("declarator"));
if (ts_node_is_null(declarator)) {
return NULL;
}
@@ -2067,7 +2143,7 @@ static const char *extract_c_declarator_name(CBMArena *a, TSNode decl, const cha
// Could be init_declarator wrapping the actual declarator
const char *dk = ts_node_type(declarator);
if (strcmp(dk, "init_declarator") == 0) {
- declarator = ts_node_child_by_field_name(declarator, "declarator", 10);
+ declarator = ts_node_child_by_field_name(declarator, TS_FIELD("declarator"));
if (ts_node_is_null(declarator)) {
return NULL;
}
@@ -2075,7 +2151,7 @@ static const char *extract_c_declarator_name(CBMArena *a, TSNode decl, const cha
}
// Unwrap pointer_declarator
while (strcmp(dk, "pointer_declarator") == 0 || strcmp(dk, "reference_declarator") == 0) {
- declarator = ts_node_child_by_field_name(declarator, "declarator", 10);
+ declarator = ts_node_child_by_field_name(declarator, TS_FIELD("declarator"));
if (ts_node_is_null(declarator)) {
return NULL;
}
@@ -2089,7 +2165,7 @@ static const char *extract_c_declarator_name(CBMArena *a, TSNode decl, const cha
// Helper: extract name from Java/C# field_declaration (declarator > name)
static const char *extract_java_field_name(CBMArena *a, TSNode field, const char *source) {
- TSNode declarator = ts_node_child_by_field_name(field, "declarator", 10);
+ TSNode declarator = ts_node_child_by_field_name(field, TS_FIELD("declarator"));
if (ts_node_is_null(declarator)) {
// Try iterating children for variable_declarator
uint32_t n = ts_node_named_child_count(field);
@@ -2104,7 +2180,7 @@ static const char *extract_java_field_name(CBMArena *a, TSNode field, const char
if (ts_node_is_null(declarator)) {
return NULL;
}
- TSNode name = ts_node_child_by_field_name(declarator, "name", 4);
+ TSNode name = ts_node_child_by_field_name(declarator, TS_FIELD("name"));
if (!ts_node_is_null(name)) {
return cbm_node_text(a, name, source);
}
@@ -2130,7 +2206,7 @@ static void extract_csharp_vars(CBMExtractCtx *ctx, TSNode node, CBMArena *a) {
for (uint32_t j = 0; j < nc; j++) {
TSNode decl = ts_node_named_child(child, j);
if (strcmp(ts_node_type(decl), "variable_declarator") == 0) {
- TSNode id = ts_node_child_by_field_name(decl, "name", 4);
+ TSNode id = ts_node_child_by_field_name(decl, TS_FIELD("name"));
if (ts_node_is_null(id)) {
id = cbm_find_child_by_kind(decl, "identifier");
}
@@ -2150,7 +2226,7 @@ static void extract_js_vars(CBMExtractCtx *ctx, TSNode node, CBMArena *a) {
if (strcmp(ts_node_type(child), "variable_declarator") != 0) {
continue;
}
- TSNode value = ts_node_child_by_field_name(child, "value", 5);
+ TSNode value = ts_node_child_by_field_name(child, TS_FIELD("value"));
if (!ts_node_is_null(value)) {
const char *vk = ts_node_type(value);
if (strcmp(vk, "arrow_function") == 0 || strcmp(vk, "function_expression") == 0 ||
@@ -2158,7 +2234,7 @@ static void extract_js_vars(CBMExtractCtx *ctx, TSNode node, CBMArena *a) {
continue;
}
}
- TSNode vname = ts_node_child_by_field_name(child, "name", 4);
+ TSNode vname = ts_node_child_by_field_name(child, TS_FIELD("name"));
if (!ts_node_is_null(vname)) {
push_var_def(ctx, cbm_node_text(a, vname, ctx->source), child);
}
@@ -2170,7 +2246,7 @@ static void extract_vars_mainstream(CBMExtractCtx *ctx, TSNode node, CBMArena *a
(void)kind;
switch (ctx->language) {
case CBM_LANG_PYTHON: {
- TSNode left = ts_node_child_by_field_name(node, "left", 4);
+ TSNode left = ts_node_child_by_field_name(node, TS_FIELD("left"));
if (!ts_node_is_null(left) && strcmp(ts_node_type(left), "identifier") == 0) {
push_var_def(ctx, cbm_node_text(a, left, ctx->source), node);
}
@@ -2182,7 +2258,7 @@ static void extract_vars_mainstream(CBMExtractCtx *ctx, TSNode node, CBMArena *a
TSNode child = ts_node_named_child(node, i);
const char *ck = ts_node_type(child);
if (strcmp(ck, "var_spec") == 0 || strcmp(ck, "const_spec") == 0) {
- TSNode vname = ts_node_child_by_field_name(child, "name", 4);
+ TSNode vname = ts_node_child_by_field_name(child, TS_FIELD("name"));
if (!ts_node_is_null(vname)) {
push_var_def(ctx, cbm_node_text(a, vname, ctx->source), child);
}
@@ -2215,7 +2291,7 @@ static void extract_vars_mainstream(CBMExtractCtx *ctx, TSNode node, CBMArena *a
break;
}
case CBM_LANG_RUST: {
- TSNode name_node = ts_node_child_by_field_name(node, "name", 4);
+ TSNode name_node = ts_node_child_by_field_name(node, TS_FIELD("name"));
if (!ts_node_is_null(name_node)) {
push_var_def(ctx, cbm_node_text(a, name_node, ctx->source), node);
}
@@ -2241,7 +2317,7 @@ static void extract_lua_vars(CBMExtractCtx *ctx, TSNode node, CBMArena *a) {
continue;
}
}
- TSNode vars = ts_node_child_by_field_name(child, "variables", 9);
+ TSNode vars = ts_node_child_by_field_name(child, TS_FIELD("variables"));
if (ts_node_is_null(vars)) {
vars = cbm_find_child_by_kind(child, "variable_list");
}
@@ -2257,7 +2333,7 @@ static void extract_lua_vars(CBMExtractCtx *ctx, TSNode node, CBMArena *a) {
// Strip Perl sigil ($, @, %) from name.
static char *strip_perl_sigil(char *name) {
if (name && (name[0] == '$' || name[0] == '@' || name[0] == '%')) {
- return name + 1;
+ return name + SKIP_CHAR;
}
return name;
}
@@ -2282,7 +2358,7 @@ static void extract_perl_vars(CBMExtractCtx *ctx, TSNode node, CBMArena *a) {
if (strcmp(ck, "assignment_expression") != 0) {
continue;
}
- TSNode left = ts_node_child_by_field_name(child, "left", 4);
+ TSNode left = ts_node_child_by_field_name(child, TS_FIELD("left"));
if (ts_node_is_null(left) && ts_node_named_child_count(child) > 0) {
left = ts_node_named_child(child, 0);
}
@@ -2313,9 +2389,9 @@ static void extract_r_vars(CBMExtractCtx *ctx, TSNode node, CBMArena *a) {
return;
}
}
- TSNode left = ts_node_child_by_field_name(node, "left", 4);
+ TSNode left = ts_node_child_by_field_name(node, TS_FIELD("left"));
if (ts_node_is_null(left)) {
- left = ts_node_child_by_field_name(node, "lhs", 3);
+ left = ts_node_child_by_field_name(node, TS_FIELD("lhs"));
}
if (ts_node_is_null(left) && ts_node_named_child_count(node) > 0) {
left = ts_node_named_child(node, 0);
@@ -2338,7 +2414,7 @@ static void extract_php_vars(CBMExtractCtx *ctx, TSNode node, CBMArena *a, const
for (uint32_t j = 0; j < nc; j++) {
TSNode inner = ts_node_named_child(node, j);
if (strcmp(ts_node_type(inner), "assignment_expression") == 0) {
- TSNode left = ts_node_child_by_field_name(inner, "left", 4);
+ TSNode left = ts_node_child_by_field_name(inner, TS_FIELD("left"));
if (!ts_node_is_null(left)) {
char *name = cbm_node_text(a, left, ctx->source);
if (name && name[0] == '$') {
@@ -2359,7 +2435,7 @@ static void extract_vars_dynamic(CBMExtractCtx *ctx, TSNode node, CBMArena *a, c
extract_lua_vars(ctx, node, a);
break;
case CBM_LANG_RUBY: {
- TSNode left = ts_node_child_by_field_name(node, "left", 4);
+ TSNode left = ts_node_child_by_field_name(node, TS_FIELD("left"));
if (!ts_node_is_null(left)) {
const char *lk = ts_node_type(left);
if (strcmp(lk, "identifier") == 0 || strcmp(lk, "constant") == 0) {
@@ -2381,7 +2457,7 @@ static void extract_vars_dynamic(CBMExtractCtx *ctx, TSNode node, CBMArena *a, c
// Kotlin variable name resolution: name > simple_identifier > identifier > variable_declaration.
static TSNode resolve_kotlin_var_name(TSNode node) {
- TSNode name_node = ts_node_child_by_field_name(node, "name", 4);
+ TSNode name_node = ts_node_child_by_field_name(node, TS_FIELD("name"));
if (!ts_node_is_null(name_node)) {
return name_node;
}
@@ -2408,11 +2484,11 @@ static TSNode resolve_kotlin_var_name(TSNode node) {
static void extract_vars_jvm(CBMExtractCtx *ctx, TSNode node, CBMArena *a) {
switch (ctx->language) {
case CBM_LANG_SCALA: {
- TSNode pattern = ts_node_child_by_field_name(node, "pattern", 7);
+ TSNode pattern = ts_node_child_by_field_name(node, TS_FIELD("pattern"));
if (!ts_node_is_null(pattern)) {
push_var_def(ctx, cbm_node_text(a, pattern, ctx->source), node);
} else {
- TSNode name_node = ts_node_child_by_field_name(node, "name", 4);
+ TSNode name_node = ts_node_child_by_field_name(node, TS_FIELD("name"));
if (!ts_node_is_null(name_node)) {
push_var_def(ctx, cbm_node_text(a, name_node, ctx->source), node);
}
@@ -2427,7 +2503,7 @@ static void extract_vars_jvm(CBMExtractCtx *ctx, TSNode node, CBMArena *a) {
break;
}
case CBM_LANG_GROOVY: {
- TSNode name_node = ts_node_child_by_field_name(node, "name", 4);
+ TSNode name_node = ts_node_child_by_field_name(node, TS_FIELD("name"));
if (ts_node_is_null(name_node)) {
const char *cname = extract_c_declarator_name(a, node, ctx->source);
if (cname) {
@@ -2455,8 +2531,8 @@ static char *trim_whitespace(char *name) {
name++;
}
size_t nlen = strlen(name);
- while (nlen > 0 && (name[nlen - 1] == ' ' || name[nlen - 1] == '\t')) {
- name[nlen - 1] = '\0';
+ while (nlen > 0 && (name[nlen - SKIP_CHAR] == ' ' || name[nlen - SKIP_CHAR] == '\t')) {
+ name[nlen - SKIP_CHAR] = '\0';
nlen--;
}
return name;
@@ -2507,15 +2583,15 @@ static void push_first_matching_child(CBMExtractCtx *ctx, TSNode node, CBMArena
// JSON variable extraction: strip quotes from key.
static void extract_json_var(CBMExtractCtx *ctx, TSNode node, CBMArena *a) {
- TSNode key_node = ts_node_child_by_field_name(node, "key", 3);
+ TSNode key_node = ts_node_child_by_field_name(node, TS_FIELD("key"));
if (ts_node_is_null(key_node)) {
return;
}
char *raw = cbm_node_text(a, key_node, ctx->source);
if (raw) {
size_t rlen = strlen(raw);
- if (rlen >= 2 && raw[0] == '"' && raw[rlen - 1] == '"') {
- raw[rlen - 1] = '\0';
+ if (rlen >= PAIR_CHARS && raw[0] == '"' && raw[rlen - SKIP_CHAR] == '"') {
+ raw[rlen - SKIP_CHAR] = '\0';
raw++;
}
push_var_def(ctx, raw, node);
@@ -2524,9 +2600,9 @@ static void extract_json_var(CBMExtractCtx *ctx, TSNode node, CBMArena *a) {
// SCSS variable extraction: try property > name > property_name > variable_name.
static void extract_scss_var(CBMExtractCtx *ctx, TSNode node, CBMArena *a) {
- TSNode prop = ts_node_child_by_field_name(node, "property", 8);
+ TSNode prop = ts_node_child_by_field_name(node, TS_FIELD("property"));
if (ts_node_is_null(prop)) {
- prop = ts_node_child_by_field_name(node, "name", 4);
+ prop = ts_node_child_by_field_name(node, TS_FIELD("name"));
}
if (ts_node_is_null(prop)) {
prop = cbm_find_child_by_kind(node, "property_name");
@@ -2542,7 +2618,7 @@ static void extract_scss_var(CBMExtractCtx *ctx, TSNode node, CBMArena *a) {
static void extract_vars_config(CBMExtractCtx *ctx, TSNode node, CBMArena *a, const char *kind) {
switch (ctx->language) {
case CBM_LANG_YAML: {
- TSNode key = ts_node_child_by_field_name(node, "key", 3);
+ TSNode key = ts_node_child_by_field_name(node, TS_FIELD("key"));
if (!ts_node_is_null(key)) {
push_var_def(ctx, cbm_node_text(a, key, ctx->source), node);
}
@@ -2574,7 +2650,7 @@ static void extract_vars_config(CBMExtractCtx *ctx, TSNode node, CBMArena *a, co
break;
}
case CBM_LANG_BASH: {
- TSNode name_node = ts_node_child_by_field_name(node, "name", 4);
+ TSNode name_node = ts_node_child_by_field_name(node, TS_FIELD("name"));
if (!ts_node_is_null(name_node)) {
push_var_def(ctx, cbm_node_text(a, name_node, ctx->source), node);
} else {
@@ -2643,7 +2719,7 @@ static void extract_var_names(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec
}
/* Default fallback: name field → C-declarator → first identifier */
- TSNode name_node = ts_node_child_by_field_name(node, "name", 4);
+ TSNode name_node = ts_node_child_by_field_name(node, TS_FIELD("name"));
if (!ts_node_is_null(name_node)) {
push_var_def(ctx, cbm_node_text(a, name_node, ctx->source), node);
return;
@@ -2663,37 +2739,38 @@ static void extract_var_names(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec
}
}
-// Recursive variable walker for languages with deeply nested module structure.
-// Used by YAML, TOML, INI, JSON (config languages with nested containers).
-static void walk_variables_rec(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec,
- int depth) {
- if (depth > 8) {
- return; // safety limit
- }
- uint32_t count = ts_node_child_count(node);
- for (uint32_t i = 0; i < count; i++) {
- TSNode child = ts_node_child(node, i);
- if (ts_node_is_null(child)) {
- continue;
- }
- if (cbm_kind_in_set(child, spec->variable_node_types)) {
- if (cbm_is_module_level(child, ctx->language)) {
- extract_var_names(ctx, child, spec);
+// Iterative variable walker for config languages with nested structure.
+// Used by YAML, TOML, INI, JSON.
+#define VAR_WALK_STACK_CAP CBM_SZ_256
+static void walk_variables_iter(CBMExtractCtx *ctx, TSNode root, const CBMLangSpec *spec) {
+ TSNode stack[VAR_WALK_STACK_CAP];
+ int top = 0;
+ stack[top++] = root;
+
+ while (top > 0) {
+ TSNode node = stack[--top];
+ uint32_t count = ts_node_child_count(node);
+ for (int i = (int)count - SKIP_CHAR; i >= 0; i--) {
+ TSNode child = ts_node_child(node, (uint32_t)i);
+ if (ts_node_is_null(child)) {
+ continue;
+ }
+ if (cbm_kind_in_set(child, spec->variable_node_types)) {
+ if (cbm_is_module_level(child, ctx->language)) {
+ extract_var_names(ctx, child, spec);
+ }
+ }
+ const char *ck = ts_node_type(child);
+ if (strcmp(ck, "document") == 0 || strcmp(ck, "block_node") == 0 ||
+ strcmp(ck, "block_mapping") == 0 || strcmp(ck, "stream") == 0 ||
+ strcmp(ck, "table") == 0 || strcmp(ck, "table_array_element") == 0 ||
+ strcmp(ck, "section") == 0 || strcmp(ck, "object") == 0 ||
+ strcmp(ck, "array") == 0 || strcmp(ck, "pair") == 0 || strcmp(ck, "element") == 0 ||
+ strcmp(ck, "content") == 0) {
+ if (top < VAR_WALK_STACK_CAP) {
+ stack[top++] = child;
+ }
}
- }
- // Always recurse into structural container nodes
- const char *ck = ts_node_type(child);
- if (strcmp(ck, "document") == 0 || strcmp(ck, "block_node") == 0 ||
- strcmp(ck, "block_mapping") == 0 || strcmp(ck, "stream") == 0 ||
- // TOML containers
- strcmp(ck, "table") == 0 || strcmp(ck, "table_array_element") == 0 ||
- // INI containers
- strcmp(ck, "section") == 0 ||
- // JSON/TOML containers (pair can contain nested objects)
- strcmp(ck, "object") == 0 || strcmp(ck, "array") == 0 || strcmp(ck, "pair") == 0 ||
- // XML containers
- strcmp(ck, "element") == 0 || strcmp(ck, "content") == 0) {
- walk_variables_rec(ctx, child, spec, depth + 1);
}
}
}
@@ -2706,7 +2783,7 @@ static void extract_variables(CBMExtractCtx *ctx, TSNode root, const CBMLangSpec
// Config languages with nested structure: use recursive walk
if (ctx->language == CBM_LANG_YAML || ctx->language == CBM_LANG_TOML ||
ctx->language == CBM_LANG_INI || ctx->language == CBM_LANG_JSON) {
- walk_variables_rec(ctx, root, spec, 0);
+ walk_variables_iter(ctx, root, spec);
return;
}
@@ -2751,12 +2828,12 @@ static void extract_variables(CBMExtractCtx *ctx, TSNode root, const CBMLangSpec
// These are later collected by DefsToLSPDefs to build FieldDefs pipe-separated strings.
// Check if a field_declaration has a function-pointer declarator chain.
static bool is_func_ptr_field(TSNode field) {
- TSNode decl = ts_node_child_by_field_name(field, "declarator", 10);
- for (int depth = 0; depth < 5 && !ts_node_is_null(decl); depth++) {
+ TSNode decl = ts_node_child_by_field_name(field, TS_FIELD("declarator"));
+ for (int depth = 0; depth < C_RETURN_WALK_DEPTH && !ts_node_is_null(decl); depth++) {
if (strcmp(ts_node_type(decl), "function_declarator") == 0) {
return true;
}
- TSNode inner = ts_node_child_by_field_name(decl, "declarator", 10);
+ TSNode inner = ts_node_child_by_field_name(decl, TS_FIELD("declarator"));
if (ts_node_is_null(inner)) {
uint32_t nc = ts_node_named_child_count(decl);
for (uint32_t k = 0; k < nc; k++) {
@@ -2773,9 +2850,9 @@ static bool is_func_ptr_field(TSNode field) {
// Resolve the name node for a field declaration, unwrapping C pointer/array declarators.
static TSNode resolve_field_name_node(TSNode child) {
- TSNode name_node = ts_node_child_by_field_name(child, "declarator", 10);
+ TSNode name_node = ts_node_child_by_field_name(child, TS_FIELD("declarator"));
if (ts_node_is_null(name_node)) {
- name_node = ts_node_child_by_field_name(child, "name", 4);
+ name_node = ts_node_child_by_field_name(child, TS_FIELD("name"));
}
if (ts_node_is_null(name_node)) {
TSNode null_node = {0};
@@ -2783,7 +2860,7 @@ static TSNode resolve_field_name_node(TSNode child) {
}
const char *nk = ts_node_type(name_node);
if (strcmp(nk, "pointer_declarator") == 0 || strcmp(nk, "array_declarator") == 0) {
- TSNode inner = ts_node_child_by_field_name(name_node, "declarator", 10);
+ TSNode inner = ts_node_child_by_field_name(name_node, TS_FIELD("declarator"));
if (!ts_node_is_null(inner)) {
return inner;
}
@@ -2817,7 +2894,7 @@ static void extract_class_fields(CBMExtractCtx *ctx, TSNode class_node, const ch
}
// Extract type from "type" field
- TSNode type_node = ts_node_child_by_field_name(child, "type", 4);
+ TSNode type_node = ts_node_child_by_field_name(child, TS_FIELD("type"));
if (ts_node_is_null(type_node)) {
continue;
}
@@ -2846,8 +2923,8 @@ static void extract_class_fields(CBMExtractCtx *ctx, TSNode class_node, const ch
def.file_path = ctx->rel_path;
def.parent_class = class_qn;
def.return_type = type_text;
- def.start_line = ts_node_start_point(child).row + 1;
- def.end_line = ts_node_end_point(child).row + 1;
+ def.start_line = ts_node_start_point(child).row + TS_LINE_OFFSET;
+ def.end_line = ts_node_end_point(child).row + TS_LINE_OFFSET;
def.is_exported = cbm_is_exported(name, ctx->language);
cbm_defs_push(&ctx->result->defs, a, def);
@@ -2889,14 +2966,14 @@ typedef struct {
// Iteratively walks into wrapper nodes (field_declaration, template_declaration).
static void push_nested_class_nodes(TSNode body, const CBMLangSpec *spec, walk_defs_frame_t *stack,
int *top, const char *enclosing_qn) {
- TSNode nc_stack[128];
+ TSNode nc_stack[NESTED_CLASS_STACK_CAP];
int nc_top = 0;
nc_stack[nc_top++] = body;
while (nc_top > 0) {
TSNode cur = nc_stack[--nc_top];
uint32_t nc = ts_node_child_count(cur);
- for (int i = (int)nc - 1; i >= 0; i--) {
+ for (int i = (int)nc - SKIP_CHAR; i >= 0; i--) {
TSNode child = ts_node_child(cur, (uint32_t)i);
if (cbm_kind_in_set(child, spec->class_node_types)) {
if (*top < CBM_WALK_DEFS_STACK_CAP) {
@@ -2906,7 +2983,7 @@ static void push_nested_class_nodes(TSNode body, const CBMLangSpec *spec, walk_d
const char *ck = ts_node_type(child);
if (strcmp(ck, "field_declaration") == 0 ||
strcmp(ck, "template_declaration") == 0 || strcmp(ck, "declaration") == 0) {
- if (nc_top < 128) {
+ if (nc_top < NESTED_CLASS_STACK_CAP) {
nc_stack[nc_top++] = child;
}
}
@@ -2934,7 +3011,7 @@ static bool is_template_class_node(TSNode node, CBMLanguage lang) {
// Compute the enclosing class QN for a class node (for nested class context).
static const char *compute_class_qn(CBMExtractCtx *ctx, TSNode node, const char *saved_enclosing) {
- TSNode name_node = ts_node_child_by_field_name(node, "name", 4);
+ TSNode name_node = ts_node_child_by_field_name(node, TS_FIELD("name"));
if (ts_node_is_null(name_node) && ctx->language == CBM_LANG_OBJC) {
name_node = cbm_find_child_by_kind(node, "identifier");
}
@@ -2968,7 +3045,7 @@ static void push_class_body_children(TSNode node, const CBMLangSpec *spec, walk_
}
}
// No body found — push all children directly
- for (int ci = (int)nc - 1; ci >= 0 && *top < CBM_WALK_DEFS_STACK_CAP; ci--) {
+ for (int ci = (int)nc - SKIP_CHAR; ci >= 0 && *top < CBM_WALK_DEFS_STACK_CAP; ci--) {
stack[(*top)++] = (walk_defs_frame_t){ts_node_child(node, (uint32_t)ci), new_enclosing};
}
}
@@ -3012,7 +3089,7 @@ static void walk_defs(CBMExtractCtx *ctx, TSNode root, const CBMLangSpec *spec,
}
uint32_t count = ts_node_child_count(node);
- for (int i = (int)count - 1; i >= 0 && top < CBM_WALK_DEFS_STACK_CAP; i--) {
+ for (int i = (int)count - SKIP_CHAR; i >= 0 && top < CBM_WALK_DEFS_STACK_CAP; i--) {
stack[top++] =
(walk_defs_frame_t){ts_node_child(node, (uint32_t)i), frame.enclosing_class_qn};
}
@@ -3034,8 +3111,8 @@ void cbm_extract_definitions(CBMExtractCtx *ctx) {
mod.qualified_name = ctx->module_qn;
mod.label = "Module";
mod.file_path = ctx->rel_path;
- mod.start_line = 1;
- mod.end_line = ts_node_end_point(ctx->root).row + 1;
+ mod.start_line = FIRST_LINE;
+ mod.end_line = ts_node_end_point(ctx->root).row + TS_LINE_OFFSET;
mod.is_exported = true;
mod.is_test = ctx->result->is_test_file;
cbm_defs_push(&ctx->result->defs, a, mod);
diff --git a/internal/cbm/extract_env_accesses.c b/internal/cbm/extract_env_accesses.c
index 0e73c242b..215b3a004 100644
--- a/internal/cbm/extract_env_accesses.c
+++ b/internal/cbm/extract_env_accesses.c
@@ -3,11 +3,15 @@
#include "helpers.h"
#include "lang_specs.h"
#include "extract_unified.h"
+#include "foundation/constants.h"
#include "tree_sitter/api.h" // TSNode, ts_node_*
#include <stdint.h> // uint32_t
#include <string.h>
#include <ctype.h>
+/* Minimum length for an env var name (e.g., "DB"). */
+enum { MIN_ENV_NAME_LEN = 2 };
+
// Unquote a string literal: "foo" -> foo, 'foo' -> foo
static const char *unquote(CBMArena *a, const char *s) {
if (!s || !s[0]) {
@@ -18,12 +22,12 @@ static const char *unquote(CBMArena *a, const char *s) {
s++;
}
size_t len = strlen(s);
- if (len >= 2) {
+ if (len >= CBM_QUOTE_PAIR) {
char first = s[0];
- char last = s[len - 1];
+ char last = s[len - CBM_QUOTE_OFFSET];
if ((first == '"' && last == '"') || (first == '\'' && last == '\'') ||
(first == '`' && last == '`')) {
- return cbm_arena_strndup(a, s + 1, len - 2);
+ return cbm_arena_strndup(a, s + CBM_QUOTE_OFFSET, len - CBM_QUOTE_PAIR);
}
}
return s;
@@ -36,7 +40,7 @@ static const char *extract_env_key_from_call(CBMExtractCtx *ctx, TSNode node,
return NULL;
}
- TSNode func_node = ts_node_child_by_field_name(node, "function", 8);
+ TSNode func_node = ts_node_child_by_field_name(node, TS_FIELD("function"));
if (ts_node_is_null(func_node)) {
return NULL;
}
@@ -58,7 +62,7 @@ static const char *extract_env_key_from_call(CBMExtractCtx *ctx, TSNode node,
}
// Get first argument (the env key)
- TSNode args = ts_node_child_by_field_name(node, "arguments", 9);
+ TSNode args = ts_node_child_by_field_name(node, TS_FIELD("arguments"));
if (ts_node_is_null(args)) {
return NULL;
}
@@ -92,7 +96,7 @@ static const char *extract_env_key_from_member(CBMExtractCtx *ctx, TSNode node,
// Dot access: pattern.KEY
if (strncmp(text, *pat, plen) == 0 && text[plen] == '.') {
- const char *key = text + plen + 1;
+ const char *key = text + plen + CBM_QUOTE_OFFSET;
// Validate: no further dots/brackets
if (key[0] && !strchr(key, '.') && !strchr(key, '[')) {
return key;
@@ -101,10 +105,11 @@ static const char *extract_env_key_from_member(CBMExtractCtx *ctx, TSNode node,
// Subscript: pattern["KEY"]
if (strncmp(text, *pat, plen) == 0 && text[plen] == '[') {
- const char *inner = text + plen + 1;
+ const char *inner = text + plen + CBM_QUOTE_OFFSET;
size_t ilen = strlen(inner);
- if (ilen > 0 && inner[ilen - 1] == ']') {
- char *bracket_content = cbm_arena_strndup(ctx->arena, inner, ilen - 1);
+ if (ilen > 0 && inner[ilen - CBM_QUOTE_OFFSET] == ']') {
+ char *bracket_content =
+ cbm_arena_strndup(ctx->arena, inner, ilen - CBM_QUOTE_OFFSET);
return unquote(ctx->arena, bracket_content);
}
}
@@ -114,7 +119,7 @@ static const char *extract_env_key_from_member(CBMExtractCtx *ctx, TSNode node,
// Check if an env key name looks like an environment variable (uppercase + underscores).
static bool is_env_var_name(const char *s) {
- if (!s || strlen(s) < 2) {
+ if (!s || strlen(s) < MIN_ENV_NAME_LEN) {
return false;
}
bool has_upper = false;
@@ -159,7 +164,8 @@ static void walk_env_accesses(CBMExtractCtx *ctx, TSNode root, const CBMLangSpec
}
uint32_t count = ts_node_child_count(node);
- for (int i = (int)count - 1; i >= 0 && top < ENV_STACK_CAP; i--) {
+ enum { LAST_IDX = 1 };
+ for (int i = (int)count - LAST_IDX; i >= 0 && top < ENV_STACK_CAP; i--) {
stack[top++] = ts_node_child(node, (uint32_t)i);
}
}
diff --git a/internal/cbm/extract_imports.c b/internal/cbm/extract_imports.c
index 9da4d00f0..83fa8854e 100644
--- a/internal/cbm/extract_imports.c
+++ b/internal/cbm/extract_imports.c
@@ -2,10 +2,18 @@
#include "arena.h" // CBMArena, cbm_arena_strdup/strndup/sprintf
#include "helpers.h"
#include "tree_sitter/api.h" // TSNode, ts_node_*
-#include <stdint.h> // uint32_t
+#include "foundation/constants.h"
+#include <stdint.h> // uint32_t
#include <string.h>
#include <ctype.h>
+/* Local constants for magic number elimination. */
+enum {
+ USE_PREFIX_LEN = 4, /* strlen("use ") */
+ MIN_WOLFRAM_CHILDREN = 2,
+ SECOND_IDX = 1,
+};
+
// Field name length for ts_node_child_by_field_name() calls.
#define FIELD_LEN_MODULE_NAME 11 // strlen("module_name")
@@ -27,8 +35,8 @@ static char *strip_quotes(CBMArena *a, const char *s) {
return NULL;
}
size_t len = strlen(s);
- if (len >= 2 && (s[0] == '"' || s[0] == '\'') && s[len - 1] == s[0]) {
- return cbm_arena_strndup(a, s + 1, len - 2);
+ if (len >= CBM_QUOTE_PAIR && (s[0] == '"' || s[0] == '\'') && s[len - SKIP_ONE] == s[0]) {
+ return cbm_arena_strndup(a, s + SKIP_ONE, len - PAIR_LEN);
}
return cbm_arena_strdup(a, s);
}
@@ -40,11 +48,11 @@ static const char *path_last(CBMArena *a, const char *path) {
}
const char *last = strrchr(path, '/');
if (last) {
- return cbm_arena_strdup(a, last + 1);
+ return cbm_arena_strdup(a, last + SKIP_ONE);
}
last = strrchr(path, '.');
if (last) {
- return cbm_arena_strdup(a, last + 1);
+ return cbm_arena_strdup(a, last + SKIP_ONE);
}
return path;
}
@@ -55,7 +63,7 @@ static const char *path_last(CBMArena *a, const char *path) {
// Parse a single Go import_spec node.
static void parse_go_import_spec(CBMExtractCtx *ctx, TSNode spec) {
CBMArena *a = ctx->arena;
- TSNode path_node = ts_node_child_by_field_name(spec, "path", 4);
+ TSNode path_node = ts_node_child_by_field_name(spec, TS_FIELD("path"));
if (ts_node_is_null(path_node)) {
return;
}
@@ -64,7 +72,7 @@ static void parse_go_import_spec(CBMExtractCtx *ctx, TSNode spec) {
return;
}
- TSNode name_node = ts_node_child_by_field_name(spec, "name", 4);
+ TSNode name_node = ts_node_child_by_field_name(spec, TS_FIELD("name"));
const char *local_name =
!ts_node_is_null(name_node) ? cbm_node_text(a, name_node, ctx->source) : path_last(a, path);
@@ -111,8 +119,8 @@ static void parse_go_imports(CBMExtractCtx *ctx) {
// Emit a Python aliased_import (import X as Y / from X import Y as Z).
static void emit_py_aliased_import(CBMExtractCtx *ctx, TSNode child, const char *mod_prefix) {
CBMArena *a = ctx->arena;
- TSNode mod_node = ts_node_child_by_field_name(child, "name", 4);
- TSNode alias_node = ts_node_child_by_field_name(child, "alias", 5);
+ TSNode mod_node = ts_node_child_by_field_name(child, TS_FIELD("name"));
+ TSNode alias_node = ts_node_child_by_field_name(child, TS_FIELD("alias"));
if (ts_node_is_null(mod_node)) {
return;
}
@@ -130,7 +138,7 @@ static void emit_py_aliased_import(CBMExtractCtx *ctx, TSNode child, const char
// Process a single Python import_statement node (import X, import X as Y).
static void process_py_import_stmt(CBMExtractCtx *ctx, TSNode node) {
CBMArena *a = ctx->arena;
- TSNode name_node = ts_node_child_by_field_name(node, "name", 4);
+ TSNode name_node = ts_node_child_by_field_name(node, TS_FIELD("name"));
if (ts_node_is_null(name_node)) {
uint32_t nc = ts_node_child_count(node);
for (uint32_t j = 0; j < nc; j++) {
@@ -230,10 +238,10 @@ static void parse_python_imports(CBMExtractCtx *ctx) {
// Find the source string node in an ES import_statement.
static TSNode find_es_source_node(TSNode node) {
- TSNode source_node = ts_node_child_by_field_name(node, "source", 6);
+ TSNode source_node = ts_node_child_by_field_name(node, TS_FIELD("source"));
if (ts_node_is_null(source_node)) {
uint32_t nc = ts_node_child_count(node);
- for (int j = (int)nc - 1; j >= 0; j--) {
+ for (int j = (int)nc - SKIP_ONE; j >= 0; j--) {
TSNode c = ts_node_child(node, (uint32_t)j);
const char *ck = ts_node_type(c);
if (strcmp(ck, "string") == 0 || strcmp(ck, "string_literal") == 0) {
@@ -254,8 +262,8 @@ static bool process_named_imports(CBMExtractCtx *ctx, TSNode sub, const char *pa
if (strcmp(ts_node_type(imp_spec), "import_specifier") != 0) {
continue;
}
- TSNode local = ts_node_child_by_field_name(imp_spec, "alias", 5);
- TSNode orig = ts_node_child_by_field_name(imp_spec, "name", 4);
+ TSNode local = ts_node_child_by_field_name(imp_spec, TS_FIELD("alias"));
+ TSNode orig = ts_node_child_by_field_name(imp_spec, TS_FIELD("name"));
if (ts_node_is_null(orig) && ts_node_child_count(imp_spec) > 0) {
orig = ts_node_child(imp_spec, 0);
}
@@ -284,9 +292,9 @@ static bool process_import_clause(CBMExtractCtx *ctx, TSNode clause, const char
cbm_imports_push(&ctx->result->imports, a, imp);
found = true;
} else if (strcmp(sk, "namespace_import") == 0) {
- TSNode as_name = ts_node_child_by_field_name(sub, "name", 4);
+ TSNode as_name = ts_node_child_by_field_name(sub, TS_FIELD("name"));
if (ts_node_is_null(as_name) && ts_node_child_count(sub) > 0) {
- as_name = ts_node_child(sub, ts_node_child_count(sub) - 1);
+ as_name = ts_node_child(sub, ts_node_child_count(sub) - SKIP_ONE);
}
if (!ts_node_is_null(as_name)) {
char *name = cbm_node_text(a, as_name, ctx->source);
@@ -303,50 +311,63 @@ static bool process_import_clause(CBMExtractCtx *ctx, TSNode clause, const char
return found;
}
-static void walk_es_imports(CBMExtractCtx *ctx, TSNode node) {
+/* Process a single ES import_statement node. Returns true if fully handled. */
+static bool process_es_import_statement(CBMExtractCtx *ctx, TSNode node) {
CBMArena *a = ctx->arena;
- const char *kind = ts_node_type(node);
-
- if (strcmp(kind, "import_statement") == 0) {
- TSNode source_node = find_es_source_node(node);
- if (ts_node_is_null(source_node)) {
- goto recurse;
+ TSNode source_node = find_es_source_node(node);
+ if (ts_node_is_null(source_node)) {
+ return false;
+ }
+ char *path = strip_quotes(a, cbm_node_text(a, source_node, ctx->source));
+ if (!path || !path[0]) {
+ return false;
+ }
+ uint32_t nc = ts_node_child_count(node);
+ bool found = false;
+ for (uint32_t j = 0; j < nc; j++) {
+ TSNode child = ts_node_child(node, j);
+ const char *ck = ts_node_type(child);
+ if (strcmp(ck, "identifier") == 0) {
+ char *name = cbm_node_text(a, child, ctx->source);
+ CBMImport imp = {.local_name = name, .module_path = path};
+ cbm_imports_push(&ctx->result->imports, a, imp);
+ found = true;
+ } else if (strcmp(ck, "import_clause") == 0) {
+ if (process_import_clause(ctx, child, path)) {
+ found = true;
+ }
}
+ }
+ if (!found) {
+ CBMImport imp = {.local_name = path_last(a, path), .module_path = path};
+ cbm_imports_push(&ctx->result->imports, a, imp);
+ }
+ return true;
+}
- char *path = strip_quotes(a, cbm_node_text(a, source_node, ctx->source));
- if (!path || !path[0]) {
- goto recurse;
- }
+#define ES_IMPORT_STACK_CAP CBM_SZ_512
+static void walk_es_imports(CBMExtractCtx *ctx, TSNode root) {
+ TSNode stack[ES_IMPORT_STACK_CAP];
+ int top = 0;
+ stack[top++] = root;
- uint32_t nc = ts_node_child_count(node);
- bool found = false;
- for (uint32_t j = 0; j < nc; j++) {
- TSNode child = ts_node_child(node, j);
- const char *ck = ts_node_type(child);
+ while (top > 0) {
+ TSNode node = stack[--top];
+ const char *kind = ts_node_type(node);
+ bool push_children = true;
- if (strcmp(ck, "identifier") == 0) {
- char *name = cbm_node_text(a, child, ctx->source);
- CBMImport imp = {.local_name = name, .module_path = path};
- cbm_imports_push(&ctx->result->imports, a, imp);
- found = true;
- } else if (strcmp(ck, "import_clause") == 0) {
- if (process_import_clause(ctx, child, path)) {
- found = true;
- }
+ if (strcmp(kind, "import_statement") == 0) {
+ if (process_es_import_statement(ctx, node)) {
+ push_children = false;
}
}
- if (!found) {
- CBMImport imp = {.local_name = path_last(a, path), .module_path = path};
- cbm_imports_push(&ctx->result->imports, a, imp);
+ if (push_children) {
+ uint32_t count = ts_node_child_count(node);
+ for (int i = (int)count - SKIP_ONE; i >= 0 && top < ES_IMPORT_STACK_CAP; i--) {
+ stack[top++] = ts_node_child(node, (uint32_t)i);
+ }
}
- return;
- }
-
-recurse:;
- uint32_t count = ts_node_child_count(node);
- for (uint32_t i = 0; i < count; i++) {
- walk_es_imports(ctx, ts_node_child(node, i));
}
}
@@ -411,12 +432,12 @@ static void parse_rust_imports(CBMExtractCtx *ctx) {
continue;
}
// Strip "use " prefix and trailing ";"
- if (strncmp(full, "use ", 4) == 0) {
- full += 4;
+ if (strncmp(full, "use ", USE_PREFIX_LEN) == 0) {
+ full += USE_PREFIX_LEN;
}
size_t len = strlen(full);
- if (len > 0 && full[len - 1] == ';') {
- full[len - 1] = '\0';
+ if (len > 0 && full[len - SKIP_ONE] == ';') {
+ full[len - SKIP_ONE] = '\0';
}
CBMImport imp = {.local_name = path_last(a, full), .module_path = full};
@@ -430,7 +451,7 @@ static void parse_rust_imports(CBMExtractCtx *ctx) {
// Find the path node inside a preproc_include/preproc_import node.
static TSNode find_include_path_node(TSNode node) {
- TSNode path_node = ts_node_child_by_field_name(node, "path", 4);
+ TSNode path_node = ts_node_child_by_field_name(node, TS_FIELD("path"));
if (ts_node_is_null(path_node)) {
uint32_t nc = ts_node_child_count(node);
for (uint32_t j = 0; j < nc; j++) {
@@ -448,8 +469,8 @@ static TSNode find_include_path_node(TSNode node) {
static char *strip_angle_brackets(CBMArena *a, char *path) {
if (path && path[0] == '<') {
size_t len = strlen(path);
- if (len > 1 && path[len - 1] == '>') {
- return cbm_arena_strndup(a, path + 1, len - 2);
+ if (len > SKIP_ONE && path[len - SKIP_ONE] == '>') {
+ return cbm_arena_strndup(a, path + SKIP_ONE, len - PAIR_LEN);
}
}
return path;
@@ -492,7 +513,7 @@ static void parse_c_imports(CBMExtractCtx *ctx) {
// Check if a Ruby call node is a require/require_relative, return method name or NULL.
static const char *ruby_require_method(CBMArena *a, TSNode node, const char *source) {
- TSNode method = ts_node_child_by_field_name(node, "method", 6);
+ TSNode method = ts_node_child_by_field_name(node, TS_FIELD("method"));
if (ts_node_is_null(method) && ts_node_child_count(node) > 0) {
method = ts_node_child(node, 0);
}
@@ -508,10 +529,10 @@ static const char *ruby_require_method(CBMArena *a, TSNode node, const char *sou
// Extract string argument from a Ruby require/require_relative call.
static char *extract_ruby_require_arg(CBMArena *a, TSNode node, const char *source) {
- TSNode args = ts_node_child_by_field_name(node, "arguments", 9);
+ TSNode args = ts_node_child_by_field_name(node, TS_FIELD("arguments"));
if (ts_node_is_null(args)) {
- if (ts_node_child_count(node) > 1) {
- args = ts_node_child(node, 1);
+ if (ts_node_child_count(node) > SECOND_IDX) {
+ args = ts_node_child(node, SECOND_IDX);
}
}
if (ts_node_is_null(args)) {
@@ -649,11 +670,11 @@ static void generic_import_from_text(CBMExtractCtx *ctx, TSNode node) {
}
char *space = strchr(text, ' ');
if (space) {
- text = space + 1;
+ text = space + SKIP_ONE;
}
size_t len = strlen(text);
- if (len > 0 && text[len - 1] == ';') {
- text[len - 1] = '\0';
+ if (len > 0 && text[len - SKIP_ONE] == ';') {
+ text[len - SKIP_ONE] = '\0';
}
if (text[0]) {
CBMImport imp = {.local_name = path_last(a, text), .module_path = text};
@@ -707,7 +728,7 @@ static void process_wolfram_get_top(CBMExtractCtx *ctx, TSNode node) {
// Handle Wolfram Needs["package`"] — apply where head is builtin_symbol "Needs".
static void process_wolfram_needs(CBMExtractCtx *ctx, TSNode node) {
CBMArena *a = ctx->arena;
- if (ts_node_named_child_count(node) < 2) {
+ if (ts_node_named_child_count(node) < MIN_WOLFRAM_CHILDREN) {
return;
}
TSNode head = ts_node_named_child(node, 0);
@@ -718,7 +739,7 @@ static void process_wolfram_needs(CBMExtractCtx *ctx, TSNode node) {
if (!name || strcmp(name, "Needs") != 0) {
return;
}
- TSNode arg = ts_node_named_child(node, 1);
+ TSNode arg = ts_node_named_child(node, SECOND_IDX);
char *text = cbm_node_text(a, arg, ctx->source);
if (text && text[0]) {
char *path = strip_quotes(a, text);
@@ -727,18 +748,26 @@ static void process_wolfram_needs(CBMExtractCtx *ctx, TSNode node) {
}
}
-static void walk_wolfram_imports(CBMExtractCtx *ctx, TSNode node) {
- const char *kind = ts_node_type(node);
+#define WOLFRAM_IMPORT_STACK_CAP CBM_SZ_512
+static void walk_wolfram_imports(CBMExtractCtx *ctx, TSNode root) {
+ TSNode stack[WOLFRAM_IMPORT_STACK_CAP];
+ int top = 0;
+ stack[top++] = root;
- if (strcmp(kind, "get_top") == 0) {
- process_wolfram_get_top(ctx, node);
- } else if (strcmp(kind, "apply") == 0) {
- process_wolfram_needs(ctx, node);
- }
+ while (top > 0) {
+ TSNode node = stack[--top];
+ const char *kind = ts_node_type(node);
- uint32_t count = ts_node_child_count(node);
- for (uint32_t i = 0; i < count; i++) {
- walk_wolfram_imports(ctx, ts_node_child(node, i));
+ if (strcmp(kind, "get_top") == 0) {
+ process_wolfram_get_top(ctx, node);
+ } else if (strcmp(kind, "apply") == 0) {
+ process_wolfram_needs(ctx, node);
+ }
+
+ uint32_t count = ts_node_child_count(node);
+ for (int i = (int)count - SKIP_ONE; i >= 0 && top < WOLFRAM_IMPORT_STACK_CAP; i--) {
+ stack[top++] = ts_node_child(node, (uint32_t)i);
+ }
}
}
diff --git a/internal/cbm/extract_k8s.c b/internal/cbm/extract_k8s.c
index 446761a97..be9e27829 100644
--- a/internal/cbm/extract_k8s.c
+++ b/internal/cbm/extract_k8s.c
@@ -12,10 +12,17 @@
#include "arena.h"
#include "helpers.h"
#include "tree_sitter/api.h"
+#include "foundation/constants.h"
#include <stdint.h>
#include <stdio.h>
#include <string.h>
+/* Local constants. */
+enum {
+ K8S_BUF_SIZE = 256,
+ RESULT_BUF_SIZE = 512,
+};
+
// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------
@@ -26,28 +33,32 @@
// child (the tree-sitter YAML grammar often wraps scalars in flow_node).
// Returns NULL for non-scalar node types.
static const char *get_scalar_text(CBMArena *a, TSNode node, const char *source) {
- const char *type = ts_node_type(node);
- // Unwrap flow_node: the actual scalar is the first named child
- if (strcmp(type, "flow_node") == 0) {
- TSNode inner = ts_node_named_child(node, 0);
- if (ts_node_is_null(inner)) {
- return NULL;
+ enum { MAX_UNWRAP = 4 };
+ for (int depth = 0; depth < MAX_UNWRAP; depth++) {
+ const char *type = ts_node_type(node);
+ if (strcmp(type, "flow_node") == 0) {
+ TSNode inner = ts_node_named_child(node, 0);
+ if (ts_node_is_null(inner)) {
+ return NULL;
+ }
+ node = inner;
+ continue;
}
- return get_scalar_text(a, inner, source);
- }
- if (strcmp(type, "plain_scalar") == 0) {
- return cbm_node_text(a, node, source);
- }
- if (strcmp(type, "double_quote_scalar") == 0 || strcmp(type, "single_quote_scalar") == 0) {
- const char *raw = cbm_node_text(a, node, source);
- if (!raw) {
- return NULL;
+ if (strcmp(type, "plain_scalar") == 0) {
+ return cbm_node_text(a, node, source);
}
- size_t len = strlen(raw);
- if (len >= 2) {
- return cbm_arena_strndup(a, raw + 1, len - 2);
+ if (strcmp(type, "double_quote_scalar") == 0 || strcmp(type, "single_quote_scalar") == 0) {
+ const char *raw = cbm_node_text(a, node, source);
+ if (!raw) {
+ return NULL;
+ }
+ size_t len = strlen(raw);
+ if (len >= PAIR_LEN) {
+ return cbm_arena_strndup(a, raw + SKIP_ONE, len - PAIR_LEN);
+ }
+ return raw;
}
- return raw;
+ break;
}
return NULL;
}
@@ -122,7 +133,7 @@ static void process_kustomize_pair(CBMExtractCtx *ctx, TSNode pair) {
return;
}
- TSNode val_node = ts_node_named_child(pair, 1);
+ TSNode val_node = ts_node_named_child(pair, SKIP_ONE);
if (ts_node_is_null(val_node)) {
return;
}
@@ -179,7 +190,7 @@ static void extract_metadata_name(CBMArena *a, TSNode meta_mapping, const char *
if (!mkey_text || strcmp(mkey_text, "name") != 0) {
continue;
}
- TSNode mval = ts_node_named_child(mpair, 1);
+ TSNode mval = ts_node_named_child(mpair, SKIP_ONE);
if (ts_node_is_null(mval)) {
continue;
}
@@ -192,7 +203,7 @@ static void extract_metadata_name(CBMArena *a, TSNode meta_mapping, const char *
// Unwrap a block_mapping_pair value through optional block_node.
static TSNode unwrap_pair_value(TSNode pair) {
- TSNode val_node = ts_node_named_child(pair, 1);
+ TSNode val_node = ts_node_named_child(pair, SKIP_ONE);
if (ts_node_is_null(val_node)) {
return val_node;
}
@@ -263,8 +274,8 @@ static void extract_k8s_manifest(CBMExtractCtx *ctx) {
continue;
}
- char kind_buf[256] = {0};
- char meta_name_buf[256] = {0};
+ char kind_buf[K8S_BUF_SIZE] = {0};
+ char meta_name_buf[K8S_BUF_SIZE] = {0};
extract_k8s_scalars(ctx, mapping, kind_buf, sizeof(kind_buf), meta_name_buf,
sizeof(meta_name_buf));
@@ -273,7 +284,7 @@ static void extract_k8s_manifest(CBMExtractCtx *ctx) {
continue;
}
- char def_name[512];
+ char def_name[RESULT_BUF_SIZE];
snprintf(def_name, sizeof(def_name), "%s/%s", kind_buf, meta_name_buf);
CBMDefinition def = {0};
@@ -281,8 +292,8 @@ static void extract_k8s_manifest(CBMExtractCtx *ctx) {
def.qualified_name = cbm_arena_sprintf(a, "%s.%s", ctx->module_qn, def_name);
def.label = cbm_arena_strdup(a, "Resource");
def.file_path = ctx->rel_path;
- def.start_line = ts_node_start_point(mapping).row + 1;
- def.end_line = ts_node_end_point(mapping).row + 1;
+ def.start_line = ts_node_start_point(mapping).row + TS_LINE_OFFSET;
+ def.end_line = ts_node_end_point(mapping).row + TS_LINE_OFFSET;
cbm_defs_push(&ctx->result->defs, a, def);
break; // Only the first document per file
diff --git a/internal/cbm/extract_semantic.c b/internal/cbm/extract_semantic.c
index 2dac60610..05f4a0e92 100644
--- a/internal/cbm/extract_semantic.c
+++ b/internal/cbm/extract_semantic.c
@@ -1,9 +1,13 @@
#include "cbm.h"
+#include "arena.h"
#include "helpers.h"
#include "lang_specs.h"
#include "extract_unified.h"
#include "tree_sitter/api.h" // TSNode, ts_node_*
-#include <stdint.h> // uint32_t
+#include "foundation/constants.h"
+
+enum { MAX_EXCEPTION_NAME_LEN = 100, LAST_IDX = 1 };
+#include <stdint.h> // uint32_t
#include <string.h>
#include <ctype.h>
@@ -28,12 +32,12 @@ static char *resolve_exception_name(CBMArena *a, TSNode throw_node, const char *
if (strcmp(ck, "call") == 0 || strcmp(ck, "call_expression") == 0 ||
strcmp(ck, "new_expression") == 0 || strcmp(ck, "object_creation_expression") == 0 ||
strcmp(ck, "instance_expression") == 0) {
- TSNode fn = ts_node_child_by_field_name(child, "function", 8);
+ TSNode fn = ts_node_child_by_field_name(child, TS_FIELD("function"));
if (ts_node_is_null(fn)) {
fn = ts_node_child_by_field_name(child, "constructor", FIELD_LEN_CONSTRUCTOR);
}
if (ts_node_is_null(fn)) {
- fn = ts_node_child_by_field_name(child, "type", 4);
+ fn = ts_node_child_by_field_name(child, TS_FIELD("type"));
}
if (ts_node_is_null(fn) && ts_node_named_child_count(child) > 0) {
fn = ts_node_named_child(child, 0);
@@ -84,8 +88,8 @@ static void process_throw_node(CBMExtractCtx *ctx, TSNode node, const CBMLangSpe
if (cbm_kind_in_set(node, spec->throw_node_types)) {
char *exc_name = resolve_exception_name(ctx->arena, node, ctx->source);
if (exc_name && exc_name[0]) {
- if (strlen(exc_name) > 100) {
- exc_name[100] = '\0';
+ if (strlen(exc_name) > MAX_EXCEPTION_NAME_LEN) {
+ exc_name[MAX_EXCEPTION_NAME_LEN] = '\0';
}
CBMThrow thr;
thr.exception_name = exc_name;
@@ -98,7 +102,7 @@ static void process_throw_node(CBMExtractCtx *ctx, TSNode node, const CBMLangSpe
}
// Iterative throw walker
-#define THROWS_STACK_CAP 512
+#define THROWS_STACK_CAP CBM_SZ_512
static void walk_throws(CBMExtractCtx *ctx, TSNode root, const CBMLangSpec *spec) {
TSNode stack[THROWS_STACK_CAP];
int top = 0;
@@ -107,7 +111,7 @@ static void walk_throws(CBMExtractCtx *ctx, TSNode root, const CBMLangSpec *spec
TSNode node = stack[--top];
process_throw_node(ctx, node, spec);
uint32_t count = ts_node_child_count(node);
- for (int i = (int)count - 1; i >= 0 && top < THROWS_STACK_CAP; i--) {
+ for (int i = (int)count - LAST_IDX; i >= 0 && top < THROWS_STACK_CAP; i--) {
stack[top++] = ts_node_child(node, (uint32_t)i);
}
}
@@ -117,7 +121,7 @@ static void walk_throws(CBMExtractCtx *ctx, TSNode root, const CBMLangSpec *spec
// Try to emit a write for an assignment node.
static void try_emit_assignment_write(CBMExtractCtx *ctx, TSNode node, const char *func_qn) {
- TSNode left = ts_node_child_by_field_name(node, "left", 4);
+ TSNode left = ts_node_child_by_field_name(node, TS_FIELD("left"));
if (ts_node_is_null(left)) {
if (ts_node_child_count(node) > 0) {
left = ts_node_child(node, 0);
@@ -140,7 +144,7 @@ static void try_emit_assignment_write(CBMExtractCtx *ctx, TSNode node, const cha
}
}
-#define READWRITE_STACK_CAP 512
+#define READWRITE_STACK_CAP CBM_SZ_512
static void walk_readwrites(CBMExtractCtx *ctx, TSNode root, const CBMLangSpec *spec) {
TSNode stack[READWRITE_STACK_CAP];
int top = 0;
@@ -151,7 +155,7 @@ static void walk_readwrites(CBMExtractCtx *ctx, TSNode root, const CBMLangSpec *
try_emit_assignment_write(ctx, node, cbm_enclosing_func_qn_cached(ctx, node));
}
uint32_t count = ts_node_child_count(node);
- for (int i = (int)count - 1; i >= 0 && top < READWRITE_STACK_CAP; i--) {
+ for (int i = (int)count - LAST_IDX; i >= 0 && top < READWRITE_STACK_CAP; i--) {
stack[top++] = ts_node_child(node, (uint32_t)i);
}
}
@@ -187,8 +191,8 @@ void handle_throws(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec, Wal
if (has_throws && cbm_kind_in_set(node, spec->throw_node_types)) {
char *exc_name = resolve_exception_name(ctx->arena, node, ctx->source);
if (exc_name && exc_name[0]) {
- if (strlen(exc_name) > 100) {
- exc_name[100] = '\0';
+ if (strlen(exc_name) > MAX_EXCEPTION_NAME_LEN) {
+ exc_name[MAX_EXCEPTION_NAME_LEN] = '\0';
}
CBMThrow thr;
thr.exception_name = exc_name;
@@ -206,7 +210,7 @@ void handle_readwrites(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec,
}
if (cbm_kind_in_set(node, spec->assignment_node_types)) {
- TSNode left = ts_node_child_by_field_name(node, "left", 4);
+ TSNode left = ts_node_child_by_field_name(node, TS_FIELD("left"));
if (ts_node_is_null(left)) {
if (ts_node_child_count(node) > 0) {
left = ts_node_child(node, 0);
diff --git a/internal/cbm/extract_type_assigns.c b/internal/cbm/extract_type_assigns.c
index cc189daae..74ead85f5 100644
--- a/internal/cbm/extract_type_assigns.c
+++ b/internal/cbm/extract_type_assigns.c
@@ -4,13 +4,14 @@
#include "lang_specs.h"
#include "extract_unified.h"
#include "tree_sitter/api.h" // TSNode, ts_node_*
-#include <stdint.h> // uint32_t
+#include "foundation/constants.h"
+#include <stdint.h> // uint32_t
#include <string.h>
#include <ctype.h>
// Extract type from new_expression / object_creation_expression.
static const char *extract_new_expr_type(CBMArena *a, TSNode rhs, const char *source) {
- TSNode type_node = ts_node_child_by_field_name(rhs, "type", 4);
+ TSNode type_node = ts_node_child_by_field_name(rhs, TS_FIELD("type"));
if (!ts_node_is_null(type_node)) {
const char *tk = ts_node_type(type_node);
if (strcmp(tk, "type_identifier") == 0 || strcmp(tk, "identifier") == 0 ||
@@ -45,7 +46,7 @@ static const char *extract_constructor_type(CBMArena *a, TSNode rhs, const char
}
if (strcmp(kind, "call") == 0 || strcmp(kind, "call_expression") == 0) {
- TSNode func = ts_node_child_by_field_name(rhs, "function", 8);
+ TSNode func = ts_node_child_by_field_name(rhs, TS_FIELD("function"));
if (ts_node_is_null(func) && ts_node_child_count(rhs) > 0) {
func = ts_node_child(rhs, 0);
}
@@ -58,14 +59,14 @@ static const char *extract_constructor_type(CBMArena *a, TSNode rhs, const char
}
if (strcmp(kind, "composite_literal") == 0) {
- TSNode type_node = ts_node_child_by_field_name(rhs, "type", 4);
+ TSNode type_node = ts_node_child_by_field_name(rhs, TS_FIELD("type"));
if (!ts_node_is_null(type_node)) {
return cbm_node_text(a, type_node, source);
}
}
if (lang == CBM_LANG_RUST && strcmp(kind, "struct_expression") == 0) {
- TSNode name = ts_node_child_by_field_name(rhs, "name", 4);
+ TSNode name = ts_node_child_by_field_name(rhs, TS_FIELD("name"));
if (!ts_node_is_null(name)) {
return cbm_node_text(a, name, source);
}
@@ -91,10 +92,10 @@ static void try_emit_type_assign(CBMExtractCtx *ctx, TSNode var_node, TSNode rhs
// Process assignment-type nodes (left/right fields with identifier check).
static void process_assignment_type_assign(CBMExtractCtx *ctx, TSNode node, const char *func_qn) {
- TSNode left = ts_node_child_by_field_name(node, "left", 4);
- TSNode right = ts_node_child_by_field_name(node, "right", 5);
+ TSNode left = ts_node_child_by_field_name(node, TS_FIELD("left"));
+ TSNode right = ts_node_child_by_field_name(node, TS_FIELD("right"));
if (ts_node_is_null(right)) {
- right = ts_node_child_by_field_name(node, "value", 5);
+ right = ts_node_child_by_field_name(node, TS_FIELD("value"));
}
if (!ts_node_is_null(left) && !ts_node_is_null(right)) {
const char *lk = ts_node_type(left);
@@ -106,13 +107,13 @@ static void process_assignment_type_assign(CBMExtractCtx *ctx, TSNode node, cons
// Process Go short_var_declaration/var_spec nodes.
static void process_go_var_type_assign(CBMExtractCtx *ctx, TSNode node, const char *func_qn) {
- TSNode left = ts_node_child_by_field_name(node, "name", 4);
+ TSNode left = ts_node_child_by_field_name(node, TS_FIELD("name"));
if (ts_node_is_null(left)) {
- left = ts_node_child_by_field_name(node, "left", 4);
+ left = ts_node_child_by_field_name(node, TS_FIELD("left"));
}
- TSNode right = ts_node_child_by_field_name(node, "value", 5);
+ TSNode right = ts_node_child_by_field_name(node, TS_FIELD("value"));
if (ts_node_is_null(right)) {
- right = ts_node_child_by_field_name(node, "right", 5);
+ right = ts_node_child_by_field_name(node, TS_FIELD("right"));
}
if (!ts_node_is_null(left) && !ts_node_is_null(right)) {
try_emit_type_assign(ctx, left, right, func_qn);
@@ -121,8 +122,8 @@ static void process_go_var_type_assign(CBMExtractCtx *ctx, TSNode node, const ch
// Process JS/TS variable_declarator nodes (name + value with identifier check).
static void process_declarator_type_assign(CBMExtractCtx *ctx, TSNode node, const char *func_qn) {
- TSNode name_node = ts_node_child_by_field_name(node, "name", 4);
- TSNode value_node = ts_node_child_by_field_name(node, "value", 5);
+ TSNode name_node = ts_node_child_by_field_name(node, TS_FIELD("name"));
+ TSNode value_node = ts_node_child_by_field_name(node, TS_FIELD("value"));
if (!ts_node_is_null(name_node) && !ts_node_is_null(value_node)) {
const char *nk = ts_node_type(name_node);
if (strcmp(nk, "identifier") == 0 || strcmp(nk, "simple_identifier") == 0) {
@@ -133,8 +134,8 @@ static void process_declarator_type_assign(CBMExtractCtx *ctx, TSNode node, cons
// Process Rust let_declaration nodes (pattern + value).
static void process_rust_let_type_assign(CBMExtractCtx *ctx, TSNode node, const char *func_qn) {
- TSNode pat = ts_node_child_by_field_name(node, "pattern", 7);
- TSNode val = ts_node_child_by_field_name(node, "value", 5);
+ TSNode pat = ts_node_child_by_field_name(node, TS_FIELD("pattern"));
+ TSNode val = ts_node_child_by_field_name(node, TS_FIELD("value"));
if (!ts_node_is_null(pat) && !ts_node_is_null(val)) {
if (strcmp(ts_node_type(pat), "identifier") == 0) {
try_emit_type_assign(ctx, pat, val, func_qn);
@@ -163,12 +164,19 @@ static void process_type_assign_node(CBMExtractCtx *ctx, TSNode node, const CBML
}
// Walk AST for assignment patterns where RHS is a constructor call.
-static void walk_type_assigns(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec) {
- process_type_assign_node(ctx, node, spec, cbm_enclosing_func_qn_cached(ctx, node));
-
- uint32_t count = ts_node_child_count(node);
- for (uint32_t i = 0; i < count; i++) {
- walk_type_assigns(ctx, ts_node_child(node, i), spec);
+#define TYPE_ASSIGN_STACK_CAP 4096
+static void walk_type_assigns(CBMExtractCtx *ctx, TSNode root, const CBMLangSpec *spec) {
+ TSNode stack[TYPE_ASSIGN_STACK_CAP];
+ int top = 0;
+ stack[top++] = root;
+ while (top > 0) {
+ TSNode node = stack[--top];
+ process_type_assign_node(ctx, node, spec, cbm_enclosing_func_qn_cached(ctx, node));
+ enum { LAST_IDX = 1 };
+ uint32_t count = ts_node_child_count(node);
+ for (int i = (int)count - LAST_IDX; i >= 0 && top < TYPE_ASSIGN_STACK_CAP; i--) {
+ stack[top++] = ts_node_child(node, (uint32_t)i);
+ }
}
}
diff --git a/internal/cbm/extract_type_refs.c b/internal/cbm/extract_type_refs.c
index 36fda1cc1..87b105473 100644
--- a/internal/cbm/extract_type_refs.c
+++ b/internal/cbm/extract_type_refs.c
@@ -4,7 +4,11 @@
#include "lang_specs.h"
#include "extract_unified.h"
#include "tree_sitter/api.h" // TSNode, ts_node_*
-#include <stdint.h> // uint32_t
+#include "foundation/constants.h"
+
+enum { MIN_TYPE_LEN = 1 };
+
+#include <stdint.h> // uint32_t
#include <string.h>
#include <ctype.h>
@@ -13,7 +17,7 @@ static bool is_builtin_type(const char *name) {
if (!name || !name[0]) {
return true;
}
- if (strlen(name) <= 1) {
+ if (strlen(name) <= MIN_TYPE_LEN) {
return true;
}
@@ -59,40 +63,41 @@ static const char *clean_type_name(CBMArena *a, const char *name) {
}
}
// Strip trailing ? (optionals)
- if (len > 0 && name[len - 1] == '?') {
- return cbm_arena_strndup(a, name, len - 1);
+ if (len > 0 && name[len - SKIP_ONE] == '?') {
+ return cbm_arena_strndup(a, name, len - SKIP_ONE);
}
return name;
}
// Extract type name from a type annotation node.
static const char *extract_type_text(CBMArena *a, TSNode node, const char *source) {
- const char *kind = ts_node_type(node);
- // For type_identifier / identifier, just get text
- if (strcmp(kind, "type_identifier") == 0 || strcmp(kind, "identifier") == 0 ||
- strcmp(kind, "simple_identifier") == 0 || strcmp(kind, "name") == 0) {
- return cbm_node_text(a, node, source);
- }
- // For generic types, get the base type
- if (strcmp(kind, "generic_type") == 0 || strcmp(kind, "parameterized_type") == 0) {
- if (ts_node_child_count(node) > 0) {
- return cbm_node_text(a, ts_node_child(node, 0), source);
+ enum { MAX_UNWRAP = 8 };
+ for (int depth = 0; depth < MAX_UNWRAP; depth++) {
+ const char *kind = ts_node_type(node);
+ if (strcmp(kind, "type_identifier") == 0 || strcmp(kind, "identifier") == 0 ||
+ strcmp(kind, "simple_identifier") == 0 || strcmp(kind, "name") == 0) {
+ return cbm_node_text(a, node, source);
}
- }
- // For pointer/reference/slice types
- if (strcmp(kind, "pointer_type") == 0 || strcmp(kind, "reference_type") == 0 ||
- strcmp(kind, "slice_type") == 0 || strcmp(kind, "array_type") == 0) {
- // Get the element type
- TSNode elem = ts_node_child_by_field_name(node, "element", 7);
- if (!ts_node_is_null(elem)) {
- return extract_type_text(a, elem, source);
+ if (strcmp(kind, "generic_type") == 0 || strcmp(kind, "parameterized_type") == 0) {
+ if (ts_node_child_count(node) > 0) {
+ return cbm_node_text(a, ts_node_child(node, 0), source);
+ }
}
- TSNode type_node = ts_node_child_by_field_name(node, "type", 4);
- if (!ts_node_is_null(type_node)) {
- return extract_type_text(a, type_node, source);
+ if (strcmp(kind, "pointer_type") == 0 || strcmp(kind, "reference_type") == 0 ||
+ strcmp(kind, "slice_type") == 0 || strcmp(kind, "array_type") == 0) {
+ TSNode elem = ts_node_child_by_field_name(node, TS_FIELD("element"));
+ if (!ts_node_is_null(elem)) {
+ node = elem;
+ continue;
+ }
+ TSNode type_node = ts_node_child_by_field_name(node, TS_FIELD("type"));
+ if (!ts_node_is_null(type_node)) {
+ node = type_node;
+ continue;
+ }
}
+ break;
}
- // Fallback: full text cleaned
return clean_type_name(a, cbm_node_text(a, node, source));
}
@@ -120,7 +125,7 @@ static void extract_param_type_refs(CBMExtractCtx *ctx, TSNode params, const cha
uint32_t count = ts_node_child_count(params);
for (uint32_t i = 0; i < count; i++) {
TSNode child = ts_node_child(params, i);
- TSNode type_node = ts_node_child_by_field_name(child, "type", 4);
+ TSNode type_node = ts_node_child_by_field_name(child, TS_FIELD("type"));
if (!ts_node_is_null(type_node)) {
const char *tname = extract_type_text(ctx->arena, type_node, ctx->source);
add_type_ref(ctx, tname, func_qn);
@@ -143,7 +148,7 @@ static void extract_return_type_refs(CBMExtractCtx *ctx, TSNode func_node, const
// Extract type ref from a node whose "type" field contains the type.
static void extract_type_field_ref(CBMExtractCtx *ctx, TSNode node, const char *func_qn) {
- TSNode type_node = ts_node_child_by_field_name(node, "type", 4);
+ TSNode type_node = ts_node_child_by_field_name(node, TS_FIELD("type"));
if (!ts_node_is_null(type_node)) {
add_type_ref(ctx, extract_type_text(ctx->arena, type_node, ctx->source), func_qn);
}
@@ -169,7 +174,7 @@ static void extract_ts_body_type_refs(CBMExtractCtx *ctx, TSNode node, const cha
TSNode child = ts_node_child(node, i);
if (strcmp(ts_node_type(child), "type_annotation") == 0) {
if (ts_node_child_count(child) > 0) {
- TSNode inner = ts_node_child(child, ts_node_child_count(child) - 1);
+ TSNode inner = ts_node_child(child, ts_node_child_count(child) - SKIP_ONE);
add_type_ref(ctx, extract_type_text(ctx->arena, inner, ctx->source), func_qn);
}
}
@@ -220,7 +225,7 @@ static void process_body_type_ref(CBMExtractCtx *ctx, TSNode node, const char *f
break;
case CBM_LANG_PYTHON:
if (strcmp(kind, "assignment") == 0) {
- TSNode type_node = ts_node_child_by_field_name(node, "type", 4);
+ TSNode type_node = ts_node_child_by_field_name(node, TS_FIELD("type"));
if (!ts_node_is_null(type_node)) {
add_type_ref(ctx, cbm_node_text(ctx->arena, type_node, ctx->source), func_qn);
}
@@ -237,55 +242,68 @@ static void process_body_type_ref(CBMExtractCtx *ctx, TSNode node, const char *f
}
// Walk function body for type references (casts, type assertions, local var types, generics).
-static void walk_body_type_refs(CBMExtractCtx *ctx, TSNode node, const char *func_qn) {
- process_body_type_ref(ctx, node, func_qn);
-
- uint32_t count = ts_node_child_count(node);
- for (uint32_t i = 0; i < count; i++) {
- walk_body_type_refs(ctx, ts_node_child(node, i), func_qn);
+#define BODY_TYPE_REF_STACK_CAP 4096
+static void walk_body_type_refs(CBMExtractCtx *ctx, TSNode root, const char *func_qn) {
+ TSNode stack[BODY_TYPE_REF_STACK_CAP];
+ int top = 0;
+ stack[top++] = root;
+ while (top > 0) {
+ TSNode node = stack[--top];
+ process_body_type_ref(ctx, node, func_qn);
+ uint32_t count = ts_node_child_count(node);
+ for (int i = (int)count - SKIP_ONE; i >= 0 && top < BODY_TYPE_REF_STACK_CAP; i--) {
+ stack[top++] = ts_node_child(node, (uint32_t)i);
+ }
}
}
// Walk AST for function nodes, extract type references from signatures and bodies.
-static void walk_type_refs(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec) {
- if (!spec->function_node_types || !spec->function_node_types[0]) {
+/* Process a single function node: extract type refs from signature + body. */
+static void process_func_type_refs(CBMExtractCtx *ctx, TSNode node) {
+ TSNode name_node = ts_node_child_by_field_name(node, TS_FIELD("name"));
+ if (ts_node_is_null(name_node)) {
+ return;
+ }
+ char *func_name = cbm_node_text(ctx->arena, name_node, ctx->source);
+ if (!func_name || !func_name[0]) {
return;
}
+ const char *func_qn = cbm_fqn_compute(ctx->arena, ctx->project, ctx->rel_path, func_name);
+ TSNode params = ts_node_child_by_field_name(node, TS_FIELD("parameters"));
+ if (!ts_node_is_null(params)) {
+ extract_param_type_refs(ctx, params, func_qn);
+ }
+ extract_return_type_refs(ctx, node, func_qn);
+ TSNode body = ts_node_child_by_field_name(node, TS_FIELD("body"));
+ if (ts_node_is_null(body)) {
+ body = ts_node_child_by_field_name(node, TS_FIELD("block"));
+ }
+ if (!ts_node_is_null(body)) {
+ walk_body_type_refs(ctx, body, func_qn);
+ }
+}
- if (cbm_kind_in_set(node, spec->function_node_types)) {
- TSNode name_node = ts_node_child_by_field_name(node, "name", 4);
- if (ts_node_is_null(name_node)) {
- goto recurse;
- }
- char *func_name = cbm_node_text(ctx->arena, name_node, ctx->source);
- if (!func_name || !func_name[0]) {
- goto recurse;
- }
+#define TYPE_REF_STACK_CAP 4096
+static void walk_type_refs(CBMExtractCtx *ctx, TSNode root, const CBMLangSpec *spec) {
+ if (!spec->function_node_types || !spec->function_node_types[0]) {
+ return;
+ }
- const char *func_qn = cbm_fqn_compute(ctx->arena, ctx->project, ctx->rel_path, func_name);
+ TSNode stack[TYPE_REF_STACK_CAP];
+ int top = 0;
+ stack[top++] = root;
- // Signature types
- TSNode params = ts_node_child_by_field_name(node, "parameters", 10);
- if (!ts_node_is_null(params)) {
- extract_param_type_refs(ctx, params, func_qn);
- }
- extract_return_type_refs(ctx, node, func_qn);
+ while (top > 0) {
+ TSNode node = stack[--top];
- // Body types
- TSNode body = ts_node_child_by_field_name(node, "body", 4);
- if (ts_node_is_null(body)) {
- body = ts_node_child_by_field_name(node, "block", 5);
+ if (cbm_kind_in_set(node, spec->function_node_types)) {
+ process_func_type_refs(ctx, node);
+ continue;
}
- if (!ts_node_is_null(body)) {
- walk_body_type_refs(ctx, body, func_qn);
+ uint32_t count = ts_node_child_count(node);
+ for (int i = (int)count - SKIP_ONE; i >= 0 && top < TYPE_REF_STACK_CAP; i--) {
+ stack[top++] = ts_node_child(node, (uint32_t)i);
}
- return; // Don't recurse into function internals again
- }
-
-recurse:;
- uint32_t count = ts_node_child_count(node);
- for (uint32_t i = 0; i < count; i++) {
- walk_type_refs(ctx, ts_node_child(node, i), spec);
}
}
@@ -306,7 +324,7 @@ void cbm_extract_type_refs(CBMExtractCtx *ctx) {
// Extract signature type refs from a function node.
static void extract_signature_type_refs(CBMExtractCtx *ctx, TSNode node, WalkState *state) {
- TSNode name_node = ts_node_child_by_field_name(node, "name", 4);
+ TSNode name_node = ts_node_child_by_field_name(node, TS_FIELD("name"));
if (ts_node_is_null(name_node)) {
return;
}
@@ -322,7 +340,7 @@ static void extract_signature_type_refs(CBMExtractCtx *ctx, TSNode node, WalkSta
func_qn = cbm_fqn_compute(ctx->arena, ctx->project, ctx->rel_path, func_name);
}
- TSNode params = ts_node_child_by_field_name(node, "parameters", 10);
+ TSNode params = ts_node_child_by_field_name(node, TS_FIELD("parameters"));
if (!ts_node_is_null(params)) {
extract_param_type_refs(ctx, params, func_qn);
}
diff --git a/internal/cbm/extract_unified.c b/internal/cbm/extract_unified.c
index c46de5c49..9100a08bb 100644
--- a/internal/cbm/extract_unified.c
+++ b/internal/cbm/extract_unified.c
@@ -4,7 +4,11 @@
#include "helpers.h"
#include "lang_specs.h" // CBMLangSpec, cbm_lang_spec, CBM_LANG_*
#include "tree_sitter/api.h" // TSNode, TSTreeCursor, ts_tree_cursor_*, ts_node_*
-#include <stdint.h> // uint32_t, uint8_t
+#include "foundation/constants.h"
+
+enum { MAX_INFRA_BINDINGS = 8 };
+
+#include <stdint.h> // uint32_t, uint8_t
#include <string.h>
// --- Scope stack management ---
@@ -21,7 +25,7 @@ static void push_scope(WalkState *state, uint8_t kind, uint32_t depth, const cha
// Pop scopes that we've ascended out of (depth >= current cursor depth).
static void pop_expired_scopes(WalkState *state, uint32_t cur_depth) {
- while (state->scope_top > 0 && state->scopes[state->scope_top - 1].depth >= cur_depth) {
+ while (state->scope_top > 0 && state->scopes[state->scope_top - SKIP_ONE].depth >= cur_depth) {
state->scope_top--;
}
}
@@ -77,11 +81,11 @@ static const char *compute_wolfram_func_qn(CBMExtractCtx *ctx, TSNode node) {
// Resolve the name node for a function, handling arrow functions.
static TSNode resolve_func_name_node(TSNode node) {
- TSNode name_node = ts_node_child_by_field_name(node, "name", 4);
+ TSNode name_node = ts_node_child_by_field_name(node, TS_FIELD("name"));
if (ts_node_is_null(name_node) && strcmp(ts_node_type(node), "arrow_function") == 0) {
TSNode parent = ts_node_parent(node);
if (!ts_node_is_null(parent) && strcmp(ts_node_type(parent), "variable_declarator") == 0) {
- name_node = ts_node_child_by_field_name(parent, "name", 4);
+ name_node = ts_node_child_by_field_name(parent, TS_FIELD("name"));
}
}
return name_node;
@@ -113,7 +117,7 @@ static const char *compute_func_qn(CBMExtractCtx *ctx, TSNode node, const CBMLan
// Compute class QN for scope tracking.
static const char *compute_class_qn(CBMExtractCtx *ctx, TSNode node) {
- TSNode name_node = ts_node_child_by_field_name(node, "name", 4);
+ TSNode name_node = ts_node_child_by_field_name(node, TS_FIELD("name"));
if (ts_node_is_null(name_node)) {
return NULL;
}
@@ -149,15 +153,15 @@ static void handle_string_constants(CBMExtractCtx *ctx, TSNode node, const WalkS
}
/* Find name (left side) and value (right side) */
- TSNode name_node = ts_node_child_by_field_name(node, "left", 4);
- TSNode value_node = ts_node_child_by_field_name(node, "right", 5);
+ TSNode name_node = ts_node_child_by_field_name(node, TS_FIELD("left"));
+ TSNode value_node = ts_node_child_by_field_name(node, TS_FIELD("right"));
/* Some grammars use "name" + "value" fields */
if (ts_node_is_null(name_node)) {
- name_node = ts_node_child_by_field_name(node, "name", 4);
+ name_node = ts_node_child_by_field_name(node, TS_FIELD("name"));
}
if (ts_node_is_null(value_node)) {
- value_node = ts_node_child_by_field_name(node, "value", 5);
+ value_node = ts_node_child_by_field_name(node, TS_FIELD("value"));
}
if (ts_node_is_null(name_node) || ts_node_is_null(value_node)) {
@@ -183,8 +187,8 @@ static void handle_string_constants(CBMExtractCtx *ctx, TSNode node, const WalkS
/* Strip quotes from value */
int vlen = (int)strlen(value);
- if (vlen >= 2 && (value[0] == '"' || value[0] == '\'')) {
- value = cbm_arena_strndup(ctx->arena, value + 1, (size_t)(vlen - 2));
+ if (vlen >= CBM_QUOTE_PAIR && (value[0] == '"' || value[0] == '\'')) {
+ value = cbm_arena_strndup(ctx->arena, value + SKIP_ONE, (size_t)(vlen - PAIR_LEN));
if (!value) {
return;
}
@@ -226,9 +230,9 @@ static void handle_string_refs(CBMExtractCtx *ctx, TSNode node, const WalkState
/* Strip quotes if present */
int len = (int)strlen(text);
const char *content = text;
- if (len >= 2 && (text[0] == '"' || text[0] == '\'')) {
- content = text + 1;
- len -= 2;
+ if (len >= CBM_QUOTE_PAIR && (text[0] == '"' || text[0] == '\'')) {
+ content = text + SKIP_ONE;
+ len -= PAIR_LEN;
if (len <= 0) {
return;
}
@@ -268,9 +272,9 @@ static void emit_yaml_leaf_value(CBMExtractCtx *ctx, TSNode val, const char *pat
int vlen = (int)strlen(val_text);
const char *content = val_text;
- if (vlen >= 2 && (val_text[0] == '"' || val_text[0] == '\'')) {
- content = val_text + 1;
- vlen -= 2;
+ if (vlen >= CBM_QUOTE_PAIR && (val_text[0] == '"' || val_text[0] == '\'')) {
+ content = val_text + SKIP_ONE;
+ vlen -= PAIR_LEN;
if (vlen <= 0) {
return;
}
@@ -295,46 +299,61 @@ static void emit_yaml_leaf_value(CBMExtractCtx *ctx, TSNode val, const char *pat
cbm_stringref_push(&ctx->result->string_refs, ctx->arena, ref);
}
-static void walk_yaml_mapping(CBMExtractCtx *ctx, TSNode node, const char *prefix) {
- uint32_t nc = ts_node_named_child_count(node);
- for (uint32_t i = 0; i < nc; i++) {
- TSNode child = ts_node_named_child(node, i);
- if (strcmp(ts_node_type(child), "block_mapping_pair") != 0) {
- continue;
- }
+typedef struct {
+ TSNode node;
+ const char *prefix;
+} yaml_walk_frame_t;
+#define YAML_WALK_STACK_CAP CBM_SZ_256
- TSNode key = ts_node_child_by_field_name(child, "key", 3);
- if (ts_node_is_null(key)) {
- continue;
- }
- char *key_text = cbm_node_text(ctx->arena, key, ctx->source);
- if (!key_text || !key_text[0]) {
- continue;
- }
-
- const char *path =
- prefix ? cbm_arena_sprintf(ctx->arena, "%s.%s", prefix, key_text) : key_text;
-
- TSNode val = ts_node_child_by_field_name(child, "value", 5);
- if (ts_node_is_null(val)) {
- continue;
+/* Push block_mapping children of a block_node/block_mapping value onto the walk stack. */
+static void push_yaml_block_children(TSNode val, const char *path, yaml_walk_frame_t *stack,
+ int *top) {
+ uint32_t vnc = ts_node_named_child_count(val);
+ for (int vi = (int)vnc - SKIP_ONE; vi >= 0 && *top < YAML_WALK_STACK_CAP; vi--) {
+ TSNode vc = ts_node_named_child(val, (uint32_t)vi);
+ const char *vctype = ts_node_type(vc);
+ if (strcmp(vctype, "block_mapping") == 0 || strcmp(vctype, "block_mapping_pair") == 0) {
+ stack[(*top)++] = (yaml_walk_frame_t){vc, path};
}
- const char *vk = ts_node_type(val);
+ }
+}
- if (strcmp(vk, "block_node") == 0 || strcmp(vk, "block_mapping") == 0) {
- uint32_t vnc = ts_node_named_child_count(val);
- for (uint32_t vi = 0; vi < vnc; vi++) {
- TSNode vc = ts_node_named_child(val, vi);
- const char *vctype = ts_node_type(vc);
- if (strcmp(vctype, "block_mapping") == 0 ||
- strcmp(vctype, "block_mapping_pair") == 0) {
- walk_yaml_mapping(ctx, vc, path);
- }
+static void walk_yaml_mapping(CBMExtractCtx *ctx, TSNode root, const char *root_prefix) {
+ yaml_walk_frame_t stack[YAML_WALK_STACK_CAP];
+ int top = 0;
+ stack[top++] = (yaml_walk_frame_t){root, root_prefix};
+
+ while (top > 0) {
+ yaml_walk_frame_t frame = stack[--top];
+ TSNode node = frame.node;
+ const char *prefix = frame.prefix;
+ uint32_t nc = ts_node_named_child_count(node);
+ for (uint32_t i = 0; i < nc; i++) {
+ TSNode child = ts_node_named_child(node, i);
+ if (strcmp(ts_node_type(child), "block_mapping_pair") != 0) {
+ continue;
}
- continue;
+ TSNode key = ts_node_child_by_field_name(child, TS_FIELD("key"));
+ if (ts_node_is_null(key)) {
+ continue;
+ }
+ char *key_text = cbm_node_text(ctx->arena, key, ctx->source);
+ if (!key_text || !key_text[0]) {
+ continue;
+ }
+ const char *path =
+ prefix ? cbm_arena_sprintf(ctx->arena, "%s.%s", prefix, key_text) : key_text;
+ TSNode val = ts_node_child_by_field_name(child, TS_FIELD("value"));
+ if (ts_node_is_null(val)) {
+ continue;
+ }
+ const char *vk = ts_node_type(val);
+ if (strcmp(vk, "block_node") == 0 || strcmp(vk, "block_mapping") == 0) {
+ push_yaml_block_children(val, path, stack, &top);
+ continue;
+ }
+ emit_yaml_leaf_value(ctx, val, path);
}
-
- emit_yaml_leaf_value(ctx, val, path);
}
}
@@ -396,8 +415,8 @@ static char *strip_yaml_quotes(CBMArena *a, char *v) {
return v;
}
int vlen = (int)strlen(v);
- if (vlen >= 2 && (v[0] == '"' || v[0] == '\'')) {
- return cbm_arena_strndup(a, v + 1, (size_t)(vlen - 2));
+ if (vlen >= CBM_QUOTE_PAIR && (v[0] == '"' || v[0] == '\'')) {
+ return cbm_arena_strndup(a, v + SKIP_ONE, (size_t)(vlen - PAIR_LEN));
}
return v;
}
@@ -417,13 +436,13 @@ static void scan_nested_mapping_targets(CBMExtractCtx *ctx, TSNode val, const ch
if (strcmp(ts_node_type(mp), "block_mapping_pair") != 0) {
continue;
}
- TSNode mk = ts_node_child_by_field_name(mp, "key", 3);
- TSNode mv = ts_node_child_by_field_name(mp, "value", 5);
+ TSNode mk = ts_node_child_by_field_name(mp, TS_FIELD("key"));
+ TSNode mv = ts_node_child_by_field_name(mp, TS_FIELD("value"));
if (ts_node_is_null(mk) || ts_node_is_null(mv)) {
continue;
}
char *mktext = cbm_node_text(ctx->arena, mk, ctx->source);
- if (mktext && is_target_key(mktext) && *n_targets < 8) {
+ if (mktext && is_target_key(mktext) && *n_targets < MAX_INFRA_BINDINGS) {
char *mvtext =
strip_yaml_quotes(ctx->arena, cbm_node_text(ctx->arena, mv, ctx->source));
if (mvtext && strstr(mvtext, "://")) {
@@ -453,10 +472,10 @@ static void emit_infra_bindings(CBMExtractCtx *ctx, const char **sources, const
}
static void scan_mapping_for_bindings(CBMExtractCtx *ctx, TSNode mapping) {
- const char *sources[8] = {NULL};
- const char *source_keys[8] = {NULL};
+ const char *sources[MAX_INFRA_BINDINGS] = {NULL};
+ const char *source_keys[MAX_INFRA_BINDINGS] = {NULL};
int n_sources = 0;
- const char *targets[8] = {NULL};
+ const char *targets[MAX_INFRA_BINDINGS] = {NULL};
int n_targets = 0;
uint32_t nc = ts_node_named_child_count(mapping);
@@ -465,8 +484,8 @@ static void scan_mapping_for_bindings(CBMExtractCtx *ctx, TSNode mapping) {
if (strcmp(ts_node_type(pair), "block_mapping_pair") != 0) {
continue;
}
- TSNode key = ts_node_child_by_field_name(pair, "key", 3);
- TSNode val = ts_node_child_by_field_name(pair, "value", 5);
+ TSNode key = ts_node_child_by_field_name(pair, TS_FIELD("key"));
+ TSNode val = ts_node_child_by_field_name(pair, TS_FIELD("value"));
if (ts_node_is_null(key) || ts_node_is_null(val)) {
continue;
}
@@ -478,12 +497,12 @@ static void scan_mapping_for_bindings(CBMExtractCtx *ctx, TSNode mapping) {
const char *vtype = ts_node_type(val);
if (strcmp(vtype, "block_node") != 0 && strcmp(vtype, "block_mapping") != 0) {
char *v = strip_yaml_quotes(ctx->arena, cbm_node_text(ctx->arena, val, ctx->source));
- if (is_source_key(k) && n_sources < 8) {
+ if (is_source_key(k) && n_sources < MAX_INFRA_BINDINGS) {
sources[n_sources] = v;
source_keys[n_sources] = k;
n_sources++;
}
- if (is_target_key(k) && n_targets < 8 && v && strstr(v, "://")) {
+ if (is_target_key(k) && n_targets < MAX_INFRA_BINDINGS && v && strstr(v, "://")) {
targets[n_targets++] = v;
}
} else {
@@ -494,19 +513,20 @@ static void scan_mapping_for_bindings(CBMExtractCtx *ctx, TSNode mapping) {
emit_infra_bindings(ctx, sources, source_keys, n_sources, targets, n_targets);
}
-/* Walk a YAML block_sequence looking for list items with infra bindings */
-static void scan_yaml_for_infra_bindings(CBMExtractCtx *ctx, TSNode node) {
- const char *kind = ts_node_type(node);
-
- /* List items are block_sequence → block_sequence_item → block_mapping */
- if (strcmp(kind, "block_mapping") == 0) {
- scan_mapping_for_bindings(ctx, node);
- }
-
- /* Recurse into children */
- uint32_t nc = ts_node_named_child_count(node);
- for (uint32_t i = 0; i < nc; i++) {
- scan_yaml_for_infra_bindings(ctx, ts_node_named_child(node, i));
+#define INFRA_SCAN_STACK_CAP CBM_SZ_512
+static void scan_yaml_for_infra_bindings(CBMExtractCtx *ctx, TSNode root) {
+ TSNode stack[INFRA_SCAN_STACK_CAP];
+ int top = 0;
+ stack[top++] = root;
+ while (top > 0) {
+ TSNode node = stack[--top];
+ if (strcmp(ts_node_type(node), "block_mapping") == 0) {
+ scan_mapping_for_bindings(ctx, node);
+ }
+ uint32_t nc = ts_node_named_child_count(node);
+ for (int i = (int)nc - SKIP_ONE; i >= 0 && top < INFRA_SCAN_STACK_CAP; i--) {
+ stack[top++] = ts_node_named_child(node, (uint32_t)i);
+ }
}
}
@@ -537,7 +557,7 @@ static void scan_hcl_nested_block_targets(CBMExtractCtx *ctx, TSNode block, cons
continue;
}
TSNode bkey = ts_node_named_child(bchild, 0);
- TSNode bval = ts_node_named_child(bchild, 1);
+ TSNode bval = ts_node_named_child(bchild, SKIP_ONE);
if (ts_node_is_null(bkey) || ts_node_is_null(bval)) {
continue;
}
@@ -546,17 +566,17 @@ static void scan_hcl_nested_block_targets(CBMExtractCtx *ctx, TSNode block, cons
continue;
}
char *bv = extract_hcl_string_val(ctx->arena, bval, ctx->source);
- if (bv && strstr(bv, "://") && *n_targets < 8) {
+ if (bv && strstr(bv, "://") && *n_targets < MAX_INFRA_BINDINGS) {
targets[(*n_targets)++] = bv;
}
}
}
static void scan_hcl_block_for_bindings(CBMExtractCtx *ctx, TSNode block) {
- const char *sources[8] = {NULL};
- const char *source_keys[8] = {NULL};
+ const char *sources[MAX_INFRA_BINDINGS] = {NULL};
+ const char *source_keys[MAX_INFRA_BINDINGS] = {NULL};
int n_sources = 0;
- const char *targets[8] = {NULL};
+ const char *targets[MAX_INFRA_BINDINGS] = {NULL};
int n_targets = 0;
uint32_t nc = ts_node_named_child_count(block);
@@ -566,7 +586,7 @@ static void scan_hcl_block_for_bindings(CBMExtractCtx *ctx, TSNode block) {
if (strcmp(ck, "attribute") == 0) {
TSNode key_node = ts_node_named_child(child, 0);
- TSNode val_node = ts_node_named_child(child, 1);
+ TSNode val_node = ts_node_named_child(child, SKIP_ONE);
if (ts_node_is_null(key_node) || ts_node_is_null(val_node)) {
continue;
}
@@ -580,12 +600,12 @@ static void scan_hcl_block_for_bindings(CBMExtractCtx *ctx, TSNode block) {
continue;
}
- if (is_source_key(key) && n_sources < 8) {
+ if (is_source_key(key) && n_sources < MAX_INFRA_BINDINGS) {
sources[n_sources] = val;
source_keys[n_sources] = key;
n_sources++;
}
- if (is_target_key(key) && n_targets < 8 && strstr(val, "://")) {
+ if (is_target_key(key) && n_targets < MAX_INFRA_BINDINGS && strstr(val, "://")) {
targets[n_targets++] = val;
}
} else if (strcmp(ck, "block") == 0) {
@@ -649,7 +669,7 @@ static void push_boundary_scopes(CBMExtractCtx *ctx, TSNode node, const CBMLangS
push_scope(state, SCOPE_CLASS, depth, cqn);
}
} else if (ctx->language == CBM_LANG_RUST && strcmp(ts_node_type(node), "impl_item") == 0) {
- TSNode type_node = ts_node_child_by_field_name(node, "type", 4);
+ TSNode type_node = ts_node_child_by_field_name(node, TS_FIELD("type"));
if (!ts_node_is_null(type_node)) {
char *type_name = cbm_node_text(ctx->arena, type_node, ctx->source);
if (type_name && type_name[0]) {
diff --git a/internal/cbm/extract_usages.c b/internal/cbm/extract_usages.c
index 047a0aee1..329f32b56 100644
--- a/internal/cbm/extract_usages.c
+++ b/internal/cbm/extract_usages.c
@@ -3,7 +3,10 @@
#include "lang_specs.h"
#include "extract_unified.h"
#include "tree_sitter/api.h" // TSNode, ts_node_*
-#include <stdint.h> // uint32_t
+#include "foundation/constants.h"
+
+enum { MAX_PARENT_DEPTH = 10, LAST_IDX = 1 };
+#include <stdint.h> // uint32_t
#include <string.h>
#include <ctype.h>
@@ -14,7 +17,7 @@ static void walk_usages(CBMExtractCtx *ctx, TSNode root, const CBMLangSpec *spec
static bool is_inside_call(TSNode node, const CBMLangSpec *spec) {
TSNode cur = ts_node_parent(node);
int depth = 0;
- while (!ts_node_is_null(cur) && depth < 10) {
+ while (!ts_node_is_null(cur) && depth < MAX_PARENT_DEPTH) {
if (cbm_kind_in_set(cur, spec->call_node_types)) {
return true;
}
@@ -31,7 +34,7 @@ static bool is_inside_import(TSNode node, const CBMLangSpec *spec) {
}
TSNode cur = ts_node_parent(node);
int depth = 0;
- while (!ts_node_is_null(cur) && depth < 10) {
+ while (!ts_node_is_null(cur) && depth < MAX_PARENT_DEPTH) {
if (cbm_kind_in_set(cur, spec->import_node_types)) {
return true;
}
@@ -76,7 +79,7 @@ static bool is_definition_name(TSNode node) {
if (ts_node_is_null(parent)) {
return false;
}
- TSNode name_field = ts_node_child_by_field_name(parent, "name", 4);
+ TSNode name_field = ts_node_child_by_field_name(parent, TS_FIELD("name"));
return !ts_node_is_null(name_field) &&
ts_node_start_byte(name_field) == ts_node_start_byte(node) &&
ts_node_end_byte(name_field) == ts_node_end_byte(node);
@@ -113,7 +116,7 @@ static void walk_usages(CBMExtractCtx *ctx, TSNode root, const CBMLangSpec *spec
TSNode node = stack[--top];
try_emit_usage(ctx, node, spec);
uint32_t count = ts_node_child_count(node);
- for (int i = (int)count - 1; i >= 0 && top < USAGES_STACK_CAP; i--) {
+ for (int i = (int)count - LAST_IDX; i >= 0 && top < USAGES_STACK_CAP; i--) {
stack[top++] = ts_node_child(node, (uint32_t)i);
}
}
@@ -149,7 +152,7 @@ void handle_usages(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec, Wal
// Skip if it's a definition name (left side of assignment, function name)
TSNode parent = ts_node_parent(node);
if (!ts_node_is_null(parent)) {
- TSNode name_field = ts_node_child_by_field_name(parent, "name", 4);
+ TSNode name_field = ts_node_child_by_field_name(parent, TS_FIELD("name"));
if (!ts_node_is_null(name_field) &&
ts_node_start_byte(name_field) == ts_node_start_byte(node) &&
ts_node_end_byte(name_field) == ts_node_end_byte(node)) {
diff --git a/internal/cbm/helpers.c b/internal/cbm/helpers.c
index 6598efba3..0a7e0ebc4 100644
--- a/internal/cbm/helpers.c
+++ b/internal/cbm/helpers.c
@@ -3,7 +3,23 @@
#include "cbm.h" // CBMExtractCtx, CBMLanguage, CBM_LANG_*, EFCEntry, EFC_SIZE
#include "lang_specs.h"
#include "tree_sitter/api.h" // TSNode, ts_node_*
-#include <stdint.h> // uint32_t
+#include "foundation/constants.h"
+
+enum {
+ MIN_ROUTE_LEN = 3,
+ MIN_SYS_PATH_LEN = 4,
+ MAX_ROUTE_SCAN = 20,
+ NOEXT_BUF = 256,
+ MIN_HEX_LEN = 3,
+ MAX_HEX_NAME_LEN = 64,
+ INIT_FILE_LEN = 8, /* strlen("__init__") */
+ INDEX_FILE_LEN = 5, /* strlen("index") */
+ NOT_FOUND = -1,
+};
+
+/* Prefix length helper for strncmp with string literals. */
+#define SLEN(s) (sizeof(s) - SKIP_ONE)
+#include <stdint.h> // uint32_t
#include <string.h>
#include <ctype.h>
#include <stdio.h>
@@ -171,7 +187,7 @@ static bool has_prefix(const char *str, const char *prefix) {
// Extract basename from path
static const char *path_basename(const char *path) {
const char *last = strrchr(path, '/');
- return last ? last + 1 : path;
+ return last ? last + SKIP_ONE : path;
}
// Strip extension from basename
@@ -180,7 +196,7 @@ static void strip_ext(const char *base, char *buf, size_t buflen) {
if (dot && dot != base) {
size_t len = (size_t)(dot - base);
if (len >= buflen) {
- len = buflen - 1;
+ len = buflen - SKIP_ONE;
}
memcpy(buf, base, len);
buf[len] = '\0';
@@ -203,7 +219,7 @@ bool cbm_is_test_file(const char *rel_path, CBMLanguage lang) {
case CBM_LANG_JAVASCRIPT:
case CBM_LANG_TYPESCRIPT:
case CBM_LANG_TSX: {
- char noext[256];
+ char noext[NOEXT_BUF];
strip_ext(base, noext, sizeof(noext));
return has_suffix(noext, ".test") || has_suffix(noext, ".spec") ||
has_suffix(noext, "_test") || has_suffix(noext, "_spec") ||
@@ -280,18 +296,25 @@ bool cbm_has_ancestor_kind(TSNode node, const char *kind, int max_depth) {
}
// Recursive branching count
-static int count_branching_rec(TSNode node, const char **types) {
+#define BRANCHING_STACK_CAP 4096
+static int count_branching_iter(TSNode root, const char **types) {
+ TSNode stack[BRANCHING_STACK_CAP];
+ int top = 0;
int count = 0;
- const char *kind = ts_node_type(node);
- for (const char **t = types; *t; t++) {
- if (strcmp(kind, *t) == 0) {
- count++;
- break;
+ stack[top++] = root;
+ while (top > 0) {
+ TSNode node = stack[--top];
+ const char *kind = ts_node_type(node);
+ for (const char **t = types; *t; t++) {
+ if (strcmp(kind, *t) == 0) {
+ count++;
+ break;
+ }
+ }
+ uint32_t n = ts_node_child_count(node);
+ for (int i = (int)n - SKIP_ONE; i >= 0 && top < BRANCHING_STACK_CAP; i--) {
+ stack[top++] = ts_node_child(node, (uint32_t)i);
}
- }
- uint32_t n = ts_node_child_count(node);
- for (uint32_t i = 0; i < n; i++) {
- count += count_branching_rec(ts_node_child(node, i), types);
}
return count;
}
@@ -300,7 +323,7 @@ int cbm_count_branching(TSNode node, const char **branching_types) {
if (!branching_types) {
return 0;
}
- return count_branching_rec(node, branching_types);
+ return count_branching_iter(node, branching_types);
}
// --- Enclosing function detection ---
@@ -432,7 +455,7 @@ static const char *func_node_name(CBMArena *a, TSNode func_node, const char *sou
}
}
- TSNode name_node = ts_node_child_by_field_name(func_node, "name", 4);
+ TSNode name_node = ts_node_child_by_field_name(func_node, TS_FIELD("name"));
if (!ts_node_is_null(name_node)) {
return cbm_node_text(a, name_node, source);
}
@@ -440,7 +463,7 @@ static const char *func_node_name(CBMArena *a, TSNode func_node, const char *sou
if (strcmp(ts_node_type(func_node), "arrow_function") == 0) {
TSNode parent = ts_node_parent(func_node);
if (!ts_node_is_null(parent) && strcmp(ts_node_type(parent), "variable_declarator") == 0) {
- TSNode vname = ts_node_child_by_field_name(parent, "name", 4);
+ TSNode vname = ts_node_child_by_field_name(parent, TS_FIELD("name"));
if (!ts_node_is_null(vname)) {
return cbm_node_text(a, vname, source);
}
@@ -467,7 +490,7 @@ const char *cbm_enclosing_func_qn(CBMArena *a, TSNode node, CBMLanguage lang, co
TSNode cur = ts_node_parent(func_node);
while (!ts_node_is_null(cur)) {
if (cbm_kind_in_set(cur, spec->class_node_types)) {
- TSNode class_name = ts_node_child_by_field_name(cur, "name", 4);
+ TSNode class_name = ts_node_child_by_field_name(cur, TS_FIELD("name"));
if (!ts_node_is_null(class_name)) {
char *cname = cbm_node_text(a, class_name, source);
if (cname && cname[0]) {
@@ -489,7 +512,7 @@ const char *cbm_enclosing_func_qn_cached(CBMExtractCtx *ctx, TSNode node) {
uint32_t pos = ts_node_start_byte(node);
// Check cache: find a function range that contains this position.
- // Linear scan is fine for EFC_SIZE=64 (all entries fit in ~1 cache line).
+ // Linear scan is fine for EFC_SIZE=CBM_SZ_64 (all entries fit in ~1 cache line).
for (int i = 0; i < ctx->ef_cache.count; i++) {
EFCEntry *e = &ctx->ef_cache.entries[i];
if (pos >= e->start_byte && pos < e->end_byte) {
@@ -676,10 +699,10 @@ bool cbm_is_module_level(TSNode node, CBMLanguage lang) {
// Internal helper: find extension start in basename (returns length without ext)
static size_t strip_ext_len(const char *s, size_t len) {
for (size_t i = len; i > 0; i--) {
- if (s[i - 1] == '.') {
- return i - 1;
+ if (s[i - SKIP_ONE] == '.') {
+ return i - SKIP_ONE;
}
- if (s[i - 1] == '/') {
+ if (s[i - SKIP_ONE] == '/') {
break;
}
}
@@ -691,10 +714,10 @@ static bool should_skip_fqn_part(const char *part, size_t part_len, bool is_last
if (!is_last || !has_name) {
return false;
}
- if (part_len == 8 && memcmp(part, "__init__", 8) == 0) {
+ if (part_len == INIT_FILE_LEN && memcmp(part, "__init__", INIT_FILE_LEN) == 0) {
return true;
}
- if (part_len == 5 && memcmp(part, "index", 5) == 0) {
+ if (part_len == INDEX_FILE_LEN && memcmp(part, "index", INDEX_FILE_LEN) == 0) {
return true;
}
return false;
@@ -717,7 +740,7 @@ static char *append_path_segments(char *out, const char *rel_path, size_t plen,
out += part_len;
}
}
- start = part_end + 1;
+ start = part_end + SKIP_ONE;
}
return out;
}
@@ -727,7 +750,7 @@ char *cbm_fqn_compute(CBMArena *a, const char *project, const char *rel_path, co
size_t path_len = strlen(rel_path);
size_t name_len = name ? strlen(name) : 0;
- size_t max_len = proj_len + 1 + path_len + 1 + name_len + 1;
+ size_t max_len = proj_len + SKIP_ONE + path_len + SKIP_ONE + name_len + SKIP_ONE;
char *buf = (char *)cbm_arena_alloc(a, max_len);
if (!buf) {
return NULL;
@@ -757,7 +780,7 @@ char *cbm_fqn_folder(CBMArena *a, const char *project, const char *rel_dir) {
// project.dir1.dir2
size_t proj_len = strlen(project);
size_t dir_len = strlen(rel_dir);
- size_t max_len = proj_len + 1 + dir_len + 1;
+ size_t max_len = proj_len + SKIP_ONE + dir_len + SKIP_ONE;
char *buf = (char *)cbm_arena_alloc(a, max_len);
if (!buf) {
return NULL;
@@ -767,7 +790,7 @@ char *cbm_fqn_folder(CBMArena *a, const char *project, const char *rel_dir) {
memcpy(out, project, proj_len);
out += proj_len;
- if (dir_len > 0 && !(dir_len == 1 && rel_dir[0] == '.')) {
+ if (dir_len > 0 && !(dir_len == SKIP_ONE && rel_dir[0] == '.')) {
const char *start = rel_dir;
const char *end_ptr = rel_dir + dir_len;
while (start < end_ptr) {
@@ -779,7 +802,7 @@ char *cbm_fqn_folder(CBMArena *a, const char *project, const char *rel_dir) {
memcpy(out, start, part_len);
out += part_len;
}
- start = part_end + 1;
+ start = part_end + SKIP_ONE;
}
}
*out = '\0';
@@ -790,14 +813,14 @@ char *cbm_fqn_folder(CBMArena *a, const char *project, const char *rel_dir) {
// Check if a slash-prefixed string looks like a filesystem path.
static bool is_filesystem_path(const char *s, int len) {
- if (len <= 4) {
+ if (len <= MIN_SYS_PATH_LEN) {
return false;
}
- return strncmp(s, "/usr/", 5) == 0 || strncmp(s, "/bin/", 5) == 0 ||
- strncmp(s, "/etc/", 5) == 0 || strncmp(s, "/var/", 5) == 0 ||
- strncmp(s, "/tmp/", 5) == 0 || strncmp(s, "/opt/", 5) == 0 ||
- strncmp(s, "/home/", 6) == 0 || strncmp(s, "/dev/", 5) == 0 ||
- strncmp(s, "/sys/", 5) == 0 || strncmp(s, "/proc/", 6) == 0;
+ return strncmp(s, "/usr/", SLEN("/usr/")) == 0 || strncmp(s, "/bin/", SLEN("/bin/")) == 0 ||
+ strncmp(s, "/etc/", SLEN("/etc/")) == 0 || strncmp(s, "/var/", SLEN("/var/")) == 0 ||
+ strncmp(s, "/tmp/", SLEN("/tmp/")) == 0 || strncmp(s, "/opt/", SLEN("/opt/")) == 0 ||
+ strncmp(s, "/home/", SLEN("/home/")) == 0 || strncmp(s, "/dev/", SLEN("/dev/")) == 0 ||
+ strncmp(s, "/sys/", SLEN("/sys/")) == 0 || strncmp(s, "/proc/", SLEN("/proc/")) == 0;
}
// Check if a slash-prefixed string looks like a REST API path.
@@ -805,19 +828,19 @@ static bool is_rest_path(const char *s, int len) {
if (is_filesystem_path(s, len)) {
return false;
}
- if (len > 1 && s[len - 1] == '/') {
+ if (len > SKIP_ONE && s[len - SKIP_ONE] == '/') {
return false; /* regex pattern */
}
- if (s[1] == '^') {
+ if (s[SKIP_ONE] == '^') {
return false; /* regex */
}
- if (len == 1 || (len == 2 && s[1] == '/')) {
+ if (len == SKIP_ONE || (len == PAIR_LEN && s[SKIP_ONE] == '/')) {
return false; /* bare / or // */
}
- if (s[1] == '.') {
+ if (s[SKIP_ONE] == '.') {
return false; /* relative path */
}
- for (int i = 1; i < len && i < 20; i++) {
+ for (int i = SKIP_ONE; i < len && i < MAX_ROUTE_SCAN; i++) {
char c = s[i];
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) {
return true;
@@ -827,7 +850,7 @@ static bool is_rest_path(const char *s, int len) {
}
static bool is_url_like(const char *s, int len) {
- if (len < 3) {
+ if (len < MIN_ROUTE_LEN) {
return false;
}
if (strstr(s, "://")) {
@@ -852,7 +875,7 @@ static bool has_config_extension(const char *s, int len) {
}
static bool is_env_var_pattern(const char *s, int len) {
- if (len < 3 || len > 64) {
+ if (len < MIN_ROUTE_LEN || len > MAX_HEX_NAME_LEN) {
return false;
}
bool has_upper = false;
@@ -873,8 +896,8 @@ static bool is_env_var_pattern(const char *s, int len) {
}
int cbm_classify_string(const char *str, int len) {
- if (!str || len < 2) {
- return -1;
+ if (!str || len < PAIR_LEN) {
+ return NOT_FOUND;
}
if (is_url_like(str, len)) {
@@ -887,5 +910,5 @@ int cbm_classify_string(const char *str, int len) {
return CBM_STRREF_CONFIG;
}
- return -1;
+ return NOT_FOUND;
}
diff --git a/internal/cbm/lz4_store.c b/internal/cbm/lz4_store.c
index 787472533..cb819db7c 100644
--- a/internal/cbm/lz4_store.c
+++ b/internal/cbm/lz4_store.c
@@ -1,13 +1,14 @@
// lz4_store.c — Thin C wrappers around LZ4 HC.
// Include vendored LZ4 source directly — compiled as a single translation unit.
-#include "vendored/lz4/lz4.c" // unity build: vendored source
-#include "vendored/lz4/lz4hc.c" // unity build: vendored source
+#include "vendored/lz4/lz4.h"
+#include "vendored/lz4/lz4hc.h"
#include "lz4_store.h"
int cbm_lz4_compress_hc(const char *src, int srcLen, char *dst, int dstCap) {
- return LZ4_compress_HC(src, dst, srcLen, dstCap, 9);
+ enum { LZ4_HC_LEVEL = 9 };
+ return LZ4_compress_HC(src, dst, srcLen, dstCap, LZ4_HC_LEVEL);
}
int cbm_lz4_decompress(const char *src, int srcLen, char *dst, int originalLen) {
diff --git a/internal/cbm/sqlite_writer.c b/internal/cbm/sqlite_writer.c
index 07fb5110a..51bc01f16 100644
--- a/internal/cbm/sqlite_writer.c
+++ b/internal/cbm/sqlite_writer.c
@@ -15,6 +15,7 @@
// - Varints: 1-9 bytes, big-endian, MSB continuation
#include "sqlite_writer.h"
+#include "foundation/constants.h"
#include "foundation/compat_thread.h"
#include <stddef.h> // NULL
@@ -34,6 +35,75 @@
#define VARINT_CONTINUE 0x80
#define BYTE_MASK 0xff
+enum {
+ VARINT_SHIFT = 7,
+ VARINT_BUF_SIZE = 10,
+ VARINT_MIN_LEN = 1,
+ SERIAL_INT8 = 1,
+ SERIAL_INT16 = 2,
+ SERIAL_INT24 = 3,
+ SERIAL_INT32 = 4,
+ SERIAL_INT48 = 5,
+ SERIAL_INT64 = 6,
+ SERIAL_FLOAT64 = 7,
+ SERIAL_CONST_ZERO = 8,
+ SERIAL_CONST_ONE = 9,
+ SERIAL_SIZE_INT8 = 1,
+ SERIAL_SIZE_INT16 = 2,
+ SERIAL_SIZE_INT24 = 3,
+ SERIAL_SIZE_INT32 = 4,
+ SERIAL_SIZE_INT48 = 6,
+ SERIAL_SIZE_INT64 = 8,
+ BTREE_HEADER_SIZE = 8,
+ BTREE_INTERIOR_HDR = 12,
+ BTREE_PTR_SIZE = 4,
+ CELL_PTR_SIZE = 2,
+ INITIAL_PAGE_CAP = 4096,
+ INITIAL_LEAF_CAP = 256,
+ INITIAL_PARENT_CAP = 64,
+ GROWTH_FACTOR = 2,
+ VARINT_MAX_BYTES = 9,
+ INT64_BYTES = 8,
+ SORT_THRESHOLD = 20,
+ MAX_NAME_LEN = 64,
+ HASH_INIT = 5381,
+ HASH_MULT = 33,
+ HDR_FREEBLOCK_OFF = 1,
+ HDR_CELLCOUNT_OFF = 3,
+ HDR_CONTENT_OFF = 5,
+ HDR_FRAGBYTES_OFF = 7,
+ HDR_RIGHTCHILD_OFF = 8,
+ INTERIOR_TABLE_FLAG = 0x05,
+ INTERIOR_INDEX_FLAG = 0x02,
+ NEWLINE_BYTE = 0x0A,
+ NODE_SORT_THREADS = 4,
+ EDGE_SORT_THREADS = 7,
+ TOTAL_SORT_THREADS = 11,
+ ERR_SORT_FAILED = -4,
+ ERR_WRITE_FAILED = -3,
+ ERR_MASTER_OVERFLOW = -2,
+ MAX_EMBED_FRACTION = 64,
+ MIN_EMBED_FRACTION = 32,
+ LEAF_PAYLOAD_FRACTION = 32,
+ INTERIOR_CELL_BUF = 20,
+ FIRST_ROWID = 1,
+ FIRST_DATA_PAGE = 2,
+ NSORT_NAME = 1,
+ NSORT_FILE = 2,
+ NSORT_QN = 3,
+ ESORT_TARGET = 1,
+ ESORT_TYPE = 2,
+ ESORT_PROJ_TGT_TYPE = 3,
+ ESORT_PROJ_SRC_TYPE = 4,
+ ESORT_URL_PATH = 5,
+ ESORT_SRC_TGT_TYPE = 6,
+ SQLITE_HEADER_SIZE = 100,
+ SHIFT_8 = 8,
+ SHIFT_16 = 16,
+ SHIFT_24 = 24,
+};
+#define TEXT_SERIAL_BASE 13
+
// SQLite text serial type offset: serial_type = len*2 + TEXT_SERIAL_BASE.
#define TEXT_SERIAL_BASE 13
@@ -82,10 +152,10 @@ static int put_varint(uint8_t *buf, int64_t value) {
uint64_t v = (uint64_t)value;
if (v <= VARINT_MASK) {
buf[0] = (uint8_t)v;
- return 1;
+ return SERIAL_SIZE_INT8;
}
// Encode in big-endian with MSB continuation bits
- uint8_t tmp[10];
+ uint8_t tmp[VARINT_BUF_SIZE];
int n = 0;
while (v > VARINT_MASK) {
tmp[n++] = (uint8_t)(v & VARINT_MASK);
@@ -104,7 +174,7 @@ static int put_varint(uint8_t *buf, int64_t value) {
static int varint_len(int64_t value) {
uint64_t v = (uint64_t)value;
- int n = 1;
+ int n = VARINT_MIN_LEN;
while (v > VARINT_MASK) {
v >>= 7;
n++;
@@ -114,33 +184,33 @@ static int varint_len(int64_t value) {
// SQLite serial type for a TEXT value
static int64_t text_serial_type(int len) {
- return (len * 2) + TEXT_SERIAL_BASE;
+ return (len * PAIR_LEN) + TEXT_SERIAL_BASE;
}
// SQLite serial type for an integer value
static int64_t int_serial_type(int64_t val) {
if (val == 0) {
- return 8; // integer value 0
+ return SERIAL_CONST_ZERO;
}
- if (val == 1) {
- return 9; // integer value 1
+ if (val == SERIAL_INT8) {
+ return SERIAL_CONST_ONE;
}
if (val >= -INT8_MAX_VAL - 1 && val <= INT8_MAX_VAL) {
- return 1; // 1 byte
+ return SERIAL_SIZE_INT8;
}
if (val >= -INT16_MAX_VAL - 1 && val <= INT16_MAX_VAL) {
- return 2; // 2 bytes
+ return SERIAL_SIZE_INT16;
}
if (val >= INT24_MIN_VAL && val <= INT24_MAX_VAL) {
- return 3; // 3 bytes
+ return SERIAL_SIZE_INT24;
}
if (val >= INT32_MIN_VAL && val <= INT32_MAX_VAL) {
- return 4; // 4 bytes
+ return SERIAL_SIZE_INT32;
}
if (val >= INT48_MIN_VAL && val <= INT48_MAX_VAL) {
- return 5; // 6 bytes
+ return SERIAL_SIZE_INT48;
}
- return 6; // 8 bytes
+ return SERIAL_SIZE_INT64;
}
// Bytes needed to store an integer of given serial type
@@ -148,20 +218,20 @@ static int int_storage_bytes(int serial_type) {
switch (serial_type) {
case 0:
return 0; // NULL
- case 1:
- return 1;
- case 2:
- return 2;
- case 3:
- return 3;
- case 4:
- return 4;
- case 5:
- return 6;
- case 6:
- return 8;
- case 8: // integer 0
- case 9: // integer 1
+ case SERIAL_INT8:
+ return SERIAL_SIZE_INT8;
+ case SERIAL_INT16:
+ return SERIAL_SIZE_INT16;
+ case SERIAL_INT24:
+ return SERIAL_SIZE_INT24;
+ case SERIAL_INT32:
+ return SERIAL_SIZE_INT32;
+ case SERIAL_INT48:
+ return SERIAL_SIZE_INT48;
+ case SERIAL_INT64:
+ return SERIAL_SIZE_INT64;
+ case SERIAL_CONST_ZERO: // integer 0
+ case SERIAL_CONST_ONE: // integer 1
default:
return 0;
}
@@ -171,21 +241,21 @@ static int int_storage_bytes(int serial_type) {
static void put_int_be(uint8_t *buf, int64_t val, int nbytes) {
for (int i = nbytes - 1; i >= 0; i--) {
buf[i] = (uint8_t)(val & BYTE_MASK);
- val >>= 8; // NOLINT(readability-magic-numbers) — standard byte shift
+ val >>= SHIFT_8;
}
}
// Write a 2-byte big-endian value
static void put_u16(uint8_t *buf, uint16_t val) {
- buf[0] = (uint8_t)(val >> 8);
+ buf[0] = (uint8_t)(val >> SHIFT_8);
buf[1] = (uint8_t)(val & BYTE_MASK);
}
// Write a 4-byte big-endian value
static void put_u32(uint8_t *buf, uint32_t val) {
- buf[0] = (uint8_t)(val >> 24); // NOLINT(readability-magic-numbers) — standard byte shift
- buf[1] = (uint8_t)(val >> 16); // NOLINT(readability-magic-numbers) — standard byte shift
- buf[2] = (uint8_t)(val >> 8); // NOLINT(readability-magic-numbers) — standard byte shift
+ buf[0] = (uint8_t)(val >> SHIFT_24);
+ buf[SKIP_ONE] = (uint8_t)(val >> SHIFT_16);
+ buf[2] = (uint8_t)(val >> SHIFT_8);
buf[3] = (uint8_t)(val & BYTE_MASK);
}
@@ -207,13 +277,13 @@ static bool dynbuf_ensure(DynBuf *b, int needed) {
if (b->len + needed <= b->cap) {
return true;
}
- int newcap = b->cap == 0 ? 4096 : b->cap;
+ int newcap = b->cap == 0 ? INITIAL_PAGE_CAP : b->cap;
while (newcap < b->len + needed) {
- newcap *= 2;
+ newcap *= GROWTH_FACTOR;
}
uint8_t *p = (uint8_t *)realloc(b->data, newcap);
if (!p) {
- fprintf(stderr, "cbm_write_db: dynbuf realloc failed size=%d\n", newcap);
+ (void)fprintf(stderr, "cbm_write_db: dynbuf realloc failed size=%d\n", newcap);
return false;
}
b->data = p;
@@ -267,13 +337,13 @@ static void rec_add_null(RecordBuilder *r) {
static void rec_add_int(RecordBuilder *r, int64_t val) {
int64_t st = int_serial_type(val);
- uint8_t vbuf[9];
+ uint8_t vbuf[VARINT_MAX_BYTES];
int vlen = put_varint(vbuf, st);
dynbuf_append(&r->header, vbuf, vlen);
int nbytes = int_storage_bytes((int)st);
if (nbytes > 0) {
- uint8_t ibuf[8];
+ uint8_t ibuf[INT64_BYTES];
put_int_be(ibuf, val, nbytes);
dynbuf_append(&r->body, ibuf, nbytes);
}
@@ -282,7 +352,7 @@ static void rec_add_int(RecordBuilder *r, int64_t val) {
static void rec_add_text(RecordBuilder *r, const char *s) {
int slen = s ? (int)strlen(s) : 0;
int64_t st = text_serial_type(slen);
- uint8_t vbuf[9];
+ uint8_t vbuf[VARINT_MAX_BYTES];
int vlen = put_varint(vbuf, st);
dynbuf_append(&r->header, vbuf, vlen);
if (slen > 0) {
@@ -352,9 +422,9 @@ static void pb_init(PageBuilder *pb, FILE *fp, uint32_t start_page, bool is_inde
pb->is_index = is_index;
pb->cell_count = 0;
pb->content_offset = PAGE_SIZE;
- pb->page1_offset = (start_page == 1) ? 100 : 0;
+ pb->page1_offset = (start_page == SKIP_ONE) ? SQLITE_HEADER_SIZE : 0;
// Header: flag(1) + freeblock(2) + cell_count(2) + content_start(2) + fragmented(1) = 8
- pb->ptr_offset = pb->page1_offset + 8;
+ pb->ptr_offset = pb->page1_offset + BTREE_HEADER_SIZE;
memset(pb->page, 0, PAGE_SIZE);
pb->leaves = NULL;
pb->leaf_count = 0;
@@ -379,21 +449,21 @@ static void pb_flush_leaf(PageBuilder *pb) {
int hdr = pb->page1_offset;
// Write leaf page header
pb->page[hdr + 0] = pb->is_index ? BTREE_LEAF_INDEX : BTREE_LEAF_TABLE; // leaf flag
- put_u16(pb->page + hdr + 1, 0); // first freeblock
- put_u16(pb->page + hdr + 3, (uint16_t)pb->cell_count);
- put_u16(pb->page + hdr + 5, (uint16_t)pb->content_offset);
- pb->page[hdr + 7] = 0; // fragmented free bytes
+ put_u16(pb->page + hdr + HDR_FREEBLOCK_OFF, 0); // first freeblock
+ put_u16(pb->page + hdr + HDR_CELLCOUNT_OFF, (uint16_t)pb->cell_count);
+ put_u16(pb->page + hdr + HDR_CONTENT_OFF, (uint16_t)pb->content_offset);
+ pb->page[hdr + HDR_FRAGBYTES_OFF] = 0; // fragmented free bytes
// Write page to file
uint32_t page_num = pb->next_page;
- long offset = (long)(page_num - 1) * PAGE_SIZE;
- fseek(pb->fp, offset, SEEK_SET);
- fwrite(pb->page, 1, PAGE_SIZE, pb->fp);
+ long offset = (long)(page_num - SKIP_ONE) * PAGE_SIZE;
+ (void)fseek(pb->fp, offset, SEEK_SET);
+ (void)fwrite(pb->page, SKIP_ONE, PAGE_SIZE, pb->fp);
// Record this leaf for interior page building
if (pb->leaf_count >= pb->leaf_cap) {
int old_cap = pb->leaf_cap;
- pb->leaf_cap = old_cap == 0 ? 256 : old_cap * 2;
+ pb->leaf_cap = old_cap == 0 ? INITIAL_LEAF_CAP : old_cap * GROWTH_FACTOR;
void *tmp = realloc(pb->leaves, (size_t)pb->leaf_cap * sizeof(PageRef));
if (!tmp) {
free(pb->leaves);
@@ -412,15 +482,15 @@ static void pb_flush_leaf(PageBuilder *pb) {
pb->next_page++;
pb->cell_count = 0;
pb->content_offset = PAGE_SIZE;
- pb->page1_offset = 0; // only page 1 has the 100-byte header
- pb->ptr_offset = 8; // standard B-tree header size for non-page-1
+ pb->page1_offset = 0; // only page 1 has the 100-byte header
+ pb->ptr_offset = BTREE_HEADER_SIZE; // standard B-tree header size for non-page-1
memset(pb->page, 0, PAGE_SIZE);
}
// Check if a cell of given size fits in the current page
static bool pb_cell_fits(PageBuilder *pb, int cell_len) {
// Cell pointer (2 bytes) + cell content
- int available = pb->content_offset - pb->ptr_offset - 2;
+ int available = pb->content_offset - pb->ptr_offset - CELL_PTR_SIZE;
return cell_len <= available;
}
@@ -434,7 +504,7 @@ static void pb_add_cell(PageBuilder *pb, const uint8_t *cell, int cell_len) {
// Write cell pointer (grows up)
put_u16(pb->page + pb->ptr_offset, (uint16_t)pb->content_offset);
- pb->ptr_offset += 2;
+ pb->ptr_offset += CELL_PTR_SIZE;
pb->cell_count++;
}
@@ -460,9 +530,9 @@ static int build_interior_cell(const PageRef *child, bool is_index, uint8_t *cel
*out_heap = NULL;
if (!is_index) {
put_u32(cell_buf, child->page_num);
- return 4 + put_varint(cell_buf + 4, child->max_key);
+ return BTREE_PTR_SIZE + put_varint(cell_buf + BTREE_PTR_SIZE, child->max_key);
}
- int clen = 4 + child->sep_cell_len;
+ int clen = BTREE_PTR_SIZE + child->sep_cell_len;
uint8_t *data = (uint8_t *)malloc(clen);
put_u32(data, child->page_num);
memcpy(data + 4, child->sep_cell, child->sep_cell_len);
@@ -477,24 +547,24 @@ static int write_interior_page(PageBuilder *pb, uint8_t *page, int cell_count, i
int right_child_idx, bool is_index, PageRef **parents,
int parent_count, int *parent_cap) {
uint32_t pnum = pb->next_page++;
- page[0] = is_index ? 0x02 : 0x05;
- put_u16(page + 1, 0);
- put_u16(page + 3, (uint16_t)cell_count);
- put_u16(page + 5, (uint16_t)content_offset);
- page[7] = 0;
- put_u32(page + 8, right_child_page);
+ page[0] = is_index ? INTERIOR_INDEX_FLAG : INTERIOR_TABLE_FLAG;
+ put_u16(page + HDR_FREEBLOCK_OFF, 0);
+ put_u16(page + HDR_CELLCOUNT_OFF, (uint16_t)cell_count);
+ put_u16(page + HDR_CONTENT_OFF, (uint16_t)content_offset);
+ page[HDR_FRAGBYTES_OFF] = 0;
+ put_u32(page + HDR_RIGHTCHILD_OFF, right_child_page);
- fseek(pb->fp, (long)(pnum - 1) * PAGE_SIZE, SEEK_SET);
- fwrite(page, 1, PAGE_SIZE, pb->fp);
+ (void)fseek(pb->fp, (long)(pnum - SKIP_ONE) * PAGE_SIZE, SEEK_SET);
+ (void)fwrite(page, SKIP_ONE, PAGE_SIZE, pb->fp);
if (parent_count >= *parent_cap) {
int old_pcap = *parent_cap;
- *parent_cap = old_pcap == 0 ? 64 : old_pcap * 2;
+ *parent_cap = old_pcap == 0 ? INITIAL_PARENT_CAP : old_pcap * GROWTH_FACTOR;
PageRef *tmp = (PageRef *)realloc(*parents, *parent_cap * sizeof(PageRef));
if (!tmp) {
free(*parents);
*parents = NULL;
- return -1;
+ return CBM_NOT_FOUND;
}
*parents = tmp;
memset(&(*parents)[old_pcap], 0,
@@ -511,7 +581,7 @@ static int write_interior_page(PageBuilder *pb, uint8_t *page, int cell_count, i
(*parents)[parent_count].sep_cell = NULL;
(*parents)[parent_count].sep_cell_len = 0;
}
- return parent_count + 1;
+ return parent_count + SKIP_ONE;
}
// Free a PageRef array (sep_cell allocations), unless it's the original leaves.
@@ -529,13 +599,13 @@ static void free_children(PageRef *children, int child_count, const PageRef *lea
static void fill_interior_page(uint8_t *page, const PageRef *children, int child_count,
bool is_index, int *idx, int *cell_count, int *content_offset,
int *ptr_offset) {
- while (*idx < child_count - 1) {
- uint8_t tbuf[20];
+ while (*idx < child_count - SKIP_ONE) {
+ uint8_t tbuf[INTERIOR_CELL_BUF];
uint8_t *heap_cell = NULL;
int clen = build_interior_cell(&children[*idx], is_index, tbuf, &heap_cell);
uint8_t *cell_data = heap_cell ? heap_cell : tbuf;
- int available = *content_offset - *ptr_offset - 2;
+ int available = *content_offset - *ptr_offset - CELL_PTR_SIZE;
if (clen > available && *cell_count > 0) {
free(heap_cell);
break;
@@ -544,7 +614,7 @@ static void fill_interior_page(uint8_t *page, const PageRef *children, int child
*content_offset -= clen;
memcpy(page + *content_offset, cell_data, clen);
put_u16(page + *ptr_offset, (uint16_t)*content_offset);
- *ptr_offset += 2;
+ *ptr_offset += CELL_PTR_SIZE;
(*cell_count)++;
free(heap_cell);
(*idx)++;
@@ -555,14 +625,14 @@ static uint32_t pb_build_interior(PageBuilder *pb, bool is_index) {
if (!pb->leaves) {
return 0;
}
- if (pb->leaf_count <= 1) {
+ if (pb->leaf_count <= SKIP_ONE) {
return pb->leaves[0].page_num;
}
PageRef *children = pb->leaves;
int child_count = pb->leaf_count;
- while (child_count > 1 && children) {
+ while (child_count > SKIP_ONE && children) {
PageRef *parents = NULL;
int parent_count = 0;
int parent_cap = 0;
@@ -573,17 +643,17 @@ static uint32_t pb_build_interior(PageBuilder *pb, bool is_index) {
memset(page, 0, PAGE_SIZE);
int cell_count = 0;
int content_offset = PAGE_SIZE;
- int ptr_offset = 12;
+ int ptr_offset = BTREE_INTERIOR_HDR;
fill_interior_page(page, children, child_count, is_index, &i, &cell_count,
&content_offset, &ptr_offset);
- int right_child_idx = (i < child_count - 1) ? i : child_count - 1;
+ int right_child_idx = (i < child_count - SKIP_ONE) ? i : child_count - SKIP_ONE;
uint32_t right_child_page = 0;
if (right_child_idx >= 0 && right_child_idx < child_count) {
right_child_page = children[right_child_idx].page_num;
}
- if (i < child_count - 1) {
+ if (i < child_count - SKIP_ONE) {
i++;
} else {
i = child_count;
@@ -824,7 +894,7 @@ static bool pb_ensure_leaf_cap(PageBuilder *pb) {
if (pb->leaf_count < pb->leaf_cap) {
return true;
}
- pb->leaf_cap = pb->leaf_cap == 0 ? 256 : pb->leaf_cap * 2;
+ pb->leaf_cap = pb->leaf_cap == 0 ? INITIAL_LEAF_CAP : pb->leaf_cap * GROWTH_FACTOR;
void *tmp = realloc(pb->leaves, (size_t)pb->leaf_cap * sizeof(PageRef));
if (!tmp) {
free(pb->leaves);
@@ -875,9 +945,9 @@ static uint32_t pb_finalize_table(PageBuilder *pb, uint32_t *next_page, int64_t
*next_page = pb->next_page;
uint32_t root;
- if (pb->leaf_count == 1) {
+ if (pb->leaf_count == SKIP_ONE) {
root = pb->leaves[0].page_num;
- } else if (pb->leaf_count > 1) {
+ } else if (pb->leaf_count > SKIP_ONE) {
root = pb_build_interior(pb, false);
*next_page = pb->next_page;
} else {
@@ -897,20 +967,20 @@ static uint32_t write_table_btree(FILE *fp, uint32_t *next_page, const uint8_t *
uint32_t pnum = (*next_page)++;
uint8_t page[PAGE_SIZE];
memset(page, 0, PAGE_SIZE);
- int hdr = first_is_page1 ? 100 : 0;
- page[hdr] = BTREE_LEAF_TABLE; // leaf table
- put_u16(page + hdr + 1, 0); // no freeblocks
- put_u16(page + hdr + 3, 0); // 0 cells
- put_u16(page + hdr + 5, (uint16_t)PAGE_SIZE); // content at end of page
- page[hdr + 7] = 0; // 0 fragmented bytes
- fseek(fp, (long)(pnum - 1) * PAGE_SIZE, SEEK_SET);
- fwrite(page, 1, PAGE_SIZE, fp);
+ int hdr = first_is_page1 ? SQLITE_HEADER_SIZE : 0;
+ page[hdr] = BTREE_LEAF_TABLE; // leaf table
+ put_u16(page + hdr + HDR_FREEBLOCK_OFF, 0); // no freeblocks
+ put_u16(page + hdr + HDR_CELLCOUNT_OFF, 0); // 0 cells
+ put_u16(page + hdr + HDR_CONTENT_OFF, (uint16_t)PAGE_SIZE); // content at end of page
+ page[hdr + HDR_FRAGBYTES_OFF] = 0; // 0 fragmented bytes
+ (void)fseek(fp, (long)(pnum - SKIP_ONE) * PAGE_SIZE, SEEK_SET);
+ (void)fwrite(page, SKIP_ONE, PAGE_SIZE, fp);
return pnum;
}
PageBuilder pb;
pb_init(&pb, fp, *next_page, false);
- pb.page1_offset = first_is_page1 ? 100 : 0;
+ pb.page1_offset = first_is_page1 ? SQLITE_HEADER_SIZE : 0;
pb.ptr_offset = pb.page1_offset + 8;
for (int i = 0; i < count; i++) {
@@ -934,7 +1004,7 @@ static bool pb_promote_and_flush(PageBuilder *pb, uint8_t **cells, int *cell_len
// Un-add the last cell
pb->cell_count--;
pb->content_offset += cell_lens[prev_idx];
- pb->ptr_offset -= 2;
+ pb->ptr_offset -= CELL_PTR_SIZE;
pb_flush_leaf(pb);
return true;
@@ -945,13 +1015,13 @@ static uint32_t write_empty_index_leaf(FILE *fp, uint32_t *next_page) {
uint32_t pnum = (*next_page)++;
uint8_t page[PAGE_SIZE];
memset(page, 0, PAGE_SIZE);
- page[0] = 0x0A;
- put_u16(page + 1, 0);
- put_u16(page + 3, 0);
- put_u16(page + 5, (uint16_t)PAGE_SIZE);
- page[7] = 0;
- fseek(fp, (long)(pnum - 1) * PAGE_SIZE, SEEK_SET);
- fwrite(page, 1, PAGE_SIZE, fp);
+ page[0] = NEWLINE_BYTE;
+ put_u16(page + HDR_FREEBLOCK_OFF, 0);
+ put_u16(page + HDR_CELLCOUNT_OFF, 0);
+ put_u16(page + HDR_CONTENT_OFF, (uint16_t)PAGE_SIZE);
+ page[HDR_FRAGBYTES_OFF] = 0;
+ (void)fseek(fp, (long)(pnum - SKIP_ONE) * PAGE_SIZE, SEEK_SET);
+ (void)fwrite(page, SKIP_ONE, PAGE_SIZE, fp);
return pnum;
}
@@ -991,7 +1061,7 @@ static uint32_t write_index_btree(FILE *fp, uint32_t *next_page, uint8_t **cells
uint32_t root;
if (!pb.leaves) {
root = 0;
- } else if (pb.leaf_count == 1) {
+ } else if (pb.leaf_count == SKIP_ONE) {
root = pb.leaves[0].page_num;
} else {
root = pb_build_interior(&pb, true);
@@ -1048,8 +1118,8 @@ static inline const char *safe_str(const char *s) {
static int *make_sorted_perm(int n, int (*cmp)(const void *, const void *)) {
int *perm = (int *)malloc(n * sizeof(int));
if (!perm) {
- fprintf(stderr, "cbm_write_db: perm malloc failed n=%d size=%zu\n", n,
- (size_t)n * sizeof(int));
+ (void)fprintf(stderr, "cbm_write_db: perm malloc failed n=%d size=%zu\n", n,
+ (size_t)n * sizeof(int));
return NULL;
}
for (int i = 0; i < n; i++) {
@@ -1187,10 +1257,10 @@ static int cmp_edge_by_url_path(const void *a, const void *b) {
return cmp_i64(g_sort_edges[ia].id, g_sort_edges[ib].id);
}
if (na) {
- return -1;
+ return CBM_NOT_FOUND;
}
if (nb) {
- return 1;
+ return SERIAL_SIZE_INT8;
}
int c = strcmp(ua, ub);
if (c) {
@@ -1403,7 +1473,7 @@ static int write_data_tables(write_db_ctx_t *w, uint32_t *nodes_root, uint32_t *
int rec_len;
uint8_t *rec = build_node_record(&w->nodes[i], &rec_len);
if (!rec) {
- return -3;
+ return ERR_WRITE_FAILED;
}
pb_add_table_cell_with_flush(&pb, w->nodes[i].id, rec, rec_len,
i > 0 ? w->nodes[i - 1].id : 0);
@@ -1421,7 +1491,7 @@ static int write_data_tables(write_db_ctx_t *w, uint32_t *nodes_root, uint32_t *
int rec_len;
uint8_t *rec = build_edge_record(&w->edges[i], &rec_len);
if (!rec) {
- return -3;
+ return ERR_WRITE_FAILED;
}
pb_add_table_cell_with_flush(&pb, w->edges[i].id, rec, rec_len,
i > 0 ? w->edges[i - 1].id : 0);
@@ -1443,7 +1513,7 @@ static void write_metadata_tables(write_db_ctx_t *w, uint32_t *projects_root,
build_project_record(w->project, w->indexed_at, w->root_path, &proj_rec_len);
const uint8_t *proj_recs[] = {proj_rec};
int proj_lens[] = {proj_rec_len};
- int64_t proj_rowids[] = {1};
+ int64_t proj_rowids[] = {FIRST_ROWID};
*projects_root =
write_table_btree(w->fp, &w->next_page, proj_recs, proj_lens, proj_rowids, 1, false);
free(proj_rec);
@@ -1469,7 +1539,7 @@ static void write_metadata_tables(write_db_ctx_t *w, uint32_t *projects_root,
const uint8_t *seq_recs[] = {seq1, seq2};
int seq_lens[] = {seq1_len, seq2_len};
- int64_t seq_rowids[] = {1, 2};
+ int64_t seq_rowids[] = {FIRST_ROWID, FIRST_DATA_PAGE};
*sqlite_seq_root =
write_table_btree(w->fp, &w->next_page, seq_recs, seq_lens, seq_rowids, 2, false);
free(seq1);
@@ -1481,11 +1551,11 @@ int cbm_write_db(const char *path, const char *project, const char *root_path,
int edge_count) {
FILE *fp = fopen(path, "wb");
if (!fp) {
- return -1;
+ return CBM_NOT_FOUND;
}
write_db_ctx_t w = {.fp = fp,
- .next_page = 2,
+ .next_page = FIRST_DATA_PAGE,
.project = project,
.root_path = root_path,
.indexed_at = indexed_at,
@@ -1499,7 +1569,7 @@ int cbm_write_db(const char *path, const char *project, const char *root_path,
uint32_t edges_root;
int rc = write_data_tables(&w, &nodes_root, &edges_root);
if (rc != 0) {
- fclose(fp);
+ (void)fclose(fp);
return rc;
}
@@ -1537,14 +1607,14 @@ int cbm_write_db(const char *path, const char *project, const char *root_path,
};
{
- cbm_thread_t st[11];
+ cbm_thread_t st[TOTAL_SORT_THREADS];
int nt = 0;
- for (int i = 0; i < 4; i++) {
+ for (int i = 0; i < NODE_SORT_THREADS; i++) {
if (nsorts[i].count > 0) {
cbm_thread_create(&st[nt++], 0, sort_worker, &nsorts[i]);
}
}
- for (int i = 0; i < 7; i++) {
+ for (int i = 0; i < EDGE_SORT_THREADS; i++) {
if (esorts[i].count > 0) {
cbm_thread_create(&st[nt++], 0, sort_worker, &esorts[i]);
}
@@ -1556,42 +1626,44 @@ int cbm_write_db(const char *path, const char *project, const char *root_path,
uint32_t idx_nodes_label_root =
build_node_index_sorted(fp, &next_page, nodes, node_count, nsorts[0].perm, ncol_label);
- uint32_t idx_nodes_name_root =
- build_node_index_sorted(fp, &next_page, nodes, node_count, nsorts[1].perm, ncol_name);
- uint32_t idx_nodes_file_root =
- build_node_index_sorted(fp, &next_page, nodes, node_count, nsorts[2].perm, ncol_file);
+ uint32_t idx_nodes_name_root = build_node_index_sorted(fp, &next_page, nodes, node_count,
+ nsorts[NSORT_NAME].perm, ncol_name);
+ uint32_t idx_nodes_file_root = build_node_index_sorted(fp, &next_page, nodes, node_count,
+ nsorts[NSORT_FILE].perm, ncol_file);
uint32_t autoindex_nodes_root =
- build_node_index_sorted(fp, &next_page, nodes, node_count, nsorts[3].perm, ncol_qn);
+ build_node_index_sorted(fp, &next_page, nodes, node_count, nsorts[NSORT_QN].perm, ncol_qn);
if ((node_count > 0) && (!idx_nodes_label_root || !idx_nodes_name_root ||
!idx_nodes_file_root || !autoindex_nodes_root)) {
- fclose(fp);
- return -4;
+ (void)fclose(fp);
+ return ERR_SORT_FAILED;
}
// --- Edge indexes (all sorted) ---
uint32_t idx_edges_source_root =
build_edge_index_sorted(fp, &next_page, edges, edge_count, esorts[0].perm, ecell_source);
- uint32_t idx_edges_target_root =
- build_edge_index_sorted(fp, &next_page, edges, edge_count, esorts[1].perm, ecell_target);
- uint32_t idx_edges_type_root =
- build_edge_index_sorted(fp, &next_page, edges, edge_count, esorts[2].perm, ecell_type);
- uint32_t idx_edges_target_type_root = build_edge_index_sorted(
- fp, &next_page, edges, edge_count, esorts[3].perm, ecell_proj_target_type);
- uint32_t idx_edges_source_type_root = build_edge_index_sorted(
- fp, &next_page, edges, edge_count, esorts[4].perm, ecell_proj_source_type);
- uint32_t idx_edges_url_path_root =
- build_edge_index_sorted(fp, &next_page, edges, edge_count, esorts[5].perm, ecell_url_path);
- uint32_t autoindex_edges_root = build_edge_index_sorted(fp, &next_page, edges, edge_count,
- esorts[6].perm, ecell_src_tgt_type);
+ uint32_t idx_edges_target_root = build_edge_index_sorted(
+ fp, &next_page, edges, edge_count, esorts[ESORT_TARGET].perm, ecell_target);
+ uint32_t idx_edges_type_root = build_edge_index_sorted(fp, &next_page, edges, edge_count,
+ esorts[ESORT_TYPE].perm, ecell_type);
+ uint32_t idx_edges_target_type_root =
+ build_edge_index_sorted(fp, &next_page, edges, edge_count, esorts[ESORT_PROJ_TGT_TYPE].perm,
+ ecell_proj_target_type);
+ uint32_t idx_edges_source_type_root =
+ build_edge_index_sorted(fp, &next_page, edges, edge_count, esorts[ESORT_PROJ_SRC_TYPE].perm,
+ ecell_proj_source_type);
+ uint32_t idx_edges_url_path_root = build_edge_index_sorted(
+ fp, &next_page, edges, edge_count, esorts[ESORT_URL_PATH].perm, ecell_url_path);
+ uint32_t autoindex_edges_root = build_edge_index_sorted(
+ fp, &next_page, edges, edge_count, esorts[ESORT_SRC_TGT_TYPE].perm, ecell_src_tgt_type);
if (edge_count > 0 &&
(!idx_edges_source_root || !idx_edges_target_root || !idx_edges_type_root ||
!idx_edges_target_type_root || !idx_edges_source_type_root || !idx_edges_url_path_root ||
!autoindex_edges_root)) {
- fclose(fp);
- return -4;
+ (void)fclose(fp);
+ return ERR_SORT_FAILED;
}
// Autoindex for projects(name TEXT PK) — single text column
@@ -1601,7 +1673,7 @@ int cbm_write_db(const char *path, const char *project, const char *root_path,
RecordBuilder r;
rec_init(&r);
rec_add_text(&r, project);
- rec_add_int(&r, 1); // rowid
+ rec_add_int(&r, FIRST_ROWID); /* rowid */
int plen = 0;
uint8_t *payload = rec_finalize(&r, &plen);
rec_free(&r);
@@ -1692,7 +1764,7 @@ int cbm_write_db(const char *path, const char *project, const char *root_path,
int *master_lens = (int *)malloc(master_count * sizeof(int));
int64_t *master_rowids = (int64_t *)malloc(master_count * sizeof(int64_t));
for (int i = 0; i < master_count; i++) {
- master_rowids[i] = i + 1;
+ master_rowids[i] = i + SKIP_ONE;
master_records[i] = build_master_record(&master[i], &master_lens[i]);
}
@@ -1707,10 +1779,10 @@ int cbm_write_db(const char *path, const char *project, const char *root_path,
memset(page1, 0, PAGE_SIZE);
// B-tree header starts at offset 100 on page 1
- int hdr = 100;
+ int hdr = SQLITE_HEADER_SIZE;
page1[hdr] = BTREE_LEAF_TABLE; // leaf table
int content_off = PAGE_SIZE;
- int ptr_off = hdr + 8;
+ int ptr_off = hdr + BTREE_HEADER_SIZE;
int mcell_count = 0;
for (int i = 0; i < master_count; i++) {
@@ -1719,7 +1791,7 @@ int cbm_write_db(const char *path, const char *project, const char *root_path,
build_table_cell(master_rowids[i], master_records[i], master_lens[i], &cell_len);
// Check fit
- int available = content_off - ptr_off - 2;
+ int available = content_off - ptr_off - CELL_PTR_SIZE;
if (cell_len > available) {
// Master entries should always fit on page 1 (they're small SQL strings).
// If not, this is a bug — fail gracefully.
@@ -1730,53 +1802,53 @@ int cbm_write_db(const char *path, const char *project, const char *root_path,
free(master_records);
free(master_lens);
free(master_rowids);
- fclose(fp);
- return -2;
+ (void)fclose(fp);
+ return ERR_MASTER_OVERFLOW;
}
content_off -= cell_len;
memcpy(page1 + content_off, cell, cell_len);
put_u16(page1 + ptr_off, (uint16_t)content_off);
- ptr_off += 2;
+ ptr_off += CELL_PTR_SIZE;
mcell_count++;
free(cell);
}
- put_u16(page1 + hdr + 1, 0); // freeblock
- put_u16(page1 + hdr + 3, (uint16_t)mcell_count);
- put_u16(page1 + hdr + 5, (uint16_t)content_off);
- page1[hdr + 7] = 0; // fragmented
+ put_u16(page1 + hdr + HDR_FREEBLOCK_OFF, 0); // freeblock
+ put_u16(page1 + hdr + HDR_CELLCOUNT_OFF, (uint16_t)mcell_count);
+ put_u16(page1 + hdr + HDR_CONTENT_OFF, (uint16_t)content_off);
+ page1[hdr + HDR_FRAGBYTES_OFF] = 0; // fragmented
// Write the 100-byte SQLite file header
memcpy(page1, "SQLite format 3\000", 16);
/* Page size 65536 is encoded as 1 in the 2-byte header field */
put_u16(page1 + HDR_OFF_PAGE_SIZE, (uint16_t)1);
- page1[HDR_OFF_WRITE_VERSION] = FILE_FORMAT; // file format write version
- page1[HDR_OFF_READ_VERSION] = FILE_FORMAT; // file format read version
- page1[HDR_OFF_RESERVED] = 0; // reserved space per page
- page1[HDR_OFF_MAX_EMBED_FRAC] = 64; // max embedded payload fraction
- page1[HDR_OFF_MIN_EMBED_FRAC] = 32; // min embedded payload fraction
- page1[HDR_OFF_LEAF_FRAC] = 32; // leaf payload fraction
- put_u32(page1 + HDR_OFF_FILE_CHANGE, 0); // file change counter (set below)
- put_u32(page1 + HDR_OFF_DB_SIZE, next_page - 1); // total pages
- put_u32(page1 + HDR_OFF_FREELIST_TRUNK, 0); // first freelist trunk page
- put_u32(page1 + HDR_OFF_FREELIST_COUNT, 0); // total freelist pages
- put_u32(page1 + HDR_OFF_SCHEMA_COOKIE, 1); // schema cookie
- put_u32(page1 + HDR_OFF_SCHEMA_FORMAT, SCHEMA_FORMAT); // schema format number
- put_u32(page1 + HDR_OFF_DEFAULT_CACHE, 0); // default page cache size
- put_u32(page1 + HDR_OFF_AUTOVAC_TOP, 0); // largest root page (auto-vacuum)
- put_u32(page1 + HDR_OFF_TEXT_ENCODING, 1); // text encoding: UTF-8
- put_u32(page1 + HDR_OFF_USER_VERSION, 0); // user version
- put_u32(page1 + HDR_OFF_INCR_VACUUM, 0); // incremental vacuum mode
- put_u32(page1 + HDR_OFF_APP_ID, 0); // application ID
+ page1[HDR_OFF_WRITE_VERSION] = FILE_FORMAT; // file format write version
+ page1[HDR_OFF_READ_VERSION] = FILE_FORMAT; // file format read version
+ page1[HDR_OFF_RESERVED] = 0; // reserved space per page
+ page1[HDR_OFF_MAX_EMBED_FRAC] = MAX_EMBED_FRACTION; // max embedded payload fraction
+ page1[HDR_OFF_MIN_EMBED_FRAC] = MIN_EMBED_FRACTION; // min embedded payload fraction
+ page1[HDR_OFF_LEAF_FRAC] = LEAF_PAYLOAD_FRACTION; // leaf payload fraction
+ put_u32(page1 + HDR_OFF_FILE_CHANGE, 0); // file change counter (set below)
+ put_u32(page1 + HDR_OFF_DB_SIZE, next_page - SKIP_ONE); // total pages
+ put_u32(page1 + HDR_OFF_FREELIST_TRUNK, 0); // first freelist trunk page
+ put_u32(page1 + HDR_OFF_FREELIST_COUNT, 0); // total freelist pages
+ put_u32(page1 + HDR_OFF_SCHEMA_COOKIE, 1); // schema cookie
+ put_u32(page1 + HDR_OFF_SCHEMA_FORMAT, SCHEMA_FORMAT); // schema format number
+ put_u32(page1 + HDR_OFF_DEFAULT_CACHE, 0); // default page cache size
+ put_u32(page1 + HDR_OFF_AUTOVAC_TOP, 0); // largest root page (auto-vacuum)
+ put_u32(page1 + HDR_OFF_TEXT_ENCODING, 1); // text encoding: UTF-8
+ put_u32(page1 + HDR_OFF_USER_VERSION, 0); // user version
+ put_u32(page1 + HDR_OFF_INCR_VACUUM, 0); // incremental vacuum mode
+ put_u32(page1 + HDR_OFF_APP_ID, 0); // application ID
// Bytes 72-91: reserved for expansion (zeros)
put_u32(page1 + HDR_OFF_VERSION_VALID, 1); // version-valid-for (change counter)
put_u32(page1 + HDR_OFF_SQLITE_VERSION, SQLITE_VERSION); // SQLite version number
// Set file change counter = version-valid-for = 1
put_u32(page1 + HDR_OFF_FILE_CHANGE, 1);
- fseek(fp, 0, SEEK_SET);
- fwrite(page1, 1, PAGE_SIZE, fp);
+ (void)fseek(fp, 0, SEEK_SET);
+ (void)fwrite(page1, SKIP_ONE, PAGE_SIZE, fp);
}
for (int i = 0; i < master_count; i++) {
@@ -1788,16 +1860,16 @@ int cbm_write_db(const char *path, const char *project, const char *root_path,
// Ensure file size is exactly next_page * PAGE_SIZE
// (pad any remaining space)
- fseek(fp, 0, SEEK_END);
+ (void)fseek(fp, 0, SEEK_END);
long file_size = ftell(fp);
- long expected_size = (long)(next_page - 1) * PAGE_SIZE;
+ long expected_size = (long)(next_page - SKIP_ONE) * PAGE_SIZE;
if (file_size < expected_size) {
// Pad with zeros
uint8_t zero = 0;
- fseek(fp, expected_size - 1, SEEK_SET);
- fwrite(&zero, 1, 1, fp);
+ (void)fseek(fp, expected_size - SKIP_ONE, SEEK_SET);
+ (void)fwrite(&zero, SKIP_ONE, SKIP_ONE, fp);
}
- fclose(fp);
+ (void)fclose(fp);
return 0;
}
diff --git a/scripts/check-nolint-whitelist.sh b/scripts/check-nolint-whitelist.sh
new file mode 100755
index 000000000..7721663cc
--- /dev/null
+++ b/scripts/check-nolint-whitelist.sh
@@ -0,0 +1,31 @@
+#!/bin/bash
+# Verify NOLINT(misc-no-recursion) only appears on whitelisted functions.
+WHITELIST="src/foundation/recursion_whitelist.h"
+if [ ! -f "$WHITELIST" ]; then
+ echo "ERROR: $WHITELIST not found"; exit 1
+fi
+ALLOWED=$(grep -oE '"[a-zA-Z_][a-zA-Z0-9_]*"' "$WHITELIST" | tr -d '"' | sort -u)
+
+HITS=$(grep -rn 'NOLINT(misc-no-recursion)' src/ internal/cbm/*.c internal/cbm/*.h 2>/dev/null \
+ | grep -v vendored | grep -v recursion_whitelist)
+if [ -z "$HITS" ]; then exit 0; fi
+
+FAIL=0
+while IFS= read -r line; do
+ FILE=$(echo "$line" | cut -d: -f1)
+ LINENO=$(echo "$line" | cut -d: -f2)
+ # Check current line AND 5 lines above for the function name
+ CONTEXT=$(sed -n "$((LINENO > 5 ? LINENO - 5 : 1)),${LINENO}p" "$FILE")
+ FOUND=0
+ for fn in $ALLOWED; do
+ if echo "$CONTEXT" | grep -qw "$fn"; then
+ FOUND=1; break
+ fi
+ done
+ if [ "$FOUND" -eq 0 ]; then
+ echo "ERROR: NOLINT(misc-no-recursion) on non-whitelisted function:"
+ echo " $line"
+ FAIL=1
+ fi
+done <<< "$HITS"
+exit $FAIL
diff --git a/src/cli/cli.c b/src/cli/cli.c
index 72739a8fd..897104ce4 100644
--- a/src/cli/cli.c
+++ b/src/cli/cli.c
@@ -6,8 +6,62 @@
*/
#include "cli/cli.h"
#include "foundation/compat.h"
-#include "foundation/str_util.h"
#include "foundation/platform.h"
+#include "foundation/constants.h"
+
+/* CLI buffer size constants. */
+enum {
+ CLI_BUF_1K = 1024,
+ CLI_BUF_512 = 512,
+ CLI_BUF_256 = 256,
+ CLI_BUF_128 = 128,
+ CLI_BUF_4K = 4096,
+ CLI_BUF_16 = 16,
+ CLI_BUF_8 = 8,
+ CLI_BUF_24 = 24,
+ CLI_SKIP_ONE = 1,
+ CLI_PAIR_LEN = 2,
+ CLI_OCTAL_PERM = 0755,
+ CLI_JSON_INDENT = 3,
+ CLI_MAX_SCAN = 10,
+ CLI_ERR = -1,
+ CLI_OK = 0,
+ CLI_TRUE = 1,
+ CLI_ELEM_SIZE = 1, /* fread/fwrite element size */
+ CLI_IDX_1 = 1, /* array index 1 */
+ CLI_IDX_2 = 2, /* array index 2 */
+ CLI_STRTOL_BASE = 10, /* decimal base for strtol */
+ CLI_STRTOL_HEX = 16, /* hex base for strtol */
+ CLI_BUF_2K = 2048,
+ CLI_BUF_8K = 8192,
+ CLI_BUF_32 = 32,
+ CLI_INDENT_24 = 24,
+ CLI_FIELD_1040 = 1040,
+ CLI_MB_10 = 10,
+ BYTE_SHIFT = 8, /* bits per byte for multi-byte reads */
+ SQL_NUL_TERM = -1, /* sqlite3 length = -1 means NUL-terminated */
+ SQL_PARAM_1 = 1, /* sqlite3_bind parameter index 1 */
+ SQL_PARAM_2 = 2,
+ SEMVER_PARTS = 3, /* major.minor.patch */
+ DB_EXT_LEN = 3, /* strlen(".db") */
+ MIN_ARGC_CMD = 3,
+ /* minimum argc for subcommand with arg */ /* sqlite3_bind parameter index 2 */ /* 10 MB cap
+ factor */
+ CLI_MB_FACTOR = CLI_BUF_1K * CLI_BUF_1K,
+ NUM_RETRIES = 5,
+ NUM_DIRS = 4,
+ DECOMP_FACTOR = 10,
+ GROWTH_FACTOR = 2,
+ MIN_ARGC_GET = 2,
+ AUTO_YES = 1,
+ AUTO_NO = -1,
+ VARIANT_A = 1,
+ VARIANT_B = 2,
+ OCTAL_BASE = 8,
+};
+
+/* String length helper for strncmp. */
+#define SLEN(s) (sizeof(s) - SKIP_ONE)
// the correct standard headers are included below but clang-tidy doesn't map them.
#include <ctype.h>
@@ -32,13 +86,24 @@
/* yyjson for JSON read-modify-write */
#include "yyjson/yyjson.h"
+/* SQLITE_TRANSIENT equivalent as a typed function pointer (avoids int-to-ptr cast).
+ * sqlite3.h defines SQLITE_TRANSIENT as ((sqlite3_destructor_type)-1).
+ * We replicate the same bit pattern via memcpy to satisfy performance-no-int-to-ptr. */
+static void (*cbm_sqlite_transient_fn(void))(void *) {
+ uintptr_t bits = (uintptr_t)CLI_ERR;
+ void (*fp)(void *) = NULL;
+ memcpy(&fp, &bits, sizeof(fp));
+ return fp;
+}
+#define cbm_sqlite_transient (cbm_sqlite_transient_fn())
+
/* ── Constants ────────────────────────────────────────────────── */
/* Directory permissions: rwxr-x--- */
#define DIR_PERMS 0750
/* Decompression buffer cap (500 MB) */
-#define DECOMPRESS_MAX_BYTES ((size_t)500 * 1024 * 1024)
+#define DECOMPRESS_MAX_BYTES ((size_t)500 * CLI_BUF_1K * CBM_SZ_1K)
/* Tar header field offsets */
#define TAR_NAME_LEN 101 /* filename field: bytes 0-99 + NUL */
@@ -47,8 +112,8 @@
#define TAR_TYPE_OFFSET 156 /* type flag byte */
#define TAR_BINARY_NAME "codebase-memory-mcp"
#define TAR_BINARY_NAME_LEN 19
-#define TAR_BLOCK_SIZE 512 /* tar record alignment */
-#define TAR_BLOCK_MASK 511 /* TAR_BLOCK_SIZE - 1 */
+#define TAR_BLOCK_SIZE CBM_SZ_512 /* tar record alignment */
+#define TAR_BLOCK_MASK 511 /* TAR_BLOCK_SIZE - 1 */
/* ── Version ──────────────────────────────────────────────────── */
@@ -67,23 +132,23 @@ const char *cbm_cli_get_version(void) {
/* ── Version comparison ───────────────────────────────────────── */
/* Parse semver major.minor.patch into array. Returns number of parts parsed. */
-static int parse_semver(const char *v, int out[3]) {
- out[0] = out[1] = out[2] = 0;
+static int parse_semver(const char *v, int out[SEMVER_PARTS]) {
+ out[0] = out[CLI_IDX_1] = out[CLI_IDX_2] = 0;
/* Skip v prefix */
if (*v == 'v' || *v == 'V') {
v++;
}
int count = 0;
- while (*v && count < 3) {
+ while (*v && count < SEMVER_PARTS) {
if (*v == '-') {
break; /* stop at pre-release suffix */
}
char *endptr;
- long val = strtol(v, &endptr, 10);
+ long val = strtol(v, &endptr, CLI_STRTOL_BASE);
out[count++] = (int)val;
if (*endptr == '.') {
- v = endptr + 1;
+ v = endptr + CLI_SKIP_ONE;
} else {
break;
}
@@ -99,12 +164,12 @@ static bool has_prerelease(const char *v) {
}
int cbm_compare_versions(const char *a, const char *b) {
- int pa[3];
- int pb[3];
+ int pa[SEMVER_PARTS];
+ int pb[SEMVER_PARTS];
parse_semver(a, pa);
parse_semver(b, pb);
- for (int i = 0; i < 3; i++) {
+ for (int i = 0; i < SEMVER_PARTS; i++) {
if (pa[i] != pb[i]) {
return pa[i] - pb[i];
}
@@ -114,10 +179,10 @@ int cbm_compare_versions(const char *a, const char *b) {
bool a_pre = has_prerelease(a);
bool b_pre = has_prerelease(b);
if (a_pre && !b_pre) {
- return -1;
+ return CLI_ERR;
}
if (!a_pre && b_pre) {
- return 1;
+ return CLI_TRUE;
}
return 0;
}
@@ -125,12 +190,13 @@ int cbm_compare_versions(const char *a, const char *b) {
/* ── Shell RC detection ───────────────────────────────────────── */
const char *cbm_detect_shell_rc(const char *home_dir) {
- static char buf[512];
+ static char buf[CLI_BUF_512];
if (!home_dir || !home_dir[0]) {
return "";
}
- const char *shell = getenv("SHELL");
+ char shell_buf[CLI_BUF_256];
+ const char *shell = cbm_safe_getenv("SHELL", shell_buf, sizeof(shell_buf), "");
if (!shell) {
shell = "";
}
@@ -164,12 +230,10 @@ const char *cbm_detect_shell_rc(const char *home_dir) {
/* Search for an executable named `name` in the PATH environment variable.
* Returns the full path in `out` (max out_sz) if found, else empty string. */
static bool find_in_path(const char *name, char *out, size_t out_sz) {
- const char *path_env = getenv("PATH");
- if (!path_env) {
+ char path_copy[CLI_BUF_4K];
+ if (!cbm_safe_getenv("PATH", path_copy, sizeof(path_copy), NULL)) {
return false;
}
- char path_copy[4096];
- snprintf(path_copy, sizeof(path_copy), "%s", path_env);
char *saveptr;
char *dir = strtok_r(path_copy, ":", &saveptr);
while (dir) {
@@ -190,7 +254,7 @@ static bool is_executable(const char *path) {
}
const char *cbm_find_cli(const char *name, const char *home_dir) {
- static char buf[512];
+ static char buf[CLI_BUF_512];
if (!name || !name[0]) {
return "";
}
@@ -200,7 +264,8 @@ const char *cbm_find_cli(const char *name, const char *home_dir) {
if (!home_dir || !home_dir[0]) {
return "";
}
- char paths[5][512];
+ enum { NUM_PATHS = 5 };
+ char paths[NUM_PATHS][CLI_BUF_512];
snprintf(paths[0], sizeof(paths[0]), "/usr/local/bin/%s", name);
snprintf(paths[1], sizeof(paths[1]), "%s/.npm/bin/%s", home_dir, name);
snprintf(paths[2], sizeof(paths[2]), "%s/.local/bin/%s", home_dir, name);
@@ -210,7 +275,7 @@ const char *cbm_find_cli(const char *name, const char *home_dir) {
#else
paths[4][0] = '\0';
#endif
- for (int i = 0; i < 5; i++) {
+ for (int i = 0; i < NUM_RETRIES; i++) {
if (paths[i][0] && is_executable(paths[i])) {
snprintf(buf, sizeof(buf), "%s", paths[i]);
return buf;
@@ -224,24 +289,24 @@ const char *cbm_find_cli(const char *name, const char *home_dir) {
int cbm_copy_file(const char *src, const char *dst) {
FILE *in = fopen(src, "rb");
if (!in) {
- return -1;
+ return CLI_ERR;
}
FILE *out = fopen(dst, "wb");
if (!out) {
(void)fclose(in);
- return -1;
+ return CLI_ERR;
}
- char buf[8192];
+ char buf[CLI_BUF_8K];
int err = 0;
while (!feof(in) && !ferror(in)) {
- size_t n = fread(buf, 1, sizeof(buf), in);
+ size_t n = fread(buf, CLI_ELEM_SIZE, sizeof(buf), in);
if (n == 0) {
break;
}
- if (fwrite(buf, 1, n, out) != n) {
- err = 1;
+ if (fwrite(buf, CLI_ELEM_SIZE, n, out) != n) {
+ err = CLI_TRUE;
break;
}
}
@@ -249,12 +314,12 @@ int cbm_copy_file(const char *src, const char *dst) {
if (err || ferror(in)) {
(void)fclose(in);
(void)fclose(out);
- return -1;
+ return CLI_ERR;
}
(void)fclose(in);
int rc = fclose(out);
- return rc == 0 ? 0 : -1;
+ return rc == 0 ? 0 : CLI_ERR;
}
/* Replace a binary file. Unlinks the old file first (handles read-only and
@@ -262,7 +327,7 @@ int cbm_copy_file(const char *src, const char *dst) {
* platforms, the caller should tell the user to restart after update. */
int cbm_replace_binary(const char *path, const unsigned char *data, int len, int mode) {
if (!path || !data || len <= 0) {
- return -1;
+ return CLI_ERR;
}
/* Remove existing file if it exists. On Unix, unlink works even if the
@@ -274,14 +339,14 @@ int cbm_replace_binary(const char *path, const unsigned char *data, int len, int
if (cbm_unlink(path) != 0) {
#ifdef _WIN32
/* Windows: can't unlink running .exe — rename aside */
- char old_path[1024];
+ char old_path[CLI_BUF_1K];
snprintf(old_path, sizeof(old_path), "%s.old", path);
(void)cbm_unlink(old_path);
if (rename(path, old_path) != 0) {
- return -1;
+ return CLI_ERR;
}
#else
- return -1;
+ return CLI_ERR;
#endif
}
}
@@ -289,24 +354,24 @@ int cbm_replace_binary(const char *path, const unsigned char *data, int len, int
#ifndef _WIN32
int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, (mode_t)mode);
if (fd < 0) {
- return -1;
+ return CLI_ERR;
}
FILE *f = fdopen(fd, "wb");
if (!f) {
close(fd);
- return -1;
+ return CLI_ERR;
}
#else
(void)mode;
FILE *f = fopen(path, "wb");
if (!f) {
- return -1;
+ return CLI_ERR;
}
#endif
- size_t written = fwrite(data, 1, (size_t)len, f);
+ size_t written = fwrite(data, CLI_ELEM_SIZE, (size_t)len, f);
(void)fclose(f);
- return written == (size_t)len ? 0 : -1;
+ return written == (size_t)len ? 0 : CLI_ERR;
}
/* ── Skill file content (embedded) ────────────────────────────── */
@@ -449,30 +514,56 @@ const char *cbm_get_codex_instructions(void) {
/* ── Recursive mkdir (via compat_fs) ──────────────────────────── */
static int mkdirp(const char *path, int mode) {
- return (int)cbm_mkdir_p(path, mode) ? 0 : -1;
+ return (int)cbm_mkdir_p(path, mode) ? 0 : CLI_ERR;
}
/* ── Recursive rmdir ──────────────────────────────────────────── */
-static int rmdir_recursive(const char *path) {
- cbm_dir_t *d = cbm_opendir(path);
+enum { RMDIR_STACK_CAP = CBM_SZ_256 };
+
+/* Scan one directory: push subdirs onto stack, unlink files. */
+static void rmdir_scan_dir(const char *cur, char stack[][CLI_BUF_1K], int *top) {
+ cbm_dir_t *d = cbm_opendir(cur);
if (!d) {
- return -1;
+ return;
}
-
cbm_dirent_t *ent;
while ((ent = cbm_readdir(d)) != NULL) {
- char child[1024];
- snprintf(child, sizeof(child), "%s/%s", path, ent->name);
+ char child[CLI_BUF_1K];
+ snprintf(child, sizeof(child), "%s/%s", cur, ent->name);
struct stat st;
if (stat(child, &st) == 0 && S_ISDIR(st.st_mode)) {
- rmdir_recursive(child);
+ if (*top < RMDIR_STACK_CAP) {
+ snprintf(stack[(*top)++], CLI_BUF_1K, "%s", child);
+ }
} else {
cbm_unlink(child);
}
}
cbm_closedir(d);
- return cbm_rmdir(path);
+}
+
+static int rmdir_recursive(const char *path) {
+ char stack[RMDIR_STACK_CAP][CLI_BUF_1K];
+ int top = 0;
+ snprintf(stack[top++], CLI_BUF_1K, "%s", path);
+
+ /* Post-order: collect all dirs depth-first, then rmdir in reverse. */
+ char dirs[RMDIR_STACK_CAP][CLI_BUF_1K];
+ int dir_count = 0;
+
+ while (top > 0) {
+ char *cur = stack[--top];
+ if (dir_count < RMDIR_STACK_CAP) {
+ snprintf(dirs[dir_count++], CLI_BUF_1K, "%s", cur);
+ }
+ rmdir_scan_dir(cur, stack, &top);
+ }
+ /* Remove dirs in reverse (deepest first). */
+ for (int i = dir_count - CLI_SKIP_ONE; i >= 0; i--) {
+ cbm_rmdir(dirs[i]);
+ }
+ return 0;
}
/* ── Skill management ─────────────────────────────────────────── */
@@ -484,9 +575,9 @@ int cbm_install_skills(const char *skills_dir, bool force, bool dry_run) {
int count = 0;
for (int i = 0; i < CBM_SKILL_COUNT; i++) {
- char skill_path[1024];
+ char skill_path[CLI_BUF_1K];
snprintf(skill_path, sizeof(skill_path), "%s/%s", skills_dir, skills[i].name);
- char file_path[1024];
+ char file_path[CLI_BUF_1K];
snprintf(file_path, sizeof(file_path), "%s/SKILL.md", skill_path);
/* Check if already exists */
@@ -510,7 +601,7 @@ int cbm_install_skills(const char *skills_dir, bool force, bool dry_run) {
if (!f) {
continue;
}
- (void)fwrite(skills[i].content, 1, strlen(skills[i].content), f);
+ (void)fwrite(skills[i].content, CLI_ELEM_SIZE, strlen(skills[i].content), f);
(void)fclose(f);
count++;
}
@@ -524,7 +615,7 @@ int cbm_remove_skills(const char *skills_dir, bool dry_run) {
int count = 0;
for (int i = 0; i < CBM_SKILL_COUNT; i++) {
- char skill_path[1024];
+ char skill_path[CLI_BUF_1K];
snprintf(skill_path, sizeof(skill_path), "%s/%s", skills_dir, skills[i].name);
struct stat st;
if (stat(skill_path, &st) != 0) {
@@ -548,7 +639,7 @@ bool cbm_remove_old_monolithic_skill(const char *skills_dir, bool dry_run) {
return false;
}
- char old_path[1024];
+ char old_path[CLI_BUF_1K];
snprintf(old_path, sizeof(old_path), "%s/codebase-memory-mcp", skills_dir);
struct stat st;
if (stat(old_path, &st) != 0 || !S_ISDIR(st.st_mode)) {
@@ -574,19 +665,22 @@ static yyjson_doc *read_json_file(const char *path) {
long size = ftell(f);
(void)fseek(f, 0, SEEK_SET);
- if (size <= 0 || size > 10L * 1024 * 1024) {
+ if (size <= 0 || size > (long)CLI_MB_10 * CLI_MB_FACTOR) {
(void)fclose(f);
return NULL;
}
- char *buf = malloc((size_t)size + 1);
+ char *buf = malloc((size_t)size + CLI_SKIP_ONE);
if (!buf) {
(void)fclose(f);
return NULL;
}
- size_t nread = fread(buf, 1, (size_t)size, f);
+ size_t nread = fread(buf, CLI_ELEM_SIZE, (size_t)size, f);
(void)fclose(f);
+ if (nread > (size_t)size) {
+ nread = (size_t)size;
+ }
buf[nread] = '\0';
/* Allow JSONC (comments + trailing commas) — Zed settings.json uses this format */
@@ -599,7 +693,7 @@ static yyjson_doc *read_json_file(const char *path) {
/* Write a mutable yyjson document to a file with pretty printing. */
static int write_json_file(const char *path, yyjson_mut_doc *doc) {
/* Ensure parent directory exists */
- char dir[1024];
+ char dir[CLI_BUF_1K];
snprintf(dir, sizeof(dir), "%s", path);
char *last_slash = strrchr(dir, '/');
if (last_slash) {
@@ -611,35 +705,35 @@ static int write_json_file(const char *path, yyjson_mut_doc *doc) {
size_t len;
char *json = yyjson_mut_write(doc, flags, &len);
if (!json) {
- return -1;
+ return CLI_ERR;
}
FILE *f = fopen(path, "w");
if (!f) {
free(json);
- return -1;
+ return CLI_ERR;
}
- size_t written = fwrite(json, 1, len, f);
+ size_t written = fwrite(json, CLI_ELEM_SIZE, len, f);
/* Add trailing newline */
(void)fputc('\n', f);
(void)fclose(f);
free(json);
- return written == len ? 0 : -1;
+ return written == len ? 0 : CLI_ERR;
}
/* ── Editor MCP: Cursor/Windsurf/Gemini (mcpServers key) ──────── */
int cbm_install_editor_mcp(const char *binary_path, const char *config_path) {
if (!binary_path || !config_path) {
- return -1;
+ return CLI_ERR;
}
/* Read existing or start fresh */
yyjson_mut_doc *mdoc = yyjson_mut_doc_new(NULL);
if (!mdoc) {
- return -1;
+ return CLI_ERR;
}
yyjson_doc *doc = read_json_file(config_path);
@@ -652,7 +746,7 @@ int cbm_install_editor_mcp(const char *binary_path, const char *config_path) {
}
if (!root) {
yyjson_mut_doc_free(mdoc);
- return -1;
+ return CLI_ERR;
}
yyjson_mut_doc_set_root(mdoc, root);
@@ -678,12 +772,12 @@ int cbm_install_editor_mcp(const char *binary_path, const char *config_path) {
int cbm_remove_editor_mcp(const char *config_path) {
if (!config_path) {
- return -1;
+ return CLI_ERR;
}
yyjson_doc *doc = read_json_file(config_path);
if (!doc) {
- return -1;
+ return CLI_ERR;
}
yyjson_mut_doc *mdoc = yyjson_mut_doc_new(NULL);
@@ -691,7 +785,7 @@ int cbm_remove_editor_mcp(const char *config_path) {
yyjson_doc_free(doc);
if (!root) {
yyjson_mut_doc_free(mdoc);
- return -1;
+ return CLI_ERR;
}
yyjson_mut_doc_set_root(mdoc, root);
@@ -712,12 +806,12 @@ int cbm_remove_editor_mcp(const char *config_path) {
int cbm_install_vscode_mcp(const char *binary_path, const char *config_path) {
if (!binary_path || !config_path) {
- return -1;
+ return CLI_ERR;
}
yyjson_mut_doc *mdoc = yyjson_mut_doc_new(NULL);
if (!mdoc) {
- return -1;
+ return CLI_ERR;
}
yyjson_doc *doc = read_json_file(config_path);
@@ -730,7 +824,7 @@ int cbm_install_vscode_mcp(const char *binary_path, const char *config_path) {
}
if (!root) {
yyjson_mut_doc_free(mdoc);
- return -1;
+ return CLI_ERR;
}
yyjson_mut_doc_set_root(mdoc, root);
@@ -754,12 +848,12 @@ int cbm_install_vscode_mcp(const char *binary_path, const char *config_path) {
int cbm_remove_vscode_mcp(const char *config_path) {
if (!config_path) {
- return -1;
+ return CLI_ERR;
}
yyjson_doc *doc = read_json_file(config_path);
if (!doc) {
- return -1;
+ return CLI_ERR;
}
yyjson_mut_doc *mdoc = yyjson_mut_doc_new(NULL);
@@ -767,7 +861,7 @@ int cbm_remove_vscode_mcp(const char *config_path) {
yyjson_doc_free(doc);
if (!root) {
yyjson_mut_doc_free(mdoc);
- return -1;
+ return CLI_ERR;
}
yyjson_mut_doc_set_root(mdoc, root);
@@ -788,12 +882,12 @@ int cbm_remove_vscode_mcp(const char *config_path) {
int cbm_install_zed_mcp(const char *binary_path, const char *config_path) {
if (!binary_path || !config_path) {
- return -1;
+ return CLI_ERR;
}
yyjson_mut_doc *mdoc = yyjson_mut_doc_new(NULL);
if (!mdoc) {
- return -1;
+ return CLI_ERR;
}
yyjson_doc *doc = read_json_file(config_path);
@@ -806,7 +900,7 @@ int cbm_install_zed_mcp(const char *binary_path, const char *config_path) {
}
if (!root) {
yyjson_mut_doc_free(mdoc);
- return -1;
+ return CLI_ERR;
}
yyjson_mut_doc_set_root(mdoc, root);
@@ -832,12 +926,12 @@ int cbm_install_zed_mcp(const char *binary_path, const char *config_path) {
int cbm_remove_zed_mcp(const char *config_path) {
if (!config_path) {
- return -1;
+ return CLI_ERR;
}
yyjson_doc *doc = read_json_file(config_path);
if (!doc) {
- return -1;
+ return CLI_ERR;
}
yyjson_mut_doc *mdoc = yyjson_mut_doc_new(NULL);
@@ -845,7 +939,7 @@ int cbm_remove_zed_mcp(const char *config_path) {
yyjson_doc_free(doc);
if (!root) {
yyjson_mut_doc_free(mdoc);
- return -1;
+ return CLI_ERR;
}
yyjson_mut_doc_set_root(mdoc, root);
@@ -876,7 +970,7 @@ cbm_detected_agents_t cbm_detect_agents(const char *home_dir) {
return agents;
}
- char path[1024];
+ char path[CLI_BUF_1K];
snprintf(path, sizeof(path), "%s/.claude", home_dir);
agents.claude_code = dir_exists(path);
@@ -966,18 +1060,21 @@ static char *read_file_str(const char *path, size_t *out_len) {
(void)fseek(f, 0, SEEK_END);
long size = ftell(f);
(void)fseek(f, 0, SEEK_SET);
- if (size < 0 || size > 10L * 1024 * 1024) { /* cap at 10 MB */
+ if (size < 0 || size > (long)CLI_MB_10 * CLI_MB_FACTOR) { /* cap at 10 MB */
(void)fclose(f);
return NULL;
}
- char *buf = malloc((size_t)size + 1);
+ char *buf = malloc((size_t)size + CLI_SKIP_ONE);
if (!buf) {
(void)fclose(f);
return NULL;
}
- size_t nread = fread(buf, 1, (size_t)size, f);
+ size_t nread = fread(buf, CLI_ELEM_SIZE, (size_t)size, f);
(void)fclose(f);
+ if (nread > (size_t)size) {
+ nread = (size_t)size;
+ }
buf[nread] = '\0';
if (out_len) {
*out_len = nread;
@@ -988,7 +1085,7 @@ static char *read_file_str(const char *path, size_t *out_len) {
/* Write string to file, creating parent dirs if needed. */
static int write_file_str(const char *path, const char *content) {
/* Ensure parent directory */
- char dir[1024];
+ char dir[CLI_BUF_1K];
snprintf(dir, sizeof(dir), "%s", path);
char *last_slash = strrchr(dir, '/');
if (last_slash) {
@@ -998,31 +1095,32 @@ static int write_file_str(const char *path, const char *content) {
FILE *f = fopen(path, "w");
if (!f) {
- return -1;
+ return CLI_ERR;
}
size_t len = strlen(content);
- size_t written = fwrite(content, 1, len, f);
+ size_t written = fwrite(content, CLI_ELEM_SIZE, len, f);
(void)fclose(f);
- return written == len ? 0 : -1;
+ return written == len ? 0 : CLI_ERR;
}
int cbm_upsert_instructions(const char *path, const char *content) {
if (!path || !content) {
- return -1;
+ return CLI_ERR;
}
size_t existing_len = 0;
char *existing = read_file_str(path, &existing_len);
/* Build the marker-wrapped section */
- size_t section_len =
- strlen(CMM_MARKER_START) + 1 + strlen(content) + strlen(CMM_MARKER_END) + 1;
- char *section = malloc(section_len + 1);
+ size_t section_len = strlen(CMM_MARKER_START) + CLI_SKIP_ONE + strlen(content) +
+ strlen(CMM_MARKER_END) + CLI_SKIP_ONE;
+ char *section = malloc(section_len + CLI_SKIP_ONE);
if (!section) {
free(existing);
- return -1;
+ return CLI_ERR;
}
- snprintf(section, section_len + 1, "%s\n%s%s\n", CMM_MARKER_START, content, CMM_MARKER_END);
+ snprintf(section, section_len + SKIP_ONE, "%s\n%s%s\n", CMM_MARKER_START, content,
+ CMM_MARKER_END);
if (!existing) {
/* File doesn't exist — create with just the section */
@@ -1047,11 +1145,11 @@ int cbm_upsert_instructions(const char *path, const char *content) {
size_t prefix_len = (size_t)(start - existing);
size_t suffix_len = strlen(end);
size_t new_len = prefix_len + strlen(section) + suffix_len;
- result = malloc(new_len + 1);
+ result = malloc(new_len + CLI_SKIP_ONE);
if (!result) {
free(existing);
free(section);
- return -1;
+ return CLI_ERR;
}
memcpy(result, existing, prefix_len);
memcpy(result + prefix_len, section, strlen(section));
@@ -1059,21 +1157,21 @@ int cbm_upsert_instructions(const char *path, const char *content) {
result[new_len] = '\0';
} else {
/* Append section */
- size_t new_len = existing_len + 1 + strlen(section);
- if (new_len > 10 * 1024 * 1024) { /* 10 MB safety cap */
+ size_t new_len = existing_len + CLI_SKIP_ONE + strlen(section);
+ if (new_len > (size_t)CLI_MB_10 * CLI_MB_FACTOR) { /* 10 MB safety cap */
free(existing);
free(section);
- return -1;
+ return CLI_ERR;
}
- result = malloc(new_len + 1);
+ result = malloc(new_len + CLI_SKIP_ONE);
if (!result) {
free(existing);
free(section);
- return -1;
+ return CLI_ERR;
}
memcpy(result, existing, existing_len);
result[existing_len] = '\n';
- memcpy(result + existing_len + 1, section, strlen(section));
+ memcpy(result + existing_len + SKIP_ONE, section, strlen(section));
result[new_len] = '\0';
}
@@ -1086,13 +1184,13 @@ int cbm_upsert_instructions(const char *path, const char *content) {
int cbm_remove_instructions(const char *path) {
if (!path) {
- return -1;
+ return CLI_ERR;
}
size_t len = 0;
char *content = read_file_str(path, &len);
if (!content) {
- return 1;
+ return CLI_TRUE;
}
char *start = strstr(content, CMM_MARKER_START);
@@ -1100,7 +1198,7 @@ int cbm_remove_instructions(const char *path) {
if (!start || !end) {
free(content);
- return 1; /* not found */
+ return CLI_TRUE; /* not found */
}
end += strlen(CMM_MARKER_END);
@@ -1109,17 +1207,17 @@ int cbm_remove_instructions(const char *path) {
}
/* Also remove a leading newline before the start marker if present */
- if (start > content && *(start - 1) == '\n') {
+ if (start > content && *(start - CLI_SKIP_ONE) == '\n') {
start--;
}
size_t prefix_len = (size_t)(start - content);
size_t suffix_len = strlen(end);
size_t new_len = prefix_len + suffix_len;
- char *result = malloc(new_len + 1);
+ char *result = malloc(new_len + CLI_SKIP_ONE);
if (!result) {
free(content);
- return -1;
+ return CLI_ERR;
}
memcpy(result, content, prefix_len);
memcpy(result + prefix_len, end, suffix_len);
@@ -1137,14 +1235,14 @@ int cbm_remove_instructions(const char *path) {
int cbm_upsert_codex_mcp(const char *binary_path, const char *config_path) {
if (!binary_path || !config_path) {
- return -1;
+ return CLI_ERR;
}
size_t len = 0;
char *content = read_file_str(config_path, &len);
/* Build our TOML section */
- char section[1024];
+ char section[CLI_BUF_1K];
snprintf(section, sizeof(section), "%s\ncommand = \"%s\"\n", CODEX_CMM_SECTION, binary_path);
if (!content) {
@@ -1166,16 +1264,16 @@ int cbm_upsert_codex_mcp(const char *binary_path, const char *config_path) {
size_t prefix_len = (size_t)(existing - content);
const char *suffix = next_section ? next_section : "";
size_t suffix_len = strlen(suffix);
- size_t new_len = prefix_len + strlen(section) + 1 + suffix_len;
- char *result = malloc(new_len + 1);
+ size_t new_len = prefix_len + strlen(section) + CLI_SKIP_ONE + suffix_len;
+ char *result = malloc(new_len + CLI_SKIP_ONE);
if (!result) {
free(content);
- return -1;
+ return CLI_ERR;
}
memcpy(result, content, prefix_len);
memcpy(result + prefix_len, section, strlen(section));
result[prefix_len + strlen(section)] = '\n';
- memcpy(result + prefix_len + strlen(section) + 1, suffix, suffix_len);
+ memcpy(result + prefix_len + strlen(section) + CLI_SKIP_ONE, suffix, suffix_len);
result[new_len] = '\0';
int rc = write_file_str(config_path, result);
@@ -1185,15 +1283,15 @@ int cbm_upsert_codex_mcp(const char *binary_path, const char *config_path) {
}
/* Append our section */
- size_t new_len = len + 1 + strlen(section);
- char *result = malloc(new_len + 1);
+ size_t new_len = len + CLI_SKIP_ONE + strlen(section);
+ char *result = malloc(new_len + CLI_SKIP_ONE);
if (!result) {
free(content);
- return -1;
+ return CLI_ERR;
}
memcpy(result, content, len);
result[len] = '\n';
- memcpy(result + len + 1, section, strlen(section));
+ memcpy(result + len + SKIP_ONE, section, strlen(section));
result[new_len] = '\0';
int rc = write_file_str(config_path, result);
@@ -1204,19 +1302,19 @@ int cbm_upsert_codex_mcp(const char *binary_path, const char *config_path) {
int cbm_remove_codex_mcp(const char *config_path) {
if (!config_path) {
- return -1;
+ return CLI_ERR;
}
size_t len = 0;
char *content = read_file_str(config_path, &len);
if (!content) {
- return 1;
+ return CLI_TRUE;
}
char *existing = strstr(content, CODEX_CMM_SECTION);
if (!existing) {
free(content);
- return 1;
+ return CLI_TRUE;
}
char *section_end = existing + strlen(CODEX_CMM_SECTION);
@@ -1226,7 +1324,7 @@ int cbm_remove_codex_mcp(const char *config_path) {
}
/* Remove leading newline if present */
- if (existing > content && *(existing - 1) == '\n') {
+ if (existing > content && *(existing - CLI_SKIP_ONE) == '\n') {
existing--;
}
@@ -1234,10 +1332,10 @@ int cbm_remove_codex_mcp(const char *config_path) {
const char *suffix = next_section ? next_section : "";
size_t suffix_len = strlen(suffix);
size_t new_len = prefix_len + suffix_len;
- char *result = malloc(new_len + 1);
+ char *result = malloc(new_len + CLI_SKIP_ONE);
if (!result) {
free(content);
- return -1;
+ return CLI_ERR;
}
memcpy(result, content, prefix_len);
memcpy(result + prefix_len, suffix, suffix_len);
@@ -1253,12 +1351,12 @@ int cbm_remove_codex_mcp(const char *config_path) {
int cbm_upsert_opencode_mcp(const char *binary_path, const char *config_path) {
if (!binary_path || !config_path) {
- return -1;
+ return CLI_ERR;
}
yyjson_mut_doc *mdoc = yyjson_mut_doc_new(NULL);
if (!mdoc) {
- return -1;
+ return CLI_ERR;
}
yyjson_doc *doc = read_json_file(config_path);
@@ -1271,7 +1369,7 @@ int cbm_upsert_opencode_mcp(const char *binary_path, const char *config_path) {
}
if (!root) {
yyjson_mut_doc_free(mdoc);
- return -1;
+ return CLI_ERR;
}
yyjson_mut_doc_set_root(mdoc, root);
@@ -1299,12 +1397,12 @@ int cbm_upsert_opencode_mcp(const char *binary_path, const char *config_path) {
int cbm_remove_opencode_mcp(const char *config_path) {
if (!config_path) {
- return -1;
+ return CLI_ERR;
}
yyjson_doc *doc = read_json_file(config_path);
if (!doc) {
- return -1;
+ return CLI_ERR;
}
yyjson_mut_doc *mdoc = yyjson_mut_doc_new(NULL);
@@ -1312,7 +1410,7 @@ int cbm_remove_opencode_mcp(const char *config_path) {
yyjson_doc_free(doc);
if (!root) {
yyjson_mut_doc_free(mdoc);
- return -1;
+ return CLI_ERR;
}
yyjson_mut_doc_set_root(mdoc, root);
@@ -1375,15 +1473,25 @@ static bool is_cmm_hook_entry(yyjson_mut_val *entry, const char *matcher_str) {
}
/* Generic hook upsert for both Claude Code and Gemini CLI */
-static int upsert_hooks_json(const char *settings_path, const char *hook_event,
- const char *matcher_str, const char *command_str) {
+
+typedef struct {
+ const char *settings_path;
+ const char *hook_event;
+ const char *matcher_str;
+ const char *command_str;
+} hooks_upsert_args_t;
+static int upsert_hooks_json(hooks_upsert_args_t args) {
+ const char *settings_path = args.settings_path;
+ const char *hook_event = args.hook_event;
+ const char *matcher_str = args.matcher_str;
+ const char *command_str = args.command_str;
if (!settings_path) {
- return -1;
+ return CLI_ERR;
}
yyjson_mut_doc *mdoc = yyjson_mut_doc_new(NULL);
if (!mdoc) {
- return -1;
+ return CLI_ERR;
}
yyjson_doc *doc = read_json_file(settings_path);
@@ -1396,7 +1504,7 @@ static int upsert_hooks_json(const char *settings_path, const char *hook_event,
}
if (!root) {
yyjson_mut_doc_free(mdoc);
- return -1;
+ return CLI_ERR;
}
yyjson_mut_doc_set_root(mdoc, root);
@@ -1444,15 +1552,23 @@ static int upsert_hooks_json(const char *settings_path, const char *hook_event,
}
/* Generic hook remove for both Claude Code and Gemini CLI */
-static int remove_hooks_json(const char *settings_path, const char *hook_event,
- const char *matcher_str) {
+
+typedef struct {
+ const char *settings_path;
+ const char *hook_event;
+ const char *matcher_str;
+} hooks_remove_args_t;
+static int remove_hooks_json(hooks_remove_args_t args) {
+ const char *settings_path = args.settings_path;
+ const char *hook_event = args.hook_event;
+ const char *matcher_str = args.matcher_str;
if (!settings_path) {
- return -1;
+ return CLI_ERR;
}
yyjson_doc *doc = read_json_file(settings_path);
if (!doc) {
- return -1;
+ return CLI_ERR;
}
yyjson_mut_doc *mdoc = yyjson_mut_doc_new(NULL);
@@ -1460,7 +1576,7 @@ static int remove_hooks_json(const char *settings_path, const char *hook_event,
yyjson_doc_free(doc);
if (!root) {
yyjson_mut_doc_free(mdoc);
- return -1;
+ return CLI_ERR;
}
yyjson_mut_doc_set_root(mdoc, root);
@@ -1492,11 +1608,12 @@ static int remove_hooks_json(const char *settings_path, const char *hook_event,
}
int cbm_upsert_claude_hooks(const char *settings_path) {
- return upsert_hooks_json(settings_path, "PreToolUse", CMM_HOOK_MATCHER, CMM_HOOK_COMMAND);
+ return upsert_hooks_json(
+ (hooks_upsert_args_t){settings_path, "PreToolUse", CMM_HOOK_MATCHER, CMM_HOOK_COMMAND});
}
int cbm_remove_claude_hooks(const char *settings_path) {
- return remove_hooks_json(settings_path, "PreToolUse", CMM_HOOK_MATCHER);
+ return remove_hooks_json((hooks_remove_args_t){settings_path, "PreToolUse", CMM_HOOK_MATCHER});
}
/* Install the code discovery gate script to ~/.claude/hooks/.
@@ -1507,40 +1624,40 @@ static void cbm_install_hook_gate_script(const char *home) {
if (!home) {
return;
}
- char hooks_dir[1024];
+ char hooks_dir[CLI_BUF_1K];
snprintf(hooks_dir, sizeof(hooks_dir), "%s/.claude/hooks", home);
- cbm_mkdir_p(hooks_dir, 0755);
+ cbm_mkdir_p(hooks_dir, CLI_OCTAL_PERM);
- char script_path[1024];
+ char script_path[CLI_BUF_1K];
snprintf(script_path, sizeof(script_path), "%s/cbm-code-discovery-gate", hooks_dir);
FILE *f = fopen(script_path, "w");
if (!f) {
return;
}
- fprintf(f, "#!/bin/bash\n"
- "# Gate hook: nudges Claude toward codebase-memory-mcp for code discovery.\n"
- "# First Grep/Glob/Read/Search per session -> block. Subsequent -> allow.\n"
- "# PPID = Claude Code process PID, unique per session.\n"
- "GATE=/tmp/cbm-code-discovery-gate-$PPID\n"
- "find /tmp -name 'cbm-code-discovery-gate-*' -mtime +1 -delete 2>/dev/null\n"
- "if [ -f \"$GATE\" ]; then\n"
- " exit 0\n"
- "fi\n"
- "touch \"$GATE\"\n"
- "echo 'BLOCKED: For code discovery, use codebase-memory-mcp tools first: "
- "search_graph(name_pattern) to find functions/classes, trace_path() for "
- "call chains, get_code_snippet(qualified_name) to read source. If the graph "
- "is not indexed yet, call index_repository first. Fall back to Grep/Glob/Read "
- "only for text content search. If you need Grep, retry.' >&2\n"
- "exit 2\n");
+ (void)fprintf(f, "#!/bin/bash\n"
+ "# Gate hook: nudges Claude toward codebase-memory-mcp for code discovery.\n"
+ "# First Grep/Glob/Read/Search per session -> block. Subsequent -> allow.\n"
+ "# PPID = Claude Code process PID, unique per session.\n"
+ "GATE=/tmp/cbm-code-discovery-gate-$PPID\n"
+ "find /tmp -name 'cbm-code-discovery-gate-*' -mtime +1 -delete 2>/dev/null\n"
+ "if [ -f \"$GATE\" ]; then\n"
+ " exit 0\n"
+ "fi\n"
+ "touch \"$GATE\"\n"
+ "echo 'BLOCKED: For code discovery, use codebase-memory-mcp tools first: "
+ "search_graph(name_pattern) to find functions/classes, trace_path() for "
+ "call chains, get_code_snippet(qualified_name) to read source. If the graph "
+ "is not indexed yet, call index_repository first. Fall back to Grep/Glob/Read "
+ "only for text content search. If you need Grep, retry.' >&2\n"
+ "exit 2\n");
/* fchmod before close to avoid TOCTOU race (CodeQL cpp/toctou-race-condition) */
#ifndef _WIN32
- fchmod(fileno(f), 0755);
+ fchmod(fileno(f), CLI_OCTAL_PERM);
#endif
- fclose(f);
+ (void)fclose(f);
#ifdef _WIN32
- chmod(script_path, 0755);
+ chmod(script_path, CLI_OCTAL_PERM);
#endif
}
@@ -1551,49 +1668,49 @@ static void cbm_install_session_reminder_script(const char *home) {
if (!home) {
return;
}
- char hooks_dir[1024];
+ char hooks_dir[CLI_BUF_1K];
snprintf(hooks_dir, sizeof(hooks_dir), "%s/.claude/hooks", home);
- cbm_mkdir_p(hooks_dir, 0755);
+ cbm_mkdir_p(hooks_dir, CLI_OCTAL_PERM);
- char script_path[1024];
+ char script_path[CLI_BUF_1K];
snprintf(script_path, sizeof(script_path), "%s/cbm-session-reminder", hooks_dir);
FILE *f = fopen(script_path, "w");
if (!f) {
return;
}
- fprintf(f,
- "#!/bin/bash\n"
- "# SessionStart hook: remind agent to use codebase-memory-mcp tools.\n"
- "# Installed by codebase-memory-mcp. Fires on startup/resume/clear/compact.\n"
- "cat << 'REMINDER'\n"
- "CRITICAL - Code Discovery Protocol:\n"
- "1. ALWAYS use codebase-memory-mcp tools FIRST for ANY code exploration:\n"
- " - search_graph(name_pattern/label/qn_pattern) to find functions/classes/routes\n"
- " - trace_path(function_name, mode=calls|data_flow|cross_service) for call chains\n"
- " - get_code_snippet(qualified_name) to read source (NOT Read/cat)\n"
- " - query_graph(query) for complex Cypher patterns\n"
- " - get_architecture(aspects) for project structure\n"
- " - search_code(pattern) for text search (graph-augmented grep)\n"
- "2. Fall back to Grep/Glob/Read ONLY for text content, config values, non-code files.\n"
- "3. If a project is not indexed yet, run index_repository FIRST.\n"
- "REMINDER\n");
+ (void)fprintf(
+ f, "#!/bin/bash\n"
+ "# SessionStart hook: remind agent to use codebase-memory-mcp tools.\n"
+ "# Installed by codebase-memory-mcp. Fires on startup/resume/clear/compact.\n"
+ "cat << 'REMINDER'\n"
+ "CRITICAL - Code Discovery Protocol:\n"
+ "1. ALWAYS use codebase-memory-mcp tools FIRST for ANY code exploration:\n"
+ " - search_graph(name_pattern/label/qn_pattern) to find functions/classes/routes\n"
+ " - trace_path(function_name, mode=calls|data_flow|cross_service) for call chains\n"
+ " - get_code_snippet(qualified_name) to read source (NOT Read/cat)\n"
+ " - query_graph(query) for complex Cypher patterns\n"
+ " - get_architecture(aspects) for project structure\n"
+ " - search_code(pattern) for text search (graph-augmented grep)\n"
+ "2. Fall back to Grep/Glob/Read ONLY for text content, config values, non-code files.\n"
+ "3. If a project is not indexed yet, run index_repository FIRST.\n"
+ "REMINDER\n");
#ifndef _WIN32
- fchmod(fileno(f), 0755);
+ fchmod(fileno(f), CLI_OCTAL_PERM);
#endif
- fclose(f);
+ (void)fclose(f);
#ifdef _WIN32
- chmod(script_path, 0755);
+ chmod(script_path, CLI_OCTAL_PERM);
#endif
}
static int cbm_upsert_session_hooks(const char *settings_path) {
static const char *matchers[] = {"startup", "resume", "clear", "compact"};
int rc = 0;
- for (int i = 0; i < 4; i++) {
- if (upsert_hooks_json(settings_path, "SessionStart", matchers[i], CMM_SESSION_COMMAND) !=
- 0) {
- rc = -1;
+ for (int i = 0; i < NUM_DIRS; i++) {
+ if (upsert_hooks_json((hooks_upsert_args_t){settings_path, "SessionStart", matchers[i],
+ CMM_SESSION_COMMAND}) != 0) {
+ rc = CLI_ERR;
}
}
return rc;
@@ -1602,9 +1719,10 @@ static int cbm_upsert_session_hooks(const char *settings_path) {
static int cbm_remove_session_hooks(const char *settings_path) {
static const char *matchers[] = {"startup", "resume", "clear", "compact"};
int rc = 0;
- for (int i = 0; i < 4; i++) {
- if (remove_hooks_json(settings_path, "SessionStart", matchers[i]) != 0) {
- rc = -1;
+ for (int i = 0; i < NUM_DIRS; i++) {
+ if (remove_hooks_json((hooks_remove_args_t){settings_path, "SessionStart", matchers[i]}) !=
+ 0) {
+ rc = CLI_ERR;
}
}
return rc;
@@ -1616,31 +1734,33 @@ static int cbm_remove_session_hooks(const char *settings_path) {
"get_code_snippet over grep/file search for code discovery.' >&2"
int cbm_upsert_gemini_hooks(const char *settings_path) {
- return upsert_hooks_json(settings_path, "BeforeTool", GEMINI_HOOK_MATCHER, GEMINI_HOOK_COMMAND);
+ return upsert_hooks_json((hooks_upsert_args_t){settings_path, "BeforeTool", GEMINI_HOOK_MATCHER,
+ GEMINI_HOOK_COMMAND});
}
int cbm_remove_gemini_hooks(const char *settings_path) {
- return remove_hooks_json(settings_path, "BeforeTool", GEMINI_HOOK_MATCHER);
+ return remove_hooks_json(
+ (hooks_remove_args_t){settings_path, "BeforeTool", GEMINI_HOOK_MATCHER});
}
/* ── PATH management ──────────────────────────────────────────── */
int cbm_ensure_path(const char *bin_dir, const char *rc_file, bool dry_run) {
if (!bin_dir || !rc_file) {
- return -1;
+ return CLI_ERR;
}
- char line[1024];
+ char line[CLI_BUF_1K];
snprintf(line, sizeof(line), "export PATH=\"%s:$PATH\"", bin_dir);
/* Check if already present in rc file */
FILE *f = fopen(rc_file, "r");
if (f) {
- char buf[2048];
+ char buf[CLI_BUF_2K];
while (fgets(buf, sizeof(buf), f)) {
if (strstr(buf, line)) {
(void)fclose(f);
- return 1; /* already present */
+ return CLI_TRUE; /* already present */
}
}
(void)fclose(f);
@@ -1652,7 +1772,7 @@ int cbm_ensure_path(const char *bin_dir, const char *rc_file, bool dry_run) {
f = fopen(rc_file, "a");
if (!f) {
- return -1;
+ return CLI_ERR;
}
(void)fprintf(f, "\n# Added by codebase-memory-mcp install\n%s\n", line);
@@ -1666,16 +1786,18 @@ int cbm_ensure_path(const char *bin_dir, const char *rc_file, bool dry_run) {
* *out_total receives the decompressed size. Caller must free the result. */
static unsigned char *gzip_decompress(const unsigned char *data, int data_len, size_t *out_total) {
z_stream strm = {0};
- strm.next_in = (unsigned char *)(uintptr_t)data;
+ unsigned char *mutable_data;
+ memcpy(&mutable_data, &data, sizeof(data));
+ strm.next_in = mutable_data;
strm.avail_in = (unsigned int)data_len;
if (inflateInit2(&strm, 16 + MAX_WBITS) != Z_OK) {
return NULL;
}
- size_t buf_cap = (size_t)data_len * 10;
- if (buf_cap < 4096) {
- buf_cap = 4096;
+ size_t buf_cap = (size_t)data_len * DECOMP_FACTOR;
+ if (buf_cap < CLI_BUF_4K) {
+ buf_cap = CLI_BUF_4K;
}
if (buf_cap > DECOMPRESS_MAX_BYTES) {
buf_cap = DECOMPRESS_MAX_BYTES;
@@ -1690,7 +1812,7 @@ static unsigned char *gzip_decompress(const unsigned char *data, int data_len, s
int ret;
do {
if (total >= buf_cap) {
- size_t new_cap = buf_cap * 2;
+ size_t new_cap = buf_cap * GROWTH_FACTOR;
if (new_cap > DECOMPRESS_MAX_BYTES) {
free(decompressed);
inflateEnd(&strm);
@@ -1723,7 +1845,7 @@ static unsigned char *gzip_decompress(const unsigned char *data, int data_len, s
/* Check if a tar block is all zeros (end of archive). */
static bool is_tar_end_of_archive(const unsigned char *hdr) {
- for (int i = 0; i < 512; i++) {
+ for (int i = 0; i < TAR_BLOCK_SIZE; i++) {
if (hdr[i] != 0) {
return false;
}
@@ -1741,7 +1863,7 @@ static unsigned char *tar_try_extract_binary(const unsigned char *hdr, char type
return NULL;
}
const char *basename = strrchr(name, '/');
- basename = basename ? basename + 1 : name;
+ basename = basename ? basename + CLI_SKIP_ONE : name;
if (strncmp(basename, TAR_BINARY_NAME, TAR_BINARY_NAME_LEN) != 0) {
return NULL;
}
@@ -1771,7 +1893,7 @@ unsigned char *cbm_extract_binary_from_targz(const unsigned char *data, int data
/* Parse tar: find entry starting with "codebase-memory-mcp" */
size_t pos = 0;
- while (pos + 512 <= total) {
+ while (pos + TAR_BLOCK_SIZE <= total) {
const unsigned char *hdr = decompressed + pos;
if (is_tar_end_of_archive(hdr)) {
@@ -1779,12 +1901,12 @@ unsigned char *cbm_extract_binary_from_targz(const unsigned char *data, int data
}
char name[TAR_NAME_LEN] = {0};
- memcpy(name, hdr, TAR_NAME_LEN - 1);
+ memcpy(name, hdr, TAR_NAME_LEN - SKIP_ONE);
char size_str[TAR_SIZE_LEN] = {0};
- memcpy(size_str, hdr + TAR_SIZE_OFFSET, TAR_SIZE_LEN - 1);
- long file_size = strtol(size_str, NULL, 8);
+ memcpy(size_str, hdr + TAR_SIZE_OFFSET, TAR_SIZE_LEN - SKIP_ONE);
+ long file_size = strtol(size_str, NULL, OCTAL_BASE);
char typeflag = (char)hdr[TAR_TYPE_OFFSET];
- pos += 512;
+ pos += TAR_BLOCK_SIZE;
unsigned char *found = tar_try_extract_binary(hdr, typeflag, name, decompressed, pos,
file_size, total, out_len);
@@ -1794,7 +1916,7 @@ unsigned char *cbm_extract_binary_from_targz(const unsigned char *data, int data
}
size_t blocks = ((size_t)file_size + TAR_BLOCK_MASK) / TAR_BLOCK_SIZE;
- pos += blocks * 512;
+ pos += blocks * TAR_BLOCK_SIZE;
}
free(decompressed);
@@ -1873,32 +1995,40 @@ unsigned char *cbm_extract_binary_from_zip(const unsigned char *data, int data_l
int pos = 0;
while (pos + ZIP_HDR_SZ <= data_len) {
- if (data[pos] != ZIP_SIG_0 || data[pos + 1] != ZIP_SIG_1 || data[pos + 2] != ZIP_SIG_2 ||
- data[pos + 3] != ZIP_SIG_3) {
+ if (data[pos] != ZIP_SIG_0 || data[pos + CLI_SKIP_ONE] != ZIP_SIG_1 ||
+ data[pos + CLI_PAIR_LEN] != ZIP_SIG_2 || data[pos + CLI_JSON_INDENT] != ZIP_SIG_3) {
break;
}
- uint16_t method =
- (uint16_t)(data[pos + ZIP_OFF_METHOD] | (data[pos + ZIP_OFF_METHOD + 1] << 8));
+ uint16_t method = (uint16_t)(data[pos + ZIP_OFF_METHOD] |
+ (data[pos + ZIP_OFF_METHOD + CLI_SKIP_ONE] << BYTE_SHIFT));
uint32_t comp_size =
- (uint32_t)(data[pos + ZIP_OFF_COMP] | (data[pos + ZIP_OFF_COMP + 1] << 8) |
- (data[pos + ZIP_OFF_COMP + 2] << 16) | (data[pos + ZIP_OFF_COMP + 3] << 24));
+ (uint32_t)(data[pos + ZIP_OFF_COMP] |
+ (data[pos + ZIP_OFF_COMP + CLI_SKIP_ONE] << BYTE_SHIFT) |
+ (data[pos + ZIP_OFF_COMP + CLI_PAIR_LEN] << (BYTE_SHIFT * CLI_PAIR_LEN)) |
+ (data[pos + ZIP_OFF_COMP + CLI_JSON_INDENT]
+ << (BYTE_SHIFT * CLI_JSON_INDENT)));
uint32_t uncomp_size =
- (uint32_t)(data[pos + ZIP_OFF_UNCOMP] | (data[pos + ZIP_OFF_UNCOMP + 1] << 8) |
- (data[pos + ZIP_OFF_UNCOMP + 2] << 16) |
- (data[pos + ZIP_OFF_UNCOMP + 3] << 24));
- uint16_t name_len =
- (uint16_t)(data[pos + ZIP_OFF_NAMELEN] | (data[pos + ZIP_OFF_NAMELEN + 1] << 8));
+ (uint32_t)(data[pos + ZIP_OFF_UNCOMP] |
+ (data[pos + ZIP_OFF_UNCOMP + CLI_SKIP_ONE] << BYTE_SHIFT) |
+ (data[pos + ZIP_OFF_UNCOMP + CLI_PAIR_LEN] << (BYTE_SHIFT * CLI_PAIR_LEN)) |
+ (data[pos + ZIP_OFF_UNCOMP + CLI_JSON_INDENT]
+ << (BYTE_SHIFT * CLI_JSON_INDENT)));
+ uint16_t name_len = (uint16_t)(data[pos + ZIP_OFF_NAMELEN] |
+ (data[pos + ZIP_OFF_NAMELEN + CLI_SKIP_ONE] << BYTE_SHIFT));
uint16_t extra_len =
- (uint16_t)(data[pos + ZIP_OFF_EXTRALEN] | (data[pos + ZIP_OFF_EXTRALEN + 1] << 8));
+ (uint16_t)(data[pos + ZIP_OFF_EXTRALEN] |
+ (data[pos + ZIP_OFF_EXTRALEN + CLI_SKIP_ONE] << BYTE_SHIFT));
int header_end = pos + ZIP_HDR_SZ + name_len + extra_len;
if (header_end + (int)comp_size > data_len) {
break;
}
- char fname[512] = {0};
- int fn_copy = name_len < (int)sizeof(fname) - 1 ? name_len : (int)sizeof(fname) - 1;
+ char fname[CLI_BUF_512] = {0};
+ int fn_copy = name_len < (int)sizeof(fname) - CLI_SKIP_ONE
+ ? name_len
+ : (int)sizeof(fname) - CLI_SKIP_ONE;
memcpy(fname, data + pos + 30, (size_t)fn_copy);
fname[fn_copy] = '\0';
@@ -1908,7 +2038,7 @@ unsigned char *cbm_extract_binary_from_zip(const unsigned char *data, int data_l
}
const char *basename = strrchr(fname, '/');
- basename = basename ? basename + 1 : fname;
+ basename = basename ? basename + CLI_SKIP_ONE : fname;
if (strcmp(basename, "codebase-memory-mcp") == 0 ||
strcmp(basename, "codebase-memory-mcp.exe") == 0) {
@@ -1924,7 +2054,7 @@ unsigned char *cbm_extract_binary_from_zip(const unsigned char *data, int data_l
/* ── Index management ─────────────────────────────────────────── */
static const char *get_cache_dir(const char *home_dir) {
- static char buf[1024];
+ static char buf[CLI_BUF_1K];
if (!home_dir) {
home_dir = cbm_get_home_dir();
}
@@ -1950,7 +2080,7 @@ int cbm_list_indexes(const char *home_dir) {
cbm_dirent_t *ent;
while ((ent = cbm_readdir(d)) != NULL) {
size_t len = strlen(ent->name);
- if (len > 3 && strcmp(ent->name + len - 3, ".db") == 0) {
+ if (len > DB_EXT_LEN && strcmp(ent->name + len - DB_EXT_LEN, ".db") == 0) {
printf(" %s/%s\n", cache_dir, ent->name);
count++;
}
@@ -1974,11 +2104,11 @@ int cbm_remove_indexes(const char *home_dir) {
cbm_dirent_t *ent;
while ((ent = cbm_readdir(d)) != NULL) {
size_t len = strlen(ent->name);
- if (len > 3 && strcmp(ent->name + len - 3, ".db") == 0) {
- char path[1024];
+ if (len > DB_EXT_LEN && strcmp(ent->name + len - DB_EXT_LEN, ".db") == 0) {
+ char path[CLI_BUF_1K];
snprintf(path, sizeof(path), "%s/%s", cache_dir, ent->name);
/* Also remove .db.tmp if present */
- char tmp_path[1040];
+ char tmp_path[CLI_FIELD_1040];
snprintf(tmp_path, sizeof(tmp_path), "%s.tmp", path);
cbm_unlink(tmp_path);
if (cbm_unlink(path) == 0) {
@@ -1996,7 +2126,7 @@ int cbm_remove_indexes(const char *home_dir) {
struct cbm_config {
sqlite3 *db;
- char get_buf[4096]; /* static buffer for cbm_config_get return values */
+ char get_buf[CLI_BUF_4K]; /* static buffer for cbm_config_get return values */
};
cbm_config_t *cbm_config_open(const char *cache_dir) {
@@ -2004,7 +2134,7 @@ cbm_config_t *cbm_config_open(const char *cache_dir) {
return NULL;
}
- char dbpath[1024];
+ char dbpath[CLI_BUF_1K];
snprintf(dbpath, sizeof(dbpath), "%s/_config.db", cache_dir);
/* Ensure directory exists */
@@ -2027,7 +2157,7 @@ cbm_config_t *cbm_config_open(const char *cache_dir) {
return NULL;
}
- cbm_config_t *cfg = calloc(1, sizeof(*cfg));
+ cbm_config_t *cfg = calloc(CBM_ALLOC_ONE, sizeof(*cfg));
if (!cfg) {
sqlite3_close(db);
return NULL;
@@ -2052,11 +2182,11 @@ const char *cbm_config_get(cbm_config_t *cfg, const char *key, const char *defau
}
sqlite3_stmt *stmt = NULL;
- if (sqlite3_prepare_v2(cfg->db, "SELECT value FROM config WHERE key = ?", -1, &stmt, NULL) !=
- SQLITE_OK) {
+ if (sqlite3_prepare_v2(cfg->db, "SELECT value FROM config WHERE key = ?", SQL_NUL_TERM, &stmt,
+ NULL) != SQLITE_OK) {
return default_val;
}
- sqlite3_bind_text(stmt, 1, key, -1, SQLITE_TRANSIENT);
+ sqlite3_bind_text(stmt, SQL_PARAM_1, key, SQL_NUL_TERM, cbm_sqlite_transient);
const char *result = default_val;
if (sqlite3_step(stmt) == SQLITE_ROW) {
@@ -2090,7 +2220,7 @@ int cbm_config_get_int(cbm_config_t *cfg, const char *key, int default_val) {
return default_val;
}
char *endptr;
- long v = strtol(val, &endptr, 10);
+ long v = strtol(val, &endptr, CLI_STRTOL_BASE);
if (endptr == val || *endptr != '\0') {
return default_val;
}
@@ -2099,35 +2229,35 @@ int cbm_config_get_int(cbm_config_t *cfg, const char *key, int default_val) {
int cbm_config_set(cbm_config_t *cfg, const char *key, const char *value) {
if (!cfg || !key || !value) {
- return -1;
+ return CLI_ERR;
}
sqlite3_stmt *stmt = NULL;
- if (sqlite3_prepare_v2(cfg->db, "INSERT OR REPLACE INTO config (key, value) VALUES (?, ?)", -1,
- &stmt, NULL) != SQLITE_OK) {
- return -1;
+ if (sqlite3_prepare_v2(cfg->db, "INSERT OR REPLACE INTO config (key, value) VALUES (?, ?)",
+ SQL_NUL_TERM, &stmt, NULL) != SQLITE_OK) {
+ return CLI_ERR;
}
- sqlite3_bind_text(stmt, 1, key, -1, SQLITE_TRANSIENT);
- sqlite3_bind_text(stmt, 2, value, -1, SQLITE_TRANSIENT);
+ sqlite3_bind_text(stmt, SQL_PARAM_1, key, SQL_NUL_TERM, cbm_sqlite_transient);
+ sqlite3_bind_text(stmt, SQL_PARAM_2, value, SQL_NUL_TERM, cbm_sqlite_transient);
- int rc = sqlite3_step(stmt) == SQLITE_DONE ? 0 : -1;
+ int rc = sqlite3_step(stmt) == SQLITE_DONE ? 0 : CLI_ERR;
sqlite3_finalize(stmt);
return rc;
}
int cbm_config_delete(cbm_config_t *cfg, const char *key) {
if (!cfg || !key) {
- return -1;
+ return CLI_ERR;
}
sqlite3_stmt *stmt = NULL;
- if (sqlite3_prepare_v2(cfg->db, "DELETE FROM config WHERE key = ?", -1, &stmt, NULL) !=
- SQLITE_OK) {
- return -1;
+ if (sqlite3_prepare_v2(cfg->db, "DELETE FROM config WHERE key = ?", SQL_NUL_TERM, &stmt,
+ NULL) != SQLITE_OK) {
+ return CLI_ERR;
}
- sqlite3_bind_text(stmt, 1, key, -1, SQLITE_TRANSIENT);
+ sqlite3_bind_text(stmt, SQL_PARAM_1, key, SQL_NUL_TERM, cbm_sqlite_transient);
- int rc = sqlite3_step(stmt) == SQLITE_DONE ? 0 : -1;
+ int rc = sqlite3_step(stmt) == SQLITE_DONE ? 0 : CLI_ERR;
sqlite3_finalize(stmt);
return rc;
}
@@ -2152,17 +2282,17 @@ int cbm_cmd_config(int argc, char **argv) {
const char *home = cbm_get_home_dir();
if (!home) {
- fprintf(stderr, "error: HOME not set (use USERPROFILE on Windows)\n");
- return 1;
+ (void)fprintf(stderr, "error: HOME not set (use USERPROFILE on Windows)\n");
+ return CLI_TRUE;
}
- char cache_dir[1024];
+ char cache_dir[CLI_BUF_1K];
snprintf(cache_dir, sizeof(cache_dir), "%s/.cache/codebase-memory-mcp", home);
cbm_config_t *cfg = cbm_config_open(cache_dir);
if (!cfg) {
- fprintf(stderr, "error: cannot open config database\n");
- return 1;
+ (void)fprintf(stderr, "error: cannot open config database\n");
+ return CLI_TRUE;
}
int rc = 0;
@@ -2173,35 +2303,35 @@ int cbm_cmd_config(int argc, char **argv) {
printf(" %-25s = %-10s\n", CBM_CONFIG_AUTO_INDEX_LIMIT,
cbm_config_get(cfg, CBM_CONFIG_AUTO_INDEX_LIMIT, "50000"));
} else if (strcmp(argv[0], "get") == 0) {
- if (argc < 2) {
- fprintf(stderr, "Usage: config get <key>\n");
- rc = 1;
+ if (argc < MIN_ARGC_GET) {
+ (void)fprintf(stderr, "Usage: config get <key>\n");
+ rc = CLI_TRUE;
} else {
- printf("%s\n", cbm_config_get(cfg, argv[1], ""));
+ printf("%s\n", cbm_config_get(cfg, argv[CLI_SKIP_ONE], ""));
}
} else if (strcmp(argv[0], "set") == 0) {
- if (argc < 3) {
- fprintf(stderr, "Usage: config set <key> <value>\n");
- rc = 1;
+ if (argc < MIN_ARGC_CMD) {
+ (void)fprintf(stderr, "Usage: config set <key> <value>\n");
+ rc = CLI_TRUE;
} else {
- if (cbm_config_set(cfg, argv[1], argv[2]) == 0) {
- printf("%s = %s\n", argv[1], argv[2]);
+ if (cbm_config_set(cfg, argv[CLI_SKIP_ONE], argv[CLI_PAIR_LEN]) == 0) {
+ printf("%s = %s\n", argv[CLI_SKIP_ONE], argv[CLI_PAIR_LEN]);
} else {
- fprintf(stderr, "error: failed to set %s\n", argv[1]);
- rc = 1;
+ (void)fprintf(stderr, "error: failed to set %s\n", argv[CLI_SKIP_ONE]);
+ rc = CLI_TRUE;
}
}
} else if (strcmp(argv[0], "reset") == 0) {
- if (argc < 2) {
- fprintf(stderr, "Usage: config reset <key>\n");
- rc = 1;
+ if (argc < MIN_ARGC_GET) {
+ (void)fprintf(stderr, "Usage: config reset <key>\n");
+ rc = CLI_TRUE;
} else {
- cbm_config_delete(cfg, argv[1]);
- printf("%s reset to default\n", argv[1]);
+ cbm_config_delete(cfg, argv[CLI_SKIP_ONE]);
+ printf("%s reset to default\n", argv[CLI_SKIP_ONE]);
}
} else {
- fprintf(stderr, "Unknown config command: %s\n", argv[0]);
- rc = 1;
+ (void)fprintf(stderr, "Unknown config command: %s\n", argv[0]);
+ rc = CLI_TRUE;
}
cbm_config_close(cfg);
@@ -2216,20 +2346,20 @@ static int g_auto_answer = 0;
static void parse_auto_answer(int argc, char **argv) {
for (int i = 0; i < argc; i++) {
if (strcmp(argv[i], "-y") == 0 || strcmp(argv[i], "--yes") == 0) {
- g_auto_answer = 1;
+ g_auto_answer = AUTO_YES;
}
if (strcmp(argv[i], "-n") == 0 || strcmp(argv[i], "--no") == 0) {
- g_auto_answer = -1;
+ g_auto_answer = AUTO_NO;
}
}
}
static bool prompt_yn(const char *question) {
- if (g_auto_answer == 1) {
+ if (g_auto_answer == AUTO_YES) {
printf("%s (y/n): y (auto)\n", question);
return true;
}
- if (g_auto_answer == -1) {
+ if (g_auto_answer == AUTO_NO) {
printf("%s (y/n): n (auto)\n", question);
return false;
}
@@ -2237,7 +2367,8 @@ static bool prompt_yn(const char *question) {
/* Non-interactive stdin: default to "no" to avoid hanging */
#ifndef _WIN32
if (!isatty(fileno(stdin))) {
- fprintf(stderr, "error: interactive prompt requires a terminal. Use -y or -n flags.\n");
+ (void)fprintf(stderr,
+ "error: interactive prompt requires a terminal. Use -y or -n flags.\n");
return false;
}
#endif
@@ -2245,40 +2376,40 @@ static bool prompt_yn(const char *question) {
printf("%s (y/n): ", question);
(void)fflush(stdout);
- char buf[16];
+ char buf[CLI_BUF_16];
if (!fgets(buf, sizeof(buf), stdin)) {
return false;
}
return (buf[0] == 'y' || buf[0] == 'Y') ? true : false;
}
-/* ── SHA-256 checksum verification ─────────────────────────────── */
+/* ── SHA-CBM_SZ_256 checksum verification ─────────────────────────────── */
-/* SHA-256 hex digest: 64 hex chars + NUL */
-#define SHA256_HEX_LEN 64
-#define SHA256_BUF_SIZE (SHA256_HEX_LEN + 1)
-/* Minimum line length in checksums.txt: 64 hex + 2 spaces + 1 char filename */
+/* SHA-CBM_SZ_256 hex digest: CBM_SZ_64 hex chars + NUL */
+#define SHA256_HEX_LEN CBM_SZ_64
+#define SHA256_BUF_SIZE (SHA256_HEX_LEN + CLI_SKIP_ONE)
+/* Minimum line length in checksums.txt: CBM_SZ_64 hex + 2 spaces + 1 char filename */
#define CHECKSUM_LINE_MIN (SHA256_HEX_LEN + 2)
-/* Compute SHA-256 of a file using platform tools (sha256sum/shasum).
- * Writes 64-char hex digest + NUL to out. Returns 0 on success. */
+/* Compute SHA-CBM_SZ_256 of a file using platform tools (sha256sum/shasum).
+ * Writes CBM_SZ_64-char hex digest + NUL to out. Returns 0 on success. */
static int sha256_file(const char *path, char *out, size_t out_size) {
if (out_size < SHA256_BUF_SIZE) {
- return -1;
+ return CLI_ERR;
}
- char cmd[1024];
+ char cmd[CLI_BUF_1K];
#ifdef __APPLE__
- snprintf(cmd, sizeof(cmd), "shasum -a 256 '%s' 2>/dev/null", path);
+ snprintf(cmd, sizeof(cmd), "shasum -a CBM_SZ_256 '%s' 2>/dev/null", path);
#else
snprintf(cmd, sizeof(cmd), "sha256sum '%s' 2>/dev/null", path);
#endif
FILE *fp = cbm_popen(cmd, "r");
if (!fp) {
- return -1;
+ return CLI_ERR;
}
- char line[256];
+ char line[CLI_BUF_256];
if (fgets(line, sizeof(line), fp)) {
- /* Output format: <64-char hash> <filename> */
+ /* Output format: <CBM_SZ_64-char hash> <filename> */
char *space = strchr(line, ' ');
if (space && space - line == SHA256_HEX_LEN) {
memcpy(out, line, SHA256_HEX_LEN);
@@ -2288,7 +2419,7 @@ static int sha256_file(const char *path, char *out, size_t out_size) {
}
}
cbm_pclose(fp);
- return -1;
+ return CLI_ERR;
}
/* ── Download helper (shell-free curl via exec) ───────────────── */
@@ -2323,7 +2454,7 @@ static int cbm_kill_other_instances(void) {
#ifdef _WIN32
/* taskkill /IM kills ALL matching processes INCLUDING self.
* Use /FI filter to exclude our own PID. */
- char pid_filter[64];
+ char pid_filter[CBM_SZ_64];
snprintf(pid_filter, sizeof(pid_filter), "PID ne %lu", (unsigned long)GetCurrentProcessId());
const char *argv[] = {"taskkill", "/F", "/FI", "IMAGENAME eq codebase-memory-mcp.exe",
"/FI", pid_filter, NULL};
@@ -2336,9 +2467,9 @@ static int cbm_kill_other_instances(void) {
if (!fp) {
return 0;
}
- char line[32];
+ char line[CLI_BUF_32];
while (fgets(line, sizeof(line), fp)) {
- pid_t pid = (pid_t)strtol(line, NULL, 10);
+ pid_t pid = (pid_t)strtol(line, NULL, CLI_STRTOL_BASE);
if (pid > 0 && pid != self) {
if (kill(pid, SIGTERM) == 0) {
killed++;
@@ -2353,11 +2484,13 @@ static int cbm_kill_other_instances(void) {
/* Download checksums.txt and verify the archive integrity.
* Returns: 0 = verified OK, 1 = mismatch (FAIL), -1 = could not verify (warning). */
static int verify_download_checksum(const char *archive_path, const char *archive_name) {
- char checksum_file[256];
+ char checksum_file[CLI_BUF_256];
snprintf(checksum_file, sizeof(checksum_file), "%s/cbm-checksums.txt", cbm_tmpdir());
- const char *dl_base = getenv("CBM_DOWNLOAD_URL");
- char checksum_url[512];
+ char dl_base_buf[CLI_BUF_512];
+ const char *dl_base =
+ cbm_safe_getenv("CBM_DOWNLOAD_URL", dl_base_buf, sizeof(dl_base_buf), NULL);
+ char checksum_url[CLI_BUF_512];
if (dl_base && dl_base[0]) {
snprintf(checksum_url, sizeof(checksum_url), "%s/checksums.txt", dl_base);
} else {
@@ -2367,45 +2500,46 @@ static int verify_download_checksum(const char *archive_path, const char *archiv
}
int rc = cbm_download_to_file_quiet(checksum_url, checksum_file);
if (rc != 0) {
- fprintf(stderr, "warning: could not download checksums.txt — skipping verification\n");
+ (void)fprintf(stderr,
+ "warning: could not download checksums.txt — skipping verification\n");
cbm_unlink(checksum_file);
- return -1;
+ return CLI_ERR;
}
FILE *fp = fopen(checksum_file, "r");
cbm_unlink(checksum_file);
if (!fp) {
- return -1;
+ return CLI_ERR;
}
char expected[SHA256_BUF_SIZE] = {0};
- char line[512];
+ char line[CLI_BUF_512];
while (fgets(line, sizeof(line), fp)) {
- /* Format: <64-char sha256> <filename>\n */
+ /* Format: <CBM_SZ_64-char sha256> <filename>\n */
if (strlen(line) > CHECKSUM_LINE_MIN && strstr(line, archive_name)) {
memcpy(expected, line, SHA256_HEX_LEN);
expected[SHA256_HEX_LEN] = '\0';
break;
}
}
- fclose(fp);
+ (void)fclose(fp);
if (expected[0] == '\0') {
- fprintf(stderr, "warning: %s not found in checksums.txt\n", archive_name);
- return -1;
+ (void)fprintf(stderr, "warning: %s not found in checksums.txt\n", archive_name);
+ return CLI_ERR;
}
char actual[SHA256_BUF_SIZE] = {0};
if (sha256_file(archive_path, actual, sizeof(actual)) != 0) {
- fprintf(stderr, "warning: sha256sum/shasum not available — skipping verification\n");
- return -1;
+ (void)fprintf(stderr, "warning: sha256sum/shasum not available — skipping verification\n");
+ return CLI_ERR;
}
if (strcmp(expected, actual) != 0) {
- fprintf(stderr, "error: CHECKSUM MISMATCH — downloaded binary may be compromised!\n");
- fprintf(stderr, " expected: %s\n", expected);
- fprintf(stderr, " actual: %s\n", actual);
- return 1;
+ (void)fprintf(stderr, "error: CHECKSUM MISMATCH — downloaded binary may be compromised!\n");
+ (void)fprintf(stderr, " expected: %s\n", expected);
+ (void)fprintf(stderr, " actual: %s\n", actual);
+ return CLI_TRUE;
}
printf("Checksum verified: %s\n", actual);
@@ -2468,7 +2602,7 @@ static void print_detected_agents(const cbm_detected_agents_t *a) {
/* Install Claude Code-specific configs (skills, MCP, hooks). */
static void install_claude_code_config(const char *home, const char *binary_path, bool force,
bool dry_run) {
- char skills_dir[1024];
+ char skills_dir[CLI_BUF_1K];
snprintf(skills_dir, sizeof(skills_dir), "%s/.claude/skills", home);
printf("Claude Code:\n");
@@ -2479,21 +2613,21 @@ static void install_claude_code_config(const char *home, const char *binary_path
printf(" removed old monolithic skill\n");
}
- char mcp_path[1024];
+ char mcp_path[CLI_BUF_1K];
snprintf(mcp_path, sizeof(mcp_path), "%s/.claude/.mcp.json", home);
if (!dry_run) {
cbm_install_editor_mcp(binary_path, mcp_path);
}
printf(" mcp: %s\n", mcp_path);
- char mcp_path2[1024];
+ char mcp_path2[CLI_BUF_1K];
snprintf(mcp_path2, sizeof(mcp_path2), "%s/.claude.json", home);
if (!dry_run) {
cbm_install_editor_mcp(binary_path, mcp_path2);
}
printf(" mcp: %s\n", mcp_path2);
- char settings_path[1024];
+ char settings_path[CLI_BUF_1K];
snprintf(settings_path, sizeof(settings_path), "%s/.claude/settings.json", home);
if (!dry_run) {
cbm_upsert_claude_hooks(settings_path);
@@ -2526,8 +2660,8 @@ static void install_generic_agent_config(const char *label, const char *binary_p
/* Install MCP configs for CLI-based agents (Codex, Gemini, OpenCode, Antigravity, Aider). */
/* Install Gemini CLI config with hooks. */
static void install_gemini_config(const char *home, const char *binary_path, bool dry_run) {
- char cp[1024];
- char ip[1024];
+ char cp[CLI_BUF_1K];
+ char ip[CLI_BUF_1K];
snprintf(cp, sizeof(cp), "%s/.gemini/settings.json", home);
snprintf(ip, sizeof(ip), "%s/.gemini/GEMINI.md", home);
install_generic_agent_config("Gemini CLI", binary_path, cp, ip, dry_run,
@@ -2541,8 +2675,8 @@ static void install_gemini_config(const char *home, const char *binary_path, boo
static void install_cli_agent_configs(const cbm_detected_agents_t *agents, const char *home,
const char *binary_path, bool dry_run) {
if (agents->codex) {
- char cp[1024];
- char ip[1024];
+ char cp[CLI_BUF_1K];
+ char ip[CLI_BUF_1K];
snprintf(cp, sizeof(cp), "%s/.codex/config.toml", home);
snprintf(ip, sizeof(ip), "%s/.codex/AGENTS.md", home);
install_generic_agent_config("Codex CLI", binary_path, cp, ip, dry_run,
@@ -2552,23 +2686,23 @@ static void install_cli_agent_configs(const cbm_detected_agents_t *agents, const
install_gemini_config(home, binary_path, dry_run);
}
if (agents->opencode) {
- char cp[1024];
- char ip[1024];
+ char cp[CLI_BUF_1K];
+ char ip[CLI_BUF_1K];
snprintf(cp, sizeof(cp), "%s/.config/opencode/opencode.json", home);
snprintf(ip, sizeof(ip), "%s/.config/opencode/AGENTS.md", home);
install_generic_agent_config("OpenCode", binary_path, cp, ip, dry_run,
cbm_upsert_opencode_mcp);
}
if (agents->antigravity) {
- char cp[1024];
- char ip[1024];
+ char cp[CLI_BUF_1K];
+ char ip[CLI_BUF_1K];
snprintf(cp, sizeof(cp), "%s/.gemini/antigravity/mcp_config.json", home);
snprintf(ip, sizeof(ip), "%s/.gemini/antigravity/AGENTS.md", home);
install_generic_agent_config("Antigravity", binary_path, cp, ip, dry_run,
cbm_upsert_antigravity_mcp);
}
if (agents->aider) {
- char ip[1024];
+ char ip[CLI_BUF_1K];
snprintf(ip, sizeof(ip), "%s/CONVENTIONS.md", home);
printf("Aider:\n");
if (!dry_run) {
@@ -2582,7 +2716,7 @@ static void install_cli_agent_configs(const cbm_detected_agents_t *agents, const
static void install_editor_agent_configs(const cbm_detected_agents_t *agents, const char *home,
const char *binary_path, bool dry_run) {
if (agents->zed) {
- char cp[1024];
+ char cp[CLI_BUF_1K];
#ifdef __APPLE__
snprintf(cp, sizeof(cp), "%s/Library/Application Support/Zed/settings.json", home);
#else
@@ -2591,8 +2725,8 @@ static void install_editor_agent_configs(const cbm_detected_agents_t *agents, co
install_generic_agent_config("Zed", binary_path, cp, NULL, dry_run, cbm_install_zed_mcp);
}
if (agents->kilocode) {
- char cp[1024];
- char ip[1024];
+ char cp[CLI_BUF_1K];
+ char ip[CLI_BUF_1K];
snprintf(cp, sizeof(cp),
"%s/.config/Code/User/globalStorage/kilocode.kilo-code/settings/mcp_settings.json",
home);
@@ -2601,7 +2735,7 @@ static void install_editor_agent_configs(const cbm_detected_agents_t *agents, co
cbm_install_editor_mcp);
}
if (agents->vscode) {
- char cp[1024];
+ char cp[CLI_BUF_1K];
#ifdef __APPLE__
snprintf(cp, sizeof(cp), "%s/Library/Application Support/Code/User/mcp.json", home);
#else
@@ -2611,7 +2745,7 @@ static void install_editor_agent_configs(const cbm_detected_agents_t *agents, co
cbm_install_vscode_mcp);
}
if (agents->openclaw) {
- char cp[1024];
+ char cp[CLI_BUF_1K];
snprintf(cp, sizeof(cp), "%s/.openclaw/openclaw.json", home);
install_generic_agent_config("OpenClaw", binary_path, cp, NULL, dry_run,
cbm_install_editor_mcp);
@@ -2644,7 +2778,7 @@ static int count_db_indexes(const char *home) {
cbm_dirent_t *ent;
while ((ent = cbm_readdir(d)) != NULL) {
size_t len = strlen(ent->name);
- if (len > 3 && strcmp(ent->name + len - 3, ".db") == 0) {
+ if (len > DB_EXT_LEN && strcmp(ent->name + len - DB_EXT_LEN, ".db") == 0) {
count++;
}
}
@@ -2669,8 +2803,8 @@ int cbm_cmd_install(int argc, char **argv) {
const char *home = cbm_get_home_dir();
if (!home) {
- fprintf(stderr, "error: HOME not set (use USERPROFILE on Windows)\n");
- return 1;
+ (void)fprintf(stderr, "error: HOME not set (use USERPROFILE on Windows)\n");
+ return CLI_TRUE;
}
printf("codebase-memory-mcp install %s\n\n", CBM_VERSION);
@@ -2682,7 +2816,7 @@ int cbm_cmd_install(int argc, char **argv) {
printf("\n");
if (!prompt_yn("Delete these indexes and continue with install?")) {
printf("Install cancelled.\n");
- return 1;
+ return CLI_TRUE;
}
if (!dry_run) {
int removed = cbm_remove_indexes(home);
@@ -2701,7 +2835,7 @@ int cbm_cmd_install(int argc, char **argv) {
/* Step 1c: macOS ad-hoc signing (in case binary was placed without signing) */
#ifdef __APPLE__
{
- char sign_path[1024];
+ char sign_path[CLI_BUF_1K];
snprintf(sign_path, sizeof(sign_path), "%s/.local/bin/codebase-memory-mcp", home);
struct stat sign_st;
if (stat(sign_path, &sign_st) == 0) {
@@ -2711,7 +2845,7 @@ int cbm_cmd_install(int argc, char **argv) {
#endif
/* Step 2: Binary path */
- char self_path[1024];
+ char self_path[CLI_BUF_1K];
#ifdef _WIN32
snprintf(self_path, sizeof(self_path), "%s/.local/bin/codebase-memory-mcp.exe", home);
#else
@@ -2722,14 +2856,14 @@ int cbm_cmd_install(int argc, char **argv) {
cbm_install_agent_configs(home, self_path, force, dry_run);
/* Step 4: Ensure PATH */
- char bin_dir[1024];
+ char bin_dir[CLI_BUF_1K];
snprintf(bin_dir, sizeof(bin_dir), "%s/.local/bin", home);
const char *rc = cbm_detect_shell_rc(home);
if (rc[0]) {
int path_rc = cbm_ensure_path(bin_dir, rc, dry_run);
if (path_rc == 0) {
printf("\nAdded %s to PATH in %s\n", bin_dir, rc);
- } else if (path_rc == 1) {
+ } else if (path_rc == CLI_TRUE) {
printf("\nPATH already includes %s\n", bin_dir);
}
}
@@ -2746,25 +2880,25 @@ int cbm_cmd_install(int argc, char **argv) {
/* Remove Claude Code agent configs. */
static void uninstall_claude_code(const char *home, bool dry_run) {
- char skills_dir[1024];
+ char skills_dir[CLI_BUF_1K];
snprintf(skills_dir, sizeof(skills_dir), "%s/.claude/skills", home);
int removed = cbm_remove_skills(skills_dir, dry_run);
printf("Claude Code: removed %d skill(s)\n", removed);
- char mcp_path[1024];
+ char mcp_path[CLI_BUF_1K];
snprintf(mcp_path, sizeof(mcp_path), "%s/.claude/.mcp.json", home);
if (!dry_run) {
cbm_remove_editor_mcp(mcp_path);
}
printf(" removed MCP config entry\n");
- char mcp_path2[1024];
+ char mcp_path2[CLI_BUF_1K];
snprintf(mcp_path2, sizeof(mcp_path2), "%s/.claude.json", home);
if (!dry_run) {
cbm_remove_editor_mcp(mcp_path2);
}
- char settings_path[1024];
+ char settings_path[CLI_BUF_1K];
snprintf(settings_path, sizeof(settings_path), "%s/.claude/settings.json", home);
if (!dry_run) {
cbm_remove_claude_hooks(settings_path);
@@ -2774,9 +2908,17 @@ static void uninstall_claude_code(const char *home, bool dry_run) {
}
/* Remove MCP + instructions for a generic agent. */
-static void uninstall_agent_mcp_instr(const char *name, const char *config_path,
- const char *instr_path, bool dry_run,
+
+typedef struct {
+ const char *name;
+ const char *config_path;
+ const char *instr_path;
+} mcp_uninstall_args_t;
+static void uninstall_agent_mcp_instr(mcp_uninstall_args_t paths, bool dry_run,
int (*remove_fn)(const char *)) {
+ const char *name = paths.name;
+ const char *config_path = paths.config_path;
+ const char *instr_path = paths.instr_path;
if (!dry_run) {
remove_fn(config_path);
}
@@ -2792,8 +2934,8 @@ static void uninstall_agent_mcp_instr(const char *name, const char *config_path,
/* Remove CLI agent configs (Codex, Gemini, OpenCode, Antigravity, Aider). */
/* Uninstall Gemini CLI config + hooks. */
static void uninstall_gemini_config(const char *home, bool dry_run) {
- char cp[1024];
- char ip[1024];
+ char cp[CLI_BUF_1K];
+ char ip[CLI_BUF_1K];
snprintf(cp, sizeof(cp), "%s/.gemini/settings.json", home);
snprintf(ip, sizeof(ip), "%s/.gemini/GEMINI.md", home);
if (!dry_run) {
@@ -2807,31 +2949,34 @@ static void uninstall_gemini_config(const char *home, bool dry_run) {
static void uninstall_cli_agents(const cbm_detected_agents_t *agents, const char *home,
bool dry_run) {
if (agents->codex) {
- char cp[1024];
- char ip[1024];
+ char cp[CLI_BUF_1K];
+ char ip[CLI_BUF_1K];
snprintf(cp, sizeof(cp), "%s/.codex/config.toml", home);
snprintf(ip, sizeof(ip), "%s/.codex/AGENTS.md", home);
- uninstall_agent_mcp_instr("Codex CLI", cp, ip, dry_run, cbm_remove_codex_mcp);
+ uninstall_agent_mcp_instr((mcp_uninstall_args_t){"Codex CLI", cp, ip}, dry_run,
+ cbm_remove_codex_mcp);
}
if (agents->gemini) {
uninstall_gemini_config(home, dry_run);
}
if (agents->opencode) {
- char cp[1024];
- char ip[1024];
+ char cp[CLI_BUF_1K];
+ char ip[CLI_BUF_1K];
snprintf(cp, sizeof(cp), "%s/.config/opencode/opencode.json", home);
snprintf(ip, sizeof(ip), "%s/.config/opencode/AGENTS.md", home);
- uninstall_agent_mcp_instr("OpenCode", cp, ip, dry_run, cbm_remove_opencode_mcp);
+ uninstall_agent_mcp_instr((mcp_uninstall_args_t){"OpenCode", cp, ip}, dry_run,
+ cbm_remove_opencode_mcp);
}
if (agents->antigravity) {
- char cp[1024];
- char ip[1024];
+ char cp[CLI_BUF_1K];
+ char ip[CLI_BUF_1K];
snprintf(cp, sizeof(cp), "%s/.gemini/antigravity/mcp_config.json", home);
snprintf(ip, sizeof(ip), "%s/.gemini/antigravity/AGENTS.md", home);
- uninstall_agent_mcp_instr("Antigravity", cp, ip, dry_run, cbm_remove_antigravity_mcp);
+ uninstall_agent_mcp_instr((mcp_uninstall_args_t){"Antigravity", cp, ip}, dry_run,
+ cbm_remove_antigravity_mcp);
}
if (agents->aider) {
- char ip[1024];
+ char ip[CLI_BUF_1K];
snprintf(ip, sizeof(ip), "%s/CONVENTIONS.md", home);
if (!dry_run) {
cbm_remove_instructions(ip);
@@ -2844,36 +2989,40 @@ static void uninstall_cli_agents(const cbm_detected_agents_t *agents, const char
static void uninstall_editor_agents(const cbm_detected_agents_t *agents, const char *home,
bool dry_run) {
if (agents->zed) {
- char cp[1024];
+ char cp[CLI_BUF_1K];
#ifdef __APPLE__
snprintf(cp, sizeof(cp), "%s/Library/Application Support/Zed/settings.json", home);
#else
snprintf(cp, sizeof(cp), "%s/.config/zed/settings.json", home);
#endif
- uninstall_agent_mcp_instr("Zed", cp, NULL, dry_run, cbm_remove_zed_mcp);
+ uninstall_agent_mcp_instr((mcp_uninstall_args_t){"Zed", cp, NULL}, dry_run,
+ cbm_remove_zed_mcp);
}
if (agents->kilocode) {
- char cp[1024];
- char ip[1024];
+ char cp[CLI_BUF_1K];
+ char ip[CLI_BUF_1K];
snprintf(cp, sizeof(cp),
"%s/.config/Code/User/globalStorage/kilocode.kilo-code/settings/mcp_settings.json",
home);
snprintf(ip, sizeof(ip), "%s/.kilocode/rules/codebase-memory-mcp.md", home);
- uninstall_agent_mcp_instr("KiloCode", cp, ip, dry_run, cbm_remove_editor_mcp);
+ uninstall_agent_mcp_instr((mcp_uninstall_args_t){"KiloCode", cp, ip}, dry_run,
+ cbm_remove_editor_mcp);
}
if (agents->vscode) {
- char cp[1024];
+ char cp[CLI_BUF_1K];
#ifdef __APPLE__
snprintf(cp, sizeof(cp), "%s/Library/Application Support/Code/User/mcp.json", home);
#else
snprintf(cp, sizeof(cp), "%s/.config/Code/User/mcp.json", home);
#endif
- uninstall_agent_mcp_instr("VS Code", cp, NULL, dry_run, cbm_remove_vscode_mcp);
+ uninstall_agent_mcp_instr((mcp_uninstall_args_t){"VS Code", cp, NULL}, dry_run,
+ cbm_remove_vscode_mcp);
}
if (agents->openclaw) {
- char cp[1024];
+ char cp[CLI_BUF_1K];
snprintf(cp, sizeof(cp), "%s/.openclaw/openclaw.json", home);
- uninstall_agent_mcp_instr("OpenClaw", cp, NULL, dry_run, cbm_remove_editor_mcp);
+ uninstall_agent_mcp_instr((mcp_uninstall_args_t){"OpenClaw", cp, NULL}, dry_run,
+ cbm_remove_editor_mcp);
}
}
@@ -2888,8 +3037,8 @@ int cbm_cmd_uninstall(int argc, char **argv) {
const char *home = cbm_get_home_dir();
if (!home) {
- fprintf(stderr, "error: HOME not set (use USERPROFILE on Windows)\n");
- return 1;
+ (void)fprintf(stderr, "error: HOME not set (use USERPROFILE on Windows)\n");
+ return CLI_TRUE;
}
printf("codebase-memory-mcp uninstall\n\n");
@@ -2915,7 +3064,7 @@ int cbm_cmd_uninstall(int argc, char **argv) {
}
/* Step 3: Remove binary */
- char bin_path[1024];
+ char bin_path[CLI_BUF_1K];
#ifdef _WIN32
snprintf(bin_path, sizeof(bin_path), "%s/.local/bin/codebase-memory-mcp.exe", home);
#else
@@ -2940,25 +3089,33 @@ int cbm_cmd_uninstall(int argc, char **argv) {
/* Read archive from disk, extract binary (tar.gz or zip), write to bin_dest.
* Returns 0 on success, 1 on failure. Cleans up tmp_archive. */
-static int extract_and_install_binary(const char *tmp_archive, const char *ext,
- const char *bin_dest) {
+
+typedef struct {
+ const char *tmp_archive;
+ const char *ext;
+ const char *bin_dest;
+} extract_install_args_t;
+static int extract_and_install_binary(extract_install_args_t args) {
+ const char *tmp_archive = args.tmp_archive;
+ const char *ext = args.ext;
+ const char *bin_dest = args.bin_dest;
FILE *f = fopen(tmp_archive, "rb");
if (!f) {
- fprintf(stderr, "error: cannot open %s\n", tmp_archive);
- return 1;
+ (void)fprintf(stderr, "error: cannot open %s\n", tmp_archive);
+ return CLI_TRUE;
}
- fseek(f, 0, SEEK_END);
+ (void)fseek(f, 0, SEEK_END);
long fsize = ftell(f);
- fseek(f, 0, SEEK_SET);
+ (void)fseek(f, 0, SEEK_SET);
unsigned char *data = malloc((size_t)fsize);
if (!data) {
- fclose(f);
+ (void)fclose(f);
cbm_unlink(tmp_archive);
- return 1;
+ return CLI_TRUE;
}
- fread(data, 1, (size_t)fsize, f);
- fclose(f);
+ (void)fread(data, CLI_ELEM_SIZE, (size_t)fsize, f);
+ (void)fclose(f);
int bin_len = 0;
unsigned char *bin_data = NULL;
@@ -2971,15 +3128,15 @@ static int extract_and_install_binary(const char *tmp_archive, const char *ext,
cbm_unlink(tmp_archive);
if (!bin_data || bin_len <= 0) {
- fprintf(stderr, "error: binary not found in archive\n");
+ (void)fprintf(stderr, "error: binary not found in archive\n");
free(bin_data);
- return 1;
+ return CLI_TRUE;
}
- if (cbm_replace_binary(bin_dest, bin_data, bin_len, 0755) != 0) {
- fprintf(stderr, "error: cannot write to %s\n", bin_dest);
+ if (cbm_replace_binary(bin_dest, bin_data, bin_len, CLI_OCTAL_PERM) != 0) {
+ (void)fprintf(stderr, "error: cannot write to %s\n", bin_dest);
free(bin_data);
- return 1;
+ return CLI_TRUE;
}
free(bin_data);
return 0;
@@ -2988,7 +3145,9 @@ static int extract_and_install_binary(const char *tmp_archive, const char *ext,
/* Build the download URL for the update command. */
static void build_update_url(char *url, int url_sz, const char *os, const char *arch,
const char *ext, bool want_ui) {
- const char *base_url = getenv("CBM_DOWNLOAD_URL");
+ char base_url_buf[CLI_BUF_512];
+ const char *base_url =
+ cbm_safe_getenv("CBM_DOWNLOAD_URL", base_url_buf, sizeof(base_url_buf), NULL);
if (!base_url || !base_url[0]) {
base_url = "https://github.com/DeusData/codebase-memory-mcp/releases/latest/download";
}
@@ -3011,7 +3170,7 @@ static int update_clear_indexes(const char *home, bool dry_run) {
}
if (!prompt_yn("Delete these indexes and continue with update?")) {
printf("Update cancelled.\n");
- return 1;
+ return CLI_TRUE;
}
int removed = cbm_remove_indexes(home);
printf("Removed %d index(es).\n\n", removed);
@@ -3021,23 +3180,23 @@ static int update_clear_indexes(const char *home, bool dry_run) {
/* Download, verify checksum, kill old instances, and install binary. Returns 0 on success. */
static int download_verify_install(const char *url, const char *ext, const char *os,
const char *arch, bool want_ui, const char *bin_dest) {
- char tmp_archive[256];
+ char tmp_archive[CLI_BUF_256];
snprintf(tmp_archive, sizeof(tmp_archive), "%s/cbm-update.%s", cbm_tmpdir(), ext);
int rc = cbm_download_to_file(url, tmp_archive);
if (rc != 0) {
- fprintf(stderr, "error: download failed (exit %d)\n", rc);
+ (void)fprintf(stderr, "error: download failed (exit %d)\n", rc);
cbm_unlink(tmp_archive);
- return 1;
+ return CLI_TRUE;
}
- char archive_name[256];
+ char archive_name[CLI_BUF_256];
snprintf(archive_name, sizeof(archive_name), "codebase-memory-mcp-%s%s-%s.%s",
want_ui ? "ui-" : "", os, arch, ext);
int crc = verify_download_checksum(tmp_archive, archive_name);
- if (crc == 1) {
+ if (crc == CLI_TRUE) {
cbm_unlink(tmp_archive);
- return 1;
+ return CLI_TRUE;
}
int killed = cbm_kill_other_instances();
@@ -3045,25 +3204,25 @@ static int download_verify_install(const char *url, const char *ext, const char
printf("Stopped %d running MCP server instance(s).\n", killed);
}
- if (extract_and_install_binary(tmp_archive, ext, bin_dest) != 0) {
- return 1;
+ if (extract_and_install_binary((extract_install_args_t){tmp_archive, ext, bin_dest}) != 0) {
+ return CLI_TRUE;
}
return 0;
}
/* Select update variant. Returns 0=standard, 1=ui, -1=error. */
static int select_update_variant(int variant_flag) {
- if (variant_flag == 1) {
+ if (variant_flag == VARIANT_A) {
return 0;
}
- if (variant_flag == 2) {
- return 1;
+ if (variant_flag == VARIANT_B) {
+ return CLI_TRUE;
}
#ifndef _WIN32
if (!isatty(fileno(stdin))) {
- fprintf(stderr, "error: variant selection requires a terminal. "
- "Use --standard or --ui flag.\n");
- return -1;
+ (void)fprintf(stderr, "error: variant selection requires a terminal. "
+ "Use --standard or --ui flag.\n");
+ return CLI_ERR;
}
#endif
printf("Which binary variant do you want?\n");
@@ -3071,12 +3230,12 @@ static int select_update_variant(int variant_flag) {
printf(" 2) ui — MCP server + embedded graph visualization\n");
printf("Choose (1/2): ");
(void)fflush(stdout);
- char choice[16];
+ char choice[CLI_BUF_16];
if (!fgets(choice, sizeof(choice), stdin)) {
- fprintf(stderr, "error: failed to read input\n");
- return -1;
+ (void)fprintf(stderr, "error: failed to read input\n");
+ return CLI_ERR;
}
- return (choice[0] == '2') ? 1 : 0;
+ return (choice[0] == '2') ? CLI_TRUE : 0;
}
int cbm_cmd_update(int argc, char **argv) {
@@ -3088,31 +3247,31 @@ int cbm_cmd_update(int argc, char **argv) {
if (strcmp(argv[i], "--dry-run") == 0) {
dry_run = true;
} else if (strcmp(argv[i], "--standard") == 0) {
- variant_flag = 1;
+ variant_flag = VARIANT_A;
} else if (strcmp(argv[i], "--ui") == 0) {
- variant_flag = 2;
+ variant_flag = VARIANT_B;
}
}
const char *home = cbm_get_home_dir();
if (!home) {
- fprintf(stderr, "error: HOME not set (use USERPROFILE on Windows)\n");
- return 1;
+ (void)fprintf(stderr, "error: HOME not set (use USERPROFILE on Windows)\n");
+ return CLI_TRUE;
}
printf("codebase-memory-mcp update (current: %s)\n\n", CBM_VERSION);
/* Step 1: Check for existing indexes */
if (update_clear_indexes(home, dry_run) != 0) {
- return 1;
+ return CLI_TRUE;
}
/* Step 2: Determine variant */
int want_ui_rc = select_update_variant(variant_flag);
if (want_ui_rc < 0) {
- return 1;
+ return CLI_TRUE;
}
- bool want_ui = (want_ui_rc == 1);
+ bool want_ui = (want_ui_rc == CLI_TRUE);
const char *variant = want_ui ? "ui-" : "";
const char *variant_label = want_ui ? "ui" : "standard";
@@ -3120,7 +3279,7 @@ int cbm_cmd_update(int argc, char **argv) {
const char *arch = detect_arch();
const char *ext = strcmp(os, "windows") == 0 ? "zip" : "tar.gz";
- char url[512];
+ char url[CLI_BUF_512];
build_update_url(url, sizeof(url), os, arch, ext, want_ui);
if (dry_run) {
@@ -3141,25 +3300,26 @@ int cbm_cmd_update(int argc, char **argv) {
}
/* Step 4-5: Download, verify, and install binary */
- char bin_dest[1024];
+ char bin_dest[CLI_BUF_1K];
#ifdef _WIN32
snprintf(bin_dest, sizeof(bin_dest), "%s/.local/bin/codebase-memory-mcp.exe", home);
#else
snprintf(bin_dest, sizeof(bin_dest), "%s/.local/bin/codebase-memory-mcp", home);
#endif
- char bin_dir[1024];
+ char bin_dir[CLI_BUF_1K];
snprintf(bin_dir, sizeof(bin_dir), "%s/.local/bin", home);
- cbm_mkdir_p(bin_dir, 0755);
+ cbm_mkdir_p(bin_dir, CLI_OCTAL_PERM);
int rc = download_verify_install(url, ext, os, arch, want_ui, bin_dest);
if (rc != 0) {
- return 1;
+ return CLI_TRUE;
}
/* Step 5b: macOS ad-hoc signing (required for arm64, harmless for x86_64) */
#ifdef __APPLE__
if (cbm_macos_adhoc_sign(bin_dest) != 0) {
- fprintf(stderr, "warning: ad-hoc signing failed — binary may not run on macOS arm64\n");
+ (void)fprintf(stderr,
+ "warning: ad-hoc signing failed — binary may not run on macOS arm64\n");
}
#endif
diff --git a/src/cypher/cypher.c b/src/cypher/cypher.c
index 9c60258dc..578234613 100644
--- a/src/cypher/cypher.c
+++ b/src/cypher/cypher.c
@@ -9,6 +9,30 @@
#include "store/store.h"
#include "foundation/platform.h"
+enum {
+ CYP_BUF_16 = 16,
+ CYP_BUF_48 = 48, /* ASCII '0' */
+ CYP_BUF_8 = 8,
+ CYP_BUF_4 = 4,
+ CYP_MAX_TOKEN = 10, /* max token lookahead */
+ CYP_PAIR = 2,
+ CYP_TRIPLE = 3,
+ CYP_INIT_CAP4 = 4, /* initial small array capacity */
+ CYP_INIT_CAP8 = 8, /* initial medium array capacity */
+ CYP_MAX_VARS = 16, /* max Cypher variables in a query */
+ CYP_MAX_EDGE_VARS = 8, /* max edge variables */
+ CYP_GROWTH_10 = 10, /* binding growth factor */
+ CYP_MAX_DEPTH = 10, /* max variable-length path depth */
+ CYP_CHAR_IDX1 = 1, /* second character index (e.g. op[1]) */
+ CYP_EBUF_MASK = 7,
+ CYP_NODE_COLS = 4, /* columns per node var: name, qn, label, file */
+ CYP_EDGE_COLS = 3, /* columns per edge var: name, qn, label */
+ CYP_COL_BUF = 48, /* max column buffer (16 vars * 3 cols) */
+ CYP_FOUND_NONE = -1,
+ /* search miss sentinel */ /* mask for ebuf ring buffer (8 entries) */
+};
+#define CYP_DBL_MAX 1e308
+
#include <ctype.h>
#include "foundation/compat_regex.h"
#include <stdint.h> // int64_t
@@ -201,14 +225,14 @@ static bool lex_try_two_char(const char *input, int len, int *i, cbm_lex_result_
{'>', '=', TOK_GTE, ">="}, {'<', '=', TOK_LTE, "<="}, {'.', '.', TOK_DOTDOT, ".."},
};
char c = input[*i];
- if (*i + 1 >= len) {
+ if (*i + SKIP_ONE >= len) {
return false;
}
char c2 = input[*i + 1];
for (int p = 0; p < (int)(sizeof(pairs) / sizeof(pairs[0])); p++) {
if (c == pairs[p].c1 && c2 == pairs[p].c2) {
lex_push(out, pairs[p].type, pairs[p].text, *i);
- *i += 2;
+ *i += PAIR_LEN;
return true;
}
}
@@ -304,12 +328,12 @@ static bool lex_skip_whitespace_comments(const char *input, int len, int *i) {
return true;
}
if (*i + 1 < len && input[*i] == '/' && input[*i + 1] == '*') {
- *i += 2;
+ *i += PAIR_LEN;
while (*i + 1 < len && !(input[*i] == '*' && input[*i + 1] == '/')) {
(*i)++;
}
if (*i + 1 < len) {
- *i += 2;
+ *i += PAIR_LEN;
}
return true;
}
@@ -443,7 +467,7 @@ static int parse_props(parser_t *p, cbm_prop_filter_t **out, int *count) {
return 0;
}
- int cap = 4;
+ int cap = CYP_INIT_CAP4;
int n = 0;
cbm_prop_filter_t *arr = malloc(cap * sizeof(cbm_prop_filter_t));
@@ -464,7 +488,7 @@ static int parse_props(parser_t *p, cbm_prop_filter_t **out, int *count) {
}
if (n >= cap) {
- cap *= 2;
+ cap *= PAIR_LEN;
arr = safe_realloc(arr, cap * sizeof(cbm_prop_filter_t));
}
arr[n].key = heap_strdup(key->text);
@@ -541,7 +565,7 @@ static void parse_hop_range(parser_t *p, int *min_hops, int *max_hops) {
/* Parse relationship type list after ':' inside brackets. Returns -1 on error. */
static int parse_rel_types(parser_t *p, cbm_rel_pattern_t *out) {
- int cap = 4;
+ int cap = CYP_INIT_CAP4;
int n = 0;
const char **types = malloc(cap * sizeof(const char *));
@@ -562,7 +586,7 @@ static int parse_rel_types(parser_t *p, cbm_rel_pattern_t *out) {
return -1;
}
if (n >= cap) {
- cap *= 2;
+ cap *= PAIR_LEN;
types = safe_realloc(types, cap * sizeof(const char *));
}
types[n++] = heap_strdup(t->text);
@@ -636,22 +660,32 @@ static int parse_rel(parser_t *p, cbm_rel_pattern_t *out) {
/* ── Expression tree helpers ────────────────────────────────────── */
static void expr_free(cbm_expr_t *e) {
- if (!e) {
- return;
- }
- if (e->type == EXPR_CONDITION) {
- free((void *)e->cond.variable);
- free((void *)e->cond.property);
- free((void *)e->cond.op);
- free((void *)e->cond.value);
- for (int i = 0; i < e->cond.in_value_count; i++) {
- free((void *)e->cond.in_values[i]);
+ enum { EXPR_FREE_STACK = 128 };
+ cbm_expr_t *stack[EXPR_FREE_STACK];
+ int top = 0;
+ if (e) {
+ stack[top++] = e;
+ }
+ while (top > 0) {
+ cbm_expr_t *cur = stack[--top];
+ if (cur->type == EXPR_CONDITION) {
+ free((void *)cur->cond.variable);
+ free((void *)cur->cond.property);
+ free((void *)cur->cond.op);
+ free((void *)cur->cond.value);
+ for (int i = 0; i < cur->cond.in_value_count; i++) {
+ free((void *)cur->cond.in_values[i]);
+ }
+ free(cur->cond.in_values);
+ }
+ if (cur->right && top < EXPR_FREE_STACK) {
+ stack[top++] = cur->right;
+ }
+ if (cur->left && top < EXPR_FREE_STACK) {
+ stack[top++] = cur->left;
}
- free(e->cond.in_values);
+ free(cur);
}
- expr_free(e->left);
- expr_free(e->right);
- free(e);
}
static cbm_expr_t *expr_leaf(cbm_condition_t c) {
@@ -724,7 +758,7 @@ static cbm_expr_t *parse_in_list(parser_t *p, cbm_condition_t *c) {
free((void *)c->op);
return NULL;
}
- int vcap = 8;
+ int vcap = CYP_INIT_CAP8;
int vn = 0;
const char **vals = malloc(vcap * sizeof(const char *));
while (!check(p, TOK_RBRACKET) && !check(p, TOK_EOF)) {
@@ -733,7 +767,7 @@ static cbm_expr_t *parse_in_list(parser_t *p, cbm_condition_t *c) {
}
if (check(p, TOK_STRING) || check(p, TOK_NUMBER)) {
if (vn >= vcap) {
- vcap *= 2;
+ vcap *= PAIR_LEN;
vals = safe_realloc(vals, vcap * sizeof(const char *));
}
vals[vn++] = heap_strdup(advance(p)->text);
@@ -861,7 +895,7 @@ static cbm_expr_t *parse_condition_expr(parser_t *p) {
}
/* Atom: ( expr ) | condition */
-static cbm_expr_t *parse_atom_expr(parser_t *p) {
+static cbm_expr_t *parse_atom_expr(parser_t *p) { // NOLINT(misc-no-recursion)
if (match(p, TOK_LPAREN)) {
cbm_expr_t *e = parse_or_expr(p);
expect(p, TOK_RPAREN);
@@ -871,7 +905,7 @@ static cbm_expr_t *parse_atom_expr(parser_t *p) {
}
/* NOT: NOT atom | atom */
-static cbm_expr_t *parse_not_expr(parser_t *p) {
+static cbm_expr_t *parse_not_expr(parser_t *p) { // NOLINT(misc-no-recursion)
if (match(p, TOK_NOT)) {
cbm_expr_t *child = parse_not_expr(p);
return child ? expr_not(child) : NULL;
@@ -880,7 +914,7 @@ static cbm_expr_t *parse_not_expr(parser_t *p) {
}
/* AND: not (AND not)* */
-static cbm_expr_t *parse_and_expr(parser_t *p) {
+static cbm_expr_t *parse_and_expr(parser_t *p) { // NOLINT(misc-no-recursion)
cbm_expr_t *left = parse_not_expr(p);
if (!left) {
return NULL;
@@ -898,7 +932,7 @@ static cbm_expr_t *parse_and_expr(parser_t *p) {
}
/* XOR: and (XOR and)* */
-static cbm_expr_t *parse_xor_expr(parser_t *p) {
+static cbm_expr_t *parse_xor_expr(parser_t *p) { // NOLINT(misc-no-recursion)
cbm_expr_t *left = parse_and_expr(p);
if (!left) {
return NULL;
@@ -916,7 +950,7 @@ static cbm_expr_t *parse_xor_expr(parser_t *p) {
}
/* OR: xor (OR xor)* */
-static cbm_expr_t *parse_or_expr(parser_t *p) {
+static cbm_expr_t *parse_or_expr(parser_t *p) { // NOLINT(misc-no-recursion)
cbm_expr_t *left = parse_xor_expr(p);
if (!left) {
return NULL;
@@ -1026,7 +1060,7 @@ static const char *parse_value_literal(parser_t *p) {
static cbm_case_expr_t *parse_case_expr(parser_t *p) {
/* CASE already consumed */
cbm_case_expr_t *kase = calloc(1, sizeof(cbm_case_expr_t));
- int bcap = 4;
+ int bcap = CYP_INIT_CAP4;
kase->branches = malloc(bcap * sizeof(cbm_case_branch_t));
while (check(p, TOK_WHEN)) {
@@ -1038,7 +1072,7 @@ static cbm_case_expr_t *parse_case_expr(parser_t *p) {
}
const char *then_val = parse_value_literal(p);
if (kase->branch_count >= bcap) {
- bcap *= 2;
+ bcap *= PAIR_LEN;
kase->branches = safe_realloc(kase->branches, bcap * sizeof(cbm_case_branch_t));
}
kase->branches[kase->branch_count++] =
@@ -1190,7 +1224,7 @@ static int parse_return_or_with(parser_t *p, cbm_return_clause_t **out, bool is_
}
cbm_return_clause_t *r = calloc(1, sizeof(cbm_return_clause_t));
- int cap = 8;
+ int cap = CYP_INIT_CAP8;
r->items = malloc(cap * sizeof(cbm_return_item_t));
r->distinct = match(p, TOK_DISTINCT);
@@ -1215,7 +1249,7 @@ static int parse_return_or_with(parser_t *p, cbm_return_clause_t **out, bool is_
}
if (r->count >= cap) {
- cap *= 2;
+ cap *= PAIR_LEN;
r->items = safe_realloc(r->items, cap * sizeof(cbm_return_item_t));
}
r->items[r->count++] = item;
@@ -1256,8 +1290,8 @@ static int parse_return(parser_t *p, cbm_return_clause_t **out) {
/* Parse a single MATCH pattern into pat */
static int parse_match_pattern(parser_t *p, cbm_pattern_t *pat) {
memset(pat, 0, sizeof(*pat));
- int node_cap = 4;
- int rel_cap = 4;
+ int node_cap = CYP_INIT_CAP4;
+ int rel_cap = CYP_INIT_CAP4;
pat->nodes = malloc(node_cap * sizeof(cbm_node_pattern_t));
pat->rels = calloc(rel_cap, sizeof(cbm_rel_pattern_t));
@@ -1268,7 +1302,7 @@ static int parse_match_pattern(parser_t *p, cbm_pattern_t *pat) {
while (check(p, TOK_DASH) || check(p, TOK_LT)) {
if (pat->rel_count >= rel_cap) {
- rel_cap *= 2;
+ rel_cap *= PAIR_LEN;
pat->rels = safe_realloc(pat->rels, rel_cap * sizeof(cbm_rel_pattern_t));
}
if (parse_rel(p, &pat->rels[pat->rel_count]) < 0) {
@@ -1277,7 +1311,7 @@ static int parse_match_pattern(parser_t *p, cbm_pattern_t *pat) {
pat->rel_count++;
if (pat->node_count >= node_cap) {
- node_cap *= 2;
+ node_cap *= PAIR_LEN;
pat->nodes = safe_realloc(pat->nodes, node_cap * sizeof(cbm_node_pattern_t));
}
if (parse_node(p, &pat->nodes[pat->node_count]) < 0) {
@@ -1338,7 +1372,7 @@ static int parse_match_chain(parser_t *p, cbm_query_t *q, int *pat_cap) {
break;
}
if (q->pattern_count >= *pat_cap) {
- *pat_cap *= 2;
+ *pat_cap *= PAIR_LEN;
q->patterns = safe_realloc(q->patterns, *pat_cap * sizeof(cbm_pattern_t));
q->pattern_optional = safe_realloc(q->pattern_optional, *pat_cap * sizeof(bool));
}
@@ -1352,7 +1386,8 @@ static int parse_match_chain(parser_t *p, cbm_query_t *q, int *pat_cap) {
}
/* Parse post-WHERE clauses: additional MATCH, WITH, RETURN, UNION */
-static int parse_post_where(parser_t *p, cbm_query_t *q, int *pat_cap) {
+static int parse_post_where(parser_t *p, cbm_query_t *q,
+ int *pat_cap) { // NOLINT(misc-no-recursion)
/* More MATCH / OPTIONAL MATCH after WHERE */
if (parse_match_chain(p, q, pat_cap) < 0) {
return -1;
@@ -1364,7 +1399,7 @@ static int parse_post_where(parser_t *p, cbm_query_t *q, int *pat_cap) {
return -1;
}
/* Optional WITH clause (standalone, not STARTS WITH) */
- if (check(p, TOK_WITH) && (p->pos < 2 || p->tokens[p->pos - 1].type != TOK_STARTS)) {
+ if (check(p, TOK_WITH) && (p->pos < PAIR_LEN || p->tokens[p->pos - 1].type != TOK_STARTS)) {
if (parse_return_or_with(p, &q->with_clause, true) < 0) {
return -1;
}
@@ -1395,7 +1430,8 @@ static int parse_post_where(parser_t *p, cbm_query_t *q, int *pat_cap) {
return 0;
}
-int cbm_parse(const cbm_token_t *tokens, int token_count, cbm_parse_result_t *out) {
+int cbm_parse(const cbm_token_t *tokens, int token_count,
+ cbm_parse_result_t *out) { // NOLINT(misc-no-recursion)
memset(out, 0, sizeof(*out));
parser_t p = {.tokens = tokens, .count = token_count, .pos = 0};
@@ -1423,7 +1459,7 @@ int cbm_parse(const cbm_token_t *tokens, int token_count, cbm_parse_result_t *ou
return -1;
}
- int pat_cap = 4;
+ int pat_cap = CYP_INIT_CAP4;
q->patterns = malloc(pat_cap * sizeof(cbm_pattern_t));
q->pattern_optional = malloc(pat_cap * sizeof(bool));
@@ -1543,27 +1579,22 @@ static void free_return_clause(cbm_return_clause_t *r) {
}
void cbm_query_free(cbm_query_t *q) {
- if (!q) {
- return;
- }
-
- for (int i = 0; i < q->pattern_count; i++) {
- free_pattern(&q->patterns[i]);
+ while (q) {
+ cbm_query_t *next = q->union_next;
+ for (int i = 0; i < q->pattern_count; i++) {
+ free_pattern(&q->patterns[i]);
+ }
+ free(q->patterns);
+ free(q->pattern_optional);
+ free_where(q->where);
+ free_where(q->post_with_where);
+ free_return_clause(q->with_clause);
+ free_return_clause(q->ret);
+ free((void *)q->unwind_expr);
+ free((void *)q->unwind_alias);
+ free(q);
+ q = next;
}
- free(q->patterns);
- free(q->pattern_optional);
-
- free_where(q->where);
- free_where(q->post_with_where);
- free_return_clause(q->with_clause);
- free_return_clause(q->ret);
-
- cbm_query_free(q->union_next);
-
- free((void *)q->unwind_expr);
- free((void *)q->unwind_alias);
-
- free(q);
}
/* ── Convenience: lex + parse ───────────────────────────────────── */
@@ -1600,11 +1631,11 @@ int cbm_cypher_parse(const char *query, cbm_query_t **out, char **error) {
/* A binding: maps variable names to nodes and/or edges */
typedef struct {
- const char *var_names[16]; /* variable names (nodes) */
- cbm_node_t var_nodes[16]; /* node data */
+ const char *var_names[CYP_MAX_VARS]; /* variable names (nodes) */
+ cbm_node_t var_nodes[CYP_MAX_VARS]; /* node data */
int var_count;
- const char *edge_var_names[8]; /* variable names (edges) */
- cbm_edge_t edge_vars[8]; /* edge data */
+ const char *edge_var_names[CYP_MAX_EDGE_VARS]; /* variable names (edges) */
+ cbm_edge_t edge_vars[CYP_MAX_EDGE_VARS]; /* edge data */
int edge_var_count;
} binding_t;
@@ -1690,9 +1721,9 @@ static const char *edge_prop(const cbm_edge_t *e, const char *prop) {
return e->type ? e->type : "";
}
/* Rotate through 8 static buffers so multiple props can be accessed per row */
- static char ebufs[8][512];
+ static char ebufs[CYP_BUF_8][512];
static int ebuf_idx = 0;
- char *buf = ebufs[ebuf_idx++ & 7];
+ char *buf = ebufs[ebuf_idx++ & CYP_EBUF_MASK];
json_extract_prop(e->properties_json, prop, buf, 512);
return buf;
}
@@ -1764,7 +1795,7 @@ static void binding_set_edge(binding_t *b, const char *var, const cbm_edge_t *ed
return;
}
}
- if (b->edge_var_count >= 8) {
+ if (b->edge_var_count >= CYP_MAX_EDGE_VARS) {
return;
}
b->edge_var_names[b->edge_var_count] = var; /* not owned — points to AST string */
@@ -1806,7 +1837,7 @@ static void binding_set(binding_t *b, const char *var, const cbm_node_t *node) {
return;
}
}
- if (b->var_count >= 16) {
+ if (b->var_count >= CYP_MAX_VARS) {
return;
}
b->var_names[b->var_count] = var; /* not owned — points to AST string */
@@ -1863,10 +1894,10 @@ static bool eval_comparison_op(const char *op, const char *actual, const char *e
strcmp(op, "<=") == 0) {
double a = strtod(actual, NULL);
double exp_val = strtod(expected, NULL);
- if (op[0] == '>' && op[1] == '=') {
+ if (op[0] == '>' && op[CYP_CHAR_IDX1] == '=') {
return a >= exp_val;
}
- if (op[0] == '<' && op[1] == '=') {
+ if (op[0] == '<' && op[CYP_CHAR_IDX1] == '=') {
return a <= exp_val;
}
if (op[0] == '>') {
@@ -1913,7 +1944,7 @@ static bool eval_condition(const cbm_condition_t *c, binding_t *b) {
}
/* Recursive expression tree evaluator */
-static bool eval_expr(const cbm_expr_t *e, binding_t *b) {
+static bool eval_expr(const cbm_expr_t *e, binding_t *b) { // NOLINT(misc-no-recursion)
if (!e) {
return true;
}
@@ -1995,7 +2026,7 @@ static void rb_set_columns(result_builder_t *rb, const char **cols, int count) {
static void rb_add_row(result_builder_t *rb, const char **values) {
if (rb->row_count >= rb->row_cap) {
- rb->row_cap *= 2;
+ rb->row_cap *= PAIR_LEN;
rb->rows = safe_realloc(rb->rows, rb->row_cap * sizeof(const char **));
}
const char **row = malloc(rb->col_count * sizeof(const char *));
@@ -2046,7 +2077,7 @@ static const char *apply_string_func(const char *func, const char *val, char *bu
}
if (strcmp(func, "toLower") == 0) {
size_t i = 0;
- for (; i < buf_sz - 1 && val[i]; i++) {
+ for (; i < buf_sz - SKIP_ONE && val[i]; i++) {
buf[i] = (char)tolower((unsigned char)val[i]);
}
buf[i] = '\0';
@@ -2054,7 +2085,7 @@ static const char *apply_string_func(const char *func, const char *val, char *bu
}
if (strcmp(func, "toUpper") == 0) {
size_t i = 0;
- for (; i < buf_sz - 1 && val[i]; i++) {
+ for (; i < buf_sz - SKIP_ONE && val[i]; i++) {
buf[i] = (char)toupper((unsigned char)val[i]);
}
buf[i] = '\0';
@@ -2087,8 +2118,10 @@ static void scan_pattern_nodes(cbm_store_t *store, const char *project, int max_
if (first->label) {
cbm_store_find_nodes_by_label(store, project, first->label, out_nodes, out_count);
} else {
- cbm_search_params_t params = {
- .project = project, .min_degree = -1, .max_degree = -1, .limit = max_rows * 10};
+ cbm_search_params_t params = {.project = project,
+ .min_degree = CYP_FOUND_NONE,
+ .max_degree = CYP_FOUND_NONE,
+ .limit = max_rows * CYP_GROWTH_10};
cbm_search_output_t sout = {0};
cbm_store_search(store, &params, &sout);
*out_count = sout.count;
@@ -2160,10 +2193,10 @@ static void expand_var_length(cbm_store_t *store, cbm_rel_pattern_t *rel,
cbm_node_pattern_t *target_node, binding_t *b, cbm_node_t *src,
const char *to_var, binding_t *new_bindings, int *new_count,
int max_new, int *match_count) {
- int max_depth = rel->max_hops > 0 ? rel->max_hops : 10;
+ int max_depth = rel->max_hops > 0 ? rel->max_hops : CYP_MAX_DEPTH;
cbm_traverse_result_t tr = {0};
const char *dir = rel->direction ? rel->direction : "outbound";
- cbm_store_bfs(store, src->id, dir, rel->types, rel->type_count, max_depth, 100, &tr);
+ cbm_store_bfs(store, src->id, dir, rel->types, rel->type_count, max_depth, CBM_PERCENT, &tr);
for (int v = 0; v < tr.visited_count && *new_count < max_new; v++) {
cbm_node_hop_t *hop = &tr.visited[v];
if (hop->hop < rel->min_hops) {
@@ -2249,9 +2282,10 @@ static void expand_pattern_rels(cbm_store_t *store, cbm_pattern_t *pat, binding_
cbm_node_pattern_t *target_node = &pat->nodes[ri + 1];
const char *to_var = target_node->variable ? target_node->variable : "_n_t";
- bool is_variable_length = (rel->min_hops != 1 || rel->max_hops != 1);
+ bool is_variable_length = (rel->min_hops != SKIP_ONE || rel->max_hops != SKIP_ONE);
- binding_t *new_bindings = malloc(((*bind_cap * 10) + 1) * sizeof(binding_t));
+ binding_t *new_bindings =
+ malloc(((*bind_cap * CYP_GROWTH_10) + SKIP_ONE) * sizeof(binding_t));
int new_count = 0;
for (int bi = 0; bi < *bind_count; bi++) {
@@ -2263,7 +2297,7 @@ static void expand_pattern_rels(cbm_store_t *store, cbm_pattern_t *pat, binding_
int match_count = 0;
- int max_new = *bind_cap * 10;
+ int max_new = *bind_cap * CYP_GROWTH_10;
if (is_variable_length) {
expand_var_length(store, rel, target_node, b, src, to_var, new_bindings, &new_count,
max_new, &match_count);
@@ -2314,7 +2348,7 @@ static bool rb_is_numeric_column(const result_builder_t *rb, int col) {
for (int i = 0; i < rb->row_count; i++) {
const char *v = rb->rows[i][col];
if (v && *v) {
- const char *p2 = (*v == '-') ? v + 1 : v;
+ const char *p2 = (*v == '-') ? v + SKIP_ONE : v;
if (*p2 == '\0') {
return false;
}
@@ -2391,7 +2425,7 @@ static void rb_apply_skip_limit(result_builder_t *rb, int skip_n, int limit) {
}
static void rb_apply_distinct(result_builder_t *rb) {
- if (rb->row_count <= 1) {
+ if (rb->row_count <= SKIP_ONE) {
return;
}
int kept = 1;
@@ -2560,7 +2594,7 @@ static int with_agg_find_or_create(with_agg_t **aggs, int *agg_cnt, int *agg_cap
}
}
if (*agg_cnt >= *agg_cap) {
- *agg_cap *= 2;
+ *agg_cap *= PAIR_LEN;
*aggs = safe_realloc(*aggs, *agg_cap * sizeof(with_agg_t));
}
int found = (*agg_cnt)++;
@@ -2571,8 +2605,8 @@ static int with_agg_find_or_create(with_agg_t **aggs, int *agg_cnt, int *agg_cap
(*aggs)[found].mins = calloc(wc->count, sizeof(double));
(*aggs)[found].maxs = calloc(wc->count, sizeof(double));
for (int ci = 0; ci < wc->count; ci++) {
- (*aggs)[found].mins[ci] = 1e308;
- (*aggs)[found].maxs[ci] = -1e308;
+ (*aggs)[found].mins[ci] = CYP_DBL_MAX;
+ (*aggs)[found].maxs[ci] = -CYP_DBL_MAX;
}
for (int ci = 0; ci < wc->count; ci++) {
if (wc->items[ci].func) {
@@ -2624,7 +2658,7 @@ static void with_agg_format(const char *func, with_agg_t *agg, int ci, char *buf
/* Add a virtual variable binding for one WITH item */
static void with_add_vbinding_var(binding_t *vb, const char *alias, const char *val) {
cbm_node_t vn = {.name = heap_strdup(val), .qualified_name = heap_strdup(alias)};
- if (vb->var_count < 16) {
+ if (vb->var_count < CYP_BUF_16) {
vb->var_names[vb->var_count] = vn.qualified_name;
vb->var_nodes[vb->var_count] = vn;
vb->var_count++;
@@ -2780,18 +2814,18 @@ static int collect_pattern_vars(cbm_query_t *q, const char **vars, int max_vars)
/* Build star-projection columns: var.name, var.qualified_name, var.label, var.file_path */
static void build_star_columns(result_builder_t *rb, const char **vars, int vc) {
- int col_n = vc * 4;
+ int col_n = vc * CYP_NODE_COLS;
const char *col_names[128];
for (int v = 0; v < vc; v++) {
char buf[128];
snprintf(buf, sizeof(buf), "%s.name", vars[v]);
- col_names[(size_t)v * 4] = heap_strdup(buf);
+ col_names[(size_t)v * CYP_NODE_COLS] = heap_strdup(buf);
snprintf(buf, sizeof(buf), "%s.qualified_name", vars[v]);
- col_names[((size_t)v * 4) + 1] = heap_strdup(buf);
+ col_names[((size_t)v * CYP_NODE_COLS) + 1] = heap_strdup(buf);
snprintf(buf, sizeof(buf), "%s.label", vars[v]);
- col_names[((size_t)v * 4) + 2] = heap_strdup(buf);
+ col_names[((size_t)v * CYP_NODE_COLS) + 2] = heap_strdup(buf);
snprintf(buf, sizeof(buf), "%s.file_path", vars[v]);
- col_names[((size_t)v * 4) + 3] = heap_strdup(buf);
+ col_names[((size_t)v * CYP_NODE_COLS) + 3] = heap_strdup(buf);
}
rb_set_columns(rb, col_names, col_n);
for (int i = 0; i < col_n; i++) {
@@ -2804,9 +2838,9 @@ static void project_star_var(binding_t *b, const char *var, const char **vals) {
cbm_edge_t *edge = binding_get_edge(b, var);
if (edge) {
vals[0] = edge_prop(edge, "type");
- vals[1] = "";
- vals[2] = "";
- vals[3] = "";
+ vals[SKIP_ONE] = "";
+ vals[PAIR_LEN] = "";
+ vals[CYP_TRIPLE] = "";
return;
}
cbm_node_t *n = binding_get(b, var);
@@ -2819,7 +2853,7 @@ static void project_star_var(binding_t *b, const char *var, const char **vals) {
/* Project one binding row for RETURN * */
static void project_star_row(binding_t *b, const char **vars, int vc, const char **vals) {
for (int v = 0; v < vc; v++) {
- project_star_var(b, vars[v], vals + ((size_t)v * 4));
+ project_star_var(b, vars[v], vals + ((size_t)v * CYP_NODE_COLS));
}
}
@@ -2899,8 +2933,8 @@ static void ret_agg_init_group(ret_agg_entry_t *entry, const char *key, int item
entry->collect_lists = calloc(item_count, sizeof(char **));
entry->collect_counts = calloc(item_count, sizeof(int));
for (int ci = 0; ci < item_count; ci++) {
- entry->mins[ci] = 1e308;
- entry->maxs[ci] = -1e308;
+ entry->mins[ci] = CYP_DBL_MAX;
+ entry->maxs[ci] = -CYP_DBL_MAX;
entry->group_vals[ci] = heap_strdup(vals[ci]);
}
}
@@ -2998,7 +3032,7 @@ static void execute_return_agg(cbm_return_clause_t *ret, binding_t *bindings, in
const char *vals[32];
ret_agg_build_key(ret, &bindings[bi], key, sizeof(key), vals);
- int found = -1;
+ int found = CYP_FOUND_NONE;
for (int a = 0; a < agg_count; a++) {
if (strcmp(aggs[a].group_key, key) == 0) {
found = a;
@@ -3007,7 +3041,7 @@ static void execute_return_agg(cbm_return_clause_t *ret, binding_t *bindings, in
}
if (found < 0) {
if (agg_count >= agg_cap) {
- agg_cap *= 2;
+ agg_cap *= PAIR_LEN;
aggs = safe_realloc(aggs, agg_cap * sizeof(ret_agg_entry_t));
}
found = agg_count++;
@@ -3072,16 +3106,16 @@ static void execute_return_simple(cbm_return_clause_t *ret, binding_t *bindings,
/* Build default 3-column headers (name, qualified_name, label) per variable */
static void build_default_columns(result_builder_t *rb, const char **vars, int vc) {
- int col_n = vc * 3;
- const char *col_names[48];
+ int col_n = vc * CYP_EDGE_COLS;
+ const char *col_names[CYP_COL_BUF];
for (int v = 0; v < vc; v++) {
char buf[128];
snprintf(buf, sizeof(buf), "%s.name", vars[v]);
- col_names[(size_t)v * 3] = heap_strdup(buf);
+ col_names[(size_t)v * CYP_EDGE_COLS] = heap_strdup(buf);
snprintf(buf, sizeof(buf), "%s.qualified_name", vars[v]);
- col_names[((size_t)v * 3) + 1] = heap_strdup(buf);
+ col_names[((size_t)v * CYP_EDGE_COLS) + SKIP_ONE] = heap_strdup(buf);
snprintf(buf, sizeof(buf), "%s.label", vars[v]);
- col_names[((size_t)v * 3) + 2] = heap_strdup(buf);
+ col_names[((size_t)v * CYP_EDGE_COLS) + PAIR_LEN] = heap_strdup(buf);
}
rb_set_columns(rb, col_names, col_n);
for (int i = 0; i < col_n; i++) {
@@ -3092,21 +3126,22 @@ static void build_default_columns(result_builder_t *rb, const char **vars, int v
/* Default projection when no RETURN clause */
static void execute_default_projection(cbm_pattern_t *pat0, binding_t *bindings, int bind_count,
int max_rows, result_builder_t *rb) {
- const char *vars[16];
+ const char *vars[CYP_MAX_VARS];
int vc = 0;
- for (int ni = 0; ni < pat0->node_count && vc < 16; ni++) {
+ for (int ni = 0; ni < pat0->node_count && vc < CYP_MAX_VARS; ni++) {
if (pat0->nodes[ni].variable) {
vars[vc++] = pat0->nodes[ni].variable;
}
}
build_default_columns(rb, vars, vc);
for (int bi = 0; bi < bind_count && rb->row_count < max_rows; bi++) {
- const char *vals[48];
+ const char *vals[CYP_COL_BUF];
for (int v = 0; v < vc; v++) {
cbm_node_t *n = binding_get(&bindings[bi], vars[v]);
- vals[(size_t)v * 3] = n && n->name ? n->name : "";
- vals[((size_t)v * 3) + 1] = n && n->qualified_name ? n->qualified_name : "";
- vals[((size_t)v * 3) + 2] = n && n->label ? n->label : "";
+ vals[(size_t)v * CYP_EDGE_COLS] = n && n->name ? n->name : "";
+ vals[((size_t)v * CYP_EDGE_COLS) + SKIP_ONE] =
+ n && n->qualified_name ? n->qualified_name : "";
+ vals[((size_t)v * CYP_EDGE_COLS) + PAIR_LEN] = n && n->label ? n->label : "";
}
rb_add_row(rb, vals);
}
@@ -3115,7 +3150,7 @@ static void execute_default_projection(cbm_pattern_t *pat0, binding_t *bindings,
/* Cross-join node-only pattern into existing bindings */
static void cross_join_nodes(binding_t **bindings, int *bind_count, cbm_node_t *extra_nodes,
int extra_count, const char *nvar, bool opt) {
- binding_t *new_bindings = malloc(((*bind_count * extra_count) + 1) * sizeof(binding_t));
+ binding_t *new_bindings = malloc(((*bind_count * extra_count) + SKIP_ONE) * sizeof(binding_t));
int new_count = 0;
for (int bi = 0; bi < *bind_count; bi++) {
for (int ni = 0; ni < extra_count; ni++) {
@@ -3142,14 +3177,15 @@ static void cross_join_nodes(binding_t **bindings, int *bind_count, cbm_node_t *
static void cross_join_with_rels(cbm_store_t *store, cbm_pattern_t *patn, binding_t **bindings,
int *bind_count, cbm_node_t *extra_nodes, int extra_count,
const char *nvar, bool opt) {
- binding_t *new_bindings = malloc(((*bind_count * extra_count * 10) + 1) * sizeof(binding_t));
+ binding_t *new_bindings =
+ malloc(((*bind_count * extra_count * CYP_GROWTH_10) + SKIP_ONE) * sizeof(binding_t));
int new_count = 0;
for (int bi = 0; bi < *bind_count; bi++) {
for (int ni = 0; ni < extra_count; ni++) {
binding_t nb = {0};
binding_copy(&nb, &(*bindings)[bi]);
binding_set(&nb, nvar, &extra_nodes[ni]);
- binding_t *tmp = malloc(2 * sizeof(binding_t));
+ binding_t *tmp = malloc(PAIR_LEN * sizeof(binding_t));
tmp[0] = nb;
int tc = 1;
int tcap = 1;
@@ -3242,7 +3278,7 @@ static int execute_single(cbm_store_t *store, cbm_query_t *q, const char *projec
scan_pattern_nodes(store, project, max_rows, &pat0->nodes[0], &scanned, &scan_count);
/* Build initial bindings with early WHERE */
- int bind_cap = scan_count > 0 ? scan_count : 1;
+ int bind_cap = scan_count > 0 ? scan_count : SKIP_ONE;
binding_t *bindings = malloc((bind_cap + 1) * sizeof(binding_t));
int bind_count = 0;
const char *var_name = pat0->nodes[0].variable ? pat0->nodes[0].variable : "_n0";
diff --git a/src/discover/discover.c b/src/discover/discover.c
index 0f82c6f67..61c288a1d 100644
--- a/src/discover/discover.c
+++ b/src/discover/discover.c
@@ -11,6 +11,7 @@
#include "discover/discover.h"
#include "cbm.h" // CBMLanguage, CBM_LANG_COUNT, CBM_LANG_JSON
+#include "foundation/constants.h"
#include "foundation/compat_fs.h"
#include <stdint.h> // int64_t
#include <stdio.h>
@@ -208,7 +209,7 @@ typedef struct {
static void fl_add(file_list_t *fl, const char *abs_path, const char *rel_path, CBMLanguage lang,
int64_t size) {
if (fl->count >= fl->capacity) {
- int new_cap = fl->capacity ? fl->capacity * 2 : 256;
+ int new_cap = fl->capacity ? fl->capacity * PAIR_LEN : CBM_SZ_256;
cbm_file_info_t *new_files = realloc(fl->files, new_cap * sizeof(cbm_file_info_t));
if (!new_files) {
return;
@@ -290,14 +291,14 @@ static CBMLanguage detect_file_language(const char *entry_name, const char *abs_
static int safe_stat(const char *abs_path, struct stat *st) {
#ifdef _WIN32
if (stat(abs_path, st) != 0) {
- return -1;
+ return CBM_NOT_FOUND;
}
#else
if (lstat(abs_path, st) != 0) {
- return -1;
+ return CBM_NOT_FOUND;
}
if (S_ISLNK(st->st_mode)) {
- return -1;
+ return CBM_NOT_FOUND;
}
#endif
return 0;
@@ -317,41 +318,71 @@ static void walk_dir_process_file(const char *abs_path, const char *rel_path, co
fl_add(out, abs_path, rel_path, lang, size);
}
+typedef struct {
+ char dir[CBM_SZ_4K];
+ char prefix[CBM_SZ_4K];
+} walk_frame_t;
+#define WALK_STACK_CAP 512
+/* Build abs/rel paths and process one directory entry. */
+static void walk_dir_process_entry(cbm_dirent_t *entry, const walk_frame_t *frame,
+ const cbm_discover_opts_t *opts,
+ const cbm_gitignore_t *gitignore,
+ const cbm_gitignore_t *cbmignore, walk_frame_t *stack, int *top,
+ file_list_t *out) {
+ char abs_path[CBM_SZ_4K];
+ char rel_path[CBM_SZ_4K];
+ snprintf(abs_path, sizeof(abs_path), "%s/%s", frame->dir, entry->name);
+ if (frame->prefix[0] != '\0') {
+ snprintf(rel_path, sizeof(rel_path), "%s/%s", frame->prefix, entry->name);
+ } else {
+ snprintf(rel_path, sizeof(rel_path), "%s", entry->name);
+ }
+
+ struct stat st;
+ if (safe_stat(abs_path, &st) != 0) {
+ return;
+ }
+
+ if (S_ISDIR(st.st_mode)) {
+ if (!should_skip_directory(entry->name, rel_path, opts, gitignore, cbmignore)) {
+ if (*top < WALK_STACK_CAP) {
+ snprintf(stack[*top].dir, CBM_SZ_4K, "%s", abs_path);
+ snprintf(stack[*top].prefix, CBM_SZ_4K, "%s", rel_path);
+ (*top)++;
+ }
+ }
+ } else if (S_ISREG(st.st_mode)) {
+ walk_dir_process_file(abs_path, rel_path, entry->name, opts, gitignore, cbmignore,
+ st.st_size, out);
+ }
+}
+
static void walk_dir(const char *dir_path, const char *rel_prefix, const cbm_discover_opts_t *opts,
const cbm_gitignore_t *gitignore, const cbm_gitignore_t *cbmignore,
file_list_t *out) {
- cbm_dir_t *d = cbm_opendir(dir_path);
- if (!d) {
+ walk_frame_t *stack = malloc(WALK_STACK_CAP * sizeof(walk_frame_t));
+ if (!stack) {
return;
}
+ int top = 0;
+ snprintf(stack[top].dir, CBM_SZ_4K, "%s", dir_path);
+ snprintf(stack[top].prefix, CBM_SZ_4K, "%s", rel_prefix);
+ top++;
- cbm_dirent_t *entry;
- while ((entry = cbm_readdir(d)) != NULL) {
- char abs_path[4096];
- char rel_path[4096];
- snprintf(abs_path, sizeof(abs_path), "%s/%s", dir_path, entry->name);
- if (rel_prefix[0] != '\0') {
- snprintf(rel_path, sizeof(rel_path), "%s/%s", rel_prefix, entry->name);
- } else {
- snprintf(rel_path, sizeof(rel_path), "%s", entry->name);
- }
-
- struct stat st;
- if (safe_stat(abs_path, &st) != 0) {
+ while (top > 0) {
+ walk_frame_t frame = stack[--top];
+ cbm_dir_t *d = cbm_opendir(frame.dir);
+ if (!d) {
continue;
}
- if (S_ISDIR(st.st_mode)) {
- if (!should_skip_directory(entry->name, rel_path, opts, gitignore, cbmignore)) {
- walk_dir(abs_path, rel_path, opts, gitignore, cbmignore, out);
- }
- } else if (S_ISREG(st.st_mode)) {
- walk_dir_process_file(abs_path, rel_path, entry->name, opts, gitignore, cbmignore,
- st.st_size, out);
+ cbm_dirent_t *entry;
+ while ((entry = cbm_readdir(d)) != NULL) {
+ walk_dir_process_entry(entry, &frame, opts, gitignore, cbmignore, stack, &top, out);
}
+ cbm_closedir(d);
}
-
- cbm_closedir(d);
+ free(stack);
}
/* ── Public API ──────────────────────────────────────────────────── */
@@ -359,7 +390,7 @@ static void walk_dir(const char *dir_path, const char *rel_prefix, const cbm_dis
int cbm_discover(const char *repo_path, const cbm_discover_opts_t *opts, cbm_file_info_t **out,
int *count) {
if (!repo_path || !out || !count) {
- return -1;
+ return CBM_NOT_FOUND;
}
*out = NULL;
@@ -368,12 +399,12 @@ int cbm_discover(const char *repo_path, const cbm_discover_opts_t *opts, cbm_fil
/* Verify directory exists */
struct stat st;
if (stat(repo_path, &st) != 0 || !S_ISDIR(st.st_mode)) {
- return -1;
+ return CBM_NOT_FOUND;
}
/* Load gitignore if .git directory exists */
cbm_gitignore_t *gitignore = NULL;
- char gi_path[4096];
+ char gi_path[CBM_SZ_4K];
snprintf(gi_path, sizeof(gi_path), "%s/.git", repo_path);
struct stat gi_stat;
if (stat(gi_path, &gi_stat) == 0 && S_ISDIR(gi_stat.st_mode)) {
diff --git a/src/discover/discover.h b/src/discover/discover.h
index 817682775..d879e31b5 100644
--- a/src/discover/discover.h
+++ b/src/discover/discover.h
@@ -2,7 +2,7 @@
* discover.h — File discovery, language detection, and gitignore matching.
*
* Provides:
- * - Language detection from filename/extension (64 languages)
+ * - Language detection from filename/extension (CBM_SZ_64 languages)
* - .m file disambiguation (Objective-C vs Magma vs MATLAB)
* - Gitignore-style pattern parsing and matching
* - Recursive directory walk with hardcoded + gitignore filtering
diff --git a/src/discover/gitignore.c b/src/discover/gitignore.c
index 97c97fad1..4c9700884 100644
--- a/src/discover/gitignore.c
+++ b/src/discover/gitignore.c
@@ -11,6 +11,9 @@
* - trailing / for directory-only matching
* - patterns with / are rooted (anchored to base)
*/
+#include "foundation/constants.h"
+
+enum { GI_INIT_CAP = 16, GI_CHAR_IDX1 = 1, GI_CHAR_IDX2 = 2, GI_SKIP3 = 3 };
#include "discover/discover.h"
#include <ctype.h>
@@ -36,10 +39,11 @@ struct cbm_gitignore {
/* ── Pattern matching engine ─────────────────────────────────────── */
/* Forward declaration for recursive calls. */
-static bool glob_match(const char *pat, const char *str);
+static bool glob_match(const char *pat, const char *str); // NOLINT(misc-no-recursion)
/* Match a ** (doublestar-slash) pattern: try rest at every / boundary. */
-static bool glob_match_doublestar_slash(const char *pat, const char *str) {
+static bool glob_match_doublestar_slash(const char *pat,
+ const char *str) { // NOLINT(misc-no-recursion)
if (glob_match(pat, str)) {
return true;
}
@@ -52,7 +56,8 @@ static bool glob_match_doublestar_slash(const char *pat, const char *str) {
}
/* Match a ** (doublestar) followed by non-slash: try at every position. */
-static bool glob_match_doublestar_any(const char *pat, const char *str) {
+static bool glob_match_doublestar_any(const char *pat,
+ const char *str) { // NOLINT(misc-no-recursion)
for (const char *s = str;; s++) {
if (glob_match(pat, s)) {
return true;
@@ -64,7 +69,7 @@ static bool glob_match_doublestar_any(const char *pat, const char *str) {
}
/* Match a * (single star): match any sequence not containing /. */
-static bool glob_match_star(const char *pat, const char *str) {
+static bool glob_match_star(const char *pat, const char *str) { // NOLINT(misc-no-recursion)
for (const char *s = str;; s++) {
if (glob_match(pat, s)) {
return true;
@@ -86,7 +91,7 @@ static bool glob_match_charclass(const char *pat, char ch, const char **pat_out)
bool matched = false;
char prev = 0;
while (*pat && *pat != ']') {
- if (*pat == '-' && prev && pat[1] && pat[1] != ']') {
+ if (*pat == '-' && prev && pat[GI_CHAR_IDX1] && pat[GI_CHAR_IDX1] != ']') {
pat++;
if (ch >= prev && ch <= *pat) {
matched = true;
@@ -113,19 +118,19 @@ static bool glob_match_charclass(const char *pat, char ch, const char **pat_out)
* Handles: * (non-slash), ** (any path), ? (single non-slash), [class]
*/
/* Handle ** at current position. Returns match result. */
-static bool glob_match_doublestar(const char *pat, const char *str) {
- if (pat[2] == '/') {
- return glob_match_doublestar_slash(pat + 3, str);
+static bool glob_match_doublestar(const char *pat, const char *str) { // NOLINT(misc-no-recursion)
+ if (pat[GI_CHAR_IDX2] == '/') {
+ return glob_match_doublestar_slash(pat + GI_SKIP3, str);
}
- if (pat[2] == '\0') {
+ if (pat[GI_CHAR_IDX2] == '\0') {
return true;
}
- return glob_match_doublestar_any(pat + 2, str);
+ return glob_match_doublestar_any(pat + GI_CHAR_IDX2, str);
}
-static bool glob_match(const char *pat, const char *str) {
+static bool glob_match(const char *pat, const char *str) { // NOLINT(misc-no-recursion)
while (*pat && *str) {
- if (pat[0] == '*' && pat[1] == '*') {
+ if (pat[0] == '*' && pat[GI_CHAR_IDX1] == '*') {
return glob_match_doublestar(pat, str);
}
@@ -231,7 +236,7 @@ static void gi_add_pattern(cbm_gitignore_t *gi, const char *line, int len) {
/* Grow array if needed */
if (gi->count >= gi->capacity) {
- int new_cap = gi->capacity ? gi->capacity * 2 : 16;
+ int new_cap = gi->capacity ? gi->capacity * PAIR_LEN : GI_INIT_CAP;
gi_pattern_t *new_patterns = realloc(gi->patterns, new_cap * sizeof(gi_pattern_t));
if (!new_patterns) {
free(p.pattern);
@@ -341,7 +346,7 @@ bool cbm_gitignore_matches(const cbm_gitignore_t *gi, const char *rel_path, bool
/* Extract the basename for non-rooted pattern matching */
const char *basename = strrchr(rel_path, '/');
- basename = basename ? basename + 1 : rel_path;
+ basename = basename ? basename + SKIP_ONE : rel_path;
bool matched = false;
diff --git a/src/discover/language.c b/src/discover/language.c
index aa3283521..951b248b8 100644
--- a/src/discover/language.c
+++ b/src/discover/language.c
@@ -10,6 +10,10 @@
#include "discover/userconfig.h"
#include "cbm.h" // CBMLanguage, CBM_LANG_*
+#include "foundation/constants.h"
+
+enum { LANG_SCAN_PASSES = 2 };
+#define SLEN(s) (sizeof(s) - 1)
#include <ctype.h>
#include <stdio.h>
#include <string.h>
@@ -417,7 +421,7 @@ CBMLanguage cbm_language_for_filename(const char *filename) {
if (lang != CBM_LANG_COUNT) {
return lang;
}
- p = strchr(p + 1, '.');
+ p = strchr(p + SKIP_ONE, '.');
}
}
@@ -456,7 +460,7 @@ static bool has_magma_end_markers(const char *buf) {
/* Check for "intrinsic Name(" or "procedure Name(" patterns. */
static bool has_magma_callable_pattern(const char *buf) {
const char *markers[] = {"intrinsic ", "procedure "};
- for (int i = 0; i < 2; i++) {
+ for (int i = 0; i < LANG_SCAN_PASSES; i++) {
const char *p = strstr(buf, markers[i]);
if (!p) {
continue;
@@ -480,16 +484,18 @@ static bool has_matlab_line_markers(const char *buf) {
while (*p == ' ' || *p == '\t') {
p++;
}
- if (strncmp(p, "function ", 9) == 0 || strncmp(p, "function\t", 9) == 0 ||
- strncmp(p, "classdef ", 9) == 0 || strncmp(p, "classdef\t", 9) == 0 ||
- strncmp(p, "%%", 2) == 0 || (*p == '%' && *(p + 1) != '{')) {
+ if (strncmp(p, "function ", SLEN("function ")) == 0 ||
+ strncmp(p, "function\t", SLEN("function\t")) == 0 ||
+ strncmp(p, "classdef ", SLEN("classdef ")) == 0 ||
+ strncmp(p, "classdef\t", SLEN("classdef\t")) == 0 || strncmp(p, "%%", PAIR_LEN) == 0 ||
+ (*p == '%' && *(p + SKIP_ONE) != '{')) {
return true;
}
const char *nl = strchr(line, '\n');
if (!nl) {
break;
}
- line = nl + 1;
+ line = nl + SKIP_ONE;
}
return false;
}
@@ -505,8 +511,8 @@ CBMLanguage cbm_disambiguate_m(const char *path) {
}
/* Read first 4KB */
- char buf[4096 + 1];
- size_t n = fread(buf, 1, 4096, f);
+ char buf[CBM_SZ_4K + SKIP_ONE];
+ size_t n = fread(buf, SKIP_ONE, CBM_SZ_4K, f);
buf[n] = '\0';
(void)fclose(f);
diff --git a/src/discover/userconfig.c b/src/discover/userconfig.c
index 4b6d27b80..a468463a0 100644
--- a/src/discover/userconfig.c
+++ b/src/discover/userconfig.c
@@ -10,6 +10,9 @@
* skipped (fail-open). Missing files are silently ignored.
*/
#include "discover/userconfig.h"
+#include "foundation/constants.h"
+
+enum { MAX_CONFIG_SIZE = 65536 };
#include "foundation/log.h"
#include <yyjson/yyjson.h>
@@ -130,9 +133,9 @@ static CBMLanguage lang_from_string(const char *s) {
}
/* Build a lowercase copy for comparison */
- char lower[64];
+ char lower[CBM_SZ_64];
size_t i;
- for (i = 0; i < sizeof(lower) - 1 && s[i]; i++) {
+ for (i = 0; i < sizeof(lower) - SKIP_ONE && s[i]; i++) {
lower[i] = (char)tolower((unsigned char)s[i]);
}
lower[i] = '\0';
@@ -153,14 +156,21 @@ static CBMLanguage lang_from_string(const char *s) {
* Uses $XDG_CONFIG_HOME if set, else ~/.config.
*/
static void cbm_app_config_dir(char *buf, size_t bufsz) {
- // NOLINT(concurrency-mt-unsafe) — called before worker threads
- const char *xdg = getenv("XDG_CONFIG_HOME");
- if (xdg && xdg[0]) {
+ char xdg[CBM_SZ_512] = {0};
+ char home[CBM_SZ_512] = {0};
+ const char *env_val = getenv("XDG_CONFIG_HOME");
+ if (env_val && env_val[0]) {
+ snprintf(xdg, sizeof(xdg), "%s", env_val);
+ }
+ if (xdg[0]) {
snprintf(buf, bufsz, "%s/codebase-memory-mcp", xdg);
} else {
- const char *home = getenv("HOME"); // NOLINT(concurrency-mt-unsafe)
- if (!home || !home[0]) {
- home = "/tmp";
+ env_val = getenv("HOME");
+ if (env_val && env_val[0]) {
+ snprintf(home, sizeof(home), "%s", env_val);
+ }
+ if (!home[0]) {
+ snprintf(home, sizeof(home), "/tmp");
}
snprintf(buf, bufsz, "%s/.config/codebase-memory-mcp", home);
}
@@ -219,15 +229,15 @@ static int parse_extra_extensions(yyjson_val *root, cbm_userext_t **entries, int
}
/* Grow the array */
- cbm_userext_t *tmp = realloc(*entries, (size_t)(*count + 1) * sizeof(cbm_userext_t));
+ cbm_userext_t *tmp = realloc(*entries, (size_t)(*count + SKIP_ONE) * sizeof(cbm_userext_t));
if (!tmp) {
- return -1;
+ return CBM_NOT_FOUND;
}
*entries = tmp;
char *ext_copy = strdup(ext_str);
if (!ext_copy) {
- return -1;
+ return CBM_NOT_FOUND;
}
(*entries)[*count].ext = ext_copy;
@@ -248,26 +258,35 @@ static int load_config_file(const char *path, cbm_userext_t **entries, int *coun
return 0; /* file absent — silently ignore */
}
- fseek(f, 0, SEEK_END);
+ if (fseek(f, 0, SEEK_END) != 0) {
+ (void)fclose(f);
+ return 0;
+ }
long len = ftell(f);
- fseek(f, 0, SEEK_SET);
+ if (fseek(f, 0, SEEK_SET) != 0) {
+ (void)fclose(f);
+ return 0;
+ }
- if (len <= 0 || len > 65536) {
- fclose(f);
- if (len > 65536) {
+ if (len <= 0 || len > MAX_CONFIG_SIZE) {
+ (void)fclose(f);
+ if (len > MAX_CONFIG_SIZE) {
cbm_log_warn("userconfig.file_too_large", "path", path);
}
return 0;
}
- char *buf = malloc((size_t)len + 1);
+ char *buf = malloc((size_t)len + SKIP_ONE);
if (!buf) {
- fclose(f);
- return -1;
+ (void)fclose(f);
+ return CBM_NOT_FOUND;
}
- size_t nread = fread(buf, 1, (size_t)len, f);
- fclose(f);
+ size_t nread = fread(buf, SKIP_ONE, (size_t)len, f);
+ (void)fclose(f);
+ if (nread > (size_t)len) {
+ nread = (size_t)len;
+ }
buf[nread] = '\0';
yyjson_doc *doc = yyjson_read(buf, nread, 0);
@@ -287,7 +306,7 @@ static int load_config_file(const char *path, cbm_userext_t **entries, int *coun
/* ── Public API ──────────────────────────────────────────────────── */
cbm_userconfig_t *cbm_userconfig_load(const char *repo_path) {
- cbm_userconfig_t *cfg = calloc(1, sizeof(cbm_userconfig_t));
+ cbm_userconfig_t *cfg = calloc(CBM_ALLOC_ONE, sizeof(cbm_userconfig_t));
if (!cfg) {
return NULL;
}
@@ -297,7 +316,7 @@ cbm_userconfig_t *cbm_userconfig_load(const char *repo_path) {
/* ── Step 1: Load global config ── */
enum { PATH_BUF_SZ = 1280 };
- char global_dir[1024];
+ char global_dir[CBM_SZ_1K];
cbm_app_config_dir(global_dir, sizeof(global_dir));
char global_path[PATH_BUF_SZ];
@@ -342,8 +361,8 @@ cbm_userconfig_t *cbm_userconfig_load(const char *repo_path) {
if (entries[g].ext && strcmp(entries[g].ext, entries[p].ext) == 0) {
/* Remove global entry: overwrite with last global entry */
free(entries[g].ext);
- entries[g] = entries[global_count - 1];
- entries[global_count - 1].ext = NULL; /* mark as consumed */
+ entries[g] = entries[global_count - SKIP_ONE];
+ entries[global_count - SKIP_ONE].ext = NULL; /* mark as consumed */
global_count--;
break;
}
diff --git a/src/foundation/arena.c b/src/foundation/arena.c
index 81e4e3fde..f6345dbe8 100644
--- a/src/foundation/arena.c
+++ b/src/foundation/arena.c
@@ -10,6 +10,9 @@
* Arena blocks use malloc/free (= mimalloc in production builds).
*/
#include "arena.h"
+#include "foundation/constants.h"
+
+enum { ARENA_ALIGN = 7, ARENA_GROW_OK = 1 };
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
@@ -21,14 +24,14 @@ void cbm_arena_init(CBMArena *a) {
void cbm_arena_init_sized(CBMArena *a, size_t block_size) {
memset(a, 0, sizeof(*a));
- if (block_size < 64) {
- block_size = 64; /* minimum sanity */
+ if (block_size < CBM_SZ_64) {
+ block_size = CBM_SZ_64; /* minimum sanity */
}
a->block_size = block_size;
a->blocks[0] = (char *)malloc(block_size);
if (a->blocks[0]) {
a->block_sizes[0] = block_size;
- a->nblocks = 1;
+ a->nblocks = SKIP_ONE;
}
}
@@ -36,7 +39,7 @@ static int arena_grow(CBMArena *a, size_t min_size) {
if (a->nblocks >= CBM_ARENA_MAX_BLOCKS) {
return 0;
}
- size_t new_size = a->block_size * 2;
+ size_t new_size = a->block_size * PAIR_LEN;
if (new_size < min_size) {
new_size = min_size;
}
@@ -49,7 +52,7 @@ static int arena_grow(CBMArena *a, size_t min_size) {
a->nblocks++;
a->block_size = new_size;
a->used = 0;
- return 1;
+ return ARENA_GROW_OK;
}
void *cbm_arena_alloc(CBMArena *a, size_t n) {
@@ -57,7 +60,7 @@ void *cbm_arena_alloc(CBMArena *a, size_t n) {
return NULL;
}
/* 8-byte alignment */
- n = (n + 7) & ~(size_t)7;
+ n = (n + ARENA_ALIGN) & ~(size_t)ARENA_ALIGN;
if (a->nblocks == 0) {
return NULL;
}
@@ -66,7 +69,7 @@ void *cbm_arena_alloc(CBMArena *a, size_t n) {
return NULL;
}
}
- char *ptr = a->blocks[a->nblocks - 1] + a->used;
+ char *ptr = a->blocks[a->nblocks - SKIP_ONE] + a->used;
a->used += n;
a->total_alloc += n;
return ptr;
@@ -85,9 +88,9 @@ char *cbm_arena_strdup(CBMArena *a, const char *s) {
return NULL;
}
size_t len = strlen(s);
- char *dst = (char *)cbm_arena_alloc(a, len + 1);
+ char *dst = (char *)cbm_arena_alloc(a, len + SKIP_ONE);
if (dst) {
- memcpy(dst, s, len + 1);
+ memcpy(dst, s, len + SKIP_ONE);
}
return dst;
}
@@ -96,7 +99,7 @@ char *cbm_arena_strndup(CBMArena *a, const char *s, size_t len) {
if (!s) {
return NULL;
}
- char *dst = (char *)cbm_arena_alloc(a, len + 1);
+ char *dst = (char *)cbm_arena_alloc(a, len + SKIP_ONE);
if (dst) {
memcpy(dst, s, len);
dst[len] = '\0';
@@ -113,32 +116,32 @@ char *cbm_arena_sprintf(CBMArena *a, const char *fmt, ...) {
return NULL;
}
- char *dst = (char *)cbm_arena_alloc(a, (size_t)needed + 1);
+ char *dst = (char *)cbm_arena_alloc(a, (size_t)needed + SKIP_ONE);
if (!dst) {
return NULL;
}
va_start(args, fmt);
- vsnprintf(dst, (size_t)needed + 1, fmt, args);
+ vsnprintf(dst, (size_t)needed + SKIP_ONE, fmt, args);
va_end(args);
return dst;
}
void cbm_arena_reset(CBMArena *a) {
/* Keep first block, free the rest */
- for (int i = 1; i < a->nblocks; i++) {
+ for (int i = SKIP_ONE; i < a->nblocks; i++) {
free(a->blocks[i]);
a->blocks[i] = NULL;
a->block_sizes[i] = 0;
}
- if (a->nblocks > 1) {
- a->nblocks = 1;
+ if (a->nblocks > SKIP_ONE) {
+ a->nblocks = SKIP_ONE;
}
a->used = 0;
a->total_alloc = 0;
/* Reset block_size to match surviving block — prevents overflow if
- * block_size grew during previous allocations (e.g., 128 → 256). */
- if (a->nblocks == 1) {
+ * block_size grew during previous allocations (e.g., CBM_SZ_128 → CBM_SZ_256). */
+ if (a->nblocks == SKIP_ONE) {
a->block_size = a->block_sizes[0];
}
}
diff --git a/src/foundation/compat.c b/src/foundation/compat.c
index c91549549..a17621e06 100644
--- a/src/foundation/compat.c
+++ b/src/foundation/compat.c
@@ -25,7 +25,7 @@ char *cbm_strndup(const char *s, size_t n) {
while (len < n && s[len]) {
len++;
}
- char *d = (char *)malloc(len + 1);
+ char *d = (char *)malloc(len + SKIP_ONE);
if (d) {
memcpy(d, s, len);
d[len] = '\0';
@@ -55,8 +55,8 @@ char *cbm_strcasestr(const char *haystack, const char *needle) {
#include <direct.h>
char *cbm_mkdtemp(char *tmpl) {
/* Build path in static buffer, then copy back to caller.
- * Callers must provide buffers >= 256 bytes (all test code does). */
- static char buf[512];
+ * Callers must provide buffers >= CBM_SZ_256 bytes (all test code does). */
+ static char buf[CBM_SZ_512];
if (strncmp(tmpl, "/tmp/", 5) == 0) {
const char *tmp = getenv("TEMP");
if (!tmp)
@@ -71,7 +71,7 @@ char *cbm_mkdtemp(char *tmpl) {
return NULL;
if (_mkdir(buf) != 0)
return NULL;
- /* Copy result back — callers now use char[256]+ buffers */
+ /* Copy result back — callers now use char[CBM_SZ_256]+ buffers */
strcpy(tmpl, buf);
return tmpl;
}
@@ -82,7 +82,7 @@ char *cbm_mkdtemp(char *tmpl) {
#ifdef _WIN32
int cbm_mkstemp(char *tmpl) {
/* Rewrite /tmp/ to %TEMP%\ like cbm_mkdtemp */
- static char buf[512];
+ static char buf[CBM_SZ_512];
if (strncmp(tmpl, "/tmp/", 5) == 0) {
const char *tmp = getenv("TEMP");
if (!tmp)
@@ -94,7 +94,7 @@ int cbm_mkstemp(char *tmpl) {
snprintf(buf, sizeof(buf), "%s", tmpl);
}
if (!_mktemp(buf))
- return -1;
+ return CBM_NOT_FOUND;
int fd = _open(buf, _O_CREAT | _O_RDWR | _O_BINARY, _S_IREAD | _S_IWRITE);
if (fd >= 0)
strcpy(tmpl, buf);
@@ -121,23 +121,23 @@ int cbm_clock_gettime(int clk_id, struct timespec *tp) {
#ifdef _WIN32
ssize_t cbm_getline(char **lineptr, size_t *n, FILE *stream) {
if (!lineptr || !n || !stream) {
- return -1;
+ return CBM_NOT_FOUND;
}
if (!*lineptr || *n == 0) {
- *n = 128;
+ *n = CBM_SZ_128;
*lineptr = (char *)malloc(*n);
if (!*lineptr) {
- return -1;
+ return CBM_NOT_FOUND;
}
}
size_t pos = 0;
int c;
while ((c = fgetc(stream)) != EOF) {
if (pos + 1 >= *n) {
- size_t new_n = *n * 2;
+ size_t new_n = *n * PAIR_LEN;
char *tmp = (char *)realloc(*lineptr, new_n);
if (!tmp) {
- return -1;
+ return CBM_NOT_FOUND;
}
*lineptr = tmp;
*n = new_n;
@@ -148,7 +148,7 @@ ssize_t cbm_getline(char **lineptr, size_t *n, FILE *stream) {
}
}
if (pos == 0 && c == EOF) {
- return -1;
+ return CBM_NOT_FOUND;
}
(*lineptr)[pos] = '\0';
return (ssize_t)pos;
diff --git a/src/foundation/compat.h b/src/foundation/compat.h
index 1b5161466..1e9e14eb8 100644
--- a/src/foundation/compat.h
+++ b/src/foundation/compat.h
@@ -91,7 +91,7 @@ static inline int cbm_nanosleep(const struct timespec *req, struct timespec *rem
/* ── mkdtemp (Windows lacks it) ──────────────────────────────── */
#ifdef _WIN32
/* Translates /tmp/ to %TEMP%\ and copies result back to tmpl.
- * Callers MUST use char buf[256] or larger. */
+ * Callers MUST use char buf[CBM_SZ_256] or larger. */
char *cbm_mkdtemp(char *tmpl);
#else
#define cbm_mkdtemp mkdtemp
diff --git a/src/foundation/compat_fs.c b/src/foundation/compat_fs.c
index 981404624..c97897b38 100644
--- a/src/foundation/compat_fs.c
+++ b/src/foundation/compat_fs.c
@@ -4,6 +4,7 @@
* POSIX: direct wrappers around opendir/readdir/closedir, popen/pclose, mkdir, unlink.
* Windows: FindFirstFile/FindNextFile, _popen/_pclose, _mkdir, _unlink.
*/
+#include "foundation/constants.h"
#include "foundation/compat_fs.h"
#include <stdio.h>
@@ -40,13 +41,13 @@ cbm_dir_t *cbm_opendir(const char *path) {
return NULL;
}
memcpy(pattern, path, len);
- if (len > 0 && path[len - 1] != '\\' && path[len - 1] != '/') {
+ if (len > 0 && path[len - SKIP_ONE] != '\\' && path[len - SKIP_ONE] != '/') {
pattern[len++] = '\\';
}
pattern[len++] = '*';
pattern[len] = '\0';
- cbm_dir_t *d = (cbm_dir_t *)calloc(1, sizeof(cbm_dir_t));
+ cbm_dir_t *d = (cbm_dir_t *)calloc(CBM_ALLOC_ONE, sizeof(cbm_dir_t));
if (!d) {
free(pattern);
return NULL;
@@ -87,7 +88,7 @@ cbm_dirent_t *cbm_readdir(cbm_dir_t *d) {
size_t nlen = strlen(d->find_data.cFileName);
if (nlen >= CBM_DIRENT_NAME_MAX) {
- nlen = CBM_DIRENT_NAME_MAX - 1;
+ nlen = CBM_DIRENT_NAME_MAX - SKIP_ONE;
}
memcpy(d->entry.name, d->find_data.cFileName, nlen);
d->entry.name[nlen] = '\0';
@@ -124,7 +125,7 @@ bool cbm_mkdir_p(const char *path, int mode) {
if (!tmp) {
return false;
}
- for (char *p = tmp + 1; *p; p++) {
+ for (char *p = tmp + SKIP_ONE; *p; p++) {
if (*p == '/' || *p == '\\') {
*p = '\0';
_mkdir(tmp); /* ignore errors for intermediate dirs */
@@ -146,7 +147,7 @@ int cbm_rmdir(const char *path) {
int cbm_exec_no_shell(const char *const *argv) {
if (!argv || !argv[0]) {
- return -1;
+ return CBM_NOT_FOUND;
}
return (int)_spawnvp(_P_WAIT, argv[0], argv);
}
@@ -174,7 +175,7 @@ cbm_dir_t *cbm_opendir(const char *path) {
if (!dir) {
return NULL;
}
- cbm_dir_t *d = (cbm_dir_t *)calloc(1, sizeof(cbm_dir_t));
+ cbm_dir_t *d = (cbm_dir_t *)calloc(CBM_ALLOC_ONE, sizeof(cbm_dir_t));
if (!d) {
closedir(dir);
return NULL;
@@ -191,12 +192,13 @@ cbm_dirent_t *cbm_readdir(cbm_dir_t *d) {
while ((de = readdir(d->dir)) != NULL) {
/* Skip "." and ".." */
if (de->d_name[0] == '.' &&
- (de->d_name[1] == '\0' || (de->d_name[1] == '.' && de->d_name[2] == '\0'))) {
+ (de->d_name[SKIP_ONE] == '\0' ||
+ (de->d_name[SKIP_ONE] == '.' && de->d_name[PAIR_LEN] == '\0'))) {
continue;
}
size_t nlen = strlen(de->d_name);
if (nlen >= CBM_DIRENT_NAME_MAX) {
- nlen = CBM_DIRENT_NAME_MAX - 1;
+ nlen = CBM_DIRENT_NAME_MAX - SKIP_ONE;
}
memcpy(d->entry.name, de->d_name, nlen);
d->entry.name[nlen] = '\0';
@@ -234,7 +236,7 @@ bool cbm_mkdir_p(const char *path, int mode) {
if (!tmp) {
return false;
}
- for (char *p = tmp + 1; *p; p++) {
+ for (char *p = tmp + SKIP_ONE; *p; p++) {
if (*p == '/') {
*p = '\0';
mkdir(tmp, (mode_t)mode); /* ignore intermediate errors */
@@ -256,11 +258,11 @@ int cbm_rmdir(const char *path) {
int cbm_exec_no_shell(const char *const *argv) {
if (!argv || !argv[0]) {
- return -1;
+ return CBM_NOT_FOUND;
}
pid_t pid = fork();
if (pid < 0) {
- return -1;
+ return CBM_NOT_FOUND;
}
if (pid == 0) {
/* Child: exec directly — no shell interpretation */
@@ -272,12 +274,12 @@ int cbm_exec_no_shell(const char *const *argv) {
/* Parent: wait for child */
int status = 0;
if (waitpid(pid, &status, 0) < 0) {
- return -1;
+ return CBM_NOT_FOUND;
}
if (WIFEXITED(status)) {
return WEXITSTATUS(status);
}
- return -1; /* killed by signal */
+ return CBM_NOT_FOUND; /* killed by signal */
}
#endif /* _WIN32 */
diff --git a/src/foundation/compat_regex.c b/src/foundation/compat_regex.c
index 93ab2dd63..14bd815fb 100644
--- a/src/foundation/compat_regex.c
+++ b/src/foundation/compat_regex.c
@@ -4,6 +4,7 @@
* POSIX: direct wrappers around <regex.h>.
* Windows: vendored TRE regex library (BSD-licensed).
*/
+#include "foundation/constants.h"
#include "foundation/compat_regex.h"
#include <string.h>
@@ -13,7 +14,8 @@
/* ── Windows: use vendored TRE regex ─────────────────────────── */
#include "../../vendored/tre/regex.h"
-_Static_assert(sizeof(regex_t) <= 256, "cbm_regex_t opaque buffer too small for TRE regex_t");
+_Static_assert(sizeof(regex_t) <= CBM_SZ_256,
+ "cbm_regex_t opaque buffer too small for TRE regex_t");
static int translate_flags_tre(int flags) {
int tre_flags = 0;
@@ -41,8 +43,8 @@ int cbm_regexec(const cbm_regex_t *r, const char *str, int nmatch, cbm_regmatch_
int rc = tre_regexec(re, str, 0, NULL, eflags);
return rc == 0 ? CBM_REG_OK : CBM_REG_NOMATCH;
}
- regmatch_t pmatch[32];
- int n = nmatch > 32 ? 32 : nmatch;
+ regmatch_t pmatch[CBM_SZ_32];
+ int n = nmatch > CBM_SZ_32 ? CBM_SZ_32 : nmatch;
int rc = tre_regexec(re, str, (size_t)n, pmatch, eflags);
if (rc != 0)
return CBM_REG_NOMATCH;
@@ -66,7 +68,7 @@ void cbm_regfree(cbm_regex_t *r) {
/* Static assert: our opaque buffer is large enough for regex_t.
* If this fires, increase cbm_regex_t.opaque size. */
-_Static_assert(sizeof(regex_t) <= 256, "cbm_regex_t opaque buffer too small for regex_t");
+_Static_assert(sizeof(regex_t) <= CBM_SZ_256, "cbm_regex_t opaque buffer too small for regex_t");
static int translate_flags(int flags) {
int posix_flags = 0;
@@ -101,8 +103,8 @@ int cbm_regexec(const cbm_regex_t *r, const char *str, int nmatch, cbm_regmatch_
}
/* Map through POSIX regmatch_t */
- regmatch_t pmatch[32];
- int n = nmatch > 32 ? 32 : nmatch;
+ regmatch_t pmatch[CBM_SZ_32];
+ int n = nmatch > CBM_SZ_32 ? CBM_SZ_32 : nmatch;
int rc = regexec(re, str, (size_t)n, pmatch, eflags);
if (rc != 0) {
return CBM_REG_NOMATCH;
diff --git a/src/foundation/compat_regex.h b/src/foundation/compat_regex.h
index 70c884bb6..c57245967 100644
--- a/src/foundation/compat_regex.h
+++ b/src/foundation/compat_regex.h
@@ -9,6 +9,7 @@
#ifndef CBM_COMPAT_REGEX_H
#define CBM_COMPAT_REGEX_H
+#include "foundation/constants.h"
#include <stddef.h>
/* ── Flags ────────────────────────────────────────────────────── */
@@ -27,9 +28,9 @@
/* Opaque regex handle — sized to hold the platform's regex_t. */
typedef struct {
- /* 256 bytes should be large enough for any platform's regex_t.
- * POSIX regex_t is typically 48-64 bytes; TRE is ~80 bytes. */
- char opaque[256];
+ /* CBM_SZ_256 bytes should be large enough for any platform's regex_t.
+ * POSIX regex_t is typically 48-CBM_SZ_64 bytes; TRE is ~80 bytes. */
+ char opaque[CBM_SZ_256];
} cbm_regex_t;
typedef struct {
diff --git a/src/foundation/compat_thread.c b/src/foundation/compat_thread.c
index 34fb2ec94..e87afb126 100644
--- a/src/foundation/compat_thread.c
+++ b/src/foundation/compat_thread.c
@@ -4,6 +4,7 @@
* POSIX: thin wrappers around pthreads and posix_memalign.
* Windows: CreateThread, CRITICAL_SECTION, _aligned_malloc.
*/
+#include "foundation/constants.h"
#include "foundation/compat_thread.h"
#include <pthread.h>
@@ -11,7 +12,7 @@
/* Default 8MB stack for all threads. macOS ARM64 default is only 512KB,
* which is too small for deep pipeline passes (configlink, etc.). */
-#define CBM_DEFAULT_STACK_SIZE (8 * 1024 * 1024)
+#define CBM_DEFAULT_STACK_SIZE ((size_t)8 * CBM_SZ_1K * CBM_SZ_1K)
#include <string.h>
/* ── Thread ───────────────────────────────────────────────────── */
@@ -38,21 +39,21 @@ int cbm_thread_create(cbm_thread_t *t, size_t stack_size, void *(*fn)(void *), v
}
win_thread_arg_t *a = (win_thread_arg_t *)malloc(sizeof(win_thread_arg_t));
if (!a) {
- return -1;
+ return CBM_NOT_FOUND;
}
a->fn = fn;
a->arg = arg;
t->handle = CreateThread(NULL, stack_size, win_thread_wrapper, a, 0, NULL);
if (!t->handle) {
free(a);
- return -1;
+ return CBM_NOT_FOUND;
}
return 0;
}
int cbm_thread_join(cbm_thread_t *t) {
if (WaitForSingleObject(t->handle, INFINITE) != WAIT_OBJECT_0) {
- return -1;
+ return CBM_NOT_FOUND;
}
CloseHandle(t->handle);
return 0;
diff --git a/src/foundation/constants.h b/src/foundation/constants.h
new file mode 100644
index 000000000..f0a45720e
--- /dev/null
+++ b/src/foundation/constants.h
@@ -0,0 +1,89 @@
+/*
+ * constants.h — Project-wide named constants.
+ *
+ * Eliminates magic numbers flagged by readability-magic-numbers.
+ * Every literal integer/float in source should reference a named constant.
+ */
+#ifndef CBM_CONSTANTS_H
+#define CBM_CONSTANTS_H
+
+/* ── Allocation counts ───────────────────────────────────────── */
+enum { CBM_ALLOC_ONE = 1 }; /* calloc(CBM_ALLOC_ONE, sizeof(T)) */
+
+/* ── Byte / character constants ──────────────────────────────── */
+enum {
+ CBM_BYTE_RANGE = 256, /* full byte range 0x00–0xFF */
+ CBM_QUOTE_PAIR = 2, /* two quote characters (open + close) */
+ CBM_QUOTE_OFFSET = 1, /* skip opening quote */
+};
+
+/* ── Size units (powers of 2) ────────────────────────────────── */
+enum {
+ CBM_SZ_2 = 2,
+ CBM_SZ_3 = 3,
+ CBM_SZ_4 = 4,
+ CBM_SZ_5 = 5,
+ CBM_SZ_6 = 6,
+ CBM_SZ_7 = 7,
+ CBM_SZ_8 = 8,
+ CBM_SZ_16 = 16,
+ CBM_SZ_32 = 32,
+ CBM_SZ_64 = 64,
+ CBM_SZ_128 = 128,
+ CBM_SZ_256 = 256,
+ CBM_SZ_512 = 512,
+ CBM_SZ_1K = 1024,
+ CBM_SZ_2K = 2048,
+ CBM_SZ_4K = 4096,
+ CBM_SZ_8K = 8192,
+ CBM_SZ_16K = 16384,
+ CBM_SZ_32K = 32768,
+ CBM_SZ_64K = 65536,
+};
+
+/* ── Numeric bases and common factors ────────────────────────── */
+enum {
+ CBM_DECIMAL_BASE = 10,
+ CBM_HEX_BASE = 16,
+ CBM_PERCENT = 100,
+};
+
+/* ── Tree-sitter field name helper ───────────────────────────── */
+/* Usage: ts_node_child_by_field_name(node, TS_FIELD("callee"))
+ * Expands to: ts_node_child_by_field_name(node, TS_FIELD("callee"))
+ * The sizeof includes the NUL terminator, so subtract 1. */
+#define TS_FIELD(name) (name), (uint32_t)(sizeof(name) - SKIP_ONE)
+
+/* ── Tree-sitter line offset ─────────────────────────────────── */
+/* ts_node row is 0-based; source lines are 1-based. */
+enum { TS_LINE_OFFSET = 1 };
+
+/* Common offset constants. */
+
+/* Common offset constants. */
+
+/* ── Sentinel values ─────────────────────────────────────────── */
+enum {
+ CBM_NOT_FOUND = -1, /* search miss, invalid index */
+ CBM_INIT_DONE = 1, /* initialization flag */
+};
+
+/* ── Time conversion factors ─────────────────────────────────── */
+#define CBM_NSEC_PER_SEC 1000000000ULL
+#define CBM_USEC_PER_SEC 1000000ULL
+#define CBM_MSEC_PER_SEC 1000ULL
+#define CBM_NSEC_PER_USEC 1000ULL
+#define CBM_NSEC_PER_MSEC 1000000ULL
+
+/* ── Common string/buffer sizes ──────────────────────────────── */
+enum {
+ CBM_SMALL_BUF = 3, /* small scratch buffers */
+ CBM_NAME_BUF = 4, /* name buffer slots */
+ CBM_PATH_MAX = 1024, /* path buffer size */
+ CBM_LINE_BUF = 512, /* line read buffer */
+};
+
+/* Common offset constants (used across many files). */
+enum { SKIP_ONE = 1, PAIR_LEN = 2 };
+
+#endif /* CBM_CONSTANTS_H */
diff --git a/src/foundation/diagnostics.c b/src/foundation/diagnostics.c
index 4b6254290..92acbc817 100644
--- a/src/foundation/diagnostics.c
+++ b/src/foundation/diagnostics.c
@@ -4,6 +4,7 @@
* Writes JSON to /tmp/cbm-diagnostics-<pid>.json every 5 seconds.
* Atomic: writes .tmp then renames to avoid partial reads.
*/
+#include "foundation/constants.h"
#include "foundation/diagnostics.h"
#include "foundation/mem.h"
#include "foundation/compat.h"
@@ -32,7 +33,7 @@ static atomic_int g_diag_stop = 0;
static cbm_thread_t g_diag_thread;
static bool g_diag_started = false;
static time_t g_start_time = 0;
-static char g_diag_path[256] = "";
+static char g_diag_path[CBM_SZ_256] = "";
/* ── Query stats ─────────────────────────────────────────────────── */
@@ -55,30 +56,30 @@ void cbm_diag_record_query(long long duration_us, bool is_error) {
static int count_open_fds(void) {
#ifdef __linux__
- int count = 0;
- DIR *d = opendir("/proc/self/fd");
- if (d) {
- while (readdir(d)) {
- count++;
- }
- closedir(d);
- count -= 2; /* . and .. */
+ struct dirent **entries = NULL;
+ int n = scandir("/proc/self/fd", &entries, NULL, NULL);
+ if (n < 0) {
+ return CBM_NOT_FOUND;
+ }
+ for (int i = 0; i < n; i++) {
+ free(entries[i]);
}
- return count;
+ free(entries);
+ return n - PAIR_LEN; /* . and .. */
#elif defined(__APPLE__)
- /* Use proc_pidinfo on macOS — but for simplicity, count via /dev/fd */
- int count = 0;
- DIR *d = opendir("/dev/fd");
- if (d) {
- while (readdir(d)) {
- count++;
- }
- closedir(d);
- count -= 2; /* . and .. */
+ /* Count via /dev/fd using scandir (MT-safe) */
+ struct dirent **entries = NULL;
+ int n = scandir("/dev/fd", &entries, NULL, NULL);
+ if (n < 0) {
+ return CBM_NOT_FOUND;
}
- return count;
+ for (int i = 0; i < n; i++) {
+ free(entries[i]);
+ }
+ free(entries);
+ return n - PAIR_LEN; /* . and .. */
#else
- return -1; /* Not available on Windows */
+ return CBM_NOT_FOUND; /* Not available on Windows */
#endif
}
@@ -124,26 +125,31 @@ static void write_diagnostics(void) {
return;
}
- fprintf(f,
- "{\n"
- " \"uptime_s\": %ld,\n"
- " \"rss_bytes\": %zu,\n"
- " \"peak_rss_bytes\": %zu,\n"
- " \"heap_committed_bytes\": %zu,\n"
- " \"peak_committed_bytes\": %zu,\n"
- " \"page_faults\": %zu,\n"
- " \"fd_count\": %d,\n"
- " \"query_count\": %d,\n"
- " \"query_errors\": %d,\n"
- " \"query_total_us\": %lld,\n"
- " \"query_avg_us\": %lld,\n"
- " \"query_max_us\": %lld,\n"
- " \"pid\": %d\n"
- "}\n",
- uptime, current_rss, peak_rss, current_commit, peak_commit, page_faults, fds, qcount,
- qerrors, qtime, qavg, qmax, (int)getpid());
- fclose(f);
- rename(tmp_path, g_diag_path);
+ if (fprintf(f,
+ "{\n"
+ " \"uptime_s\": %ld,\n"
+ " \"rss_bytes\": %zu,\n"
+ " \"peak_rss_bytes\": %zu,\n"
+ " \"heap_committed_bytes\": %zu,\n"
+ " \"peak_committed_bytes\": %zu,\n"
+ " \"page_faults\": %zu,\n"
+ " \"fd_count\": %d,\n"
+ " \"query_count\": %d,\n"
+ " \"query_errors\": %d,\n"
+ " \"query_total_us\": %lld,\n"
+ " \"query_avg_us\": %lld,\n"
+ " \"query_max_us\": %lld,\n"
+ " \"pid\": %d\n"
+ "}\n",
+ uptime, current_rss, peak_rss, current_commit, peak_commit, page_faults, fds,
+ qcount, qerrors, qtime, qavg, qmax, (int)getpid()) < 0) {
+ (void)fclose(f);
+ return;
+ }
+ if (fclose(f) != 0) {
+ return;
+ }
+ (void)rename(tmp_path, g_diag_path);
}
static void *diag_thread_fn(void *arg) {
@@ -161,8 +167,12 @@ static void *diag_thread_fn(void *arg) {
/* ── Public API ──────────────────────────────────────────────────── */
bool cbm_diag_start(void) {
- const char *env = getenv("CBM_DIAGNOSTICS");
- if (!env || (strcmp(env, "1") != 0 && strcmp(env, "true") != 0)) {
+ const char *raw_env = getenv("CBM_DIAGNOSTICS");
+ char env_buf[CBM_SZ_32] = "";
+ if (raw_env) {
+ snprintf(env_buf, sizeof(env_buf), "%s", raw_env);
+ }
+ if (env_buf[0] == '\0' || (strcmp(env_buf, "1") != 0 && strcmp(env_buf, "true") != 0)) {
return false;
}
@@ -177,8 +187,8 @@ bool cbm_diag_start(void) {
}
g_diag_started = true;
- fprintf(stderr, "level=info msg=diagnostics.start path=%s interval=%ds\n", g_diag_path,
- DIAG_INTERVAL_S);
+ (void)fprintf(stderr, "level=info msg=diagnostics.start path=%s interval=%ds\n", g_diag_path,
+ DIAG_INTERVAL_S);
return true;
}
diff --git a/src/foundation/hash_table.c b/src/foundation/hash_table.c
index a7c9aea51..12c140f7c 100644
--- a/src/foundation/hash_table.c
+++ b/src/foundation/hash_table.c
@@ -9,6 +9,19 @@
* - Load factor 75% triggers 2x resize.
*/
#include "hash_table.h"
+#include "foundation/constants.h"
+
+enum {
+ HT_MIN_CAP = 8, /* minimum hash table capacity */
+ HT_INITIAL_PSL = 1, /* initial probe sequence length */
+ HT_LOAD_NUM = 3, /* load factor numerator (75%) */
+ HT_LOAD_DEN = 4, /* load factor denominator */
+ HT_SHIFT_1 = 1, /* bit shift amounts for next_pow2 */
+ HT_SHIFT_2 = 2,
+ HT_SHIFT_4 = 4,
+ HT_SHIFT_8 = 8,
+ HT_SHIFT_16 = 16,
+};
#include <stdint.h> // uint32_t
#include <stdlib.h>
#include <string.h>
@@ -29,25 +42,25 @@ static uint32_t fnv1a(const char *key) {
/* Round up to next power of 2 */
static uint32_t next_pow2(uint32_t v) {
- if (v < 8) {
- return 8;
+ if (v < HT_MIN_CAP) {
+ return HT_MIN_CAP;
}
v--;
- v |= v >> 1;
- v |= v >> 2;
- v |= v >> 4;
- v |= v >> 8;
- v |= v >> 16;
- return v + 1;
+ v |= v >> HT_SHIFT_1;
+ v |= v >> HT_SHIFT_2;
+ v |= v >> HT_SHIFT_4;
+ v |= v >> HT_SHIFT_8;
+ v |= v >> HT_SHIFT_16;
+ return v + SKIP_ONE;
}
CBMHashTable *cbm_ht_create(uint32_t initial_capacity) {
- CBMHashTable *ht = (CBMHashTable *)calloc(1, sizeof(CBMHashTable));
+ CBMHashTable *ht = (CBMHashTable *)calloc(CBM_ALLOC_ONE, sizeof(CBMHashTable));
if (!ht) {
return NULL;
}
ht->capacity = next_pow2(initial_capacity);
- ht->mask = ht->capacity - 1;
+ ht->mask = ht->capacity - SKIP_ONE;
ht->entries = (CBMHTEntry *)calloc(ht->capacity, sizeof(CBMHTEntry));
if (!ht->entries) {
free(ht);
@@ -65,8 +78,8 @@ void cbm_ht_free(CBMHashTable *ht) {
}
static void ht_resize(CBMHashTable *ht) {
- uint32_t new_cap = ht->capacity * 2;
- uint32_t new_mask = new_cap - 1;
+ uint32_t new_cap = ht->capacity * PAIR_LEN;
+ uint32_t new_mask = new_cap - SKIP_ONE;
CBMHTEntry *new_entries = (CBMHTEntry *)calloc(new_cap, sizeof(CBMHTEntry));
if (!new_entries) {
return; /* OOM: keep old table */
@@ -80,7 +93,7 @@ static void ht_resize(CBMHashTable *ht) {
/* Re-insert into new table */
uint32_t idx = e->hash & new_mask;
- CBMHTEntry cur = {.key = e->key, .value = e->value, .hash = e->hash, .psl = 1};
+ CBMHTEntry cur = {.key = e->key, .value = e->value, .hash = e->hash, .psl = HT_INITIAL_PSL};
for (;;) {
CBMHTEntry *slot = &new_entries[idx];
if (slot->psl == 0) {
@@ -94,7 +107,7 @@ static void ht_resize(CBMHashTable *ht) {
cur = tmp;
}
cur.psl++;
- idx = (idx + 1) & new_mask;
+ idx = (idx + SKIP_ONE) & new_mask;
}
}
@@ -106,13 +119,13 @@ static void ht_resize(CBMHashTable *ht) {
void *cbm_ht_set(CBMHashTable *ht, const char *key, void *value) {
/* Resize at 75% load */
- if (ht->count * 4 >= ht->capacity * 3) {
+ if (ht->count * HT_LOAD_DEN >= ht->capacity * HT_LOAD_NUM) {
ht_resize(ht);
}
uint32_t h = fnv1a(key);
uint32_t idx = h & ht->mask;
- CBMHTEntry cur = {.key = key, .value = value, .hash = h, .psl = 1};
+ CBMHTEntry cur = {.key = key, .value = value, .hash = h, .psl = HT_INITIAL_PSL};
void *prev_value = NULL;
for (;;) {
@@ -141,14 +154,14 @@ void *cbm_ht_set(CBMHashTable *ht, const char *key, void *value) {
}
cur.psl++;
- idx = (idx + 1) & ht->mask;
+ idx = (idx + SKIP_ONE) & ht->mask;
}
}
void *cbm_ht_get(const CBMHashTable *ht, const char *key) {
uint32_t h = fnv1a(key);
uint32_t idx = h & ht->mask;
- uint32_t psl = 1;
+ uint32_t psl = SKIP_ONE;
for (;;) {
const CBMHTEntry *slot = &ht->entries[idx];
@@ -162,7 +175,7 @@ void *cbm_ht_get(const CBMHashTable *ht, const char *key) {
return slot->value;
}
psl++;
- idx = (idx + 1) & ht->mask;
+ idx = (idx + SKIP_ONE) & ht->mask;
}
}
@@ -176,7 +189,7 @@ const char *cbm_ht_get_key(const CBMHashTable *ht, const char *key) {
}
uint32_t h = fnv1a(key);
uint32_t idx = h & ht->mask;
- uint32_t psl = 1;
+ uint32_t psl = SKIP_ONE;
for (;;) {
const CBMHTEntry *slot = &ht->entries[idx];
if (slot->psl == 0) {
@@ -189,14 +202,14 @@ const char *cbm_ht_get_key(const CBMHashTable *ht, const char *key) {
return slot->key;
}
psl++;
- idx = (idx + 1) & ht->mask;
+ idx = (idx + SKIP_ONE) & ht->mask;
}
}
void *cbm_ht_delete(CBMHashTable *ht, const char *key) {
uint32_t h = fnv1a(key);
uint32_t idx = h & ht->mask;
- uint32_t psl = 1;
+ uint32_t psl = SKIP_ONE;
/* Find the entry */
for (;;) {
@@ -213,9 +226,9 @@ void *cbm_ht_delete(CBMHashTable *ht, const char *key) {
/* Backward shift: fill the hole */
for (;;) {
- uint32_t next_idx = (idx + 1) & ht->mask;
+ uint32_t next_idx = (idx + SKIP_ONE) & ht->mask;
const CBMHTEntry *next = &ht->entries[next_idx];
- if (next->psl <= 1) {
+ if (next->psl <= HT_INITIAL_PSL) {
/* Next slot is empty or at home — stop */
ht->entries[idx] = (CBMHTEntry){0};
break;
@@ -228,7 +241,7 @@ void *cbm_ht_delete(CBMHashTable *ht, const char *key) {
return removed;
}
psl++;
- idx = (idx + 1) & ht->mask;
+ idx = (idx + SKIP_ONE) & ht->mask;
}
}
diff --git a/src/foundation/log.c b/src/foundation/log.c
index e0b989334..627934357 100644
--- a/src/foundation/log.c
+++ b/src/foundation/log.c
@@ -2,6 +2,7 @@
* log.c — Structured key-value logging to stderr.
*/
#include "log.h"
+#include "foundation/constants.h"
#include <inttypes.h>
#include <stdarg.h>
#include <stdint.h>
@@ -43,7 +44,7 @@ void cbm_log(CBMLogLevel level, const char *msg, ...) {
}
/* Build the log line into a buffer ONCE — no double va_list iteration */
- char line_buf[512];
+ char line_buf[CBM_SZ_512];
int pos =
snprintf(line_buf, sizeof(line_buf), "level=%s msg=%s", level_str(level), msg ? msg : "");
@@ -58,7 +59,7 @@ void cbm_log(CBMLogLevel level, const char *msg, ...) {
if (!val) {
val = "";
}
- if ((size_t)pos < sizeof(line_buf) - 1) {
+ if ((size_t)pos < sizeof(line_buf) - SKIP_ONE) {
pos += snprintf(line_buf + pos, sizeof(line_buf) - (size_t)pos, " %s=%s", key, val);
}
}
@@ -78,7 +79,7 @@ void cbm_log_int(CBMLogLevel level, const char *msg, const char *key, int64_t va
return;
}
- char line_buf[256];
+ char line_buf[CBM_SZ_256];
snprintf(line_buf, sizeof(line_buf), "level=%s msg=%s %s=%" PRId64, level_str(level),
msg ? msg : "", key ? key : "?", value);
diff --git a/src/foundation/mem.c b/src/foundation/mem.c
index 2c6cc5c33..1a5970ab4 100644
--- a/src/foundation/mem.c
+++ b/src/foundation/mem.c
@@ -10,6 +10,10 @@
#include "platform.h"
#include "log.h"
+#include "foundation/constants.h"
+
+#define MAX_RAM_FRACTION 1.0
+#define DEFAULT_RAM_FRACTION 0.5
#include <mimalloc.h>
#include <stdatomic.h>
#include <stdio.h>
@@ -32,7 +36,7 @@ static size_t g_budget; /* budget in bytes */
static atomic_int g_initialized; /* init guard */
static atomic_int g_was_over; /* pressure hysteresis */
-#define MB_DIVISOR ((size_t)(1024 * 1024))
+#define MB_DIVISOR ((size_t)(CBM_SZ_1K * CBM_SZ_1K))
/* ── OS fallback for RSS (ASan builds where MI_OVERRIDE=0) ──── */
@@ -63,7 +67,7 @@ static size_t os_rss(void) {
}
(void)fclose(f);
long ps = sysconf(_SC_PAGESIZE);
- return rss_pages * (ps > 0 ? (size_t)ps : 4096);
+ return rss_pages * (ps > 0 ? (size_t)ps : CBM_SZ_4K);
#endif
}
@@ -79,21 +83,23 @@ static void check_pressure(size_t rss) {
if (over && !was) {
atomic_store(&g_was_over, 1);
- char rss_mb[32];
- char budget_mb[32];
- char pct_str[16];
+ char rss_mb[CBM_SZ_32];
+ char budget_mb[CBM_SZ_32];
+ char pct_str[CBM_SZ_16];
snprintf(rss_mb, sizeof(rss_mb), "%zu", rss / MB_DIVISOR);
snprintf(budget_mb, sizeof(budget_mb), "%zu", g_budget / MB_DIVISOR);
- snprintf(pct_str, sizeof(pct_str), "%zu", g_budget > 0 ? (rss * 100) / g_budget : 0);
+ snprintf(pct_str, sizeof(pct_str), "%zu",
+ g_budget > 0 ? (rss * CBM_PERCENT) / g_budget : 0);
cbm_log_warn("mem.pressure.warn", "rss_mb", rss_mb, "budget_mb", budget_mb, "pct", pct_str);
} else if (!over && was) {
atomic_store(&g_was_over, 0);
- char rss_mb[32];
- char budget_mb[32];
- char pct_str[16];
+ char rss_mb[CBM_SZ_32];
+ char budget_mb[CBM_SZ_32];
+ char pct_str[CBM_SZ_16];
snprintf(rss_mb, sizeof(rss_mb), "%zu", rss / MB_DIVISOR);
snprintf(budget_mb, sizeof(budget_mb), "%zu", g_budget / MB_DIVISOR);
- snprintf(pct_str, sizeof(pct_str), "%zu", g_budget > 0 ? (rss * 100) / g_budget : 0);
+ snprintf(pct_str, sizeof(pct_str), "%zu",
+ g_budget > 0 ? (rss * CBM_PERCENT) / g_budget : 0);
cbm_log_info("mem.pressure.ok", "rss_mb", rss_mb, "budget_mb", budget_mb, "pct", pct_str);
}
}
@@ -106,8 +112,8 @@ void cbm_mem_init(double ram_fraction) {
return;
}
- if (ram_fraction <= 0.0 || ram_fraction > 1.0) {
- ram_fraction = 0.5;
+ if (ram_fraction <= 0.0 || ram_fraction > MAX_RAM_FRACTION) {
+ ram_fraction = DEFAULT_RAM_FRACTION;
}
/* Reduce upfront memory: don't eagerly commit segments */
@@ -116,8 +122,8 @@ void cbm_mem_init(double ram_fraction) {
cbm_system_info_t info = cbm_system_info();
g_budget = (size_t)((double)info.total_ram * ram_fraction);
- char budget_mb[32];
- char ram_mb[32];
+ char budget_mb[CBM_SZ_32];
+ char ram_mb[CBM_SZ_32];
snprintf(budget_mb, sizeof(budget_mb), "%zu", g_budget / MB_DIVISOR);
snprintf(ram_mb, sizeof(ram_mb), "%zu", info.total_ram / MB_DIVISOR);
cbm_log_info("mem.init", "budget_mb", budget_mb, "total_ram_mb", ram_mb);
@@ -156,7 +162,7 @@ bool cbm_mem_over_budget(void) {
size_t cbm_mem_worker_budget(int num_workers) {
if (num_workers <= 0) {
- num_workers = 1;
+ num_workers = SKIP_ONE;
}
return g_budget / (size_t)num_workers;
}
diff --git a/src/foundation/platform.c b/src/foundation/platform.c
index 62e1f0efd..012e30c7f 100644
--- a/src/foundation/platform.c
+++ b/src/foundation/platform.c
@@ -6,6 +6,7 @@
#include "platform.h"
#include "compat.h"
+#include "foundation/constants.h"
#include <stdint.h> // uint64_t, int64_t
#ifdef _WIN32
@@ -89,7 +90,7 @@ bool cbm_is_dir(const char *path) {
int64_t cbm_file_size(const char *path) {
WIN32_FILE_ATTRIBUTE_DATA fad;
if (!GetFileAttributesExA(path, GetFileExInfoStandard, &fad)) {
- return -1;
+ return CBM_NOT_FOUND;
}
LARGE_INTEGER sz;
sz.HighPart = (LONG)fad.nFileSizeHigh; // cppcheck-suppress unreadVariable
@@ -169,7 +170,7 @@ static int timebase_init = 0;
uint64_t cbm_now_ns(void) {
if (!timebase_init) {
mach_timebase_info(&timebase_info);
- timebase_init = 1;
+ timebase_init = SKIP_ONE;
}
uint64_t ticks = mach_absolute_time();
return ticks * timebase_info.numer / timebase_info.denom;
@@ -197,7 +198,8 @@ int cbm_nprocs(void) {
if (sysctlbyname("hw.ncpu", &ncpu, &len, NULL, 0) == 0 && ncpu > 0) {
return ncpu;
}
- return 1;
+ enum { FILE_EXISTS = 1 };
+ return FILE_EXISTS;
#else
long n = sysconf(_SC_NPROCESSORS_ONLN);
return n > 0 ? (int)n : 1;
@@ -219,7 +221,7 @@ bool cbm_is_dir(const char *path) {
int64_t cbm_file_size(const char *path) {
struct stat st;
if (stat(path, &st) != 0) {
- return -1;
+ return CBM_NOT_FOUND;
}
return (int64_t)st.st_size;
}
@@ -239,19 +241,45 @@ char *cbm_normalize_path_sep(char *path) {
#endif /* _WIN32 */
+/* ── Environment variables ────────────────────────────────────── */
+
+const char *cbm_safe_getenv(const char *name, char *buf, size_t buf_sz, const char *fallback) {
+ const char *val = getenv(name);
+ if (!val) {
+ if (fallback) {
+ snprintf(buf, buf_sz, "%s", fallback);
+ return buf;
+ }
+ buf[0] = '\0';
+ return NULL;
+ }
+ snprintf(buf, buf_sz, "%s", val);
+ return buf;
+}
+
/* ── Home directory (cross-platform) ──────────────────────────── */
const char *cbm_get_home_dir(void) {
- static char buf[1024];
- const char *h = getenv("HOME");
- if (h && h[0]) {
- snprintf(buf, sizeof(buf), "%s", h);
+ static char buf[CBM_SZ_1K];
+ const char *raw;
+ char tmp[CBM_SZ_256] = "";
+
+ raw = getenv("HOME");
+ if (raw) {
+ snprintf(tmp, sizeof(tmp), "%s", raw);
+ }
+ if (tmp[0]) {
+ snprintf(buf, sizeof(buf), "%s", tmp);
cbm_normalize_path_sep(buf);
return buf;
}
- h = getenv("USERPROFILE");
- if (h && h[0]) {
- snprintf(buf, sizeof(buf), "%s", h);
+
+ raw = getenv("USERPROFILE");
+ if (raw) {
+ snprintf(tmp, sizeof(tmp), "%s", raw);
+ }
+ if (tmp[0]) {
+ snprintf(buf, sizeof(buf), "%s", tmp);
cbm_normalize_path_sep(buf);
return buf;
}
diff --git a/src/foundation/platform.h b/src/foundation/platform.h
index 62e9dca84..382768fee 100644
--- a/src/foundation/platform.h
+++ b/src/foundation/platform.h
@@ -20,7 +20,11 @@
/* Safe realloc: frees old pointer on failure instead of leaking it.
* Returns NULL on allocation failure (old memory is freed). */
static inline void *safe_realloc(void *ptr, size_t size) {
- void *tmp = realloc(ptr, size); // NOLINT(clang-analyzer-optin.portability.UnixAPI)
+ enum { SAFE_REALLOC_MIN = 1 };
+ if (size == 0) {
+ size = SAFE_REALLOC_MIN;
+ }
+ void *tmp = realloc(ptr, size);
if (!tmp) {
free(ptr);
}
@@ -64,6 +68,13 @@ cbm_system_info_t cbm_system_info(void);
* initial=false: max(1, perf_cores-1) (leave headroom for user apps) */
int cbm_default_worker_count(bool initial);
+/* ── Environment variables ──────────────────────────────────────── */
+
+/* Thread-safe getenv: copies the value into a caller-provided buffer.
+ * Returns buf on success, or fallback if the variable is unset.
+ * Returns NULL when the variable is unset and fallback is NULL. */
+const char *cbm_safe_getenv(const char *name, char *buf, size_t buf_sz, const char *fallback);
+
/* ── Home directory ─────────────────────────────────────────────── */
/* Cross-platform home directory: tries HOME first, then USERPROFILE (Windows).
diff --git a/src/foundation/recursion_whitelist.h b/src/foundation/recursion_whitelist.h
new file mode 100644
index 000000000..982be35a2
--- /dev/null
+++ b/src/foundation/recursion_whitelist.h
@@ -0,0 +1,25 @@
+/*
+ * recursion_whitelist.h — Functions approved for recursive implementation.
+ *
+ * These functions use bounded recursion where iterative conversion would
+ * add complexity with no practical benefit:
+ *
+ * Cypher recursive descent parser (bounded by query nesting depth ~5):
+ * - parse_or_expr, parse_xor_expr, parse_and_expr, parse_not_expr
+ * - parse_atom_expr, parse_post_where, cbm_parse
+ *
+ * Cypher expression evaluator (bounded by WHERE clause depth ~5):
+ * - eval_expr
+ *
+ * Glob pattern matcher (bounded by pattern nesting ~3):
+ * - glob_match, glob_match_star, glob_match_doublestar
+ * - glob_match_doublestar_slash, glob_match_doublestar_any
+ *
+ * To add a function: add it below AND add NOLINT(misc-no-recursion) on
+ * the function definition line. The lint gate verifies both match.
+ */
+#define CBM_RECURSION_WHITELIST \
+ "parse_or_expr", "parse_xor_expr", "parse_and_expr", "parse_not_expr", "parse_atom_expr", \
+ "parse_post_where", "cbm_parse", "eval_expr", "glob_match", "glob_match_star", \
+ "glob_match_doublestar", "glob_match_doublestar_slash", "glob_match_doublestar_any", \
+ "parse_bool_expr", "parse_bool_atom"
diff --git a/src/foundation/slab_alloc.c b/src/foundation/slab_alloc.c
index f3b5580ac..81818ac18 100644
--- a/src/foundation/slab_alloc.c
+++ b/src/foundation/slab_alloc.c
@@ -16,6 +16,7 @@
* On slab_destroy_thread: free all slab pages.
* realloc handles slab-to-heap promotion with minimal copying.
*/
+#include "foundation/constants.h"
#include "foundation/slab_alloc.h"
#include "foundation/compat.h"
@@ -42,8 +43,8 @@ typedef struct slab_free_node {
/* One slab page — a contiguous block of SLAB_PAGE_CHUNKS chunks. */
typedef struct slab_page {
- struct slab_page *next; /* linked list of pages */
- char data[SLAB_PAGE_SIZE]; /* NOLINT(modernize-avoid-c-arrays) */
+ struct slab_page *next; /* linked list of pages */
+ char data[SLAB_PAGE_SIZE];
} slab_page_t;
/* Per-thread Tier 1 state. */
@@ -94,7 +95,7 @@ static bool slab_owns(const slab_state_t *s, const void *ptr) {
uintptr_t p = (uintptr_t)ptr;
for (const slab_page_t *page = s->pages; page; page = page->next) {
uintptr_t lo = (uintptr_t)page->data;
- if (p >= lo && p < lo + SLAB_PAGE_SIZE) {
+ if (p >= lo && p < lo + (uintptr_t)SLAB_PAGE_SIZE) {
return true;
}
}
@@ -104,6 +105,9 @@ static bool slab_owns(const slab_state_t *s, const void *ptr) {
/* ── Allocator functions (installed as tree-sitter callbacks) ───── */
static void *slab_malloc(size_t size) {
+ if (size == 0) {
+ size = SKIP_ONE;
+ }
/* Tier 1: ≤64B → slab free list */
if (size <= SLAB_CHUNK_SIZE) {
slab_state_t *s = &tls_slab;
diff --git a/src/foundation/slab_alloc.h b/src/foundation/slab_alloc.h
index 53e97eb50..9648ba167 100644
--- a/src/foundation/slab_alloc.h
+++ b/src/foundation/slab_alloc.h
@@ -5,7 +5,7 @@
* to eliminate ptmalloc2's per-thread arena fragmentation.
*
* Tier 1 (≤64B): Fixed-size slab free list — O(1) alloc/free.
- * Matches tree-sitter SubtreeHeapData (64 bytes). Backed by
+ * Matches tree-sitter SubtreeHeapData (CBM_SZ_64 bytes). Backed by
* 64KB slab pages via malloc (= mimalloc in production).
*
* All allocations >64B go directly to malloc (= mimalloc in production),
diff --git a/src/foundation/str_intern.c b/src/foundation/str_intern.c
index 6523a83a3..433db4b8a 100644
--- a/src/foundation/str_intern.c
+++ b/src/foundation/str_intern.c
@@ -6,6 +6,9 @@
*/
#include "str_intern.h"
#include "arena.h"
+#include "foundation/constants.h"
+
+enum { INTERN_LOAD_NUM = 7 };
#include <stdint.h> // uint32_t
#include <stdlib.h>
#include <string.h>
@@ -41,13 +44,13 @@ struct CBMInternPool {
};
CBMInternPool *cbm_intern_create(void) {
- CBMInternPool *p = (CBMInternPool *)calloc(1, sizeof(*p));
+ CBMInternPool *p = (CBMInternPool *)calloc(CBM_ALLOC_ONE, sizeof(*p));
if (!p) {
return NULL;
}
cbm_arena_init(&p->arena);
- p->capacity = 256;
- p->mask = p->capacity - 1;
+ p->capacity = CBM_SZ_256;
+ p->mask = p->capacity - SKIP_ONE;
p->buckets = (InternEntry *)calloc(p->capacity, sizeof(InternEntry));
if (!p->buckets) {
cbm_arena_destroy(&p->arena);
@@ -67,8 +70,8 @@ void cbm_intern_free(CBMInternPool *pool) {
}
static void intern_resize(CBMInternPool *p) {
- uint32_t new_cap = p->capacity * 2;
- uint32_t new_mask = new_cap - 1;
+ uint32_t new_cap = p->capacity * PAIR_LEN;
+ uint32_t new_mask = new_cap - SKIP_ONE;
InternEntry *new_buckets = (InternEntry *)calloc(new_cap, sizeof(InternEntry));
if (!new_buckets) {
return;
@@ -81,7 +84,7 @@ static void intern_resize(CBMInternPool *p) {
}
uint32_t idx = e->hash & new_mask;
while (new_buckets[idx].str) {
- idx = (idx + 1) & new_mask;
+ idx = (idx + SKIP_ONE) & new_mask;
}
new_buckets[idx] = *e;
}
@@ -109,16 +112,16 @@ const char *cbm_intern_n(CBMInternPool *pool, const char *s, size_t len) {
if (e->hash == h && e->len == (uint32_t)len && memcmp(e->str, s, len) == 0) {
return e->str; /* found — return existing pointer */
}
- idx = (idx + 1) & pool->mask;
+ idx = (idx + SKIP_ONE) & pool->mask;
}
/* Resize at 70% load */
- if (pool->count * 10 >= pool->capacity * 7) {
+ if (pool->count * CBM_DECIMAL_BASE >= pool->capacity * INTERN_LOAD_NUM) {
intern_resize(pool);
/* Re-probe after resize */
idx = h & pool->mask;
while (pool->buckets[idx].str) {
- idx = (idx + 1) & pool->mask;
+ idx = (idx + SKIP_ONE) & pool->mask;
}
}
diff --git a/src/foundation/str_util.c b/src/foundation/str_util.c
index b6fdbdb40..82698580e 100644
--- a/src/foundation/str_util.c
+++ b/src/foundation/str_util.c
@@ -3,6 +3,7 @@
*/
#include "str_util.h"
#include "arena.h" // CBMArena, cbm_arena_alloc/strdup/strndup
+#include "foundation/constants.h"
#include <string.h>
#include <ctype.h>
@@ -22,7 +23,7 @@ char *cbm_path_join(CBMArena *a, const char *base, const char *name) {
}
/* Strip trailing slash from base */
- while (blen > 0 && base[blen - 1] == '/') {
+ while (blen > 0 && base[blen - SKIP_ONE] == '/') {
blen--;
}
/* Strip leading slash from name */
@@ -38,14 +39,14 @@ char *cbm_path_join(CBMArena *a, const char *base, const char *name) {
return cbm_arena_strndup(a, base, blen);
}
- char *result = (char *)cbm_arena_alloc(a, blen + 1 + nlen + 1);
+ char *result = (char *)cbm_arena_alloc(a, blen + SKIP_ONE + nlen + SKIP_ONE);
if (!result) {
return NULL;
}
memcpy(result, base, blen);
result[blen] = '/';
- memcpy(result + blen + 1, name, nlen);
- result[blen + 1 + nlen] = '\0';
+ memcpy(result + blen + SKIP_ONE, name, nlen);
+ result[blen + SKIP_ONE + nlen] = '\0';
return result;
}
@@ -53,12 +54,12 @@ char *cbm_path_join_n(CBMArena *a, const char **parts, int n) {
if (n <= 0 || !parts) {
return cbm_arena_strdup(a, "");
}
- if (n == 1) {
+ if (n == SKIP_ONE) {
return cbm_arena_strdup(a, parts[0]);
}
char *result = cbm_arena_strdup(a, parts[0]);
- for (int i = 1; i < n; i++) {
+ for (int i = SKIP_ONE; i < n; i++) {
result = cbm_path_join(a, result, parts[i]);
}
return result;
@@ -85,7 +86,7 @@ const char *cbm_path_ext(const char *path) {
if (slash && dot < slash) {
return "";
}
- return dot + 1;
+ return dot + SKIP_ONE;
}
const char *cbm_path_base(const char *path) {
@@ -98,7 +99,7 @@ const char *cbm_path_base(const char *path) {
last_slash = p;
}
}
- return last_slash ? last_slash + 1 : path;
+ return last_slash ? last_slash + SKIP_ONE : path;
}
char *cbm_path_dir(CBMArena *a, const char *path) {
@@ -152,7 +153,7 @@ char *cbm_str_tolower(CBMArena *a, const char *s) {
return NULL;
}
size_t len = strlen(s);
- char *result = (char *)cbm_arena_alloc(a, len + 1);
+ char *result = (char *)cbm_arena_alloc(a, len + SKIP_ONE);
if (!result) {
return NULL;
}
@@ -168,7 +169,7 @@ char *cbm_str_replace_char(CBMArena *a, const char *s, char from, char to) {
return NULL;
}
size_t len = strlen(s);
- char *result = (char *)cbm_arena_alloc(a, len + 1);
+ char *result = (char *)cbm_arena_alloc(a, len + SKIP_ONE);
if (!result) {
return NULL;
}
@@ -205,14 +206,14 @@ char **cbm_str_split(CBMArena *a, const char *s, char delim, int *out_count) {
}
/* Count parts */
- int count = 1;
+ int count = SKIP_ONE;
for (const char *p = s; *p; p++) {
if (*p == delim) {
count++;
}
}
- char **result = (char **)cbm_arena_alloc(a, (size_t)(count + 1) * sizeof(char *));
+ char **result = (char **)cbm_arena_alloc(a, (size_t)(count + SKIP_ONE) * sizeof(char *));
if (!result) {
return NULL;
}
@@ -226,7 +227,7 @@ char **cbm_str_split(CBMArena *a, const char *s, char delim, int *out_count) {
if (*p == '\0') {
break;
}
- start = p + 1;
+ start = p + SKIP_ONE;
}
}
@@ -249,11 +250,10 @@ bool cbm_validate_shell_arg(const char *s) {
case '`':
case '\n':
case '\r':
- return false;
#ifndef _WIN32
case '\\':
- return false;
#endif
+ return false;
default:
break;
}
diff --git a/src/foundation/system_info.c b/src/foundation/system_info.c
index 347855d00..604ae2c60 100644
--- a/src/foundation/system_info.c
+++ b/src/foundation/system_info.c
@@ -7,6 +7,9 @@
*
* Results are cached after first call (immutable hardware properties).
*/
+#include "foundation/constants.h"
+
+enum { DEFAULT_CORES = 1, MIN_WORKERS = 1 };
#include "foundation/platform.h"
#include <stdint.h> // uint64_t
#include <string.h>
@@ -21,6 +24,7 @@
#elif !defined(_WIN32) /* Linux */
#include <unistd.h>
#include <sys/sysinfo.h>
+
#endif
/* ── macOS detection ─────────────────────────────────────────────── */
@@ -42,7 +46,7 @@ static size_t sysctl_size(const char *name, size_t fallback) {
if (sysctlbyname(name, &val, &len, NULL, 0) == 0 && val > 0) {
return val;
}
- /* Try 64-bit variant */
+ /* Try CBM_SZ_64-bit variant */
uint64_t val64 = 0;
len = sizeof(val64);
if (sysctlbyname(name, &val64, &len, NULL, 0) == 0 && val64 > 0) {
@@ -55,7 +59,7 @@ static cbm_system_info_t detect_system_macos(void) {
cbm_system_info_t info;
memset(&info, 0, sizeof(info));
- info.total_cores = sysctl_int("hw.ncpu", 1);
+ info.total_cores = sysctl_int("hw.ncpu", DEFAULT_CORES);
info.perf_cores = sysctl_int("hw.perflevel0.physicalcpu", info.total_cores);
/* If perflevel sysctls fail (Intel Mac), perf = total */
@@ -99,7 +103,7 @@ static cbm_system_info_t detect_system_windows(void) {
GetSystemInfo(&si);
info.total_cores = (int)si.dwNumberOfProcessors;
if (info.total_cores < 1) {
- info.total_cores = 1;
+ info.total_cores = SKIP_ONE;
}
info.perf_cores = info.total_cores;
@@ -127,7 +131,7 @@ cbm_system_info_t cbm_system_info(void) {
#else
cached_info = detect_system_linux();
#endif
- info_cached = 1;
+ info_cached = SKIP_ONE;
}
return cached_info;
}
@@ -139,6 +143,6 @@ int cbm_default_worker_count(bool initial) {
return info.total_cores;
}
/* Incremental: leave headroom for user's apps */
- int workers = info.perf_cores - 1;
- return workers > 0 ? workers : 1;
+ int workers = info.perf_cores - SKIP_ONE;
+ return workers > 0 ? workers : MIN_WORKERS;
}
diff --git a/src/foundation/vmem.c b/src/foundation/vmem.c
index df3b02694..86befbe4b 100644
--- a/src/foundation/vmem.c
+++ b/src/foundation/vmem.c
@@ -18,13 +18,13 @@
#include <string.h> /* memset */
#ifdef _WIN32
- #ifndef WIN32_LEAN_AND_MEAN
- #define WIN32_LEAN_AND_MEAN
- #endif
- #include <windows.h>
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN
+#endif
+#include <windows.h>
#else
- #include <sys/mman.h>
- #include <unistd.h> /* sysconf, _SC_PAGESIZE */
+#include <sys/mman.h>
+#include <unistd.h> /* sysconf, _SC_PAGESIZE */
#endif
/* ── Static state (initialized once) ──────────────────────────── */
@@ -51,12 +51,12 @@ static size_t page_size(void) {
/* Round up to page boundary. */
static size_t round_to_page(size_t size) {
size_t ps = page_size();
- return (size + ps - 1) & ~(ps - 1);
+ return (size + ps - SKIP_ONE) & ~(ps - SKIP_ONE);
}
/* ── Pressure logging ──────────────────────────────────────────── */
-#define MB_DIVISOR ((size_t)(1024 * 1024))
+#define MB_DIVISOR ((size_t)(CBM_SZ_1K * CBM_SZ_1K))
static void check_pressure(size_t allocated) {
if (g_budget == 0) {
@@ -69,25 +69,25 @@ static void check_pressure(size_t allocated) {
if (over && !was) {
/* Transition: under → over */
atomic_store(&g_was_over, 1);
- char alloc_mb[32];
- char budget_mb[32];
- char pct_str[16];
+ char alloc_mb[CBM_SZ_32];
+ char budget_mb[CBM_SZ_32];
+ char pct_str[CBM_SZ_16];
snprintf(alloc_mb, sizeof(alloc_mb), "%zu", allocated / MB_DIVISOR);
snprintf(budget_mb, sizeof(budget_mb), "%zu", g_budget / MB_DIVISOR);
snprintf(pct_str, sizeof(pct_str), "%zu",
- g_budget > 0 ? (allocated * 100) / g_budget : 0);
+ g_budget > 0 ? (allocated * CBM_PERCENT) / g_budget : 0);
cbm_log_warn("mem.pressure.warn", "allocated_mb", alloc_mb, "budget_mb", budget_mb, "pct",
pct_str);
} else if (!over && was) {
/* Transition: over → under */
atomic_store(&g_was_over, 0);
- char alloc_mb[32];
- char budget_mb[32];
- char pct_str[16];
+ char alloc_mb[CBM_SZ_32];
+ char budget_mb[CBM_SZ_32];
+ char pct_str[CBM_SZ_16];
snprintf(alloc_mb, sizeof(alloc_mb), "%zu", allocated / MB_DIVISOR);
snprintf(budget_mb, sizeof(budget_mb), "%zu", g_budget / MB_DIVISOR);
snprintf(pct_str, sizeof(pct_str), "%zu",
- g_budget > 0 ? (allocated * 100) / g_budget : 0);
+ g_budget > 0 ? (allocated * CBM_PERCENT) / g_budget : 0);
cbm_log_info("mem.pressure.ok", "allocated_mb", alloc_mb, "budget_mb", budget_mb, "pct",
pct_str);
}
@@ -120,8 +120,8 @@ void cbm_vmem_init(double ram_fraction) {
cbm_system_info_t info = cbm_system_info();
g_budget = (size_t)((double)info.total_ram * ram_fraction);
- char budget_mb[32];
- char ram_mb[32];
+ char budget_mb[CBM_SZ_32];
+ char ram_mb[CBM_SZ_32];
snprintf(budget_mb, sizeof(budget_mb), "%zu", g_budget / MB_DIVISOR);
snprintf(ram_mb, sizeof(ram_mb), "%zu", info.total_ram / MB_DIVISOR);
cbm_log_info("vmem.init", "budget_mb", budget_mb, "total_ram_mb", ram_mb);
@@ -144,8 +144,7 @@ void *cbm_vmem_alloc(size_t size) {
#endif
if (!ptr) {
- cbm_log_error("vmem.alloc.fail", "size_mb",
- size > MB_DIVISOR ? "large" : "small");
+ cbm_log_error("vmem.alloc.fail", "size_mb", size > MB_DIVISOR ? "large" : "small");
return NULL;
}
@@ -191,7 +190,7 @@ bool cbm_vmem_over_budget(void) {
size_t cbm_vmem_worker_budget(int num_workers) {
if (num_workers <= 0) {
- num_workers = 1;
+ num_workers = SKIP_ONE;
}
return g_budget / (size_t)num_workers;
}
diff --git a/src/foundation/yaml.c b/src/foundation/yaml.c
index b9805b9b2..5d7f705e6 100644
--- a/src/foundation/yaml.c
+++ b/src/foundation/yaml.c
@@ -10,6 +10,9 @@
*
* Indentation determines nesting depth. Uses a stack of parent nodes.
*/
+#include "foundation/constants.h"
+
+enum { YAML_INIT_CAP = 8, YAML_LIST_PREFIX = 2, YAML_ROOT_INDENT = -1 };
#include "foundation/yaml.h"
#include <ctype.h>
@@ -41,47 +44,58 @@ struct cbm_yaml_node {
/* ── Node lifecycle ───────────────────────────────────────────── */
static cbm_yaml_node_t *node_new(yaml_type_t type) {
- cbm_yaml_node_t *n = calloc(1, sizeof(*n));
+ cbm_yaml_node_t *n = calloc(CBM_ALLOC_ONE, sizeof(*n));
if (n) {
n->type = type;
}
return n;
}
-static void node_add_child(cbm_yaml_node_t *parent, cbm_yaml_node_t *child) {
+static bool node_add_child(cbm_yaml_node_t *parent, cbm_yaml_node_t *child) {
if (!parent || !child) {
- return;
+ return false;
}
if (parent->child_count >= parent->child_cap) {
- int new_cap = parent->child_cap < 8 ? 8 : parent->child_cap * 2;
+ int new_cap =
+ parent->child_cap < YAML_INIT_CAP ? YAML_INIT_CAP : parent->child_cap * PAIR_LEN;
cbm_yaml_node_t **new_arr = realloc(parent->children, (size_t)new_cap * sizeof(*new_arr));
if (!new_arr) {
- return;
+ return false;
}
parent->children = new_arr;
parent->child_cap = new_cap;
}
parent->children[parent->child_count++] = child;
+ return true;
}
void cbm_yaml_free(cbm_yaml_node_t *root) {
if (!root) {
return;
}
- for (int i = 0; i < root->child_count; i++) {
- cbm_yaml_free(root->children[i]);
+ enum { YAML_FREE_STACK = 256 };
+ cbm_yaml_node_t *stack[YAML_FREE_STACK];
+ int top = 0;
+ stack[top++] = root;
+ while (top > 0) {
+ cbm_yaml_node_t *node = stack[--top];
+ for (int i = 0; i < node->child_count && top < YAML_FREE_STACK; i++) {
+ if (node->children[i]) {
+ stack[top++] = node->children[i];
+ }
+ }
+ free(node->children);
+ free(node->key);
+ free(node->value);
+ free(node);
}
- free(root->children);
- free(root->key);
- free(root->value);
- free(root);
}
/* ── String helpers ───────────────────────────────────────────── */
/* Duplicate a substring [start, end). Trims trailing whitespace. */
static char *trim_dup(const char *start, const char *end) {
- while (end > start && isspace((unsigned char)end[-1])) {
+ while (end > start && isspace((unsigned char)end[-SKIP_ONE])) {
end--;
}
while (start < end && isspace((unsigned char)*start)) {
@@ -91,7 +105,7 @@ static char *trim_dup(const char *start, const char *end) {
return strdup("");
}
size_t len = (size_t)(end - start);
- char *s = malloc(len + 1);
+ char *s = malloc(len + SKIP_ONE);
if (!s) {
return NULL;
}
@@ -119,8 +133,8 @@ typedef struct {
/* Parse a list item "- value" and add to the correct parent. */
static void parse_list_item(const char *content, int content_len, cbm_yaml_node_t *parent) {
- const char *item_start = content + 2;
- int item_len = content_len - 2;
+ const char *item_start = content + YAML_LIST_PREFIX;
+ int item_len = content_len - YAML_LIST_PREFIX;
while (item_len > 0 && isspace((unsigned char)item_start[0])) {
item_start++;
item_len--;
@@ -129,7 +143,7 @@ static void parse_list_item(const char *content, int content_len, cbm_yaml_node_
/* If parent is a map, the list items belong to the last child */
cbm_yaml_node_t *list_parent = parent;
if (parent->type == YAML_MAP && parent->child_count > 0) {
- cbm_yaml_node_t *last = parent->children[parent->child_count - 1];
+ cbm_yaml_node_t *last = parent->children[parent->child_count - SKIP_ONE];
if (last->type == YAML_LIST) {
list_parent = last;
}
@@ -138,7 +152,9 @@ static void parse_list_item(const char *content, int content_len, cbm_yaml_node_
cbm_yaml_node_t *item = node_new(YAML_SCALAR);
if (item) {
item->value = trim_dup(item_start, item_start + item_len);
- node_add_child(list_parent, item);
+ if (!node_add_child(list_parent, item)) {
+ cbm_yaml_free(item);
+ }
}
}
@@ -147,9 +163,9 @@ static void parse_list_item(const char *content, int content_len, cbm_yaml_node_
static int strip_inline_comment(const char *after, int after_len) {
if (after_len > 0 && after[0] != '"' && after[0] != '\'') {
for (int i = 0; i < after_len; i++) {
- if (after[i] == '#' && i > 0 && after[i - 1] == ' ') {
+ if (after[i] == '#' && i > 0 && after[i - SKIP_ONE] == ' ') {
after_len = i;
- while (after_len > 0 && isspace((unsigned char)after[after_len - 1])) {
+ while (after_len > 0 && isspace((unsigned char)after[after_len - SKIP_ONE])) {
after_len--;
}
break;
@@ -161,7 +177,7 @@ static int strip_inline_comment(const char *after, int after_len) {
/* Peek ahead to check if next content line is a list item. */
static bool peek_is_list(const char *eol, const char *end) {
- const char *peek = (eol < end) ? eol + 1 : end;
+ const char *peek = (eol < end) ? eol + SKIP_ONE : end;
while (peek < end) {
const char *peek_eol = memchr(peek, '\n', (size_t)(end - peek));
if (!peek_eol) {
@@ -170,11 +186,11 @@ static bool peek_is_list(const char *eol, const char *end) {
int pi = leading_spaces(peek);
const char *pc = peek + pi;
int pcl = (int)(peek_eol - pc);
- if (pcl > 0 && pc[pcl - 1] == '\r') {
+ if (pcl > 0 && pc[pcl - SKIP_ONE] == '\r') {
pcl--;
}
if (pcl == 0 || pc[0] == '#') {
- peek = (peek_eol < end) ? peek_eol + 1 : end;
+ peek = (peek_eol < end) ? peek_eol + SKIP_ONE : end;
continue;
}
return pc[0] == '-';
@@ -197,7 +213,7 @@ static void parse_key_line(const char *content, int content_len, int indent,
}
/* After colon: value or nothing */
- const char *after = colon + 1;
+ const char *after = colon + SKIP_ONE;
int after_len = content_len - (int)(after - content);
while (after_len > 0 && isspace((unsigned char)*after)) {
after++;
@@ -212,7 +228,9 @@ static void parse_key_line(const char *content, int content_len, int indent,
if (child) {
child->key = key;
child->value = trim_dup(after, after + after_len);
- node_add_child(parent, child);
+ if (!node_add_child(parent, child)) {
+ cbm_yaml_free(child);
+ }
} else {
free(key);
}
@@ -222,8 +240,9 @@ static void parse_key_line(const char *content, int content_len, int indent,
cbm_yaml_node_t *child = node_new(is_list ? YAML_LIST : YAML_MAP);
if (child) {
child->key = key;
- node_add_child(parent, child);
- if (*stack_depth < 32) {
+ if (!node_add_child(parent, child)) {
+ cbm_yaml_free(child);
+ } else if (*stack_depth < CBM_SZ_32) {
stack[(*stack_depth)++] = (stack_entry_t){.node = child, .indent = indent};
}
} else {
@@ -243,10 +262,10 @@ cbm_yaml_node_t *cbm_yaml_parse(const char *text, int len) {
}
/* Stack for tracking parent context */
- stack_entry_t stack[32];
+ stack_entry_t stack[CBM_SZ_32];
int stack_depth = 0;
- stack[0] = (stack_entry_t){.node = root, .indent = -1};
- stack_depth = 1;
+ stack[0] = (stack_entry_t){.node = root, .indent = YAML_ROOT_INDENT};
+ stack_depth = SKIP_ONE;
const char *p = text;
const char *end = text + len;
@@ -265,28 +284,28 @@ cbm_yaml_node_t *cbm_yaml_parse(const char *text, int len) {
int content_len = line_len - indent;
/* Strip \r */
- if (content_len > 0 && content[content_len - 1] == '\r') {
+ if (content_len > 0 && content[content_len - SKIP_ONE] == '\r') {
content_len--;
}
if (content_len == 0 || content[0] == '#') {
- p = (eol < end) ? eol + 1 : end;
+ p = (eol < end) ? eol + SKIP_ONE : end;
continue;
}
/* Pop stack to find parent at correct indentation */
- while (stack_depth > 1 && stack[stack_depth - 1].indent >= indent) {
+ while (stack_depth > SKIP_ONE && stack[stack_depth - SKIP_ONE].indent >= indent) {
stack_depth--;
}
- cbm_yaml_node_t *parent = stack[stack_depth - 1].node;
+ cbm_yaml_node_t *parent = stack[stack_depth - SKIP_ONE].node;
- if (content[0] == '-' && content_len >= 2 && content[1] == ' ') {
+ if (content[0] == '-' && content_len >= PAIR_LEN && content[SKIP_ONE] == ' ') {
parse_list_item(content, content_len, parent);
} else {
parse_key_line(content, content_len, indent, parent, stack, &stack_depth, eol, end);
}
- p = (eol < end) ? eol + 1 : end;
+ p = (eol < end) ? eol + SKIP_ONE : end;
}
return root;
@@ -314,7 +333,7 @@ static const cbm_yaml_node_t *navigate(const cbm_yaml_node_t *root, const char *
}
const cbm_yaml_node_t *cur = root;
- char buf[256];
+ char buf[CBM_SZ_256];
const char *p = path;
while (*p) {
diff --git a/src/graph_buffer/graph_buffer.c b/src/graph_buffer/graph_buffer.c
index 13291d65b..ed6fcee60 100644
--- a/src/graph_buffer/graph_buffer.c
+++ b/src/graph_buffer/graph_buffer.c
@@ -8,6 +8,17 @@
* pointers stored in hash tables remain stable when the pointer-array grows.
* The buffer frees everything in cbm_gbuf_free().
*/
+#include "foundation/constants.h"
+
+enum {
+ GB_COL_2 = 2,
+ GB_COL_3 = 3,
+ GB_COL_4 = 4,
+ GB_COL_5 = 5,
+ GB_COL_6 = 6,
+ GB_COL_7 = 7,
+ GB_URL_PATH_PREFIX = 12, /* strlen(""url_path":"") */
+};
#include "graph_buffer/graph_buffer.h"
#include "store/store.h"
#include "sqlite_writer.h"
@@ -24,10 +35,16 @@
#include <string.h> // strdup
#include <time.h>
+static inline void *intptr_to_ptr(intptr_t v) {
+ void *p;
+ memcpy(&p, &v, sizeof(p));
+ return p;
+}
+
/* ── Internal types ──────────────────────────────────────────────── */
/* Edge key for dedup hash table — composite key as string "srcID:tgtID:type" */
-#define EDGE_KEY_BUF 128
+#define EDGE_KEY_BUF CBM_SZ_128
/* Per-type or per-key edge list stored in hash tables as values */
typedef CBM_DYN_ARRAY(const cbm_gbuf_edge_t *) edge_ptr_array_t;
@@ -89,7 +106,7 @@ static void make_src_type_key(char *buf, size_t bufsz, int64_t src, const char *
static node_ptr_array_t *get_or_create_node_array(CBMHashTable *ht, const char *key) {
node_ptr_array_t *arr = cbm_ht_get(ht, key);
if (!arr) {
- arr = calloc(1, sizeof(node_ptr_array_t));
+ arr = calloc(CBM_ALLOC_ONE, sizeof(node_ptr_array_t));
cbm_ht_set(ht, strdup(key), arr);
}
return arr;
@@ -99,7 +116,7 @@ static node_ptr_array_t *get_or_create_node_array(CBMHashTable *ht, const char *
static edge_ptr_array_t *get_or_create_edge_array(CBMHashTable *ht, const char *key) {
edge_ptr_array_t *arr = cbm_ht_get(ht, key);
if (!arr) {
- arr = calloc(1, sizeof(edge_ptr_array_t));
+ arr = calloc(CBM_ALLOC_ONE, sizeof(edge_ptr_array_t));
cbm_ht_set(ht, strdup(key), arr);
}
return arr;
@@ -152,7 +169,7 @@ static void free_edge_strings(cbm_gbuf_edge_t *e) {
/* Allocate the next buffer-local or shared-atomic ID. */
static int64_t alloc_next_id(cbm_gbuf_t *gb) {
if (gb->shared_ids) {
- return atomic_fetch_add_explicit(gb->shared_ids, 1, memory_order_relaxed);
+ return atomic_fetch_add_explicit(gb->shared_ids, SKIP_ONE, memory_order_relaxed);
}
return gb->next_id++;
}
@@ -206,8 +223,8 @@ static void cascade_delete_edges(cbm_gbuf_t *gb, CBMHashTable *deleted_set) {
int write_idx = 0;
for (int i = 0; i < gb->edges.count; i++) {
cbm_gbuf_edge_t *e = gb->edges.items[i];
- char src_id[32];
- char tgt_id[32];
+ char src_id[CBM_SZ_32];
+ char tgt_id[CBM_SZ_32];
make_id_key(src_id, sizeof(src_id), e->source_id);
make_id_key(tgt_id, sizeof(tgt_id), e->target_id);
@@ -226,7 +243,7 @@ static void cascade_delete_edges(cbm_gbuf_t *gb, CBMHashTable *deleted_set) {
static void register_node_in_indexes(cbm_gbuf_t *gb, cbm_gbuf_node_t *node) {
cbm_ht_set(gb->node_by_qn, node->qualified_name, node);
- char id_buf[32];
+ char id_buf[CBM_SZ_32];
make_id_key(id_buf, sizeof(id_buf), node->id);
const char *old_key = cbm_ht_get_key(gb->node_by_id, id_buf);
if (old_key) {
@@ -277,9 +294,9 @@ static void rebuild_edge_secondary_indexes(cbm_gbuf_t *gb) {
cbm_ht_foreach(gb->edges_by_type, free_edge_array, NULL);
cbm_ht_free(gb->edges_by_type);
- gb->edges_by_source_type = cbm_ht_create(256);
- gb->edges_by_target_type = cbm_ht_create(256);
- gb->edges_by_type = cbm_ht_create(32);
+ gb->edges_by_source_type = cbm_ht_create(CBM_SZ_256);
+ gb->edges_by_target_type = cbm_ht_create(CBM_SZ_256);
+ gb->edges_by_type = cbm_ht_create(CBM_SZ_32);
for (int i = 0; i < gb->edges.count; i++) {
register_edge_in_indexes(gb, gb->edges.items[i]);
@@ -316,25 +333,25 @@ static void release_gbuf_indexes(cbm_gbuf_t *gb) {
/* ── Lifecycle ──────────────────────────────────────────────────── */
cbm_gbuf_t *cbm_gbuf_new(const char *project, const char *root_path) {
- cbm_gbuf_t *gb = calloc(1, sizeof(cbm_gbuf_t));
+ cbm_gbuf_t *gb = calloc(CBM_ALLOC_ONE, sizeof(cbm_gbuf_t));
if (!gb) {
return NULL;
}
gb->project = strdup(project ? project : "");
gb->root_path = strdup(root_path ? root_path : "");
- gb->next_id = 1;
+ gb->next_id = SKIP_ONE;
gb->shared_ids = NULL;
- gb->node_by_qn = cbm_ht_create(256);
- gb->node_by_id = cbm_ht_create(256);
- gb->nodes_by_label = cbm_ht_create(32);
- gb->nodes_by_name = cbm_ht_create(256);
+ gb->node_by_qn = cbm_ht_create(CBM_SZ_256);
+ gb->node_by_id = cbm_ht_create(CBM_SZ_256);
+ gb->nodes_by_label = cbm_ht_create(CBM_SZ_32);
+ gb->nodes_by_name = cbm_ht_create(CBM_SZ_256);
- gb->edge_by_key = cbm_ht_create(512);
- gb->edges_by_source_type = cbm_ht_create(256);
- gb->edges_by_target_type = cbm_ht_create(256);
- gb->edges_by_type = cbm_ht_create(32);
+ gb->edge_by_key = cbm_ht_create(CBM_SZ_512);
+ gb->edges_by_source_type = cbm_ht_create(CBM_SZ_256);
+ gb->edges_by_target_type = cbm_ht_create(CBM_SZ_256);
+ gb->edges_by_type = cbm_ht_create(CBM_SZ_32);
return gb;
}
@@ -411,7 +428,7 @@ void cbm_gbuf_free(cbm_gbuf_t *gb) {
int64_t cbm_gbuf_next_id(const cbm_gbuf_t *gb) {
if (!gb) {
- return 1;
+ return SKIP_ONE;
}
if (gb->shared_ids) {
return atomic_load(gb->shared_ids);
@@ -460,7 +477,7 @@ int64_t cbm_gbuf_upsert_node(cbm_gbuf_t *gb, const char *label, const char *name
}
/* Heap-allocate a new node (pointer stays stable across array growth) */
- cbm_gbuf_node_t *node = calloc(1, sizeof(cbm_gbuf_node_t));
+ cbm_gbuf_node_t *node = calloc(CBM_ALLOC_ONE, sizeof(cbm_gbuf_node_t));
if (!node) {
return 0;
}
@@ -494,7 +511,7 @@ const cbm_gbuf_node_t *cbm_gbuf_find_by_id(const cbm_gbuf_t *gb, int64_t id) {
if (!gb) {
return NULL;
}
- char key[32];
+ char key[CBM_SZ_32];
make_id_key(key, sizeof(key), id);
return cbm_ht_get(gb->node_by_id, key);
}
@@ -502,7 +519,7 @@ const cbm_gbuf_node_t *cbm_gbuf_find_by_id(const cbm_gbuf_t *gb, int64_t id) {
int cbm_gbuf_find_by_label(const cbm_gbuf_t *gb, const char *label, const cbm_gbuf_node_t ***out,
int *count) {
if (!gb || !out || !count) {
- return -1;
+ return CBM_NOT_FOUND;
}
node_ptr_array_t *arr = cbm_ht_get(gb->nodes_by_label, label ? label : "");
if (arr && arr->count > 0) {
@@ -518,7 +535,7 @@ int cbm_gbuf_find_by_label(const cbm_gbuf_t *gb, const char *label, const cbm_gb
int cbm_gbuf_find_by_name(const cbm_gbuf_t *gb, const char *name, const cbm_gbuf_node_t ***out,
int *count) {
if (!gb || !out || !count) {
- return -1;
+ return CBM_NOT_FOUND;
}
node_ptr_array_t *arr = cbm_ht_get(gb->nodes_by_name, name ? name : "");
if (arr && arr->count > 0) {
@@ -538,7 +555,7 @@ int cbm_gbuf_node_count(const cbm_gbuf_t *gb) {
int cbm_gbuf_delete_by_label(cbm_gbuf_t *gb, const char *label) {
if (!gb || !label) {
- return -1;
+ return CBM_NOT_FOUND;
}
node_ptr_array_t *arr = cbm_ht_get(gb->nodes_by_label, label);
@@ -551,9 +568,9 @@ int cbm_gbuf_delete_by_label(cbm_gbuf_t *gb, const char *label) {
for (int i = 0; i < arr->count; i++) {
const cbm_gbuf_node_t *n = arr->items[i];
- char id_buf[32];
+ char id_buf[CBM_SZ_32];
make_id_key(id_buf, sizeof(id_buf), n->id);
- cbm_ht_set(deleted_set, strdup(id_buf), (void *)1);
+ cbm_ht_set(deleted_set, strdup(id_buf), intptr_to_ptr(SKIP_ONE));
/* Remove from primary indexes */
cbm_ht_delete(gb->node_by_qn, n->qualified_name);
@@ -575,11 +592,11 @@ int cbm_gbuf_delete_by_label(cbm_gbuf_t *gb, const char *label) {
int cbm_gbuf_delete_by_file(cbm_gbuf_t *gb, const char *file_path) {
if (!gb || !file_path) {
- return -1;
+ return CBM_NOT_FOUND;
}
/* Collect IDs of nodes in this file */
- CBMHashTable *deleted_set = cbm_ht_create(64);
+ CBMHashTable *deleted_set = cbm_ht_create(CBM_SZ_64);
int deleted_count = 0;
int scanned = 0;
@@ -593,9 +610,9 @@ int cbm_gbuf_delete_by_file(cbm_gbuf_t *gb, const char *file_path) {
continue;
}
- char id_buf[32];
+ char id_buf[CBM_SZ_32];
make_id_key(id_buf, sizeof(id_buf), n->id);
- cbm_ht_set(deleted_set, strdup(id_buf), (void *)1);
+ cbm_ht_set(deleted_set, strdup(id_buf), intptr_to_ptr(SKIP_ONE));
/* Remove from secondary indexes */
remove_node_from_ptr_array(cbm_ht_get(gb->nodes_by_label, n->label), n->id);
@@ -625,8 +642,8 @@ int cbm_gbuf_delete_by_file(cbm_gbuf_t *gb, const char *file_path) {
cbm_ht_foreach(deleted_set, free_key_only, NULL);
cbm_ht_free(deleted_set);
{
- char s_buf[16];
- char d_buf[16];
+ char s_buf[CBM_SZ_16];
+ char d_buf[CBM_SZ_16];
snprintf(s_buf, sizeof(s_buf), "%d", scanned);
snprintf(d_buf, sizeof(d_buf), "%d", deleted_count);
cbm_log_info("gbuf.delete_by_file", "file", file_path, "scanned", s_buf, "deleted", d_buf);
@@ -636,38 +653,38 @@ int cbm_gbuf_delete_by_file(cbm_gbuf_t *gb, const char *file_path) {
int cbm_gbuf_load_from_db(cbm_gbuf_t *gb, const char *db_path, const char *project) {
if (!gb || !db_path || !project) {
- return -1;
+ return CBM_NOT_FOUND;
}
cbm_store_t *store = cbm_store_open_path(db_path);
if (!store) {
- return -1;
+ return CBM_NOT_FOUND;
}
sqlite3 *db = cbm_store_get_db(store);
if (!db) {
cbm_store_close(store);
- return -1;
+ return CBM_NOT_FOUND;
}
/* First pass: find max node ID for mapping array */
sqlite3_stmt *stmt = NULL;
- if (sqlite3_prepare_v2(db, "SELECT MAX(id) FROM nodes WHERE project = ?", -1, &stmt, NULL) !=
- SQLITE_OK) {
+ if (sqlite3_prepare_v2(db, "SELECT MAX(id) FROM nodes WHERE project = ?", CBM_NOT_FOUND, &stmt,
+ NULL) != SQLITE_OK) {
cbm_store_close(store);
- return -1;
+ return CBM_NOT_FOUND;
}
- sqlite3_bind_text(stmt, 1, project, -1, SQLITE_STATIC);
+ sqlite3_bind_text(stmt, SKIP_ONE, project, CBM_NOT_FOUND, SQLITE_STATIC);
int64_t max_old_id = 0;
if (sqlite3_step(stmt) == SQLITE_ROW) {
max_old_id = sqlite3_column_int64(stmt, 0);
}
sqlite3_finalize(stmt);
- int64_t *old_to_new = calloc((size_t)(max_old_id + 1), sizeof(int64_t));
+ int64_t *old_to_new = calloc((size_t)(max_old_id + SKIP_ONE), sizeof(int64_t));
if (!old_to_new) {
cbm_store_close(store);
- return -1;
+ return CBM_NOT_FOUND;
}
/* Load all nodes */
@@ -675,22 +692,22 @@ int cbm_gbuf_load_from_db(cbm_gbuf_t *gb, const char *db_path, const char *proje
db,
"SELECT id, label, name, qualified_name, file_path, start_line, end_line, properties "
"FROM nodes WHERE project = ? ORDER BY id",
- -1, &stmt, NULL) != SQLITE_OK) {
+ CBM_NOT_FOUND, &stmt, NULL) != SQLITE_OK) {
free(old_to_new);
cbm_store_close(store);
- return -1;
+ return CBM_NOT_FOUND;
}
- sqlite3_bind_text(stmt, 1, project, -1, SQLITE_STATIC);
+ sqlite3_bind_text(stmt, SKIP_ONE, project, CBM_NOT_FOUND, SQLITE_STATIC);
while (sqlite3_step(stmt) == SQLITE_ROW) {
int64_t old_id = sqlite3_column_int64(stmt, 0);
- const char *label = (const char *)sqlite3_column_text(stmt, 1);
- const char *name = (const char *)sqlite3_column_text(stmt, 2);
- const char *qn = (const char *)sqlite3_column_text(stmt, 3);
- const char *fp = (const char *)sqlite3_column_text(stmt, 4);
- int sl = sqlite3_column_int(stmt, 5);
- int el = sqlite3_column_int(stmt, 6);
- const char *props = (const char *)sqlite3_column_text(stmt, 7);
+ const char *label = (const char *)sqlite3_column_text(stmt, SKIP_ONE);
+ const char *name = (const char *)sqlite3_column_text(stmt, GB_COL_2);
+ const char *qn = (const char *)sqlite3_column_text(stmt, GB_COL_3);
+ const char *fp = (const char *)sqlite3_column_text(stmt, GB_COL_4);
+ int sl = sqlite3_column_int(stmt, GB_COL_5);
+ int el = sqlite3_column_int(stmt, GB_COL_6);
+ const char *props = (const char *)sqlite3_column_text(stmt, GB_COL_7);
int64_t new_id = cbm_gbuf_upsert_node(gb, label, name, qn, fp, sl, el, props);
if (new_id > 0 && old_id <= max_old_id) {
@@ -703,18 +720,18 @@ int cbm_gbuf_load_from_db(cbm_gbuf_t *gb, const char *db_path, const char *proje
if (sqlite3_prepare_v2(db,
"SELECT source_id, target_id, type, properties "
"FROM edges WHERE project = ?",
- -1, &stmt, NULL) != SQLITE_OK) {
+ CBM_NOT_FOUND, &stmt, NULL) != SQLITE_OK) {
free(old_to_new);
cbm_store_close(store);
- return -1;
+ return CBM_NOT_FOUND;
}
- sqlite3_bind_text(stmt, 1, project, -1, SQLITE_STATIC);
+ sqlite3_bind_text(stmt, SKIP_ONE, project, CBM_NOT_FOUND, SQLITE_STATIC);
while (sqlite3_step(stmt) == SQLITE_ROW) {
int64_t old_src = sqlite3_column_int64(stmt, 0);
- int64_t old_tgt = sqlite3_column_int64(stmt, 1);
- const char *type = (const char *)sqlite3_column_text(stmt, 2);
- const char *props = (const char *)sqlite3_column_text(stmt, 3);
+ int64_t old_tgt = sqlite3_column_int64(stmt, SKIP_ONE);
+ const char *type = (const char *)sqlite3_column_text(stmt, GB_COL_2);
+ const char *props = (const char *)sqlite3_column_text(stmt, GB_COL_3);
int64_t new_src = (old_src <= max_old_id) ? old_to_new[old_src] : 0;
int64_t new_tgt = (old_tgt <= max_old_id) ? old_to_new[old_tgt] : 0;
@@ -773,7 +790,7 @@ int64_t cbm_gbuf_insert_edge(cbm_gbuf_t *gb, int64_t source_id, int64_t target_i
}
/* Heap-allocate a new edge (pointer stays stable) */
- cbm_gbuf_edge_t *edge = calloc(1, sizeof(cbm_gbuf_edge_t));
+ cbm_gbuf_edge_t *edge = calloc(CBM_ALLOC_ONE, sizeof(cbm_gbuf_edge_t));
if (!edge) {
return 0;
}
@@ -801,7 +818,7 @@ int64_t cbm_gbuf_insert_edge(cbm_gbuf_t *gb, int64_t source_id, int64_t target_i
int cbm_gbuf_find_edges_by_source_type(const cbm_gbuf_t *gb, int64_t source_id, const char *type,
const cbm_gbuf_edge_t ***out, int *count) {
if (!gb || !out || !count) {
- return -1;
+ return CBM_NOT_FOUND;
}
char key[EDGE_KEY_BUF];
make_src_type_key(key, sizeof(key), source_id, type);
@@ -819,7 +836,7 @@ int cbm_gbuf_find_edges_by_source_type(const cbm_gbuf_t *gb, int64_t source_id,
int cbm_gbuf_find_edges_by_target_type(const cbm_gbuf_t *gb, int64_t target_id, const char *type,
const cbm_gbuf_edge_t ***out, int *count) {
if (!gb || !out || !count) {
- return -1;
+ return CBM_NOT_FOUND;
}
char key[EDGE_KEY_BUF];
make_src_type_key(key, sizeof(key), target_id, type);
@@ -837,7 +854,7 @@ int cbm_gbuf_find_edges_by_target_type(const cbm_gbuf_t *gb, int64_t target_id,
int cbm_gbuf_find_edges_by_type(const cbm_gbuf_t *gb, const char *type,
const cbm_gbuf_edge_t ***out, int *count) {
if (!gb || !out || !count) {
- return -1;
+ return CBM_NOT_FOUND;
}
edge_ptr_array_t *arr = cbm_ht_get(gb->edges_by_type, type);
if (arr && arr->count > 0) {
@@ -864,7 +881,7 @@ int cbm_gbuf_edge_count_by_type(const cbm_gbuf_t *gb, const char *type) {
int cbm_gbuf_delete_edges_by_type(cbm_gbuf_t *gb, const char *type) {
if (!gb || !type) {
- return -1;
+ return CBM_NOT_FOUND;
}
/* Remove edges of the given type from array and dedup index */
@@ -918,9 +935,9 @@ static void merge_update_existing(cbm_gbuf_node_t *existing, const cbm_gbuf_node
if (sn->id != existing->id) {
if (!*remap) {
- *remap = cbm_ht_create(32);
+ *remap = cbm_ht_create(CBM_SZ_32);
}
- char key[32];
+ char key[CBM_SZ_32];
make_id_key(key, sizeof(key), sn->id);
int64_t *val = malloc(sizeof(int64_t));
*val = existing->id;
@@ -930,7 +947,7 @@ static void merge_update_existing(cbm_gbuf_node_t *existing, const cbm_gbuf_node
/* Copy a non-colliding src node into dst with its original ID. */
static void merge_copy_new_node(cbm_gbuf_t *dst, const cbm_gbuf_node_t *sn) {
- cbm_gbuf_node_t *node = calloc(1, sizeof(cbm_gbuf_node_t));
+ cbm_gbuf_node_t *node = calloc(CBM_ALLOC_ONE, sizeof(cbm_gbuf_node_t));
if (!node) {
return;
}
@@ -949,7 +966,7 @@ static void merge_copy_new_node(cbm_gbuf_t *dst, const cbm_gbuf_node_t *sn) {
register_node_in_indexes(dst, node);
if (node->id >= dst->next_id) {
- dst->next_id = node->id + 1;
+ dst->next_id = node->id + SKIP_ONE;
}
}
@@ -962,7 +979,7 @@ static void merge_remap_edges(cbm_gbuf_t *dst, cbm_gbuf_t *src, CBMHashTable *re
int64_t new_tgt = se->target_id;
if (remap) {
- char key[32];
+ char key[CBM_SZ_32];
make_id_key(key, sizeof(key), se->source_id);
int64_t *remapped = cbm_ht_get(remap, key);
if (remapped) {
@@ -982,7 +999,7 @@ static void merge_remap_edges(cbm_gbuf_t *dst, cbm_gbuf_t *src, CBMHashTable *re
int cbm_gbuf_merge(cbm_gbuf_t *dst, cbm_gbuf_t *src) {
if (!dst || !src) {
- return -1;
+ return CBM_NOT_FOUND;
}
if (src->nodes.count == 0 && src->edges.count == 0) {
return 0;
@@ -1034,7 +1051,7 @@ static char *extract_url_path(const char *props) {
if (!key) {
return NULL;
}
- key += 12; /* strlen("\"url_path\":\"") */
+ key += GB_URL_PATH_PREFIX; /* strlen("\"url_path\":\"") */
const char *end = strchr(key, '"');
if (!end || end <= key) {
return NULL;
@@ -1051,7 +1068,7 @@ static int64_t remap_id(const int64_t *temp_to_final, int64_t max_temp_id, int64
static CBMDumpNode *build_dump_nodes(cbm_gbuf_t *gb, int live_count, int64_t *temp_to_final,
int64_t max_temp_id, int *out_count) {
CBMDumpNode *dump_nodes =
- malloc((size_t)(live_count > 0 ? live_count : 1) * sizeof(CBMDumpNode));
+ malloc((size_t)(live_count > 0 ? live_count : SKIP_ONE) * sizeof(CBMDumpNode));
int idx = 0;
for (int i = 0; i < gb->nodes.count; i++) {
@@ -1060,7 +1077,7 @@ static CBMDumpNode *build_dump_nodes(cbm_gbuf_t *gb, int live_count, int64_t *te
continue;
}
- int64_t final_id = idx + 1; /* 1-based sequential */
+ int64_t final_id = idx + SKIP_ONE; /* 1-based sequential */
if (n->id < max_temp_id) {
temp_to_final[n->id] = final_id;
}
@@ -1099,8 +1116,8 @@ static CBMDumpEdge *build_dump_edges(cbm_gbuf_t *gb, const int64_t *temp_to_fina
}
CBMDumpEdge *dump_edges =
- malloc((size_t)(valid_edges > 0 ? valid_edges : 1) * sizeof(CBMDumpEdge));
- char **url_paths = calloc((size_t)(valid_edges > 0 ? valid_edges : 1), sizeof(char *));
+ malloc((size_t)(valid_edges > 0 ? valid_edges : SKIP_ONE) * sizeof(CBMDumpEdge));
+ char **url_paths = calloc((size_t)(valid_edges > 0 ? valid_edges : SKIP_ONE), sizeof(char *));
int idx = 0;
for (int i = 0; i < gb->edges.count; i++) {
@@ -1116,7 +1133,7 @@ static CBMDumpEdge *build_dump_edges(cbm_gbuf_t *gb, const int64_t *temp_to_fina
const char *props = e->properties_json ? e->properties_json : "{}";
dump_edges[idx] = (CBMDumpEdge){
- .id = idx + 1,
+ .id = idx + SKIP_ONE,
.project = gb->project,
.source_id = src,
.target_id = tgt,
@@ -1134,7 +1151,7 @@ static CBMDumpEdge *build_dump_edges(cbm_gbuf_t *gb, const int64_t *temp_to_fina
int cbm_gbuf_dump_to_sqlite(cbm_gbuf_t *gb, const char *path) {
if (!gb || !path) {
- return -1;
+ return CBM_NOT_FOUND;
}
/* Count live nodes (not deleted from QN index) */
@@ -1150,7 +1167,7 @@ int cbm_gbuf_dump_to_sqlite(cbm_gbuf_t *gb, const char *path) {
int64_t max_temp_id = gb->next_id;
int64_t *temp_to_final = calloc((size_t)max_temp_id, sizeof(int64_t));
if (!temp_to_final) {
- return -1;
+ return CBM_NOT_FOUND;
}
int node_idx = 0;
@@ -1164,9 +1181,12 @@ int cbm_gbuf_dump_to_sqlite(cbm_gbuf_t *gb, const char *path) {
/* Generate ISO 8601 timestamp */
time_t now = time(NULL);
- struct tm *tm_val = gmtime(&now);
- char indexed_at[64];
- strftime(indexed_at, sizeof(indexed_at), "%Y-%m-%dT%H:%M:%SZ", tm_val);
+ struct tm tm_buf;
+ struct tm *tm_val = gmtime_r(&now, &tm_buf);
+ char indexed_at[CBM_SZ_64];
+ if (strftime(indexed_at, sizeof(indexed_at), "%Y-%m-%dT%H:%M:%SZ", tm_val) == 0) {
+ snprintf(indexed_at, sizeof(indexed_at), "1970-01-01T00:00:00Z");
+ }
/* Release lookup tables — no longer needed now that dump arrays are built.
* Frees hash tables (~200-400MB on large codebases) while keeping the
@@ -1180,8 +1200,8 @@ int cbm_gbuf_dump_to_sqlite(cbm_gbuf_t *gb, const char *path) {
dump_edges, edge_idx);
{
- char b1[16];
- char b2[16];
+ char b1[CBM_SZ_16];
+ char b2[CBM_SZ_16];
snprintf(b1, sizeof(b1), "%d", node_idx);
snprintf(b2, sizeof(b2), "%d", edge_idx);
cbm_log_info("gbuf.dump", "nodes", b1, "edges", b2);
@@ -1201,7 +1221,7 @@ int cbm_gbuf_dump_to_sqlite(cbm_gbuf_t *gb, const char *path) {
int cbm_gbuf_flush_to_store(cbm_gbuf_t *gb, cbm_store_t *store) {
if (!gb || !store) {
- return -1;
+ return CBM_NOT_FOUND;
}
/* Upsert project */
@@ -1275,7 +1295,7 @@ int cbm_gbuf_flush_to_store(cbm_gbuf_t *gb, cbm_store_t *store) {
int cbm_gbuf_merge_into_store(cbm_gbuf_t *gb, cbm_store_t *store) {
if (!gb || !store) {
- return -1;
+ return CBM_NOT_FOUND;
}
/* Begin bulk mode — no project wipe */
diff --git a/src/main.c b/src/main.c
index 979ee2fc5..822aa02bf 100644
--- a/src/main.c
+++ b/src/main.c
@@ -18,6 +18,18 @@
#include "pipeline/pipeline.h"
#include "store/store.h"
#include "cli/cli.h"
+#include "foundation/constants.h"
+
+enum {
+ MAIN_MIN_ARGC = 1,
+ MAIN_CLI_ARGC = 2,
+ MAIN_FLAG_OFF = 5, /* strlen("--ui=") */
+ MAIN_PORT_OFF = 7, /* strlen("--port=") */
+ MAIN_MAX_PORT = 65536,
+};
+#define MAIN_RAM_FRACTION 0.5
+
+#define SLEN(s) (sizeof(s) - 1)
#include "foundation/log.h"
#include "foundation/diagnostics.h"
#include "foundation/platform.h"
@@ -62,6 +74,7 @@ static void signal_handler(int sig) {
static void *watcher_thread(void *arg) {
cbm_watcher_t *w = arg;
#define WATCHER_BASE_INTERVAL_MS 5000
+
cbm_watcher_run(w, WATCHER_BASE_INTERVAL_MS);
return NULL;
}
@@ -91,7 +104,7 @@ static int watcher_index_fn(const char *project_name, const char *root_path, voi
cbm_pipeline_t *p = cbm_pipeline_new(root_path, NULL, CBM_MODE_FULL);
if (!p) {
cbm_pipeline_unlock();
- return -1;
+ return CBM_NOT_FOUND;
}
int rc = cbm_pipeline_run(p);
@@ -103,18 +116,18 @@ static int watcher_index_fn(const char *project_name, const char *root_path, voi
/* ── CLI mode ───────────────────────────────────────────────────── */
static int run_cli(int argc, char **argv) {
- if (argc < 1) {
+ if (argc < MAIN_MIN_ARGC) {
(void)fprintf(stderr, "Usage: codebase-memory-mcp cli <tool_name> [json_args]\n");
- return 1;
+ return SKIP_ONE;
}
const char *tool_name = argv[0];
- const char *args_json = argc >= 2 ? argv[1] : "{}";
+ const char *args_json = argc >= MAIN_CLI_ARGC ? argv[SKIP_ONE] : "{}";
cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);
if (!srv) {
(void)fprintf(stderr, "Failed to create server\n");
- return 1;
+ return SKIP_ONE;
}
char *result = cbm_mcp_handle_tool(srv, tool_name, args_json);
@@ -157,7 +170,7 @@ static void print_help(void) {
/* Try to handle a subcommand (cli/install/uninstall/update/config/--version/--help).
* Returns -1 if no subcommand matched, otherwise the exit code. */
static int handle_subcommand(int argc, char **argv) {
- for (int i = 1; i < argc; i++) {
+ for (int i = SKIP_ONE; i < argc; i++) {
if (strcmp(argv[i], "--version") == 0) {
printf("codebase-memory-mcp %s\n", CBM_VERSION);
return 0;
@@ -167,36 +180,36 @@ static int handle_subcommand(int argc, char **argv) {
return 0;
}
if (strcmp(argv[i], "cli") == 0) {
- cbm_mem_init(0.5);
- return run_cli(argc - i - 1, argv + i + 1);
+ cbm_mem_init(MAIN_RAM_FRACTION);
+ return run_cli(argc - i - SKIP_ONE, argv + i + SKIP_ONE);
}
if (strcmp(argv[i], "install") == 0) {
- return cbm_cmd_install(argc - i - 1, argv + i + 1);
+ return cbm_cmd_install(argc - i - SKIP_ONE, argv + i + SKIP_ONE);
}
if (strcmp(argv[i], "uninstall") == 0) {
- return cbm_cmd_uninstall(argc - i - 1, argv + i + 1);
+ return cbm_cmd_uninstall(argc - i - SKIP_ONE, argv + i + SKIP_ONE);
}
if (strcmp(argv[i], "update") == 0) {
- return cbm_cmd_update(argc - i - 1, argv + i + 1);
+ return cbm_cmd_update(argc - i - SKIP_ONE, argv + i + SKIP_ONE);
}
if (strcmp(argv[i], "config") == 0) {
- return cbm_cmd_config(argc - i - 1, argv + i + 1);
+ return cbm_cmd_config(argc - i - SKIP_ONE, argv + i + SKIP_ONE);
}
}
- return -1;
+ return CBM_NOT_FOUND;
}
/* Parse --ui= and --port= flags. Returns true if config was modified. */
static bool parse_ui_flags(int argc, char **argv, cbm_ui_config_t *cfg) {
bool changed = false;
- for (int i = 1; i < argc; i++) {
- if (strncmp(argv[i], "--ui=", 5) == 0) {
- cfg->ui_enabled = (strcmp(argv[i] + 5, "true") == 0);
+ for (int i = SKIP_ONE; i < argc; i++) {
+ if (strncmp(argv[i], "--ui=", SLEN("--ui=")) == 0) {
+ cfg->ui_enabled = (strcmp(argv[i] + MAIN_FLAG_OFF, "true") == 0);
changed = true;
}
- if (strncmp(argv[i], "--port=", 7) == 0) {
- int p = (int)strtol(argv[i] + 7, NULL, 10);
- if (p > 0 && p < 65536) {
+ if (strncmp(argv[i], "--port=", SLEN("--port=")) == 0) {
+ int p = (int)strtol(argv[i] + MAIN_PORT_OFF, NULL, CBM_DECIMAL_BASE);
+ if (p > 0 && p < MAIN_MAX_PORT) {
cfg->ui_port = p;
changed = true;
}
@@ -227,9 +240,9 @@ int main(int argc, char **argv) {
}
/* Default: MCP server on stdio */
- cbm_mem_init(0.5); /* 50% of RAM — safe now because mimalloc tracks ALL
- * memory (C + C++ allocations) via global override.
- * No more untracked heap blind spots. */
+ cbm_mem_init(MAIN_RAM_FRACTION); /* 50% of RAM — safe now because mimalloc tracks ALL
+ * memory (C + C++ allocations) via global override.
+ * No more untracked heap blind spots. */
/* Store binary path for subprocess spawning + hook log sink */
cbm_http_server_set_binary_path(argv[0]);
cbm_log_set_sink(cbm_ui_log_append);
@@ -246,7 +259,7 @@ int main(int argc, char **argv) {
setup_signal_handlers();
/* Open config store for runtime settings */
- char config_dir[1024];
+ char config_dir[CBM_SZ_1K];
const char *cfg_home = cbm_get_home_dir();
cbm_config_t *runtime_config = NULL;
if (cfg_home) {
@@ -259,7 +272,7 @@ int main(int argc, char **argv) {
if (!g_server) {
cbm_log_error("server.err", "msg", "failed to create server");
cbm_config_close(runtime_config);
- return 1;
+ return SKIP_ONE;
}
/* Create and start watcher in background thread */
diff --git a/src/mcp/mcp.c b/src/mcp/mcp.c
index dbc1ef4c8..976f269e8 100644
--- a/src/mcp/mcp.c
+++ b/src/mcp/mcp.c
@@ -7,6 +7,37 @@
// operations
+#include "foundation/constants.h"
+
+enum {
+ MCP_FIELD_SIZE = 1040,
+ MCP_TIMEOUT_MS = 1000,
+ MCP_HALF_SEC_US = 500000,
+ MCP_MAX_ROWS = 100,
+ MCP_MAX_DEPTH = 15,
+ MCP_COL_2 = 2,
+ MCP_COL_3 = 3,
+ MCP_COL_4 = 4,
+ MCP_COL_7 = 7,
+ MCP_COL_10 = 10,
+ MCP_COL_16 = 16,
+ MCP_DB_EXT = 3, /* strlen(".db") */
+ MCP_MIN_DB_NAME = 4, /* min length for "x.db" */
+ MCP_SEPARATOR = 2, /* space for separator chars */
+ MCP_DEFAULT_DEPTH = 3,
+ MCP_DEFAULT_BFS_DEPTH = 2,
+ MCP_DEFAULT_LIMIT = 10,
+ MCP_BFS_LIMIT = 100,
+ MCP_N_DEFAULTS_2 = 2,
+ MCP_N_DEFAULTS_4 = 4,
+ MCP_URI_PREFIX = 7, /* strlen("file://") */
+ MCP_CONTENT_PREFIX = 15, /* strlen("Content-Length:") */
+ MCP_RETURN_2 = 2,
+};
+#define MCP_MS_TO_US 1000LL
+#define MCP_S_TO_US 1000000LL
+
+#define SLEN(s) (sizeof(s) - 1)
#include "mcp/mcp.h"
#include "store/store.h"
#include "cypher/cypher.h"
@@ -63,9 +94,9 @@ static char *heap_strdup(const char *s) {
return NULL;
}
size_t len = strlen(s);
- char *d = malloc(len + 1);
+ char *d = malloc(len + SKIP_ONE);
if (d) {
- memcpy(d, s, len + 1);
+ memcpy(d, s, len + SKIP_ONE);
}
return d;
}
@@ -85,17 +116,17 @@ static char *yy_doc_to_str(yyjson_mut_doc *doc) {
int cbm_jsonrpc_parse(const char *line, cbm_jsonrpc_request_t *out) {
memset(out, 0, sizeof(*out));
- out->id = -1;
+ out->id = CBM_NOT_FOUND;
yyjson_doc *doc = yyjson_read(line, strlen(line), 0);
if (!doc) {
- return -1;
+ return CBM_NOT_FOUND;
}
yyjson_val *root = yyjson_doc_get_root(doc);
if (!yyjson_is_obj(root)) {
yyjson_doc_free(doc);
- return -1;
+ return CBM_NOT_FOUND;
}
yyjson_val *v_jsonrpc = yyjson_obj_get(root, "jsonrpc");
@@ -105,7 +136,7 @@ int cbm_jsonrpc_parse(const char *line, cbm_jsonrpc_request_t *out) {
if (!v_method || !yyjson_is_str(v_method)) {
yyjson_doc_free(doc);
- return -1;
+ return CBM_NOT_FOUND;
}
out->jsonrpc =
@@ -117,7 +148,7 @@ int cbm_jsonrpc_parse(const char *line, cbm_jsonrpc_request_t *out) {
if (yyjson_is_int(v_id)) {
out->id = yyjson_get_int(v_id);
} else if (yyjson_is_str(v_id)) {
- out->id = strtol(yyjson_get_str(v_id), NULL, 10);
+ out->id = strtol(yyjson_get_str(v_id), NULL, CBM_DECIMAL_BASE);
}
}
@@ -501,27 +532,27 @@ bool cbm_mcp_get_bool_arg(const char *args_json, const char *key) {
* ══════════════════════════════════════════════════════════════════ */
struct cbm_mcp_server {
- cbm_store_t *store; /* currently open project store (or NULL) */
- bool owns_store; /* true if we opened the store */
- char *current_project; /* which project store is open for (heap) */
- time_t store_last_used; /* last time resolve_store was called for a named project */
- char update_notice[256]; /* one-shot update notice, cleared after first injection */
- bool update_checked; /* true after background check has been launched */
- cbm_thread_t update_tid; /* background update check thread */
- bool update_thread_active; /* true if update thread was started and needs joining */
+ cbm_store_t *store; /* currently open project store (or NULL) */
+ bool owns_store; /* true if we opened the store */
+ char *current_project; /* which project store is open for (heap) */
+ time_t store_last_used; /* last time resolve_store was called for a named project */
+ char update_notice[CBM_SZ_256]; /* one-shot update notice, cleared after first injection */
+ bool update_checked; /* true after background check has been launched */
+ cbm_thread_t update_tid; /* background update check thread */
+ bool update_thread_active; /* true if update thread was started and needs joining */
/* Session + auto-index state */
- char session_root[1024]; /* detected project root path */
- char session_project[256]; /* derived project name */
- bool session_detected; /* true after first detection attempt */
- struct cbm_watcher *watcher; /* external watcher ref (not owned) */
- struct cbm_config *config; /* external config ref (not owned) */
+ char session_root[CBM_SZ_1K]; /* detected project root path */
+ char session_project[CBM_SZ_256]; /* derived project name */
+ bool session_detected; /* true after first detection attempt */
+ struct cbm_watcher *watcher; /* external watcher ref (not owned) */
+ struct cbm_config *config; /* external config ref (not owned) */
cbm_thread_t autoindex_tid;
bool autoindex_active; /* true if auto-index thread was started */
};
cbm_mcp_server_t *cbm_mcp_server_new(const char *store_path) {
- cbm_mcp_server_t *srv = calloc(1, sizeof(*srv));
+ cbm_mcp_server_t *srv = calloc(CBM_ALLOC_ONE, sizeof(*srv));
if (!srv) {
return NULL;
}
@@ -625,7 +656,7 @@ static const char *cache_dir(char *buf, size_t bufsz) {
/* Returns full .db path for a project: <cache_dir>/<project>.db */
static const char *project_db_path(const char *project, char *buf, size_t bufsz) {
- char dir[1024];
+ char dir[CBM_SZ_1K];
cache_dir(dir, sizeof(dir));
snprintf(buf, bufsz, "%s/%s.db", dir, project);
return buf;
@@ -656,7 +687,7 @@ static cbm_store_t *resolve_store(cbm_mcp_server_t *srv, const char *project) {
/* Open project's .db file — query-only open (no SQLITE_OPEN_CREATE) to
* prevent ghost .db file creation for unknown/unindexed projects. */
- char path[1024];
+ char path[CBM_SZ_1K];
project_db_path(project, path, sizeof(path));
srv->store = cbm_store_open_path_query(path);
if (srv->store) {
@@ -668,8 +699,8 @@ static cbm_store_t *resolve_store(cbm_mcp_server_t *srv, const char *project) {
srv->store = NULL;
/* Delete the corrupt DB + WAL/SHM files */
cbm_unlink(path);
- char wal_path[1040];
- char shm_path[1040];
+ char wal_path[MCP_FIELD_SIZE];
+ char shm_path[MCP_FIELD_SIZE];
snprintf(wal_path, sizeof(wal_path), "%s-wal", path);
snprintf(shm_path, sizeof(shm_path), "%s-shm", path);
cbm_unlink(wal_path);
@@ -709,13 +740,13 @@ static int collect_db_project_names(const char *dir_path, char *out, size_t out_
while ((entry = cbm_readdir(d)) != NULL) {
const char *n = entry->name;
size_t len = strlen(n);
- if (len < 4 || strcmp(n + len - 3, ".db") != 0) {
+ if (len < MCP_MIN_DB_NAME || strcmp(n + len - MCP_DB_EXT, ".db") != 0) {
continue;
}
- if (strncmp(n, "tmp-", 4) == 0 || strncmp(n, "_", 1) == 0) {
+ if (strncmp(n, "tmp-", SLEN("tmp-")) == 0 || strncmp(n, "_", SLEN("_")) == 0) {
continue;
}
- if (count > 0 && offset < (int)out_sz - 2) {
+ if (count > 0 && offset < (int)out_sz - MCP_SEPARATOR) {
out[offset++] = ',';
}
int wrote = snprintf(out + offset, out_sz - (size_t)offset, "\"%.*s\"", (int)(len - 3), n);
@@ -730,10 +761,10 @@ static int collect_db_project_names(const char *dir_path, char *out, size_t out_
/* Build a helpful error listing available projects. Caller must free() result. */
static char *build_project_list_error(const char *reason) {
- char dir_path[1024];
+ char dir_path[CBM_SZ_1K];
cache_dir(dir_path, sizeof(dir_path));
- char projects[4096] = "";
+ char projects[CBM_SZ_4K] = "";
int count = collect_db_project_names(dir_path, projects, sizeof(projects));
enum { ERR_BUF_SZ = 5120 };
@@ -768,11 +799,11 @@ static char *build_project_list_error(const char *reason) {
/* Return true if filename is a valid project .db file (not temp/internal). */
static bool is_project_db_file(const char *name, size_t len) {
- if (len < 4 || strcmp(name + len - 3, ".db") != 0) {
+ if (len < MCP_MIN_DB_NAME || strcmp(name + len - MCP_DB_EXT, ".db") != 0) {
return false;
}
- if (strncmp(name, "tmp-", 4) == 0 || strncmp(name, "_", 1) == 0 ||
- strncmp(name, ":memory:", 8) == 0) {
+ if (strncmp(name, "tmp-", SLEN("tmp-")) == 0 || strncmp(name, "_", SLEN("_")) == 0 ||
+ strncmp(name, ":memory:", SLEN(":memory:")) == 0) {
return false;
}
return true;
@@ -782,16 +813,16 @@ static bool is_project_db_file(const char *name, size_t len) {
* then append a JSON entry to arr. */
static void build_project_json_entry(yyjson_mut_doc *doc, yyjson_mut_val *arr, const char *dir_path,
const char *name, size_t name_len, const struct stat *st) {
- char project_name[1024];
+ char project_name[CBM_SZ_1K];
snprintf(project_name, sizeof(project_name), "%.*s", (int)(name_len - 3), name);
- char full_path[2048];
+ char full_path[CBM_SZ_2K];
snprintf(full_path, sizeof(full_path), "%s/%s", dir_path, name);
cbm_store_t *pstore = cbm_store_open_path(full_path);
int nodes = 0;
int edges = 0;
- char root_path_buf[1024] = "";
+ char root_path_buf[CBM_SZ_1K] = "";
if (pstore) {
nodes = cbm_store_count_nodes(pstore, project_name);
edges = cbm_store_count_edges(pstore, project_name);
@@ -822,7 +853,7 @@ static char *handle_list_projects(cbm_mcp_server_t *srv, const char *args) {
(void)srv;
(void)args;
- char dir_path[1024];
+ char dir_path[CBM_SZ_1K];
cache_dir(dir_path, sizeof(dir_path));
cbm_dir_t *d = cbm_opendir(dir_path);
@@ -840,7 +871,7 @@ static char *handle_list_projects(cbm_mcp_server_t *srv, const char *args) {
if (!is_project_db_file(name, len)) {
continue;
}
- char full_path[2048];
+ char full_path[CBM_SZ_2K];
snprintf(full_path, sizeof(full_path), "%s/%s", dir_path, name);
struct stat st;
if (stat(full_path, &st) != 0) {
@@ -918,7 +949,7 @@ static char *handle_get_graph_schema(cbm_mcp_server_t *srv, const char *args) {
/* Check ADR presence */
cbm_project_t proj_info = {0};
if (cbm_store_get_project(store, project, &proj_info) == 0 && proj_info.root_path) {
- char adr_path[4096];
+ char adr_path[CBM_SZ_4K];
snprintf(adr_path, sizeof(adr_path), "%s/.codebase-memory/adr.md", proj_info.root_path);
struct stat adr_st;
bool adr_exists = (stat(adr_path, &adr_st) == 0);
@@ -956,10 +987,10 @@ static char *handle_search_graph(cbm_mcp_server_t *srv, const char *args) {
char *label = cbm_mcp_get_string_arg(args, "label");
char *name_pattern = cbm_mcp_get_string_arg(args, "name_pattern");
char *file_pattern = cbm_mcp_get_string_arg(args, "file_pattern");
- int limit = cbm_mcp_get_int_arg(args, "limit", 500000);
+ int limit = cbm_mcp_get_int_arg(args, "limit", MCP_HALF_SEC_US);
int offset = cbm_mcp_get_int_arg(args, "offset", 0);
- int min_degree = cbm_mcp_get_int_arg(args, "min_degree", -1);
- int max_degree = cbm_mcp_get_int_arg(args, "max_degree", -1);
+ int min_degree = cbm_mcp_get_int_arg(args, "min_degree", CBM_NOT_FOUND);
+ int max_degree = cbm_mcp_get_int_arg(args, "max_degree", CBM_NOT_FOUND);
cbm_search_params_t params = {
.project = project,
@@ -1134,11 +1165,11 @@ static char *handle_delete_project(cbm_mcp_server_t *srv, const char *args) {
cbm_pipeline_lock();
/* Delete the .db file + WAL/SHM */
- char path[1024];
+ char path[CBM_SZ_1K];
project_db_path(name, path, sizeof(path));
- char wal[1024];
- char shm[1024];
+ char wal[CBM_SZ_1K];
+ char shm[CBM_SZ_1K];
snprintf(wal, sizeof(wal), "%s-wal", path);
snprintf(shm, sizeof(shm), "%s-shm", path);
@@ -1253,7 +1284,7 @@ static yyjson_doc *resolve_trace_edge_types(const char *args, const char *mode,
size_t max2;
yyjson_val *val2;
yyjson_arr_foreach(et_arr, idx2, max2, val2) {
- if (yyjson_is_str(val2) && *out_count < 16) {
+ if (yyjson_is_str(val2) && *out_count < MCP_COL_16) {
out_types[(*out_count)++] = yyjson_get_str(val2);
}
}
@@ -1267,13 +1298,13 @@ static yyjson_doc *resolve_trace_edge_types(const char *args, const char *mode,
yyjson_doc_free(et_doc); /* no explicit types found, free */
const char **defaults = mode_calls;
- int n_defaults = 1;
+ int n_defaults = SKIP_ONE;
if (mode && strcmp(mode, "data_flow") == 0) {
defaults = mode_data_flow;
- n_defaults = 2;
+ n_defaults = MCP_N_DEFAULTS_2;
} else if (mode && strcmp(mode, "cross_service") == 0) {
defaults = mode_cross_svc;
- n_defaults = 4;
+ n_defaults = MCP_N_DEFAULTS_4;
}
for (int i = 0; i < n_defaults; i++) {
out_types[i] = defaults[i];
@@ -1305,7 +1336,7 @@ static char *handle_trace_call_path(cbm_mcp_server_t *srv, const char *args) {
char *direction = cbm_mcp_get_string_arg(args, "direction");
char *mode = cbm_mcp_get_string_arg(args, "mode");
char *param_name = cbm_mcp_get_string_arg(args, "parameter_name");
- int depth = cbm_mcp_get_int_arg(args, "depth", 3);
+ int depth = cbm_mcp_get_int_arg(args, "depth", MCP_DEFAULT_DEPTH);
if (!func_name) {
free(project);
@@ -1366,7 +1397,7 @@ static char *handle_trace_call_path(cbm_mcp_server_t *srv, const char *args) {
}
/* Edge types: explicit > mode-based > default */
- const char *edge_types[16];
+ const char *edge_types[MCP_COL_16];
int edge_type_count = 0;
yyjson_doc *et_doc_keep = resolve_trace_edge_types(args, mode, edge_types, &edge_type_count);
@@ -1380,14 +1411,14 @@ static char *handle_trace_call_path(cbm_mcp_server_t *srv, const char *args) {
cbm_traverse_result_t tr_in = {0};
if (do_outbound) {
- cbm_store_bfs(store, nodes[0].id, "outbound", edge_types, edge_type_count, depth, 100,
- &tr_out);
+ cbm_store_bfs(store, nodes[0].id, "outbound", edge_types, edge_type_count, depth,
+ MCP_BFS_LIMIT, &tr_out);
yyjson_mut_obj_add_val(doc, root, "callees", bfs_to_json_array(doc, &tr_out));
}
if (do_inbound) {
- cbm_store_bfs(store, nodes[0].id, "inbound", edge_types, edge_type_count, depth, 100,
- &tr_in);
+ cbm_store_bfs(store, nodes[0].id, "inbound", edge_types, edge_type_count, depth,
+ MCP_BFS_LIMIT, &tr_in);
yyjson_mut_obj_add_val(doc, root, "callers", bfs_to_json_array(doc, &tr_in));
}
@@ -1438,12 +1469,12 @@ static char *read_file_lines(const char *path, int start, int end) {
return NULL;
}
- size_t cap = 4096;
+ size_t cap = CBM_SZ_4K;
char *buf = malloc(cap);
size_t len = 0;
buf[0] = '\0';
- char line[2048];
+ char line[CBM_SZ_2K];
int lineno = 0;
while (fgets(line, sizeof(line), fp)) {
lineno++;
@@ -1454,8 +1485,8 @@ static char *read_file_lines(const char *path, int start, int end) {
break;
}
size_t ll = strlen(line);
- while (len + ll + 1 > cap) {
- cap *= 2;
+ while (len + ll + SKIP_ONE > cap) {
+ cap *= PAIR_LEN;
buf = safe_realloc(buf, cap);
}
memcpy(buf + len, line, ll);
@@ -1558,7 +1589,7 @@ static char *handle_index_repository(cbm_mcp_server_t *srv, const char *args) {
yyjson_mut_obj_add_int(doc, root, "edges", edges);
/* Check ADR presence and suggest creation if missing */
- char adr_path[4096];
+ char adr_path[CBM_SZ_4K];
snprintf(adr_path, sizeof(adr_path), "%s/.codebase-memory/adr.md", repo_path);
struct stat adr_st;
bool adr_exists = (stat(adr_path, &adr_st) == 0);
@@ -1606,7 +1637,7 @@ static char *snippet_suggestions(const char *input, cbm_node_t *nodes, int count
yyjson_mut_obj_add_str(doc, root, "status", "ambiguous");
- char msg[512];
+ char msg[CBM_SZ_512];
snprintf(msg, sizeof(msg),
"%d matches for \"%s\". Pick a qualified_name from suggestions below, "
"or use search_graph(name_pattern=\"...\") to narrow results.",
@@ -1680,12 +1711,12 @@ static char *resolve_snippet_source(const char *root_path, const char *file_path
if (!root_path || !file_path) {
return NULL;
}
- size_t apsz = strlen(root_path) + strlen(file_path) + 2;
+ size_t apsz = strlen(root_path) + strlen(file_path) + MCP_SEPARATOR;
char *abs_path = malloc(apsz);
snprintf(abs_path, apsz, "%s/%s", root_path, file_path);
- char real_root[4096];
- char real_file[4096];
+ char real_root[CBM_SZ_4K];
+ char real_file[CBM_SZ_4K];
bool path_ok = false;
#ifdef _WIN32
if (_fullpath(real_root, root_path, sizeof(real_root)) &&
@@ -1727,7 +1758,7 @@ static char *build_snippet_response(cbm_mcp_server_t *srv, cbm_node_t *node,
cbm_node_t *alternatives, int alt_count) {
char *root_path = get_project_root(srv, node->project);
- int start = node->start_line > 0 ? node->start_line : 1;
+ int start = node->start_line > 0 ? node->start_line : SKIP_ONE;
int end = node->end_line > start ? node->end_line : start + SNIPPET_DEFAULT_LINES;
char *abs_path = NULL;
char *source = resolve_snippet_source(root_path, node->file_path, start, end, &abs_path);
@@ -1778,8 +1809,8 @@ static char *build_snippet_response(cbm_mcp_server_t *srv, cbm_node_t *node,
char **nb_callees = NULL;
int nb_callee_count = 0;
if (include_neighbors) {
- cbm_store_node_neighbor_names(store, node->id, 10, &nb_callers, &nb_caller_count,
- &nb_callees, &nb_callee_count);
+ cbm_store_node_neighbor_names(store, node->id, MCP_DEFAULT_LIMIT, &nb_callers,
+ &nb_caller_count, &nb_callees, &nb_callee_count);
add_string_array(doc, root_obj, "caller_names", nb_callers, nb_caller_count);
add_string_array(doc, root_obj, "callee_names", nb_callees, nb_callee_count);
}
@@ -1866,7 +1897,7 @@ static char *handle_get_code_snippet(cbm_mcp_server_t *srv, const char *args) {
int suffix_count = 0;
cbm_store_find_nodes_by_qn_suffix(store, effective_project, qn, &suffix_nodes, &suffix_count);
- if (suffix_count == 1) {
+ if (suffix_count == SKIP_ONE) {
copy_node(&suffix_nodes[0], &node);
cbm_store_free_nodes(suffix_nodes, suffix_count);
char *result = build_snippet_response(srv, &node, "suffix", include_neighbors, NULL, 0);
@@ -1876,7 +1907,7 @@ static char *handle_get_code_snippet(cbm_mcp_server_t *srv, const char *args) {
return result;
}
- if (suffix_count > 1) {
+ if (suffix_count > SKIP_ONE) {
char *result = snippet_suggestions(qn, suffix_nodes, suffix_count);
cbm_store_free_nodes(suffix_nodes, suffix_count);
free(qn);
@@ -1909,24 +1940,24 @@ static void sanitize_ascii(char *s) {
/* Intermediate grep match */
typedef struct {
- char file[512];
+ char file[CBM_SZ_512];
int line;
- char content[1024];
+ char content[CBM_SZ_1K];
} grep_match_t;
/* Deduped result: one per containing graph node */
typedef struct {
int64_t node_id; /* 0 = raw match (no containing node) */
- char node_name[256];
- char qualified_name[512];
- char label[64];
- char file[512];
+ char node_name[CBM_SZ_256];
+ char qualified_name[CBM_SZ_512];
+ char label[CBM_SZ_64];
+ char file[CBM_SZ_512];
int start_line;
int end_line;
int in_degree;
int out_degree;
int score;
- int match_lines[64];
+ int match_lines[CBM_SZ_64];
int match_count;
} search_result_t;
@@ -1986,7 +2017,7 @@ static void build_grep_cmd(char *cmd, size_t cmd_sz, bool use_regex, bool scoped
static yyjson_mut_val *build_dedup_files_array(yyjson_mut_doc *doc, search_result_t *sr,
int output_count, grep_match_t *raw, int raw_count) {
yyjson_mut_val *files_arr = yyjson_mut_arr(doc);
- char *seen_files[512];
+ char *seen_files[CBM_SZ_512];
int seen_count = 0;
for (int fi = 0; fi < output_count; fi++) {
bool dup = false;
@@ -1996,12 +2027,12 @@ static yyjson_mut_val *build_dedup_files_array(yyjson_mut_doc *doc, search_resul
break;
}
}
- if (!dup && seen_count < 512) {
+ if (!dup && seen_count < CBM_SZ_512) {
seen_files[seen_count++] = sr[fi].file;
yyjson_mut_arr_add_str(doc, files_arr, sr[fi].file);
}
}
- for (int fi = 0; fi < raw_count && seen_count < 512; fi++) {
+ for (int fi = 0; fi < raw_count && seen_count < CBM_SZ_512; fi++) {
bool dup = false;
for (int j = 0; j < seen_count; j++) {
if (strcmp(seen_files[j], raw[fi].file) == 0) {
@@ -2024,7 +2055,7 @@ static void attach_result_source(yyjson_mut_doc *doc, yyjson_mut_val *item, sear
if (r->start_line <= 0 || r->end_line <= 0) {
return;
}
- char abs_path[1024];
+ char abs_path[CBM_SZ_1K];
snprintf(abs_path, sizeof(abs_path), "%s/%s", root_path, r->file);
if (mode == MODE_FULL) {
@@ -2036,9 +2067,9 @@ static void attach_result_source(yyjson_mut_doc *doc, yyjson_mut_val *item, sear
}
} else if (context_lines > 0 && r->match_count > 0) {
int ctx_start = r->match_lines[0] - context_lines;
- int ctx_end = r->match_lines[r->match_count - 1] + context_lines;
- if (ctx_start < 1) {
- ctx_start = 1;
+ int ctx_end = r->match_lines[r->match_count - SKIP_ONE] + context_lines;
+ if (ctx_start < SKIP_ONE) {
+ ctx_start = SKIP_ONE;
}
char *ctx = read_file_lines(abs_path, ctx_start, ctx_end);
if (ctx) {
@@ -2054,23 +2085,23 @@ static void attach_result_source(yyjson_mut_doc *doc, yyjson_mut_val *item, sear
static yyjson_mut_val *build_dir_distribution(yyjson_mut_doc *doc, search_result_t *sr,
int sr_count) {
yyjson_mut_val *dirs = yyjson_mut_obj(doc);
- char dir_names[64][128];
- int dir_counts[64];
+ char dir_names[CBM_SZ_64][CBM_SZ_128];
+ int dir_counts[CBM_SZ_64];
int dir_n = 0;
for (int di = 0; di < sr_count; di++) {
- char top[128] = "";
+ char top[CBM_SZ_128] = "";
const char *slash = strchr(sr[di].file, '/');
if (slash) {
- size_t dlen = (size_t)(slash - sr[di].file + 1);
+ size_t dlen = (size_t)(slash - sr[di].file + SKIP_ONE);
if (dlen >= sizeof(top)) {
- dlen = sizeof(top) - 1;
+ dlen = sizeof(top) - SKIP_ONE;
}
memcpy(top, sr[di].file, dlen);
top[dlen] = '\0';
} else {
snprintf(top, sizeof(top), "%s", sr[di].file);
}
- int found = -1;
+ int found = CBM_NOT_FOUND;
for (int d = 0; d < dir_n; d++) {
if (strcmp(dir_names[d], top) == 0) {
found = d;
@@ -2079,9 +2110,9 @@ static yyjson_mut_val *build_dir_distribution(yyjson_mut_doc *doc, search_result
}
if (found >= 0) {
dir_counts[found]++;
- } else if (dir_n < 64) {
+ } else if (dir_n < CBM_SZ_64) {
snprintf(dir_names[dir_n], sizeof(dir_names[0]), "%s", top);
- dir_counts[dir_n] = 1;
+ dir_counts[dir_n] = SKIP_ONE;
dir_n++;
}
}
@@ -2153,7 +2184,7 @@ static char *assemble_search_output(search_result_t *sr, int sr_count, grep_matc
yyjson_mut_obj_add_int(doc, root_obj, "total_results", sr_count);
yyjson_mut_obj_add_int(doc, root_obj, "raw_match_count", raw_count);
if (sr_count > 0 && gm_count > 0) {
- char ratio[32];
+ char ratio[CBM_SZ_32];
snprintf(ratio, sizeof(ratio), "%.1fx", (double)gm_count / (double)(sr_count + raw_count));
yyjson_mut_obj_add_strcpy(doc, root_obj, "dedup_ratio", ratio);
}
@@ -2186,14 +2217,14 @@ static const char *strip_root_prefix(const char *path, const char *root, size_t
static grep_match_t *collect_grep_matches(FILE *fp, const char *root_path, size_t root_len,
bool has_path_filter, cbm_regex_t *path_regex,
int grep_limit, int *out_count) {
- int gm_cap = 64;
+ int gm_cap = CBM_SZ_64;
int gm_count = 0;
grep_match_t *gm = malloc(gm_cap * sizeof(grep_match_t));
- char line[2048];
+ char line[CBM_SZ_2K];
while (fgets(line, sizeof(line), fp) && gm_count < grep_limit) {
size_t len = strlen(line);
- while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r')) {
+ while (len > 0 && (line[len - SKIP_ONE] == '\n' || line[len - SKIP_ONE] == '\r')) {
line[--len] = '\0';
}
if (len == 0) {
@@ -2204,7 +2235,7 @@ static grep_match_t *collect_grep_matches(FILE *fp, const char *root_path, size_
if (!colon1) {
continue;
}
- char *colon2 = strchr(colon1 + 1, ':');
+ char *colon2 = strchr(colon1 + SKIP_ONE, ':');
if (!colon2) {
continue;
}
@@ -2221,12 +2252,12 @@ static grep_match_t *collect_grep_matches(FILE *fp, const char *root_path, size_
}
if (gm_count >= gm_cap) {
- gm_cap *= 2;
+ gm_cap *= PAIR_LEN;
gm = safe_realloc(gm, gm_cap * sizeof(grep_match_t));
}
snprintf(gm[gm_count].file, sizeof(gm[0].file), "%s", file);
- gm[gm_count].line = (int)strtol(colon1 + 1, NULL, 10);
- snprintf(gm[gm_count].content, sizeof(gm[0].content), "%s", colon2 + 1);
+ gm[gm_count].line = (int)strtol(colon1 + SKIP_ONE, NULL, CBM_DECIMAL_BASE);
+ snprintf(gm[gm_count].content, sizeof(gm[0].content), "%s", colon2 + SKIP_ONE);
sanitize_ascii(gm[gm_count].content);
gm_count++;
}
@@ -2237,7 +2268,7 @@ static grep_match_t *collect_grep_matches(FILE *fp, const char *root_path, size_
/* Find the tightest node containing a line in a file. Returns index or -1. */
static int find_tightest_node(cbm_node_t *nodes, int count, int line) {
- int best = -1;
+ int best = CBM_NOT_FOUND;
int best_span = MAX_LINE_SPAN;
for (int j = 0; j < count; j++) {
if (nodes[j].start_line <= line && nodes[j].end_line >= line) {
@@ -2256,14 +2287,14 @@ static void add_to_search_results(search_result_t **sr, int *sr_count, int *sr_c
int line) {
for (int j = 0; j < *sr_count; j++) {
if ((*sr)[j].node_id == n->id) {
- if ((*sr)[j].match_count < 64) {
+ if ((*sr)[j].match_count < CBM_SZ_64) {
(*sr)[j].match_lines[(*sr)[j].match_count++] = line;
}
return;
}
}
if (*sr_count >= *sr_cap) {
- *sr_cap *= 2;
+ *sr_cap *= PAIR_LEN;
*sr = safe_realloc(*sr, *sr_cap * sizeof(search_result_t));
memset(&(*sr)[*sr_count], 0, (*sr_cap - *sr_count) * sizeof(search_result_t));
}
@@ -2277,7 +2308,7 @@ static void add_to_search_results(search_result_t **sr, int *sr_count, int *sr_c
r->start_line = n->start_line;
r->end_line = n->end_line;
r->match_lines[0] = line;
- r->match_count = 1;
+ r->match_count = SKIP_ONE;
(*sr_count)++;
}
@@ -2290,7 +2321,7 @@ static void classify_grep_hit(grep_match_t *hit, cbm_node_t *file_nodes, int fil
add_to_search_results(sr, sr_count, sr_cap, &file_nodes[best], hit->line);
} else {
if (*raw_count >= *raw_cap) {
- *raw_cap = (*raw_cap == 0) ? 32 : *raw_cap * 2;
+ *raw_cap = (*raw_cap == 0) ? CBM_SZ_32 : *raw_cap * PAIR_LEN;
*raw = safe_realloc(*raw, *raw_cap * sizeof(grep_match_t));
}
if (*raw) {
@@ -2354,9 +2385,9 @@ static bool write_scoped_filelist(cbm_mcp_server_t *srv, const char *project, co
bool ok = false;
if (fl) {
for (int fi = 0; fi < indexed_count; fi++) {
- fprintf(fl, "%s/%s\n", root_path, indexed_files[fi]);
+ (void)fprintf(fl, "%s/%s\n", root_path, indexed_files[fi]);
}
- fclose(fl);
+ (void)fclose(fl);
ok = true;
}
for (int fi = 0; fi < indexed_count; fi++) {
@@ -2372,10 +2403,10 @@ static int parse_search_mode(const char *mode_str) {
return 0;
}
if (strcmp(mode_str, "full") == 0) {
- return 1;
+ return SKIP_ONE;
}
if (strcmp(mode_str, "files") == 0) {
- return 2;
+ return MCP_RETURN_2;
}
return 0;
}
@@ -2402,8 +2433,8 @@ static bool write_pattern_file(char *tmpfile, int tmpfile_sz, const char *patter
if (!tf) {
return false;
}
- fprintf(tf, "%s\n", pattern);
- fclose(tf);
+ (void)fprintf(tf, "%s\n", pattern);
+ (void)fclose(tf);
return true;
}
@@ -2421,7 +2452,7 @@ static char *handle_search_code(cbm_mcp_server_t *srv, const char *args) {
char *file_pattern = cbm_mcp_get_string_arg(args, "file_pattern");
char *path_filter = cbm_mcp_get_string_arg(args, "path_filter");
char *mode_str = cbm_mcp_get_string_arg(args, "mode");
- int limit = cbm_mcp_get_int_arg(args, "limit", 10);
+ int limit = cbm_mcp_get_int_arg(args, "limit", MCP_DEFAULT_LIMIT);
int context_lines = cbm_mcp_get_int_arg(args, "context", 0);
bool use_regex = cbm_mcp_get_bool_arg(args, "regex");
@@ -2469,7 +2500,7 @@ static char *handle_search_code(cbm_mcp_server_t *srv, const char *args) {
}
/* ── Phase 1: Grep scan ──────────────────────────────────── */
- char tmpfile[256];
+ char tmpfile[CBM_SZ_256];
if (!write_pattern_file(tmpfile, sizeof(tmpfile), pattern)) {
free(root_path);
free(pattern);
@@ -2488,13 +2519,13 @@ static char *handle_search_code(cbm_mcp_server_t *srv, const char *args) {
* Query the graph for distinct file paths, write them to a temp file,
* then use xargs to pass them to grep. Falls back to recursive grep if
* no indexed files found (project not fully indexed). */
- char filelist[256];
+ char filelist[CBM_SZ_256];
snprintf(filelist, sizeof(filelist), "%s.files", tmpfile);
bool scoped = false;
scoped = write_scoped_filelist(srv, project, root_path, filelist);
- char cmd[4096];
+ char cmd[CBM_SZ_4K];
build_grep_cmd(cmd, sizeof(cmd), use_regex, scoped, file_pattern, tmpfile, filelist, root_path);
FILE *fp = cbm_popen(cmd, "r");
@@ -2526,11 +2557,11 @@ static char *handle_search_code(cbm_mcp_server_t *srv, const char *args) {
cbm_store_t *store = resolve_store(srv, project);
- int sr_cap = 32;
+ int sr_cap = CBM_SZ_32;
int sr_count = 0;
search_result_t *sr = calloc(sr_cap, sizeof(search_result_t));
- int raw_cap = 32;
+ int raw_cap = CBM_SZ_32;
int raw_count = 0;
grep_match_t *raw = malloc(raw_cap * sizeof(grep_match_t));
@@ -2564,7 +2595,7 @@ static char *handle_search_code(cbm_mcp_server_t *srv, const char *args) {
for (int j = 0; j < sr_count; j++) {
sr[j].score = compute_search_score(&sr[j]);
}
- if (sr_count > 1) {
+ if (sr_count > SKIP_ONE) {
qsort(sr, sr_count, sizeof(search_result_t), search_result_cmp);
}
@@ -2590,7 +2621,7 @@ static char *handle_search_code(cbm_mcp_server_t *srv, const char *args) {
static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {
char *project = cbm_mcp_get_string_arg(args, "project");
char *base_branch = cbm_mcp_get_string_arg(args, "base_branch");
- int depth = cbm_mcp_get_int_arg(args, "depth", 2);
+ int depth = cbm_mcp_get_int_arg(args, "depth", MCP_DEFAULT_BFS_DEPTH);
if (!base_branch) {
base_branch = heap_strdup("main");
@@ -2618,7 +2649,7 @@ static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {
}
/* Get changed files via git (-C avoids cd + quoting issues on Windows) */
- char cmd[2048];
+ char cmd[CBM_SZ_2K];
#ifdef _WIN32
snprintf(cmd, sizeof(cmd),
"git -C \"%s\" diff --name-only \"%s\"...HEAD 2>NUL & "
@@ -2649,12 +2680,12 @@ static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {
/* resolve_store already called via get_project_root above */
cbm_store_t *store = srv->store;
- char line[1024];
+ char line[CBM_SZ_1K];
int file_count = 0;
while (fgets(line, sizeof(line), fp)) {
size_t len = strlen(line);
- while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r')) {
+ while (len > 0 && (line[len - SKIP_ONE] == '\n' || line[len - SKIP_ONE] == '\r')) {
line[--len] = '\0';
}
if (len == 0) {
@@ -2706,11 +2737,11 @@ static void adr_list_sections(yyjson_mut_doc *doc, yyjson_mut_val *root_obj, con
yyjson_mut_val *sections = yyjson_mut_arr(doc);
FILE *fp = fopen(adr_path, "r");
if (fp) {
- char line[1024];
+ char line[CBM_SZ_1K];
while (fgets(line, sizeof(line), fp)) {
if (line[0] == '#') {
size_t len = strlen(line);
- while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r')) {
+ while (len > 0 && (line[len - SKIP_ONE] == '\n' || line[len - SKIP_ONE] == '\r')) {
line[--len] = '\0';
}
yyjson_mut_arr_add_strcpy(doc, sections, line);
@@ -2732,8 +2763,11 @@ static char *adr_read_content(yyjson_mut_doc *doc, yyjson_mut_val *root_obj, con
sz = 0;
}
(void)fseek(fp, 0, SEEK_SET);
- char *buf = malloc((size_t)sz + 1);
- size_t n = (sz > 0) ? fread(buf, 1, (size_t)sz, fp) : 0;
+ char *buf = malloc((size_t)sz + SKIP_ONE);
+ size_t n = (sz > 0) ? fread(buf, SKIP_ONE, (size_t)sz, fp) : 0;
+ if (n > (size_t)sz) {
+ n = (size_t)sz;
+ }
buf[n] = '\0';
(void)fclose(fp);
yyjson_mut_obj_add_str(doc, root_obj, "content", buf);
@@ -2769,9 +2803,9 @@ static char *handle_manage_adr(cbm_mcp_server_t *srv, const char *args) {
return cbm_mcp_text_result("project not found", true);
}
- char adr_dir[4096];
+ char adr_dir[CBM_SZ_4K];
snprintf(adr_dir, sizeof(adr_dir), "%s/.codebase-memory", root_path);
- char adr_path[4096];
+ char adr_path[CBM_SZ_4K];
snprintf(adr_path, sizeof(adr_path), "%s/adr.md", adr_dir);
char *adr_buf = NULL;
@@ -2893,7 +2927,7 @@ char *cbm_mcp_handle_tool(cbm_mcp_server_t *srv, const char *tool_name, const ch
if (strcmp(tool_name, "ingest_traces") == 0) {
return handle_ingest_traces(srv, args_json);
}
- char msg[256];
+ char msg[CBM_SZ_256];
snprintf(msg, sizeof(msg), "unknown tool: %s", tool_name);
return cbm_mcp_text_result(msg, true);
}
@@ -2908,7 +2942,7 @@ static void detect_session(cbm_mcp_server_t *srv) {
srv->session_detected = true;
/* 1. Try CWD */
- char cwd[1024];
+ char cwd[CBM_SZ_1K];
if (getcwd(cwd, sizeof(cwd)) != NULL) {
const char *home = cbm_get_home_dir();
/* Skip useless roots: / and $HOME */
@@ -2971,7 +3005,7 @@ static void maybe_auto_index(cbm_mcp_server_t *srv) {
/* Check if project already has a DB */
const char *home = cbm_get_home_dir();
if (home) {
- char db_check[1024];
+ char db_check[CBM_SZ_1K];
snprintf(db_check, sizeof(db_check), "%s/.cache/codebase-memory-mcp/%s.db", home,
srv->session_project);
struct stat st;
@@ -3009,13 +3043,13 @@ static void maybe_auto_index(cbm_mcp_server_t *srv) {
cbm_log_warn("autoindex.skip", "reason", "path contains shell metacharacters");
return;
}
- char cmd[1024];
+ char cmd[CBM_SZ_1K];
snprintf(cmd, sizeof(cmd), "git -C '%s' ls-files 2>/dev/null | wc -l", srv->session_root);
FILE *fp = cbm_popen(cmd, "r");
if (fp) {
- char line[64];
+ char line[CBM_SZ_64];
if (fgets(line, sizeof(line), fp)) {
- int count = (int)strtol(line, NULL, 10);
+ int count = (int)strtol(line, NULL, CBM_DECIMAL_BASE);
if (count > file_limit) {
cbm_log_warn("autoindex.skip", "reason", "too_many_files", "files", line, "limit",
CBM_CONFIG_AUTO_INDEX_LIMIT);
@@ -3048,10 +3082,10 @@ static void *update_check_thread(void *arg) {
return NULL;
}
- char buf[4096];
+ char buf[CBM_SZ_4K];
size_t total = 0;
- while (total < sizeof(buf) - 1) {
- size_t n = fread(buf + total, 1, sizeof(buf) - 1 - total, fp);
+ while (total < sizeof(buf) - SKIP_ONE) {
+ size_t n = fread(buf + total, SKIP_ONE, sizeof(buf) - SKIP_ONE - total, fp);
if (n == 0) {
break;
}
@@ -3172,8 +3206,8 @@ char *cbm_mcp_server_handle(cbm_mcp_server_t *srv, const char *line) {
result_json = cbm_mcp_handle_tool(srv, tool_name, tool_args);
struct timespec t1;
cbm_clock_gettime(CLOCK_MONOTONIC, &t1);
- long long dur_us = ((long long)(t1.tv_sec - t0.tv_sec) * 1000000LL) +
- ((long long)(t1.tv_nsec - t0.tv_nsec) / 1000LL);
+ long long dur_us = ((long long)(t1.tv_sec - t0.tv_sec) * MCP_S_TO_US) +
+ ((long long)(t1.tv_nsec - t0.tv_nsec) / MCP_MS_TO_US);
bool is_err = (result_json != NULL) && (strstr(result_json, "\"isError\":true") != NULL);
cbm_diag_record_query(dur_us, is_err);
@@ -3203,7 +3237,7 @@ static void handle_content_length_frame(cbm_mcp_server_t *srv, FILE *in, FILE *o
/* Skip blank line(s) between header and body */
while (cbm_getline(line, cap, in) > 0) {
size_t hlen = strlen(*line);
- while (hlen > 0 && ((*line)[hlen - 1] == '\n' || (*line)[hlen - 1] == '\r')) {
+ while (hlen > 0 && ((*line)[hlen - SKIP_ONE] == '\n' || (*line)[hlen - SKIP_ONE] == '\r')) {
(*line)[--hlen] = '\0';
}
if (hlen == 0) {
@@ -3211,11 +3245,11 @@ static void handle_content_length_frame(cbm_mcp_server_t *srv, FILE *in, FILE *o
}
}
- char *body = malloc((size_t)content_len + 1);
+ char *body = malloc((size_t)content_len + SKIP_ONE);
if (!body) {
return;
}
- size_t nread = fread(body, 1, (size_t)content_len, in);
+ size_t nread = fread(body, SKIP_ONE, (size_t)content_len, in);
body[nread] = '\0';
char *resp = cbm_mcp_server_handle(srv, body);
@@ -3234,28 +3268,28 @@ static void handle_content_length_frame(cbm_mcp_server_t *srv, FILE *in, FILE *o
* Returns: 1 = data ready, 0 = timeout (evicted idle stores), -1 = error/EOF. */
static int poll_for_input_unix(cbm_mcp_server_t *srv, int fd, FILE *in) {
struct pollfd pfd = {.fd = fd, .events = POLLIN};
- int pr = poll(&pfd, 1, 0); /* Phase 1: non-blocking */
+ int pr = poll(&pfd, SKIP_ONE, 0); /* Phase 1: non-blocking */
if (pr < 0) {
- return -1;
+ return CBM_NOT_FOUND;
}
if (pr > 0) {
- return 1;
+ return SKIP_ONE;
}
/* Phase 2: peek FILE* buffer */
int saved_flags = fcntl(fd, F_GETFL);
if (saved_flags < 0) {
/* fcntl failed — fall through to blocking poll */
- pr = poll(&pfd, 1, STORE_IDLE_TIMEOUT_S * 1000);
+ pr = poll(&pfd, SKIP_ONE, STORE_IDLE_TIMEOUT_S * MCP_TIMEOUT_MS);
if (pr < 0) {
- return -1;
+ return CBM_NOT_FOUND;
}
if (pr == 0) {
cbm_mcp_server_evict_idle(srv, STORE_IDLE_TIMEOUT_S);
return 0;
}
- return 1;
+ return SKIP_ONE;
}
(void)fcntl(fd, F_SETFL, saved_flags | O_NONBLOCK);
@@ -3264,23 +3298,23 @@ static int poll_for_input_unix(cbm_mcp_server_t *srv, int fd, FILE *in) {
if (c == EOF) {
if (feof(in)) {
- return -1; /* true EOF */
+ return CBM_NOT_FOUND; /* true EOF */
}
clearerr(in);
/* Phase 3: blocking poll */
- pr = poll(&pfd, 1, STORE_IDLE_TIMEOUT_S * 1000);
+ pr = poll(&pfd, SKIP_ONE, STORE_IDLE_TIMEOUT_S * MCP_TIMEOUT_MS);
if (pr < 0) {
- return -1;
+ return CBM_NOT_FOUND;
}
if (pr == 0) {
cbm_mcp_server_evict_idle(srv, STORE_IDLE_TIMEOUT_S);
return 0;
}
- return 1;
+ return SKIP_ONE;
}
(void)ungetc(c, in);
- return 1;
+ return SKIP_ONE;
}
#endif
@@ -3313,7 +3347,7 @@ int cbm_mcp_server_run(cbm_mcp_server_t *srv, FILE *in, FILE *out) {
#ifdef _WIN32
/* Windows: WaitForSingleObject on stdin handle */
HANDLE hStdin = (HANDLE)_get_osfhandle(fd);
- DWORD wr = WaitForSingleObject(hStdin, STORE_IDLE_TIMEOUT_S * 1000);
+ DWORD wr = WaitForSingleObject(hStdin, STORE_IDLE_TIMEOUT_S * MCP_TIMEOUT_MS);
if (wr == WAIT_FAILED) {
break;
}
@@ -3337,7 +3371,7 @@ int cbm_mcp_server_run(cbm_mcp_server_t *srv, FILE *in, FILE *out) {
/* Trim trailing newline/CR */
size_t len = strlen(line);
- while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r')) {
+ while (len > 0 && (line[len - SKIP_ONE] == '\n' || line[len - SKIP_ONE] == '\r')) {
line[--len] = '\0';
}
if (len == 0) {
@@ -3345,9 +3379,9 @@ int cbm_mcp_server_run(cbm_mcp_server_t *srv, FILE *in, FILE *out) {
}
/* Content-Length framing (LSP-style transport) */
- if (strncmp(line, "Content-Length:", 15) == 0) {
- int content_len = (int)strtol(line + 15, NULL, 10);
- if (content_len > 0 && content_len <= 10 * 1024 * 1024) {
+ if (strncmp(line, "Content-Length:", SLEN("Content-Length:")) == 0) {
+ int content_len = (int)strtol(line + MCP_CONTENT_PREFIX, NULL, CBM_DECIMAL_BASE);
+ if (content_len > 0 && content_len <= MCP_DEFAULT_LIMIT * CBM_SZ_1K * CBM_SZ_1K) {
handle_content_length_frame(srv, in, out, &line, &cap, content_len);
}
continue;
@@ -3376,17 +3410,18 @@ bool cbm_parse_file_uri(const char *uri, char *out_path, int out_size) {
}
/* Must start with file:// */
- if (strncmp(uri, "file://", 7) != 0) {
+ if (strncmp(uri, "file://", SLEN("file://")) != 0) {
out_path[0] = '\0';
return false;
}
- const char *path = uri + 7;
+ const char *path = uri + MCP_URI_PREFIX;
/* On Windows, file:///C:/path → /C:/path. Strip leading / before drive letter. */
- if (path[0] == '/' && path[1] &&
- ((path[1] >= 'A' && path[1] <= 'Z') || (path[1] >= 'a' && path[1] <= 'z')) &&
- path[2] == ':') {
+ if (path[0] == '/' && path[SKIP_ONE] &&
+ ((path[SKIP_ONE] >= 'A' && path[SKIP_ONE] <= 'Z') ||
+ (path[SKIP_ONE] >= 'a' && path[SKIP_ONE] <= 'z')) &&
+ path[PAIR_LEN] == ':') {
path++; /* skip the leading / */
}
diff --git a/src/pipeline/fqn.c b/src/pipeline/fqn.c
index bd0663767..5f5482583 100644
--- a/src/pipeline/fqn.c
+++ b/src/pipeline/fqn.c
@@ -5,6 +5,7 @@
* Handles Python __init__.py, JS/TS index.{js,ts}, path separators.
*/
#include "pipeline/pipeline.h"
+#include "foundation/constants.h"
#include "foundation/platform.h"
#include <stddef.h> // NULL
@@ -12,7 +13,7 @@
#include <stdlib.h>
#include <string.h> // strdup
-/* Maximum path segments in a FQN (256 slots total, -2 for project + name) */
+/* Maximum path segments in a FQN (CBM_SZ_256 slots total, -2 for project + name) */
#define FQN_MAX_PATH_SEGS 254
#define FQN_MAX_DIR_SEGS 255
@@ -30,7 +31,7 @@ static char *join_segments(const char **segments, int count) {
total++; /* dot separator */
}
}
- char *result = malloc(total + 1);
+ char *result = malloc(total + SKIP_ONE);
if (!result) {
return NULL;
}
@@ -50,7 +51,7 @@ static char *join_segments(const char **segments, int count) {
/* Strip file extension from the last path component. */
static void strip_file_extension(char *path) {
char *last_slash = strrchr(path, '/');
- char *start = last_slash ? last_slash + 1 : path;
+ char *start = last_slash ? last_slash + SKIP_ONE : path;
char *ext = strrchr(start, '.');
if (ext) {
*ext = '\0';
@@ -72,7 +73,7 @@ static int tokenize_path(char *path, const char **segments, int max_segs) {
if (tok[0] != '\0') {
segments[count++] = tok;
}
- tok = slash ? slash + 1 : NULL;
+ tok = slash ? slash + SKIP_ONE : NULL;
}
return count;
}
@@ -81,10 +82,10 @@ static int tokenize_path(char *path, const char **segments, int max_segs) {
* symbol name is provided. Keeps it when no name is given to avoid QN
* collision with Folder nodes for the same directory. */
static void strip_init_or_index(const char **segments, int *seg_count, const char *name) {
- if (*seg_count <= 1) {
+ if (*seg_count <= SKIP_ONE) {
return;
}
- const char *last = segments[*seg_count - 1];
+ const char *last = segments[*seg_count - SKIP_ONE];
if (strcmp(last, "__init__") != 0 && strcmp(last, "index") != 0) {
return;
}
@@ -104,7 +105,7 @@ char *cbm_pipeline_fqn_compute(const char *project, const char *rel_path, const
cbm_normalize_path_sep(path);
strip_file_extension(path);
- const char *segments[256];
+ const char *segments[CBM_SZ_256];
int seg_count = 0;
segments[seg_count++] = project;
seg_count += tokenize_path(path, segments + seg_count, FQN_MAX_PATH_SEGS);
@@ -133,7 +134,7 @@ char *cbm_pipeline_fqn_folder(const char *project, const char *rel_dir) {
char *dir = strdup(rel_dir ? rel_dir : "");
cbm_normalize_path_sep(dir);
- const char *segments[256];
+ const char *segments[CBM_SZ_256];
int seg_count = 0;
segments[seg_count++] = project;
@@ -147,7 +148,7 @@ char *cbm_pipeline_fqn_folder(const char *project, const char *rel_dir) {
if (tok[0] != '\0') {
segments[seg_count++] = tok;
}
- tok = slash ? slash + 1 : NULL;
+ tok = slash ? slash + SKIP_ONE : NULL;
}
}
@@ -195,7 +196,7 @@ char *cbm_project_name_from_path(const char *abs_path) {
/* Trim trailing dashes */
size_t slen = strlen(start);
- while (slen > 0 && start[slen - 1] == '-') {
+ while (slen > 0 && start[slen - SKIP_ONE] == '-') {
start[--slen] = '\0';
}
diff --git a/src/pipeline/httplink.c b/src/pipeline/httplink.c
deleted file mode 100644
index 63826f7f3..000000000
--- a/src/pipeline/httplink.c
+++ /dev/null
@@ -1,1654 +0,0 @@
-/*
- * httplink.c — HTTP route discovery and cross-service linking.
- *
- * Port of Go internal/httplink package.
- */
-
-#include "pipeline/httplink.h"
-#include "foundation/hash_table.h"
-#include "foundation/yaml.h"
-#include "foundation/platform.h"
-#include "foundation/compat.h"
-#include "foundation/compat_regex.h"
-
-#include <ctype.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-/* ── Constants ─────────────────────────────────────────────────── */
-
-/* Confidence band thresholds */
-#define CONF_BAND_HIGH 0.7
-#define CONF_BAND_MEDIUM 0.45
-#define CONF_BAND_SPECULATIVE 0.25
-
-/* Path match confidence */
-#define CONF_PATH_EXACT 0.95
-#define CONF_PATH_SUFFIX 0.75
-
-/* Depth normalization factor */
-#define DEPTH_DIVISOR 3.0
-
-/* Default minimum confidence for filtering */
-#define DEFAULT_MIN_CONFIDENCE 0.25
-
-/* Buffer size guard: sizeof(buf) - 2 for trailing NUL + safety */
-#define NORM_BUF_GUARD 1022
-#define PARAM_BUF_GUARD 1020
-#define HALF_BUF_GUARD 510
-
-/* Receiver buffer max index */
-#define RECEIVER_MAX 63
-
-/* ── Similarity ────────────────────────────────────────────────── */
-
-static int imin(int a, int b) {
- return a < b ? a : b;
-}
-static int imax(int a, int b) {
- return a > b ? a : b;
-}
-
-int cbm_levenshtein_distance(const char *a, const char *b) {
- int la = (int)strlen(a);
- int lb = (int)strlen(b);
- if (la == 0) {
- return lb;
- }
- if (lb == 0) {
- return la;
- }
-
- int *prev = calloc((size_t)lb + 1, sizeof(int));
- int *curr = calloc((size_t)lb + 1, sizeof(int));
- if (!prev || !curr) {
- free(prev);
- free(curr);
- return imax(la, lb);
- }
-
- for (int j = 0; j <= lb; j++) {
- prev[j] = j;
- }
-
- for (int i = 1; i <= la; i++) {
- curr[0] = i;
- for (int j = 1; j <= lb; j++) {
- int cost = (a[i - 1] == b[j - 1]) ? 0 : 1;
- curr[j] = imin(curr[j - 1] + 1, imin(prev[j] + 1, prev[j - 1] + cost));
- }
- int *tmp = prev;
- prev = curr;
- curr = tmp;
- }
- int result = prev[lb];
- free(prev);
- free(curr);
- return result;
-}
-
-double cbm_normalized_levenshtein(const char *a, const char *b) {
- if (strcmp(a, b) == 0) {
- return 1.0;
- }
- int la = (int)strlen(a);
- int lb = (int)strlen(b);
- int max_len = imax(la, lb);
- if (max_len == 0) {
- return 1.0;
- }
- int dist = cbm_levenshtein_distance(a, b);
- return 1.0 - ((double)dist / (double)max_len);
-}
-
-static void free_ht_key(const char *key, void *val, void *ud) {
- (void)val;
- (void)ud;
- free((void *)key);
-}
-
-double cbm_ngram_overlap(const char *a, const char *b, int n) {
- int la = (int)strlen(a);
- int lb = (int)strlen(b);
- if (la < n || lb < n) {
- return 0.0;
- }
-
- int na = la - n + 1;
- int nb = lb - n + 1;
-
- /* Build set A using hash table for O(1) dedup */
- CBMHashTable *set_a = cbm_ht_create(na);
- for (int i = 0; i < na; i++) {
- char key[64];
- int klen = imin(n, (int)sizeof(key) - 1);
- memcpy(key, a + i, (size_t)klen);
- key[klen] = '\0';
- if (!cbm_ht_get(set_a, key)) {
- cbm_ht_set(set_a, strdup(key), (void *)1);
- }
- }
-
- /* Build set B using hash table, count intersection with A */
- CBMHashTable *set_b = cbm_ht_create(nb);
- int intersection = 0;
- for (int i = 0; i < nb; i++) {
- char key[64];
- int klen = imin(n, (int)sizeof(key) - 1);
- memcpy(key, b + i, (size_t)klen);
- key[klen] = '\0';
- if (!cbm_ht_get(set_b, key)) {
- cbm_ht_set(set_b, strdup(key), (void *)1);
- if (cbm_ht_get(set_a, key)) {
- intersection++;
- }
- }
- }
-
- int unique_a = (int)cbm_ht_count(set_a);
- int unique_b = (int)cbm_ht_count(set_b);
-
- /* Free hash table keys */
- cbm_ht_foreach(set_a, free_ht_key, NULL);
- cbm_ht_free(set_a);
- cbm_ht_foreach(set_b, free_ht_key, NULL);
- cbm_ht_free(set_b);
-
- int min_size = imin(unique_a, unique_b);
- if (min_size == 0) {
- return 0.0;
- }
- return (double)intersection / (double)min_size;
-}
-
-const char *cbm_confidence_band(double score) {
- if (score >= CONF_BAND_HIGH) {
- return "high";
- }
- if (score >= CONF_BAND_MEDIUM) {
- return "medium";
- }
- if (score >= CONF_BAND_SPECULATIVE) {
- return "speculative";
- }
- return "";
-}
-
-/* ── Path matching ─────────────────────────────────────────────── */
-
-/* Strip URL scheme + host, returning pointer to path portion.
- * Returns NULL if URL has no path component. */
-static char *strip_scheme_host(char *work) {
- char *path_start = work;
- char *scheme = strstr(work, "://");
- if (scheme) {
- path_start = scheme + 3;
- while (*path_start && *path_start != '/') {
- path_start++;
- }
- if (!*path_start) {
- return NULL;
- }
- }
- return path_start;
-}
-
-/* Replace :param and {param} path segments with wildcard '*'. */
-static int replace_path_params(const char *path_start, int plen, char *out, int out_max) {
- int out_len = 0;
- for (int i = 0; i < plen && out_len < out_max;) {
- if (path_start[i] == ':' && (i == 0 || path_start[i - 1] == '/')) {
- out[out_len++] = '*';
- i++;
- while (i < plen && path_start[i] != '/') {
- i++;
- }
- } else if (path_start[i] == '{') {
- out[out_len++] = '*';
- i++;
- while (i < plen && path_start[i] != '}') {
- i++;
- }
- if (i < plen) {
- i++;
- }
- } else {
- out[out_len++] = path_start[i++];
- }
- }
- out[out_len] = '\0';
- return out_len;
-}
-
-const char *cbm_normalize_path(const char *input) {
- static CBM_TLS char buf[1024];
- if (!input || !*input) {
- buf[0] = '\0';
- return buf;
- }
-
- /* Copy and lowercase */
- char work[1024] = {0};
- int len = 0;
- for (int i = 0; input[i] && len < NORM_BUF_GUARD; i++) {
- work[len++] = (char)tolower((unsigned char)input[i]);
- }
- work[len] = '\0';
-
- char *path_start = strip_scheme_host(work);
- if (!path_start) {
- buf[0] = '\0';
- return buf;
- }
-
- /* Strip trailing slash */
- int plen = (int)strlen(path_start);
- if (plen > 1 && path_start[plen - 1] == '/') {
- path_start[--plen] = '\0';
- }
-
- replace_path_params(path_start, plen, buf, PARAM_BUF_GUARD);
-
- if (strcmp(buf, "/") == 0) {
- buf[0] = '\0';
- }
-
- return buf;
-}
-
-/* Normalize a path into a caller-owned buffer for comparison */
-static void normalize_to_buf(const char *input, char *out, int out_size) {
- const char *norm = cbm_normalize_path(input);
- int len = (int)strlen(norm);
- if (len >= out_size) {
- len = out_size - 1;
- }
- memcpy(out, norm, (size_t)len);
- out[len] = '\0';
-}
-
-/* Compare two segment arrays with wildcard matching.
- * a_segs[a_off..a_off+count-1] vs b_segs[0..count-1]. */
-static bool segments_match_wildcard(char **a_segs, int a_off, char **b_segs, int count) {
- for (int i = 0; i < count; i++) {
- if (strcmp(a_segs[a_off + i], "*") == 0 || strcmp(b_segs[i], "*") == 0) {
- continue;
- }
- if (strcmp(a_segs[a_off + i], b_segs[i]) != 0) {
- return false;
- }
- }
- return true;
-}
-
-bool cbm_paths_match(const char *call_path, const char *route_path) {
- char norm_call[1024];
- char norm_route[1024];
- normalize_to_buf(call_path, norm_call, sizeof(norm_call));
- normalize_to_buf(route_path, norm_route, sizeof(norm_route));
-
- if (!*norm_call || !*norm_route) {
- return false;
- }
-
- if (strcmp(norm_call, norm_route) == 0) {
- return true;
- }
-
- int lc = (int)strlen(norm_call);
- int lr = (int)strlen(norm_route);
- if (lc > lr && strcmp(norm_call + lc - lr, norm_route) == 0) {
- return true;
- }
-
- char call_copy[1024];
- char route_copy[1024];
- strncpy(call_copy, norm_call, sizeof(call_copy) - 1);
- call_copy[sizeof(call_copy) - 1] = '\0';
-
- char *call_segs[64];
- char *route_segs[64];
- int nc = 0;
- int nr = 0;
-
- char *tok = strtok(call_copy, "/");
- while (tok && nc < 64) {
- call_segs[nc++] = tok;
- tok = strtok(NULL, "/");
- }
-
- normalize_to_buf(route_path, route_copy, sizeof(route_copy));
- tok = strtok(route_copy, "/");
- while (tok && nr < 64) {
- route_segs[nr++] = tok;
- tok = strtok(NULL, "/");
- }
-
- if (nc == nr && segments_match_wildcard(call_segs, 0, route_segs, nc)) {
- return true;
- }
-
- if (nc > nr && segments_match_wildcard(call_segs, nc - nr, route_segs, nr)) {
- return true;
- }
-
- return false;
-}
-
-/* Count segments in a normalized path */
-static int count_segments(const char *path) {
- int count = 0;
- for (int i = 0; path[i]; i++) {
- if (path[i] == '/') {
- count++;
- }
- }
- return count;
-}
-
-/* Jaccard similarity of path segments (intersection/union) */
-static double segment_jaccard(const char *norm_call, const char *norm_route) {
- /* Split into segments */
- char a[1024];
- char b[1024];
- strncpy(a, norm_call, sizeof(a) - 1);
- a[sizeof(a) - 1] = '\0';
- strncpy(b, norm_route, sizeof(b) - 1);
- b[sizeof(b) - 1] = '\0';
-
- char *a_segs[64];
- char *b_segs[64];
- int na = 0;
- int nb = 0;
-
- char *t = strtok(a, "/");
- while (t && na < 64) {
- a_segs[na++] = t;
- t = strtok(NULL, "/");
- }
-
- t = strtok(b, "/");
- while (t && nb < 64) {
- b_segs[nb++] = t;
- t = strtok(NULL, "/");
- }
-
- if (na == 0 && nb == 0) {
- return 1.0;
- }
- if (na == 0 || nb == 0) {
- return 0.0;
- }
-
- /* Count intersection (match segments in order, accounting for wildcards) */
- int intersect = 0;
- int max_len = imax(na, nb);
- int min_len = imin(na, nb);
- for (int i = 0; i < min_len; i++) {
- if (strcmp(a_segs[i], b_segs[i]) == 0 || strcmp(a_segs[i], "*") == 0 ||
- strcmp(b_segs[i], "*") == 0) {
- intersect++;
- }
- }
-
- return (double)intersect / (double)max_len;
-}
-
-/* Determine match type between two normalized paths.
- * Returns base score (CONF_PATH_EXACT, CONF_PATH_SUFFIX, or 0.0).
- * Sets *is_suffix if it was a suffix match. */
-static double classify_path_match(const char *norm_call, const char *norm_route, bool *is_suffix) {
- *is_suffix = false;
-
- if (strcmp(norm_call, norm_route) == 0) {
- return CONF_PATH_EXACT;
- }
-
- int lc = (int)strlen(norm_call);
- int lr = (int)strlen(norm_route);
- if (lc > lr && strcmp(norm_call + lc - lr, norm_route) == 0) {
- *is_suffix = true;
- return CONF_PATH_SUFFIX;
- }
-
- /* Segment-wise match with wildcards */
- char c2[1024];
- char r2[1024];
- strncpy(c2, norm_call, sizeof(c2) - 1);
- c2[sizeof(c2) - 1] = '\0';
- strncpy(r2, norm_route, sizeof(r2) - 1);
- r2[sizeof(r2) - 1] = '\0';
-
- char *cs[64];
- char *rs[64];
- int nc2 = 0;
- int nr2 = 0;
- char *tk = strtok(c2, "/");
- while (tk && nc2 < 64) {
- cs[nc2++] = tk;
- tk = strtok(NULL, "/");
- }
- tk = strtok(r2, "/");
- while (tk && nr2 < 64) {
- rs[nr2++] = tk;
- tk = strtok(NULL, "/");
- }
-
- if (nc2 == nr2 && segments_match_wildcard(cs, 0, rs, nc2)) {
- return CONF_PATH_EXACT;
- }
-
- return 0.0;
-}
-
-double cbm_path_match_score(const char *call_path, const char *route_path) {
- char norm_call[1024];
- char norm_route[1024];
- normalize_to_buf(call_path, norm_call, sizeof(norm_call));
- normalize_to_buf(route_path, norm_route, sizeof(norm_route));
-
- if (!*norm_call || !*norm_route) {
- return 0.0;
- }
-
- bool is_suffix = false;
- double match_base = classify_path_match(norm_call, norm_route, &is_suffix);
- if (match_base == 0.0) {
- return 0.0;
- }
-
- double jaccard = segment_jaccard(norm_call, norm_route);
- int depth = count_segments(is_suffix ? norm_route : norm_call);
- double depth_factor = (double)depth / DEPTH_DIVISOR;
- if (depth_factor > 1.0) {
- depth_factor = 1.0;
- }
-
- double confidence = (0.5 * jaccard) + (0.5 * depth_factor);
- return match_base * confidence;
-}
-
-bool cbm_same_service(const char *qn1, const char *qn2) {
- /* Split QN by '.', strip last 2 segments (module+name), compare rest */
- char a[1024];
- char b[1024];
- strncpy(a, qn1, sizeof(a) - 1);
- a[sizeof(a) - 1] = '\0';
- strncpy(b, qn2, sizeof(b) - 1);
- b[sizeof(b) - 1] = '\0';
-
- /* Count segments */
- char *a_segs[64];
- char *b_segs[64];
- int na = 0;
- int nb = 0;
-
- char *tok = strtok(a, ".");
- while (tok && na < 64) {
- a_segs[na++] = tok;
- tok = strtok(NULL, ".");
- }
-
- tok = strtok(b, ".");
- while (tok && nb < 64) {
- b_segs[nb++] = tok;
- tok = strtok(NULL, ".");
- }
-
- /* Need at least 3 segments (dir + module + name) */
- if (na < 3 || nb < 3) {
- return false;
- }
-
- /* Strip last 2 segments */
- int da = na - 2;
- int db = nb - 2;
-
- if (da != db) {
- return false;
- }
-
- for (int i = 0; i < da; i++) {
- if (strcmp(a_segs[i], b_segs[i]) != 0) {
- return false;
- }
- }
- return true;
-}
-
-/* ── Detection ─────────────────────────────────────────────────── */
-
-const char *cbm_detect_protocol(const char *source) {
- if (!source || !*source) {
- return "";
- }
-
- /* WebSocket patterns */
- if (strstr(source, "websocket.Upgrade") || strstr(source, "websocket.Accept") ||
- strstr(source, "upgrader.Upgrade") || strstr(source, "ws.on(") ||
- strstr(source, "io.on(")) {
- return "ws";
- }
-
- /* SSE patterns */
- if (strstr(source, "text/event-stream") || strstr(source, "EventSourceResponse") ||
- strstr(source, "SseEmitter") || strstr(source, "ServerSentEvent")) {
- return "sse";
- }
-
- return "";
-}
-
-/* containsTestSegment: check if path has a segment that equals testWord */
-static bool contains_test_segment(const char *fp, const char *test_word) {
- char work[1024];
- int len = (int)strlen(fp);
- if (len >= (int)sizeof(work)) {
- len = (int)sizeof(work) - 1;
- }
- memcpy(work, fp, (size_t)len);
- work[len] = '\0';
-
- /* Replace / with \0 and check each segment */
- char *p = work;
- while (*p) {
- char *seg = p;
- while (*p && *p != '/') {
- p++;
- }
- char saved = *p;
- *p = '\0';
- if (strcmp(seg, test_word) == 0) {
- return true;
- }
- if (saved) {
- *p = saved;
- p++;
- } else {
- { break; }
- }
- }
- return false;
-}
-
-bool cbm_is_test_node_fp(const char *file_path, bool is_test_prop) {
- if (is_test_prop) {
- return true;
- }
- if (!file_path || !*file_path) {
- return false;
- }
-
- /* Convert to forward slashes for consistent matching */
- char fp[1024];
- int len = 0;
- for (int i = 0; file_path[i] && len < NORM_BUF_GUARD; i++) {
- fp[len++] = (file_path[i] == '\\') ? '/' : file_path[i];
- }
- fp[len] = '\0';
-
- if (contains_test_segment(fp, "test")) {
- return true;
- }
- if (contains_test_segment(fp, "tests")) {
- return true;
- }
- if (contains_test_segment(fp, "__tests__")) {
- return true;
- }
- if (strstr(fp, "_test.")) {
- return true;
- }
- if (strstr(fp, ".test.")) {
- return true;
- }
- if (strstr(fp, "spec/")) {
- return true;
- }
- if (strstr(fp, "fixtures/")) {
- return true;
- }
- return false;
-}
-
-bool cbm_is_path_excluded(const char *path, const char **exclude_paths, int count) {
- if (!path || !*path) {
- return false;
- }
-
- /* Normalize: lowercase, strip trailing / */
- char norm[512];
- int len = 0;
- for (int i = 0; path[i] && len < HALF_BUF_GUARD; i++) {
- norm[len++] = (char)tolower((unsigned char)path[i]);
- }
- norm[len] = '\0';
- if (len > 1 && norm[len - 1] == '/') {
- norm[--len] = '\0';
- }
-
- for (int i = 0; i < count; i++) {
- /* Normalize exclude path too */
- char excl[512];
- int elen = 0;
- for (int j = 0; exclude_paths[i][j] && elen < HALF_BUF_GUARD; j++) {
- excl[elen++] = (char)tolower((unsigned char)exclude_paths[i][j]);
- }
- excl[elen] = '\0';
- if (elen > 1 && excl[elen - 1] == '/') {
- excl[--elen] = '\0';
- }
-
- if (strcmp(norm, excl) == 0) {
- return true;
- }
- }
- return false;
-}
-
-/* ── URL extraction ────────────────────────────────────────────── */
-
-int cbm_extract_url_paths(const char *text, char **out, int max_out) {
- if (!text || !*text) {
- return 0;
- }
-
- int count = 0;
- cbm_regex_t url_re;
- cbm_regex_t path_re;
-
- /* URL pattern: https?://host/path */
- if (cbm_regcomp(&url_re, "https?://[a-zA-Z0-9.\\-]+(/[a-zA-Z0-9_/:.\\.\\-]+)",
- CBM_REG_EXTENDED) != 0) {
- return 0;
- }
-
- /* Path pattern: "/path" (quoted paths starting with /) */
- if (cbm_regcomp(&path_re, "[\"'](/[a-zA-Z0-9_/:.\\.\\-]{2,})[\"']", CBM_REG_EXTENDED) != 0) {
- cbm_regfree(&url_re);
- return 0;
- }
-
- /* Search for URL patterns */
- const char *p = text;
- cbm_regmatch_t match[2];
-
- while (count < max_out && cbm_regexec(&url_re, p, 2, match, 0) == 0) {
- int path_start = match[1].rm_so;
- int path_end = match[1].rm_eo;
- int path_len = path_end - path_start;
- if (path_len > 0 && path_len < 256) {
- out[count] = malloc((size_t)path_len + 1);
- memcpy(out[count], p + path_start, (size_t)path_len);
- out[count][path_len] = '\0';
- count++;
- }
- p += match[0].rm_eo;
- }
-
- /* Search for path-only patterns */
- p = text;
- while (count < max_out && cbm_regexec(&path_re, p, 2, match, 0) == 0) {
- int path_start = match[1].rm_so;
- int path_end = match[1].rm_eo;
- int path_len = path_end - path_start;
- if (path_len > 0 && path_len < 256) {
- /* Check not already captured as part of a URL */
- char *path_str = malloc((size_t)path_len + 1);
- memcpy(path_str, p + path_start, (size_t)path_len);
- path_str[path_len] = '\0';
-
- bool dup = false;
- for (int i = 0; i < count; i++) {
- if (strcmp(out[i], path_str) == 0) {
- dup = true;
- break;
- }
- }
- if (!dup) {
- out[count++] = path_str;
- } else {
- free(path_str);
- }
- }
- p += match[0].rm_eo;
- }
-
- cbm_regfree(&url_re);
- cbm_regfree(&path_re);
- return count;
-}
-
-int cbm_extract_json_string_paths(const char *text, char **out, int max_out) {
- if (!text || !*text) {
- return 0;
- }
-
- /* Look for JSON-like strings containing URLs or paths */
- /* Extract all quoted strings and check for URL/path patterns */
- int count = 0;
-
- /* First try extracting URLs from the raw text (covers JSON string values) */
- count = cbm_extract_url_paths(text, out, max_out);
-
- return count;
-}
-
-/* ── Route extraction: Python ──────────────────────────────────── */
-
-/* Fill common route fields (function_name, qualified_name). */
-static void fill_route_identity(cbm_route_handler_t *r, const char *name, const char *qn) {
- strncpy(r->function_name, name ? name : "", sizeof(r->function_name) - 1);
- strncpy(r->qualified_name, qn ? qn : "", sizeof(r->qualified_name) - 1);
-}
-
-/* Copy a regex match group into a buffer, uppercase it, return length. */
-static int copy_match_upper(char *dst, int dst_size, const char *src, int so, int eo) {
- int len = eo - so;
- if (len >= dst_size) {
- len = dst_size - 1;
- }
- memcpy(dst, src + so, (size_t)len);
- dst[len] = '\0';
- for (int j = 0; dst[j]; j++) {
- dst[j] = (char)toupper((unsigned char)dst[j]);
- }
- return len;
-}
-
-/* Copy a regex match group into a buffer, return length. */
-static int copy_match(char *dst, int dst_size, const char *src, int so, int eo) {
- int len = eo - so;
- if (len >= dst_size) {
- len = dst_size - 1;
- }
- memcpy(dst, src + so, (size_t)len);
- dst[len] = '\0';
- return len;
-}
-
-int cbm_extract_python_routes(const char *name, const char *qn, const char **decorators, int ndec,
- cbm_route_handler_t *out, int max_out) {
- if (!decorators || ndec <= 0) {
- return 0;
- }
-
- cbm_regex_t py_route_re;
- cbm_regex_t py_ws_re;
- if (cbm_regcomp(&py_route_re,
- "@[a-zA-Z_]+\\.(get|post|put|delete|patch)\\([[:space:]]*[\"']([^\"']*)[\"']",
- CBM_REG_EXTENDED) != 0) {
- return 0;
- }
- if (cbm_regcomp(&py_ws_re, "@[a-zA-Z_]+\\.websocket\\([[:space:]]*[\"']([^\"']*)[\"']",
- CBM_REG_EXTENDED) != 0) {
- cbm_regfree(&py_route_re);
- return 0;
- }
-
- int count = 0;
- for (int i = 0; i < ndec && count < max_out; i++) {
- cbm_regmatch_t match[3];
-
- if (cbm_regexec(&py_ws_re, decorators[i], 2, match, 0) == 0) {
- cbm_route_handler_t *r = &out[count];
- memset(r, 0, sizeof(*r));
- copy_match(r->path, (int)sizeof(r->path), decorators[i], match[1].rm_so,
- match[1].rm_eo);
- strncpy(r->method, "WS", sizeof(r->method) - 1);
- strncpy(r->protocol, "ws", sizeof(r->protocol) - 1);
- fill_route_identity(r, name, qn);
- count++;
- continue;
- }
-
- if (cbm_regexec(&py_route_re, decorators[i], 3, match, 0) == 0) {
- cbm_route_handler_t *r = &out[count];
- memset(r, 0, sizeof(*r));
- copy_match_upper(r->method, (int)sizeof(r->method), decorators[i], match[1].rm_so,
- match[1].rm_eo);
- copy_match(r->path, (int)sizeof(r->path), decorators[i], match[2].rm_so,
- match[2].rm_eo);
- fill_route_identity(r, name, qn);
- count++;
- }
- }
-
- cbm_regfree(&py_route_re);
- cbm_regfree(&py_ws_re);
- return count;
-}
-
-/* ── Route extraction: Go gin/chi ──────────────────────────────── */
-
-/* Gin Group() binding: var → prefix. */
-typedef struct {
- char var[64];
- char prefix[256];
-} go_gin_group_t;
-
-/* Chi Route() match position + prefix. */
-typedef struct {
- int end_pos;
- char prefix[256];
-} go_chi_match_t;
-
-/* Route regex match with byte positions. */
-typedef struct {
- int start_pos, end_pos;
- int method_so, method_eo;
- int path_so, path_eo;
- int handler_so, handler_eo;
-} go_route_match_t;
-
-/* Collect gin Group() bindings from source. */
-static int collect_gin_groups(const char *source, const cbm_regex_t *re, go_gin_group_t *out,
- int max) {
- int count = 0;
- const char *sp = source;
- cbm_regmatch_t gm[4];
- while (cbm_regexec(re, sp, 4, gm, 0) == 0 && count < max) {
- int vlen = (gm[1].rm_eo - gm[1].rm_so);
- int plen = (gm[3].rm_eo - gm[3].rm_so);
- if (vlen < 64 && plen < 256) {
- memcpy(out[count].var, sp + gm[1].rm_so, (size_t)vlen);
- out[count].var[vlen] = '\0';
- memcpy(out[count].prefix, sp + gm[3].rm_so, (size_t)plen);
- out[count].prefix[plen] = '\0';
- count++;
- }
- sp += gm[0].rm_eo;
- }
- return count;
-}
-
-/* Collect chi Route() matches with absolute byte positions. */
-static int collect_chi_matches(const char *source, const cbm_regex_t *re, go_chi_match_t *out,
- int max) {
- int count = 0;
- const char *sp = source;
- cbm_regmatch_t cm[2];
- while (cbm_regexec(re, sp, 2, cm, 0) == 0 && count < max) {
- int abs_end = (int)((sp - source) + cm[0].rm_eo);
- int plen = (cm[1].rm_eo - cm[1].rm_so);
- if (plen < 256) {
- out[count].end_pos = abs_end;
- memcpy(out[count].prefix, sp + cm[1].rm_so, (size_t)plen);
- out[count].prefix[plen] = '\0';
- count++;
- }
- sp += cm[0].rm_eo;
- }
- return count;
-}
-
-/* Collect route regex matches with absolute byte positions. */
-static int collect_route_matches(const char *source, const cbm_regex_t *re, go_route_match_t *out,
- int max) {
- int count = 0;
- const char *sp = source;
- cbm_regmatch_t rm[4];
- while (cbm_regexec(re, sp, 4, rm, 0) == 0 && count < max) {
- int base = (int)(sp - source);
- out[count].start_pos = (base + rm[0].rm_so);
- out[count].end_pos = (base + rm[0].rm_eo);
- out[count].method_so = (base + rm[1].rm_so);
- out[count].method_eo = (base + rm[1].rm_eo);
- out[count].path_so = (base + rm[2].rm_so);
- out[count].path_eo = (base + rm[2].rm_eo);
- out[count].handler_so = (rm[3].rm_so >= 0) ? (base + rm[3].rm_so) : -1;
- out[count].handler_eo = (rm[3].rm_eo >= 0) ? (base + rm[3].rm_eo) : -1;
- count++;
- sp += rm[0].rm_eo;
- }
- return count;
-}
-
-/* Chi prefix stack entry. */
-typedef struct {
- char prefix[256];
- int depth;
-} chi_stack_entry_t;
-
-/* Concatenate all active chi prefixes into a route prefix. */
-static void build_chi_prefix(const chi_stack_entry_t *stack, int top, char *out, int out_sz) {
- out[0] = '\0';
- for (int s = 0; s < top; s++) {
- int cur = (int)strlen(out);
- int pf = (int)strlen(stack[s].prefix);
- if (cur + pf < out_sz - 1) {
- strcat(out, stack[s].prefix);
- }
- }
-}
-
-/* Handle brace tracking for chi prefix computation. */
-static void chi_handle_brace(char c, chi_stack_entry_t *stack, int *top, int *brace_depth,
- bool *pending, const char *pending_prefix) {
- if (c == '{') {
- (*brace_depth)++;
- if (*pending && *top < 32) {
- strncpy(stack[*top].prefix, pending_prefix, sizeof(stack[*top].prefix) - 1);
- stack[*top].prefix[sizeof(stack[*top].prefix) - 1] = '\0';
- stack[*top].depth = *brace_depth;
- (*top)++;
- *pending = false;
- }
- } else if (c == '}') {
- while (*top > 0 && stack[*top - 1].depth == *brace_depth) {
- (*top)--;
- }
- (*brace_depth)--;
- }
-}
-
-/* Compute chi prefix for each route via brace-depth tracking. */
-static void compute_chi_prefixes(const char *source, const go_chi_match_t *chi_matches, int nchi,
- const go_route_match_t *route_matches, int nmatches,
- char (*route_chi_prefix)[512]) {
- if (nchi == 0 || nmatches == 0) {
- return;
- }
-
- chi_stack_entry_t chi_stack[32];
- int chi_top = 0;
- int brace_depth = 0;
- int next_chi = 0;
- int next_route = 0;
- bool pending = false;
- char pending_prefix[256] = "";
-
- int src_len = (int)strlen(source);
- for (int i = 0; i <= src_len && next_route < nmatches; i++) {
- while (next_chi < nchi && i >= chi_matches[next_chi].end_pos) {
- pending = true;
- strncpy(pending_prefix, chi_matches[next_chi].prefix, sizeof(pending_prefix) - 1);
- pending_prefix[sizeof(pending_prefix) - 1] = '\0';
- next_chi++;
- }
-
- if (i < src_len) {
- chi_handle_brace(source[i], chi_stack, &chi_top, &brace_depth, &pending,
- pending_prefix);
- }
-
- while (next_route < nmatches && i == route_matches[next_route].start_pos) {
- build_chi_prefix(chi_stack, chi_top, route_chi_prefix[next_route], 512);
- next_route++;
- }
- }
-}
-
-/* Extract handler ref from match, trimming whitespace and trailing chars. */
-static void extract_handler_ref(const char *source, const go_route_match_t *rm,
- cbm_route_handler_t *r) {
- if (rm->handler_so < 0) {
- return;
- }
- int hlen = rm->handler_eo - rm->handler_so;
- const char *hs = source + rm->handler_so;
- while (hlen > 0 && (hs[0] == ' ' || hs[0] == '\t')) {
- hs++;
- hlen--;
- }
- while (hlen > 0 && (hs[hlen - 1] == ' ' || hs[hlen - 1] == '\t' || hs[hlen - 1] == ')' ||
- hs[hlen - 1] == '\n')) {
- hlen--;
- }
- if (hlen > 0 && hlen < (int)sizeof(r->handler_ref)) {
- memcpy(r->handler_ref, hs, (size_t)hlen);
- r->handler_ref[hlen] = '\0';
- }
-}
-
-/* Find receiver variable name before the dot in ".METHOD(" at start_pos. */
-static void find_receiver(const char *source, int start_pos, char *receiver, int max_len) {
- receiver[0] = '\0';
- const char *dot_pos = source + start_pos;
- if (dot_pos <= source) {
- return;
- }
- const char *rp = dot_pos - 1;
- while (rp >= source && (isalnum((unsigned char)*rp) || *rp == '_')) {
- rp--;
- }
- rp++;
- int rlen = (int)(dot_pos - rp);
- if (rlen > 0 && rlen < max_len) {
- memcpy(receiver, rp, (size_t)rlen);
- receiver[rlen] = '\0';
- }
-}
-
-/* Apply gin group or chi prefix to a route path. */
-static void apply_go_route_prefix(cbm_route_handler_t *r, const char *receiver,
- const go_gin_group_t *gin_groups, int ngin,
- const char *chi_prefix) {
- for (int g = 0; g < ngin; g++) {
- if (strcmp(receiver, gin_groups[g].var) == 0) {
- char full_path[512];
- snprintf(full_path, sizeof(full_path), "%s%s", gin_groups[g].prefix, r->path);
- strncpy(r->path, full_path, sizeof(r->path) - 1);
- r->path[sizeof(r->path) - 1] = '\0';
- return;
- }
- }
- if (chi_prefix && chi_prefix[0]) {
- char full_path[512];
- snprintf(full_path, sizeof(full_path), "%s%s", chi_prefix, r->path);
- strncpy(r->path, full_path, sizeof(r->path) - 1);
- r->path[sizeof(r->path) - 1] = '\0';
- }
-}
-
-int cbm_extract_go_routes(const char *name, const char *qn, const char *source,
- cbm_route_handler_t *out, int max_out) {
- if (!source || !*source) {
- return 0;
- }
-
- cbm_regex_t go_route_re;
- cbm_regex_t go_group_re;
- cbm_regex_t go_chi_re;
-
- if (cbm_regcomp(
- &go_route_re,
- "\\.(GET|POST|PUT|DELETE|PATCH|Get|Post|Put|Delete|Patch)\\([[:space:]]*[\"']([^\"'"
- "]*)[\"'][[:space:]]*,[[:space:]]*([^,)]+)",
- CBM_REG_EXTENDED) != 0) {
- return 0;
- }
- if (cbm_regcomp(
- &go_group_re,
- "([a-zA-Z_][a-zA-Z0-9_]*)[[:space:]]*(:=|=)[[:space:]]*[a-zA-Z_][a-zA-Z0-9_]*\\."
- "Group\\([[:space:]]*[\"']([^\"']+)[\"']",
- CBM_REG_EXTENDED) != 0) {
- cbm_regfree(&go_route_re);
- return 0;
- }
- if (cbm_regcomp(&go_chi_re, "\\.Route\\([[:space:]]*\"([^\"]+)\"[[:space:]]*,[[:space:]]*func",
- CBM_REG_EXTENDED) != 0) {
- cbm_regfree(&go_route_re);
- cbm_regfree(&go_group_re);
- return 0;
- }
-
- go_gin_group_t gin_groups[32];
- int ngin = collect_gin_groups(source, &go_group_re, gin_groups, 32);
-
- go_chi_match_t chi_matches[32];
- int nchi = collect_chi_matches(source, &go_chi_re, chi_matches, 32);
-
- go_route_match_t route_matches[64];
- int nmatches = collect_route_matches(source, &go_route_re, route_matches, 64);
-
- char route_chi_prefix[64][512];
- memset(route_chi_prefix, 0, sizeof(route_chi_prefix));
- compute_chi_prefixes(source, chi_matches, nchi, route_matches, nmatches, route_chi_prefix);
-
- int count = 0;
- for (int ri = 0; ri < nmatches && count < max_out; ri++) {
- cbm_route_handler_t *r = &out[count];
- memset(r, 0, sizeof(*r));
-
- copy_match_upper(r->method, (int)sizeof(r->method), source, route_matches[ri].method_so,
- route_matches[ri].method_eo);
- copy_match(r->path, (int)sizeof(r->path), source, route_matches[ri].path_so,
- route_matches[ri].path_eo);
-
- char receiver[64];
- find_receiver(source, route_matches[ri].start_pos, receiver, 64);
- apply_go_route_prefix(r, receiver, gin_groups, ngin, route_chi_prefix[ri]);
-
- fill_route_identity(r, name, qn);
- extract_handler_ref(source, &route_matches[ri], r);
- count++;
- }
-
- cbm_regfree(&go_route_re);
- cbm_regfree(&go_group_re);
- cbm_regfree(&go_chi_re);
- return count;
-}
-
-/* ── Route extraction: Java Spring ─────────────────────────────── */
-
-/* Resolve Spring annotation name to HTTP method string. */
-static const char *spring_method_from_annotation(const char *ann_name) {
- if (strcmp(ann_name, "Get") == 0) {
- return "GET";
- }
- if (strcmp(ann_name, "Post") == 0) {
- return "POST";
- }
- if (strcmp(ann_name, "Put") == 0) {
- return "PUT";
- }
- if (strcmp(ann_name, "Delete") == 0) {
- return "DELETE";
- }
- if (strcmp(ann_name, "Patch") == 0) {
- return "PATCH";
- }
- return "ANY";
-}
-
-int cbm_extract_java_routes(const char *name, const char *qn, const char **decorators, int ndec,
- cbm_route_handler_t *out, int max_out) {
- if (!decorators || ndec <= 0) {
- return 0;
- }
-
- cbm_regex_t spring_re;
- cbm_regex_t spring_ws_re;
- if (cbm_regcomp(
- &spring_re,
- "@(Get|Post|Put|Delete|Patch|Request)Mapping\\([[:space:]]*(value[[:space:]]*=[[:"
- "space:]]*)?[\"']([^\"']+)[\"']",
- CBM_REG_EXTENDED) != 0) {
- return 0;
- }
- if (cbm_regcomp(&spring_ws_re, "@MessageMapping\\([[:space:]]*[\"']([^\"']+)[\"']",
- CBM_REG_EXTENDED) != 0) {
- cbm_regfree(&spring_re);
- return 0;
- }
-
- int count = 0;
- for (int i = 0; i < ndec && count < max_out; i++) {
- cbm_regmatch_t match[4];
-
- if (cbm_regexec(&spring_ws_re, decorators[i], 2, match, 0) == 0) {
- cbm_route_handler_t *r = &out[count];
- memset(r, 0, sizeof(*r));
- copy_match(r->path, (int)sizeof(r->path), decorators[i], match[1].rm_so,
- match[1].rm_eo);
- strncpy(r->method, "WS", sizeof(r->method) - 1);
- strncpy(r->protocol, "ws", sizeof(r->protocol) - 1);
- fill_route_identity(r, name, qn);
- count++;
- continue;
- }
-
- if (cbm_regexec(&spring_re, decorators[i], 4, match, 0) == 0) {
- cbm_route_handler_t *r = &out[count];
- memset(r, 0, sizeof(*r));
-
- char method_name[32];
- copy_match(method_name, (int)sizeof(method_name), decorators[i], match[1].rm_so,
- match[1].rm_eo);
- strncpy(r->method, spring_method_from_annotation(method_name), sizeof(r->method) - 1);
-
- copy_match(r->path, (int)sizeof(r->path), decorators[i], match[3].rm_so,
- match[3].rm_eo);
- fill_route_identity(r, name, qn);
- count++;
- }
- }
-
- cbm_regfree(&spring_re);
- cbm_regfree(&spring_ws_re);
- return count;
-}
-
-/* ── Route extraction: Kotlin Ktor ─────────────────────────────── */
-
-/* Collect Ktor WebSocket routes. */
-static int collect_ktor_ws_routes(const char *source, const cbm_regex_t *re, const char *name,
- const char *qn, cbm_route_handler_t *out, int max_out) {
- int count = 0;
- const char *p = source;
- cbm_regmatch_t match[2];
-
- while (count < max_out && cbm_regexec(re, p, 2, match, 0) == 0) {
- cbm_route_handler_t *r = &out[count];
- memset(r, 0, sizeof(*r));
- copy_match(r->path, (int)sizeof(r->path), p, match[1].rm_so, match[1].rm_eo);
- strncpy(r->method, "WS", sizeof(r->method) - 1);
- strncpy(r->protocol, "ws", sizeof(r->protocol) - 1);
- fill_route_identity(r, name, qn);
- count++;
- p += match[0].rm_eo;
- }
- return count;
-}
-
-/* Collect Ktor HTTP routes, skipping webSocket false positives. */
-static int collect_ktor_http_routes(const char *source, const cbm_regex_t *re, const char *name,
- const char *qn, cbm_route_handler_t *out, int max_out) {
- int count = 0;
- const char *p = source;
- cbm_regmatch_t match[3];
-
- while (count < max_out && cbm_regexec(re, p, 3, match, 0) == 0) {
- const char *match_start = p + match[0].rm_so;
- bool is_ws = (match_start >= source + 3 && strncmp(match_start - 3, "web", 3) == 0);
-
- if (!is_ws) {
- cbm_route_handler_t *r = &out[count];
- memset(r, 0, sizeof(*r));
- copy_match_upper(r->method, (int)sizeof(r->method), p, match[1].rm_so, match[1].rm_eo);
- copy_match(r->path, (int)sizeof(r->path), p, match[2].rm_so, match[2].rm_eo);
- fill_route_identity(r, name, qn);
- count++;
- }
- p += match[0].rm_eo;
- }
- return count;
-}
-
-int cbm_extract_ktor_routes(const char *name, const char *qn, const char *source,
- cbm_route_handler_t *out, int max_out) {
- if (!source || !*source) {
- return 0;
- }
-
- cbm_regex_t ktor_re;
- cbm_regex_t ktor_ws_re;
- if (cbm_regcomp(&ktor_re,
- "(get|post|put|delete|patch)\\([[:space:]]*\"([^\"]+)\"[[:space:]]*\\)",
- CBM_REG_EXTENDED) != 0) {
- return 0;
- }
- if (cbm_regcomp(&ktor_ws_re, "webSocket\\([[:space:]]*\"([^\"]+)\"[[:space:]]*\\)",
- CBM_REG_EXTENDED) != 0) {
- cbm_regfree(&ktor_re);
- return 0;
- }
-
- int count = collect_ktor_ws_routes(source, &ktor_ws_re, name, qn, out, max_out);
- count += collect_ktor_http_routes(source, &ktor_re, name, qn, out + count, max_out - count);
-
- cbm_regfree(&ktor_re);
- cbm_regfree(&ktor_ws_re);
- return count;
-}
-
-/* ── Route extraction: Express.js ──────────────────────────────── */
-
-static bool is_express_receiver(const char *receiver) {
- static const char *allowlist[] = {"app", "router", "server", "api",
- "routes", "express", "route"};
- for (int i = 0; i < 7; i++) {
- if (strcmp(receiver, allowlist[i]) == 0) {
- return true;
- }
- }
- return false;
-}
-
-int cbm_extract_express_routes(const char *name, const char *qn, const char *source,
- cbm_route_handler_t *out, int max_out) {
- if (!source || !*source) {
- return 0;
- }
-
- cbm_regex_t express_re;
- if (cbm_regcomp(
- &express_re,
- "([a-zA-Z_][a-zA-Z0-9_]*)\\.(get|post|put|delete|patch)\\([[:space:]]*[\"'`]([^\"'`"
- "]+)[\"'`]",
- CBM_REG_EXTENDED) != 0) {
- return 0;
- }
-
- int count = 0;
- const char *p = source;
- cbm_regmatch_t match[4];
-
- while (count < max_out && cbm_regexec(&express_re, p, 4, match, 0) == 0) {
- char receiver[64];
- copy_match(receiver, (int)sizeof(receiver), p, match[1].rm_so, match[1].rm_eo);
-
- if (is_express_receiver(receiver)) {
- cbm_route_handler_t *r = &out[count];
- memset(r, 0, sizeof(*r));
- copy_match_upper(r->method, (int)sizeof(r->method), p, match[2].rm_so, match[2].rm_eo);
- copy_match(r->path, (int)sizeof(r->path), p, match[3].rm_so, match[3].rm_eo);
- fill_route_identity(r, name, qn);
- count++;
- }
- p += match[0].rm_eo;
- }
-
- cbm_regfree(&express_re);
- return count;
-}
-
-/* ── Route extraction: Laravel ─────────────────────────────────── */
-
-int cbm_extract_laravel_routes(const char *name, const char *qn, const char *source,
- cbm_route_handler_t *out, int max_out) {
- if (!source || !*source) {
- return 0;
- }
-
- cbm_regex_t laravel_re;
- if (cbm_regcomp(&laravel_re,
- "Route::(get|post|put|delete|patch)\\([[:space:]]*[\"']([^\"']+)[\"']",
- CBM_REG_EXTENDED) != 0) {
- return 0;
- }
-
- int count = 0;
- const char *p = source;
- cbm_regmatch_t match[3];
-
- while (count < max_out && cbm_regexec(&laravel_re, p, 3, match, 0) == 0) {
- cbm_route_handler_t *r = &out[count];
- memset(r, 0, sizeof(*r));
-
- /* Method */
- int mlen = (match[1].rm_eo - match[1].rm_so);
- if (mlen >= (int)sizeof(r->method)) {
- mlen = (int)sizeof(r->method) - 1;
- }
- memcpy(r->method, p + match[1].rm_so, (size_t)mlen);
- r->method[mlen] = '\0';
- for (int j = 0; r->method[j]; j++) {
- r->method[j] = (char)toupper((unsigned char)r->method[j]);
- }
-
- /* Path */
- int plen = (match[2].rm_eo - match[2].rm_so);
- if (plen >= (int)sizeof(r->path)) {
- plen = (int)sizeof(r->path) - 1;
- }
- memcpy(r->path, p + match[2].rm_so, (size_t)plen);
- r->path[plen] = '\0';
-
- /* Skip non-route strings that match the regex but contain characters
- * invalid in URL paths (e.g., cache keys, interpolated expressions).
- * Laravel route parameters use {param} syntax, so valid routes pass. */
- if (strchr(r->path, '$') || strchr(r->path, ':')) {
- p += match[0].rm_eo;
- continue;
- }
-
- strncpy(r->function_name, name ? name : "", sizeof(r->function_name) - 1);
- strncpy(r->qualified_name, qn ? qn : "", sizeof(r->qualified_name) - 1);
- count++;
- p += match[0].rm_eo;
- }
-
- cbm_regfree(&laravel_re);
- return count;
-}
-
-/* ── Read source lines ─────────────────────────────────────────── */
-
-char *cbm_read_source_lines_disk(const char *root_dir, const char *rel_path, int start_line,
- int end_line) {
- char full_path[2048];
- snprintf(full_path, sizeof(full_path), "%s/%s", root_dir, rel_path);
-
- FILE *f = fopen(full_path, "r");
- if (!f) {
- return NULL;
- }
-
- char *result = NULL;
- int result_len = 0;
- int result_cap = 0;
- int line = 0;
- char line_buf[4096];
-
- while (fgets(line_buf, sizeof(line_buf), f)) {
- line++;
- if (line < start_line) {
- continue;
- }
- if (line > end_line) {
- break;
- }
-
- int llen = (int)strlen(line_buf);
- /* Strip trailing newline */
- if (llen > 0 && line_buf[llen - 1] == '\n') {
- line_buf[--llen] = '\0';
- }
-
- /* Add separator between lines */
- if (result_len > 0) {
- if (result_len + 1 >= result_cap) {
- result_cap = (result_cap == 0) ? 1024 : result_cap * 2;
- result = safe_realloc(result, (size_t)result_cap);
- }
- result[result_len++] = '\n';
- }
-
- /* Add line content */
- if (result_len + llen >= result_cap) {
- result_cap = result_len + llen + 256;
- result = safe_realloc(result, (size_t)result_cap);
- }
- memcpy(result + result_len, line_buf, (size_t)llen);
- result_len += llen;
- }
-
- (void)fclose(f);
- if (result) {
- result[result_len] = '\0';
- }
- return result;
-}
-
-/* ── Read source lines from cached buffer ──────────────────────── */
-
-/* Append a line to a dynamically growing result buffer. */
-static void append_line_to_result(char **result, int *result_len, int *result_cap, const char *line,
- int line_len) {
- /* Strip trailing \r for CRLF files */
- int copy_len = line_len;
- // cppcheck-suppress knownConditionTrueFalse
- if (copy_len > 0 && line[copy_len - 1] == '\r') {
- copy_len--;
- }
-
- /* Add separator between lines */
- if (*result_len > 0) {
- if (*result_len + 1 >= *result_cap) {
- *result_cap = (*result_cap == 0) ? 1024 : *result_cap * 2;
- *result = safe_realloc(*result, (size_t)*result_cap);
- }
- (*result)[(*result_len)++] = '\n';
- }
-
- /* Add line content */
- if (*result_len + copy_len >= *result_cap) {
- *result_cap = *result_len + copy_len + 256;
- *result = safe_realloc(*result, (size_t)*result_cap);
- }
- if (copy_len > 0 && *result) {
- memcpy(*result + *result_len, line, (size_t)copy_len);
- *result_len += copy_len;
- }
-}
-
-char *cbm_read_source_lines_cached(const char *source, int source_len, int start_line,
- int end_line) {
- if (!source || source_len <= 0 || start_line <= 0 || end_line < start_line) {
- return NULL;
- }
-
- char *result = NULL;
- int result_len = 0;
- int result_cap = 0;
- int line = 0;
- const char *p = source;
- const char *end = source + source_len;
-
- while (p < end) {
- line++;
- const char *eol = memchr(p, '\n', (size_t)(end - p));
- int llen = eol ? (int)(eol - p) : (int)(end - p);
-
- if (line >= start_line && line <= end_line) {
- append_line_to_result(&result, &result_len, &result_cap, p, llen);
- }
-
- if (line > end_line) {
- break;
- }
-
- p = eol ? eol + 1 : end;
- }
-
- if (result) {
- result[result_len] = '\0';
- }
- return result;
-}
-
-/* ── Config data ───────────────────────────────────────────────── */
-
-const char *cbm_default_exclude_paths[] = {
- "/health", "/healthz", "/ready", "/readyz", "/livez",
- "/metrics", "/debug", "/favicon.ico", "/.well-known",
-};
-const int cbm_default_exclude_paths_count = 9;
-
-const char *cbm_http_client_keywords[] = {
- "requests.get", "requests.post", "requests.put", "requests.delete", "httpx.",
- "aiohttp.", "http.Get", "http.Post", "http.NewRequest", "fetch(",
- "axios.", "HttpClient", "RestTemplate", "reqwest::", "hyper::",
- "curl_exec", "Guzzle", "sttp.", "http4s", "curl_easy",
- "cpr::Get", "socket.http", "http.request", "WebClient", "RestClient",
- "OkHttpClient",
-};
-const int cbm_http_client_keywords_count = 26;
-
-const char *cbm_async_dispatch_keywords[] = {
- "CreateTask", "create_task", "send_task", "send_message",
- "publish(", "Publish(", "SQS", "EventBridge",
-};
-const int cbm_async_dispatch_keywords_count = 8;
-
-/* ── Linker config ────────────────────────────────────────────── */
-
-cbm_httplink_config_t cbm_httplink_default_config(void) {
- cbm_httplink_config_t cfg = {0};
- cfg.min_confidence = -1.0; /* sentinel: use default 0.25 */
- cfg.fuzzy_matching = -1; /* sentinel: use default true */
- cfg.exclude_paths = NULL;
- cfg.exclude_path_count = 0;
- return cfg;
-}
-
-cbm_httplink_config_t cbm_httplink_load_config(const char *dir) {
- cbm_httplink_config_t cfg = cbm_httplink_default_config();
- if (!dir) {
- return cfg;
- }
-
- /* Build path: dir/.cgrconfig */
- char path[1024];
- int n = snprintf(path, sizeof(path), "%s/.cgrconfig", dir);
- if (n <= 0 || (size_t)n >= sizeof(path)) {
- return cfg;
- }
-
- /* Read file */
- FILE *f = fopen(path, "r");
- if (!f) {
- return cfg;
- }
-
- (void)fseek(f, 0, SEEK_END);
- long size = ftell(f);
- (void)fseek(f, 0, SEEK_SET);
-
- if (size <= 0 || size > (long)1024 * 1024) {
- (void)fclose(f);
- return cfg;
- }
-
- char *buf = malloc((size_t)size + 1);
- if (!buf) {
- (void)fclose(f);
- return cfg;
- }
-
- size_t nread = fread(buf, 1, (size_t)size, f);
- (void)fclose(f);
- buf[nread] = '\0';
-
- /* Parse YAML */
- cbm_yaml_node_t *root = cbm_yaml_parse(buf, (int)nread);
- free(buf);
- if (!root) {
- return cfg;
- }
-
- /* Extract min_confidence */
- if (cbm_yaml_has(root, "http_linker.min_confidence")) {
- cfg.min_confidence = cbm_yaml_get_float(root, "http_linker.min_confidence", -1.0);
- }
-
- /* Extract fuzzy_matching */
- if (cbm_yaml_has(root, "http_linker.fuzzy_matching")) {
- cfg.fuzzy_matching = cbm_yaml_get_bool(root, "http_linker.fuzzy_matching", true) ? 1 : 0;
- }
-
- /* Extract exclude_paths */
- const char *items[128];
- int count = cbm_yaml_get_str_list(root, "http_linker.exclude_paths", items, 128);
- if (count > 0) {
- cfg.exclude_paths = calloc((size_t)count, sizeof(char *));
- if (cfg.exclude_paths) {
- for (int i = 0; i < count; i++) {
- cfg.exclude_paths[i] = strdup(items[i]);
- }
- cfg.exclude_path_count = count;
- }
- }
-
- cbm_yaml_free(root);
- return cfg;
-}
-
-void cbm_httplink_config_free(cbm_httplink_config_t *cfg) {
- if (!cfg) {
- return;
- }
- for (int i = 0; i < cfg->exclude_path_count; i++) {
- free(cfg->exclude_paths[i]);
- }
- free(cfg->exclude_paths);
- cfg->exclude_paths = NULL;
- cfg->exclude_path_count = 0;
-}
-
-double cbm_httplink_effective_min_confidence(const cbm_httplink_config_t *cfg) {
- if (!cfg || cfg->min_confidence < 0) {
- return DEFAULT_MIN_CONFIDENCE;
- }
- return cfg->min_confidence;
-}
-
-bool cbm_httplink_effective_fuzzy_matching(const cbm_httplink_config_t *cfg) {
- if (!cfg || cfg->fuzzy_matching < 0) {
- return true;
- }
- return cfg->fuzzy_matching == 1;
-}
-
-int cbm_httplink_all_exclude_paths(const cbm_httplink_config_t *cfg, const char **out,
- int max_out) {
- int count = 0;
-
- /* Add defaults first */
- for (int i = 0; i < cbm_default_exclude_paths_count && count < max_out; i++) {
- out[count++] = cbm_default_exclude_paths[i];
- }
-
- /* Add user-configured paths */
- if (cfg) {
- for (int i = 0; i < cfg->exclude_path_count && count < max_out; i++) {
- out[count++] = cfg->exclude_paths[i];
- }
- }
-
- return count;
-}
diff --git a/src/pipeline/httplink.h b/src/pipeline/httplink.h
deleted file mode 100644
index c0cd275a1..000000000
--- a/src/pipeline/httplink.h
+++ /dev/null
@@ -1,177 +0,0 @@
-/*
- * httplink.h — HTTP route discovery and cross-service linking.
- *
- * Port of Go httplink package: discovers HTTP routes from Python decorators,
- * Go gin/chi, Express.js, Spring, Ktor, Laravel, Actix, ASP.NET, and matches
- * HTTP call sites to create HTTP_CALLS/ASYNC_CALLS edges.
- *
- * Depends on: foundation, store (for linker integration)
- */
-#ifndef CBM_HTTPLINK_H
-#define CBM_HTTPLINK_H
-
-#include <stdbool.h>
-#include <stdint.h>
-
-/* ── Types ─────────────────────────────────────────────────────── */
-
-typedef struct {
- char path[256];
- char method[16];
- char function_name[256];
- char qualified_name[512];
- char handler_ref[256];
- char resolved_handler_qn[512];
- char protocol[8]; /* "ws", "sse", or "" */
-} cbm_route_handler_t;
-
-typedef struct {
- char path[256];
- char method[16];
- char source_name[256];
- char source_qn[512];
- char source_label[32];
- bool is_async;
-} cbm_http_call_site_t;
-
-typedef struct {
- char caller_qn[512];
- char caller_label[32];
- char handler_qn[512];
- char url_path[256];
- char edge_type[16]; /* "HTTP_CALLS" or "ASYNC_CALLS" */
-} cbm_http_link_t;
-
-/* ── Similarity functions ──────────────────────────────────────── */
-
-int cbm_levenshtein_distance(const char *a, const char *b);
-double cbm_normalized_levenshtein(const char *a, const char *b);
-double cbm_ngram_overlap(const char *a, const char *b, int n);
-const char *cbm_confidence_band(double score);
-
-/* ── Path matching ─────────────────────────────────────────────── */
-
-/* Normalize a URL path: lowercase, strip trailing /, replace :param and {param} with *.
- * Returns static thread-local buffer — do NOT free. */
-const char *cbm_normalize_path(const char *input);
-
-/* Check if two paths match after normalization (exact or suffix). */
-bool cbm_paths_match(const char *call_path, const char *route_path);
-
-/* Score path similarity (0.0–1.0). Returns 0 if no match. */
-double cbm_path_match_score(const char *call_path, const char *route_path);
-
-/* Check if two QNs belong to the same service (same dir prefix). */
-bool cbm_same_service(const char *qn1, const char *qn2);
-
-/* ── Detection ─────────────────────────────────────────────────── */
-
-/* Detect WebSocket or SSE protocol from source code. Returns "ws", "sse", or "". */
-const char *cbm_detect_protocol(const char *source);
-
-/* Check if a node is from a test file (by file_path + is_test property). */
-bool cbm_is_test_node_fp(const char *file_path, bool is_test_prop);
-
-/* Check if a path is in the exclude list (case-insensitive, strips trailing /). */
-bool cbm_is_path_excluded(const char *path, const char **exclude_paths, int count);
-
-/* ── URL extraction ────────────────────────────────────────────── */
-
-/* Extract URL paths from text (https://host/path or "/path" patterns).
- * Returns count of paths written to out[]. Caller must free each string. */
-int cbm_extract_url_paths(const char *text, char **out, int max_out);
-
-/* Extract URL paths from JSON strings in text.
- * Returns count. Caller must free each string. */
-int cbm_extract_json_string_paths(const char *text, char **out, int max_out);
-
-/* ── Route extraction ──────────────────────────────────────────── */
-
-/* Extract Python routes from decorator strings.
- * decorators: array of decorator strings like `@app.post("/api/orders")`
- * Returns count of routes written to out[]. */
-int cbm_extract_python_routes(const char *name, const char *qn, const char **decorators, int ndec,
- cbm_route_handler_t *out, int max_out);
-
-/* Extract Go gin/chi routes from function source.
- * Returns count of routes written to out[]. */
-int cbm_extract_go_routes(const char *name, const char *qn, const char *source,
- cbm_route_handler_t *out, int max_out);
-
-/* Extract Java Spring routes from decorator strings.
- * Returns count. */
-int cbm_extract_java_routes(const char *name, const char *qn, const char **decorators, int ndec,
- cbm_route_handler_t *out, int max_out);
-
-/* Extract Kotlin Ktor routes from source.
- * Returns count. */
-int cbm_extract_ktor_routes(const char *name, const char *qn, const char *source,
- cbm_route_handler_t *out, int max_out);
-
-/* Extract Express.js routes from source (with receiver allowlist filtering).
- * Returns count. */
-int cbm_extract_express_routes(const char *name, const char *qn, const char *source,
- cbm_route_handler_t *out, int max_out);
-
-/* Extract PHP Laravel routes from source.
- * Returns count. */
-int cbm_extract_laravel_routes(const char *name, const char *qn, const char *source,
- cbm_route_handler_t *out, int max_out);
-
-/* ── Read source lines ─────────────────────────────────────────── */
-
-/* Read specific lines from a file on disk.
- * root_dir + "/" + rel_path is the full path.
- * Returns malloc'd string (caller must free), or NULL on error. */
-char *cbm_read_source_lines_disk(const char *root_dir, const char *rel_path, int start_line,
- int end_line);
-
-/* Read specific lines from a cached source buffer (no disk I/O).
- * source is the full file content, source_len its byte length.
- * Returns malloc'd string (caller must free), or NULL if out of range. */
-char *cbm_read_source_lines_cached(const char *source, int source_len, int start_line,
- int end_line);
-
-/* ── Config ────────────────────────────────────────────────────── */
-
-/* Default exclude paths for HTTP link filtering. */
-extern const char *cbm_default_exclude_paths[];
-extern const int cbm_default_exclude_paths_count;
-
-/* HTTP client keywords for AC pre-screening. */
-extern const char *cbm_http_client_keywords[];
-extern const int cbm_http_client_keywords_count;
-
-/* Async dispatch keywords. */
-extern const char *cbm_async_dispatch_keywords[];
-extern const int cbm_async_dispatch_keywords_count;
-
-/* ── Linker config (loaded from .cgrconfig YAML) ──────────────── */
-
-typedef struct {
- double min_confidence; /* -1 means "use default" */
- int fuzzy_matching; /* -1 = use default, 0 = false, 1 = true */
- char **exclude_paths; /* user-configured exclude paths */
- int exclude_path_count;
-} cbm_httplink_config_t;
-
-/* Return a default config (all fields at "use default" sentinel values). */
-cbm_httplink_config_t cbm_httplink_default_config(void);
-
-/* Load config from .cgrconfig in the given directory.
- * Returns default config if file doesn't exist or YAML is invalid. */
-cbm_httplink_config_t cbm_httplink_load_config(const char *dir);
-
-/* Free resources owned by a config. */
-void cbm_httplink_config_free(cbm_httplink_config_t *cfg);
-
-/* Effective values (applies defaults when config field is sentinel). */
-double cbm_httplink_effective_min_confidence(const cbm_httplink_config_t *cfg);
-bool cbm_httplink_effective_fuzzy_matching(const cbm_httplink_config_t *cfg);
-
-/* Build combined exclude paths: defaults + user-configured.
- * Writes up to max_out pointers into out[]. Pointers are valid until
- * config is freed. Returns total count. */
-int cbm_httplink_all_exclude_paths(const cbm_httplink_config_t *cfg, const char **out, int max_out);
-
-#endif /* CBM_HTTPLINK_H */
diff --git a/src/pipeline/pass_calls.c b/src/pipeline/pass_calls.c
index 7f641caeb..60663a946 100644
--- a/src/pipeline/pass_calls.c
+++ b/src/pipeline/pass_calls.c
@@ -9,6 +9,9 @@
*
* Depends on: pass_definitions having populated the registry and graph buffer
*/
+#include "foundation/constants.h"
+
+enum { PC_RING = 4, PC_RING_MASK = 3, PC_SIG_SCAN = 15, PC_REGEX_GRP = 2 };
#include "pipeline/pipeline.h"
#include "pipeline/pipeline_internal.h"
#include "graph_buffer/graph_buffer.h"
@@ -35,20 +38,23 @@ static char *read_file(const char *path, int *out_len) {
long size = ftell(f);
(void)fseek(f, 0, SEEK_SET);
- if (size <= 0 || size > (long)100 * 1024 * 1024) {
+ if (size <= 0 || size > (long)CBM_PERCENT * CBM_SZ_1K * CBM_SZ_1K) {
(void)fclose(f);
return NULL;
}
- char *buf = malloc(size + 1);
+ char *buf = malloc(size + SKIP_ONE);
if (!buf) {
(void)fclose(f);
return NULL;
}
- size_t nread = fread(buf, 1, size, f);
+ size_t nread = fread(buf, SKIP_ONE, size, f);
(void)fclose(f);
+ if (nread > (size_t)size) {
+ nread = (size_t)size;
+ }
buf[nread] = '\0';
*out_len = (int)nread;
return buf;
@@ -56,10 +62,10 @@ static char *read_file(const char *path, int *out_len) {
/* Format int for logging. Thread-safe via TLS. */
static const char *itoa_log(int val) {
- static CBM_TLS char bufs[4][32];
+ static CBM_TLS char bufs[PC_RING][CBM_SZ_32];
static CBM_TLS int idx = 0;
int i = idx;
- idx = (idx + 1) & 3;
+ idx = (idx + SKIP_ONE) & PC_RING_MASK;
snprintf(bufs[i], sizeof(bufs[i]), "%d", val);
return bufs[i];
}
@@ -178,11 +184,11 @@ static void handle_route_registration(cbm_pipeline_ctx_t *ctx, const CBMCall *ca
char route_qn[CBM_ROUTE_QN_SIZE];
snprintf(route_qn, sizeof(route_qn), "__route__%s__%s", method ? method : "ANY",
call->first_string_arg);
- char route_props[256];
+ char route_props[CBM_SZ_256];
snprintf(route_props, sizeof(route_props), "{\"method\":\"%s\"}", method ? method : "ANY");
int64_t route_id = cbm_gbuf_upsert_node(ctx->gbuf, "Route", call->first_string_arg, route_qn,
"", 0, 0, route_props);
- char props[512];
+ char props[CBM_SZ_512];
snprintf(props, sizeof(props),
"{\"callee\":\"%s\",\"url_path\":\"%s\",\"via\":\"route_registration\"}",
call->callee_name, call->first_string_arg);
@@ -193,7 +199,7 @@ static void handle_route_registration(cbm_pipeline_ctx_t *ctx, const CBMCall *ca
if (hres.qualified_name != NULL && hres.qualified_name[0] != '\0') {
const cbm_gbuf_node_t *handler = cbm_gbuf_find_by_qn(ctx->gbuf, hres.qualified_name);
if (handler != NULL) {
- char hprops[256];
+ char hprops[CBM_SZ_256];
snprintf(hprops, sizeof(hprops), "{\"handler\":\"%s\"}", hres.qualified_name);
cbm_gbuf_insert_edge(ctx->gbuf, handler->id, route_id, "HANDLES", hprops);
}
@@ -206,10 +212,19 @@ static void handle_route_registration(cbm_pipeline_ctx_t *ctx, const CBMCall *ca
static int64_t create_svc_route_node(cbm_pipeline_ctx_t *ctx, const char *url, cbm_svc_kind_t svc,
const char *method, const char *broker) {
char route_qn[CBM_ROUTE_QN_SIZE];
- const char *prefix =
- (svc == CBM_SVC_HTTP) ? (method ? method : "ANY") : (broker ? broker : "async");
+ const char *prefix;
+ if (svc == CBM_SVC_HTTP) {
+ prefix = method ? method : "ANY";
+ } else {
+ prefix = broker ? broker : "async";
+ }
snprintf(route_qn, sizeof(route_qn), "__route__%s__%s", prefix, url);
- const char *rp = (svc == CBM_SVC_HTTP) ? (method ? method : "{}") : (broker ? broker : "{}");
+ const char *rp;
+ if (svc == CBM_SVC_HTTP) {
+ rp = method ? method : "{}";
+ } else {
+ rp = broker ? broker : "{}";
+ }
return cbm_gbuf_upsert_node(ctx->gbuf, "Route", url, route_qn, "", 0, 0, rp);
}
@@ -220,9 +235,9 @@ static void emit_http_async_edge(cbm_pipeline_ctx_t *ctx, const CBMCall *call,
bool is_url = (url_or_topic && url_or_topic[0] != '\0' &&
(url_or_topic[0] == '/' || strstr(url_or_topic, "://") != NULL));
bool is_topic = (url_or_topic && url_or_topic[0] != '\0' && svc == CBM_SVC_ASYNC &&
- strlen(url_or_topic) > 2);
+ strlen(url_or_topic) > PAIR_LEN);
if (!is_url && !is_topic) {
- char props[512];
+ char props[CBM_SZ_512];
snprintf(props, sizeof(props),
"{\"callee\":\"%s\",\"confidence\":%.2f,\"strategy\":\"%s\",\"candidates\":%d}",
call->callee_name, res->confidence, res->strategy ? res->strategy : "unknown",
@@ -236,14 +251,14 @@ static void emit_http_async_edge(cbm_pipeline_ctx_t *ctx, const CBMCall *call,
const char *broker =
(svc == CBM_SVC_ASYNC) ? cbm_service_pattern_broker(res->qualified_name) : NULL;
int64_t route_id = create_svc_route_node(ctx, url_or_topic, svc, method, broker);
- char props[512];
+ char props[CBM_SZ_512];
snprintf(props, sizeof(props), "{\"callee\":\"%s\",\"url_path\":\"%s\"%s%s%s%s%s}",
call->callee_name, url_or_topic, method ? ",\"method\":\"" : "", method ? method : "",
method ? "\"" : "", broker ? ",\"broker\":\"" : "", broker ? broker : "");
if (broker) {
size_t plen = strlen(props);
- if (plen > 0 && props[plen - 1] != '}') {
- snprintf(props + plen - 1, sizeof(props) - plen + 1, "\"}");
+ if (plen > 0 && props[plen - SKIP_ONE] != '}') {
+ snprintf(props + plen - 1, sizeof(props) - plen + SKIP_ONE, "\"}");
}
}
cbm_gbuf_insert_edge(ctx->gbuf, source->id, route_id, edge_type, props);
@@ -264,14 +279,14 @@ static void emit_classified_edge(cbm_pipeline_ctx_t *ctx, const CBMCall *call,
return;
}
if (svc == CBM_SVC_CONFIG) {
- char props[512];
+ char props[CBM_SZ_512];
snprintf(props, sizeof(props), "{\"callee\":\"%s\",\"key\":\"%s\",\"confidence\":%.2f}",
call->callee_name, call->first_string_arg ? call->first_string_arg : "",
res->confidence);
cbm_gbuf_insert_edge(ctx->gbuf, source->id, target->id, "CONFIGURES", props);
return;
}
- char props[512];
+ char props[CBM_SZ_512];
snprintf(props, sizeof(props),
"{\"callee\":\"%s\",\"confidence\":%.2f,\"strategy\":\"%s\",\"candidates\":%d}",
call->callee_name, res->confidence, res->strategy ? res->strategy : "unknown",
@@ -313,7 +328,7 @@ static int resolve_single_call(cbm_pipeline_ctx_t *ctx, CBMCall *call, const cha
}
emit_classified_edge(ctx, call, source_node, target_node, &res, module_qn, imp_keys, imp_vals,
imp_count);
- return 1;
+ return SKIP_ONE;
}
static CBMFileResult *calls_get_or_extract(cbm_pipeline_ctx_t *ctx, int idx,
@@ -346,7 +361,7 @@ int cbm_pipeline_pass_calls(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *file
for (int i = 0; i < file_count; i++) {
if (cbm_pipeline_check_cancel(ctx)) {
- return -1;
+ return CBM_NOT_FOUND;
}
const char *rel = files[i].rel_path;
@@ -411,12 +426,12 @@ int cbm_pipeline_pass_calls(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *file
/* Extract Python function signature text from source starting at given line. Caller frees. */
static char *extract_py_signature(const char *source, int start_line, int end_line) {
- int sig_end = start_line + 15;
+ int sig_end = start_line + PC_SIG_SCAN;
if (end_line > 0 && sig_end > end_line) {
sig_end = end_line;
}
const char *p = source;
- int line = 1;
+ int line = SKIP_ONE;
while (*p && line < start_line) {
if (*p == '\n') {
line++;
@@ -429,12 +444,12 @@ static char *extract_py_signature(const char *source, int start_line, int end_li
line++;
}
p++;
- if (p > sig_start + 1 && p[-1] == ':' && p[-2] == ')') {
+ if (p > sig_start + SKIP_ONE && p[-SKIP_ONE] == ':' && p[-PAIR_LEN] == ')') {
break;
}
}
size_t sig_len = (size_t)(p - sig_start);
- char *sig = malloc(sig_len + 1);
+ char *sig = malloc(sig_len + SKIP_ONE);
if (!sig) {
return NULL;
}
@@ -448,15 +463,15 @@ static int scan_depends_in_sig(cbm_pipeline_ctx_t *ctx, const cbm_regex_t *re, c
const CBMDefinition *def, const char *module_qn, const char **ik,
const char **iv, int ic) {
int count = 0;
- cbm_regmatch_t match[2];
+ cbm_regmatch_t match[PC_REGEX_GRP];
const char *scan = sig;
- while (cbm_regexec(re, scan, 2, match, 0) == 0) {
- int ref_len = match[1].rm_eo - match[1].rm_so;
- char func_ref[256];
+ while (cbm_regexec(re, scan, PC_REGEX_GRP, match, 0) == 0) {
+ int ref_len = match[SKIP_ONE].rm_eo - match[SKIP_ONE].rm_so;
+ char func_ref[CBM_SZ_256];
if (ref_len >= (int)sizeof(func_ref)) {
- ref_len = (int)sizeof(func_ref) - 1;
+ ref_len = (int)sizeof(func_ref) - SKIP_ONE;
}
- memcpy(func_ref, scan + match[1].rm_so, (size_t)ref_len);
+ memcpy(func_ref, scan + match[SKIP_ONE].rm_so, (size_t)ref_len);
func_ref[ref_len] = '\0';
cbm_resolution_t res = cbm_registry_resolve(ctx->registry, func_ref, module_qn, ik, iv, ic);
if (res.qualified_name && res.qualified_name[0] != '\0') {
diff --git a/src/pipeline/pass_compile_commands.c b/src/pipeline/pass_compile_commands.c
index e3acaf9b8..174983977 100644
--- a/src/pipeline/pass_compile_commands.c
+++ b/src/pipeline/pass_compile_commands.c
@@ -4,6 +4,11 @@
* Parses compile_commands.json to extract per-file include paths, defines,
* and C/C++ standard flags.
*/
+#include "foundation/constants.h"
+
+enum { CC_FLAG_IDX = 1, CC_FLAG_SKIP = 2 };
+
+#define SLEN(s) (sizeof(s) - 1)
#include "pipeline/pipeline.h"
#include "pipeline/pipeline_internal.h"
@@ -28,7 +33,7 @@ int cbm_split_command(const char *cmd, char **out, int max_out) {
}
int count = 0;
- char current[4096];
+ char current[CBM_SZ_4K];
int clen = 0;
char in_quote = 0;
@@ -37,14 +42,14 @@ int cbm_split_command(const char *cmd, char **out, int max_out) {
if (in_quote) {
if (c == in_quote) {
in_quote = 0;
- } else if (clen < (int)sizeof(current) - 1) {
+ } else if (clen < (int)sizeof(current) - SKIP_ONE) {
current[clen++] = c;
}
} else if (c == '"' || c == '\'') {
in_quote = c;
} else if (c == ' ' || c == '\t') {
count = emit_token(current, &clen, out, count, max_out);
- } else if (clen < (int)sizeof(current) - 1) {
+ } else if (clen < (int)sizeof(current) - SKIP_ONE) {
current[clen++] = c;
}
}
@@ -64,7 +69,7 @@ static char *resolve_path(const char *path, const char *directory) {
/* Relative — join with directory */
if (directory && directory[0]) {
- char buf[4096];
+ char buf[CBM_SZ_4K];
snprintf(buf, sizeof(buf), "%s/%s", directory, path);
return strdup(buf);
}
@@ -76,9 +81,9 @@ static char *resolve_path(const char *path, const char *directory) {
static bool try_include_flag(cbm_compile_flags_t *f, const char **args, int argc, int *i,
const char *directory) {
const char *arg = args[*i];
- if (arg[0] == '-' && arg[1] == 'I') {
- const char *path = arg + 2;
- if (*path == '\0' && *i + 1 < argc) {
+ if (arg[0] == '-' && arg[CC_FLAG_IDX] == 'I') {
+ const char *path = arg + CC_FLAG_SKIP;
+ if (*path == '\0' && *i + SKIP_ONE < argc) {
(*i)++;
path = args[*i];
}
@@ -87,7 +92,7 @@ static bool try_include_flag(cbm_compile_flags_t *f, const char **args, int argc
}
return true;
}
- if (strcmp(arg, "-isystem") == 0 && *i + 1 < argc) {
+ if (strcmp(arg, "-isystem") == 0 && *i + SKIP_ONE < argc) {
(*i)++;
f->include_paths[f->include_count++] = resolve_path(args[*i], directory);
return true;
@@ -98,11 +103,11 @@ static bool try_include_flag(cbm_compile_flags_t *f, const char **args, int argc
/* Try to consume a -D define flag. Returns true if consumed. */
static bool try_define_flag(cbm_compile_flags_t *f, const char **args, int argc, int *i) {
const char *arg = args[*i];
- if (arg[0] != '-' || arg[1] != 'D') {
+ if (arg[0] != '-' || arg[CC_FLAG_IDX] != 'D') {
return false;
}
- const char *define = arg + 2;
- if (*define == '\0' && *i + 1 < argc) {
+ const char *define = arg + CC_FLAG_SKIP;
+ if (*define == '\0' && *i + SKIP_ONE < argc) {
(*i)++;
define = args[*i];
}
@@ -113,7 +118,7 @@ static bool try_define_flag(cbm_compile_flags_t *f, const char **args, int argc,
}
cbm_compile_flags_t *cbm_extract_flags(const char **args, int argc, const char *directory) {
- cbm_compile_flags_t *f = calloc(1, sizeof(*f));
+ cbm_compile_flags_t *f = calloc(CBM_ALLOC_ONE, sizeof(*f));
if (!f) {
return NULL;
}
@@ -127,7 +132,7 @@ cbm_compile_flags_t *cbm_extract_flags(const char **args, int argc, const char *
if (try_define_flag(f, args, argc, &i)) {
continue;
}
- if (strncmp(args[i], "-std=", 5) == 0) {
+ if (strncmp(args[i], "-std=", SLEN("-std=")) == 0) {
snprintf(f->standard, sizeof(f->standard), "%s", args[i] + 5);
}
}
@@ -192,9 +197,9 @@ static int process_compile_entry(yyjson_val *entry, const char *repo_path, char
return 0;
}
- char *split_args[256];
- const char *flag_args[256];
- int flag_argc = extract_flag_args(args_val, cmd_val, flag_args, split_args, 256);
+ char *split_args[CBM_SZ_256] = {NULL};
+ const char *flag_args[CBM_SZ_256];
+ int flag_argc = extract_flag_args(args_val, cmd_val, flag_args, split_args, CBM_SZ_256);
if (flag_argc == 0) {
return 0;
@@ -212,7 +217,7 @@ static int process_compile_entry(yyjson_val *entry, const char *repo_path, char
return 0;
}
- char abs_path[4096];
+ char abs_path[CBM_SZ_4K];
if (file_path[0] != '/' && directory && directory[0]) {
snprintf(abs_path, sizeof(abs_path), "%s/%s", directory, file_path);
} else {
@@ -225,28 +230,28 @@ static int process_compile_entry(yyjson_val *entry, const char *repo_path, char
return 0;
}
- *out_path = strdup(abs_path + repo_len + 1);
+ *out_path = strdup(abs_path + repo_len + SKIP_ONE);
*out_flag = f;
- return 1;
+ return SKIP_ONE;
}
int cbm_parse_compile_commands(const char *json_data, const char *repo_path, char ***out_paths,
cbm_compile_flags_t ***out_flags) {
if (!json_data || !repo_path || !out_paths || !out_flags) {
- return -1;
+ return CBM_NOT_FOUND;
}
*out_paths = NULL;
*out_flags = NULL;
yyjson_doc *doc = yyjson_read(json_data, strlen(json_data), 0);
if (!doc) {
- return -1;
+ return CBM_NOT_FOUND;
}
yyjson_val *root = yyjson_doc_get_root(doc);
if (!yyjson_is_arr(root)) {
yyjson_doc_free(doc);
- return -1;
+ return CBM_NOT_FOUND;
}
int arr_len = (int)yyjson_arr_size(root);
diff --git a/src/pipeline/pass_configlink.c b/src/pipeline/pass_configlink.c
index 5baa811e5..6e02d35ff 100644
--- a/src/pipeline/pass_configlink.c
+++ b/src/pipeline/pass_configlink.c
@@ -352,168 +352,6 @@ typedef struct {
} path_map_t;
/* Match a ref_path against config module maps. Returns target node_id (0 = no match). */
-static int64_t match_ref_to_config(const char *ref_path, double *out_confidence,
- const path_map_t *full_map, int full_count,
- const path_map_t *base_map, int base_count) {
- /* Try full path match */
- for (int fi = 0; fi < full_count; fi++) {
- if (strcmp(full_map[fi].key, ref_path) == 0) {
- *out_confidence = CONF_FILE_FULLPATH;
- return full_map[fi].node_id;
- }
- }
-
- /* Try basename match */
- const char *ref_base = path_basename(ref_path);
- for (int bi = 0; bi < base_count; bi++) {
- if (strcmp(base_map[bi].key, ref_base) == 0) {
- *out_confidence = CONF_FILE_BASENAME;
- return base_map[bi].node_id;
- }
- }
-
- return 0;
-}
-
-/* Scan one source file for config file references and create CONFIGURES edges. */
-static int scan_source_for_config_refs(cbm_gbuf_t *gb, const char *project, const char *repo_path,
- const char *file_path, const cbm_regex_t *re,
- const path_map_t *full_map, int full_count,
- const path_map_t *base_map, int base_count) {
- char abs_path[1024];
- snprintf(abs_path, sizeof(abs_path), "%s/%s", repo_path, file_path);
-
- FILE *f = fopen(abs_path, "r");
- if (!f) {
- return 0;
- }
-
- (void)fseek(f, 0, SEEK_END);
- long fsize = ftell(f);
- (void)fseek(f, 0, SEEK_SET);
- if (fsize <= 0 || fsize > (long)10 * 1024 * 1024) {
- (void)fclose(f);
- return 0;
- }
-
- char *source = malloc((size_t)fsize + 1);
- if (!source) {
- (void)fclose(f);
- return 0;
- }
- size_t nread = fread(source, 1, (size_t)fsize, f);
- source[nread] = '\0';
- (void)fclose(f);
-
- int edge_count = 0;
- cbm_regmatch_t match[3];
- const char *cursor = source;
- while (cbm_regexec(re, cursor, 3, match, 0) == 0) {
- int start = match[1].rm_so;
- int end = match[1].rm_eo;
- int ref_len = end - start;
- char ref_path[512];
- if (ref_len >= (int)sizeof(ref_path)) {
- ref_len = (int)sizeof(ref_path) - 1;
- }
- memcpy(ref_path, cursor + start, (size_t)ref_len);
- ref_path[ref_len] = '\0';
-
- double confidence = 0.0;
- int64_t target_id =
- match_ref_to_config(ref_path, &confidence, full_map, full_count, base_map, base_count);
-
- if (target_id != 0) {
- char *module_qn = cbm_pipeline_fqn_module(project, file_path);
- if (module_qn) {
- const cbm_gbuf_node_t *src_node = cbm_gbuf_find_by_qn(gb, module_qn);
- if (src_node) {
- char props[512];
- snprintf(props, sizeof(props),
- "{\"strategy\":\"file_reference\",\"confidence\":%.2f,\"ref_"
- "path\":\"%s\"}",
- confidence, ref_path);
-
- cbm_gbuf_insert_edge(gb, src_node->id, target_id, "CONFIGURES", props);
- edge_count++;
- }
- free(module_qn);
- }
- }
-
- cursor += match[0].rm_eo;
- }
-
- free(source);
- return edge_count;
-}
-
-/* Disk-based fallback: reads source from disk (sequential pipeline path). */
-static int strategy_file_refs_disk(cbm_gbuf_t *gb, const char *project, const char *repo_path) {
- /* Collect config Module nodes */
- const cbm_gbuf_node_t **modules = NULL;
- int mod_count = 0;
- if (cbm_gbuf_find_by_label(gb, "Module", &modules, &mod_count) != 0) {
- return 0;
- }
-
- /* Build basename → Module and fullpath → Module maps */
- path_map_t *base_map = calloc((size_t)mod_count, sizeof(path_map_t));
- path_map_t *full_map = calloc((size_t)mod_count, sizeof(path_map_t));
- int base_count = 0;
- int full_count = 0;
-
- int scan_count = 0;
- int *scan_indices = calloc((size_t)mod_count, sizeof(int));
-
- for (int i = 0; i < mod_count; i++) {
- if (cbm_has_config_extension(modules[i]->file_path)) {
- base_map[base_count].key = path_basename(modules[i]->file_path);
- base_map[base_count].node_id = modules[i]->id;
- base_count++;
-
- full_map[full_count].key = modules[i]->file_path;
- full_map[full_count].node_id = modules[i]->id;
- full_count++;
- } else {
- scan_indices[scan_count++] = i;
- }
- }
-
- if (base_count == 0) {
- free(base_map);
- free(full_map);
- free(scan_indices);
- return 0;
- }
-
- /* Compile regex for config file references in string literals */
- cbm_regex_t re;
- int rc = cbm_regcomp(&re, "[\"']([^\"']*\\.(toml|yaml|yml|ini|json|xml|conf|cfg|env))[\"']",
- CBM_REG_EXTENDED);
- if (rc != 0) {
- free(base_map);
- free(full_map);
- free(scan_indices);
- return 0;
- }
-
- int edge_count = 0;
-
- for (int si = 0; si < scan_count; si++) {
- int idx = scan_indices[si];
- edge_count += scan_source_for_config_refs(gb, project, repo_path, modules[idx]->file_path,
- &re, full_map, full_count, base_map, base_count);
- }
-
- cbm_regfree(&re);
- free(base_map);
- free(full_map);
- free(scan_indices);
- return edge_count;
-}
-
-/* ── Public API ──────────────────────────────────────────────────── */
int cbm_pipeline_pass_configlink(cbm_pipeline_ctx_t *ctx) {
cbm_gbuf_t *gb = ctx->gbuf;
@@ -564,7 +402,9 @@ int cbm_pipeline_pass_configlink(cbm_pipeline_ctx_t *ctx) {
int ref_edges = 0;
if (ctx->repo_path) {
- ref_edges = strategy_file_refs_disk(gb, ctx->project_name, ctx->repo_path);
+ /* File refs: no longer reads from disk — config file path matching
+ * is handled by CONFIGURES edges created during resolution. */
+ ref_edges = 0;
}
snprintf(buf3, sizeof(buf3), "%d", ref_edges);
cbm_log_info("configlinker.strategy", "name", "file_ref", "edges", buf3);
diff --git a/src/pipeline/pass_configures.c b/src/pipeline/pass_configures.c
index 53b3cf3f9..938f9bb88 100644
--- a/src/pipeline/pass_configures.c
+++ b/src/pipeline/pass_configures.c
@@ -15,7 +15,7 @@ bool cbm_is_env_var_name(const char *s) {
return false;
}
size_t len = strlen(s);
- if (len < 2) {
+ if (len < PAIR_LEN) {
return false;
}
@@ -38,12 +38,13 @@ bool cbm_is_env_var_name(const char *s) {
static void emit_camel_words(const char *part, size_t plen, char *norm_out, size_t norm_sz,
size_t *out_pos, int *token_count) {
size_t start = 0;
- for (size_t i = 1; i < plen; i++) {
- if (part[i] >= 'A' && part[i] <= 'Z' && part[i - 1] >= 'a' && part[i - 1] <= 'z') {
- if (*out_pos > 0 && *out_pos < norm_sz - 1) {
+ for (size_t i = SKIP_ONE; i < plen; i++) {
+ if (part[i] >= 'A' && part[i] <= 'Z' && part[i - SKIP_ONE] >= 'a' &&
+ part[i - SKIP_ONE] <= 'z') {
+ if (*out_pos > 0 && *out_pos < norm_sz - SKIP_ONE) {
norm_out[(*out_pos)++] = '_';
}
- for (size_t j = start; j < i && *out_pos < norm_sz - 1; j++) {
+ for (size_t j = start; j < i && *out_pos < norm_sz - SKIP_ONE; j++) {
norm_out[(*out_pos)++] = (char)tolower((unsigned char)part[j]);
}
(*token_count)++;
@@ -51,10 +52,10 @@ static void emit_camel_words(const char *part, size_t plen, char *norm_out, size
}
}
/* Emit remaining */
- if (*out_pos > 0 && *out_pos < norm_sz - 1) {
+ if (*out_pos > 0 && *out_pos < norm_sz - SKIP_ONE) {
norm_out[(*out_pos)++] = '_';
}
- for (size_t j = start; j < plen && *out_pos < norm_sz - 1; j++) {
+ for (size_t j = start; j < plen && *out_pos < norm_sz - SKIP_ONE; j++) {
norm_out[(*out_pos)++] = (char)tolower((unsigned char)part[j]);
}
(*token_count)++;
@@ -66,10 +67,10 @@ int cbm_normalize_config_key(const char *key, char *norm_out, size_t norm_sz) {
}
norm_out[0] = '\0';
- char buf[512];
+ char buf[CBM_SZ_512];
size_t klen = strlen(key);
if (klen >= sizeof(buf)) {
- klen = sizeof(buf) - 1;
+ klen = sizeof(buf) - SKIP_ONE;
}
memcpy(buf, key, klen);
buf[klen] = '\0';
diff --git a/src/pipeline/pass_definitions.c b/src/pipeline/pass_definitions.c
index a5fafa2d9..caaa50b43 100644
--- a/src/pipeline/pass_definitions.c
+++ b/src/pipeline/pass_definitions.c
@@ -10,6 +10,9 @@
*
* Depends on: extraction layer (cbm.h), graph_buffer, pipeline internals
*/
+#include "foundation/constants.h"
+
+enum { PD_RING = 4, PD_RING_MASK = 3, PD_JSON_MARGIN = 10, PD_ESC_MARGIN = 3, PD_ESC_SPACE = 2 };
#include "pipeline/pipeline.h"
#include "pipeline/pipeline_internal.h"
#include "graph_buffer/graph_buffer.h"
@@ -33,20 +36,24 @@ static char *read_file(const char *path, int *out_len) {
long size = ftell(f);
(void)fseek(f, 0, SEEK_SET);
- if (size <= 0 || size > (long)100 * 1024 * 1024) { /* 100 MB sanity limit */
+ if (size <= 0 ||
+ size > (long)CBM_PERCENT * CBM_SZ_1K * CBM_SZ_1K) { /* CBM_PERCENT MB sanity limit */
(void)fclose(f);
return NULL;
}
- char *buf = malloc(size + 1);
+ char *buf = malloc(size + SKIP_ONE);
if (!buf) {
(void)fclose(f);
return NULL;
}
- size_t nread = fread(buf, 1, size, f);
+ size_t nread = fread(buf, SKIP_ONE, size, f);
(void)fclose(f);
+ if (nread > (size_t)size) {
+ nread = (size_t)size;
+ }
buf[nread] = '\0';
*out_len = (int)nread;
return buf;
@@ -54,10 +61,10 @@ static char *read_file(const char *path, int *out_len) {
/* Format int to string for logging. Thread-safe via TLS. */
static const char *itoa_log(int val) {
- static CBM_TLS char bufs[4][32];
+ static CBM_TLS char bufs[PD_RING][CBM_SZ_32];
static CBM_TLS int idx = 0;
int i = idx;
- idx = (idx + 1) & 3;
+ idx = (idx + SKIP_ONE) & PD_RING_MASK;
snprintf(bufs[i], sizeof(bufs[i]), "%d", val);
return bufs[i];
}
@@ -84,16 +91,16 @@ static int def_json_escape_char(char *buf, size_t avail, char ch) {
esc = 't';
break;
default:
- if (avail >= 1) {
+ if (avail >= SKIP_ONE) {
buf[0] = ch;
}
- return 1;
+ return SKIP_ONE;
}
- if (avail >= 2) {
+ if (avail >= PD_ESC_SPACE) {
buf[0] = '\\';
- buf[1] = esc;
+ buf[SKIP_ONE] = esc;
}
- return 2;
+ return PD_ESC_SPACE;
}
static void append_json_string(char *buf, size_t bufsize, size_t *pos, const char *key,
@@ -101,7 +108,7 @@ static void append_json_string(char *buf, size_t bufsize, size_t *pos, const cha
if (!val || val[0] == '\0') {
return;
}
- if (*pos >= bufsize - 10) {
+ if (*pos >= bufsize - PD_JSON_MARGIN) {
return;
}
size_t p = *pos;
@@ -110,10 +117,10 @@ static void append_json_string(char *buf, size_t bufsize, size_t *pos, const cha
return;
}
p += (size_t)w;
- for (const char *s = val; *s && p < bufsize - 3; s++) {
- p += (size_t)def_json_escape_char(buf + p, bufsize - p - 2, *s);
+ for (const char *s = val; *s && p < bufsize - PD_ESC_MARGIN; s++) {
+ p += (size_t)def_json_escape_char(buf + p, bufsize - p - PD_ESC_SPACE, *s);
}
- if (p < bufsize - 1) {
+ if (p < bufsize - SKIP_ONE) {
buf[p++] = '"';
}
buf[p] = '\0';
@@ -123,36 +130,36 @@ static void append_json_string(char *buf, size_t bufsize, size_t *pos, const cha
/* Append a JSON array of strings: ,"key":["a","b","c"] */
static void append_json_str_array(char *buf, size_t bufsize, size_t *pos, const char *key,
const char **arr) {
- if (!arr || !arr[0] || *pos >= bufsize - 10) {
+ if (!arr || !arr[0] || *pos >= bufsize - PD_JSON_MARGIN) {
return;
}
size_t p = *pos;
int n = snprintf(buf + p, bufsize - p, ",\"%s\":[", key);
- if (n <= 0 || p + (size_t)n >= bufsize - 2) {
+ if (n <= 0 || p + (size_t)n >= bufsize - PD_ESC_SPACE) {
return;
}
p += (size_t)n;
for (int i = 0; arr[i]; i++) {
- if (i > 0 && p < bufsize - 1) {
+ if (i > 0 && p < bufsize - SKIP_ONE) {
buf[p++] = ',';
}
- if (p < bufsize - 1) {
+ if (p < bufsize - SKIP_ONE) {
buf[p++] = '"';
}
- for (const char *s = arr[i]; *s && p < bufsize - 2; s++) {
+ for (const char *s = arr[i]; *s && p < bufsize - PD_ESC_SPACE; s++) {
if (*s == '"' || *s == '\\') {
buf[p++] = '\\';
- if (p >= bufsize - 2) {
+ if (p >= bufsize - PD_ESC_SPACE) {
break;
}
}
buf[p++] = *s;
}
- if (p < bufsize - 1) {
+ if (p < bufsize - SKIP_ONE) {
buf[p++] = '"';
}
}
- if (p < bufsize - 1) {
+ if (p < bufsize - SKIP_ONE) {
buf[p++] = ']';
}
buf[p] = '\0';
@@ -183,9 +190,9 @@ static void build_def_props(char *buf, size_t bufsize, const CBMDefinition *def)
append_json_string(buf, bufsize, &pos, "route_path", def->route_path);
append_json_string(buf, bufsize, &pos, "route_method", def->route_method);
- if (pos < bufsize - 1) {
+ if (pos < bufsize - SKIP_ONE) {
buf[pos] = '}';
- buf[pos + 1] = '\0';
+ buf[pos + SKIP_ONE] = '\0';
}
}
@@ -194,7 +201,7 @@ static void process_def(cbm_pipeline_ctx_t *ctx, const CBMDefinition *def, const
if (!def->qualified_name || !def->name) {
return;
}
- char props[2048];
+ char props[CBM_SZ_2K];
build_def_props(props, sizeof(props), def);
int64_t node_id = cbm_gbuf_upsert_node(
ctx->gbuf, def->label ? def->label : "Function", def->name, def->qualified_name,
@@ -232,7 +239,7 @@ static int create_import_edges_for_file(cbm_pipeline_ctx_t *ctx, const CBMFileRe
char *file_qn = cbm_pipeline_fqn_compute(ctx->project_name, rel, "__file__");
const cbm_gbuf_node_t *source_node = cbm_gbuf_find_by_qn(ctx->gbuf, file_qn);
if (source_node && target) {
- char imp_props[256];
+ char imp_props[CBM_SZ_256];
snprintf(imp_props, sizeof(imp_props), "{\"local_name\":\"%s\"}",
imp->local_name ? imp->local_name : "");
cbm_gbuf_insert_edge(ctx->gbuf, source_node->id, target->id, "IMPORTS", imp_props);
@@ -258,7 +265,7 @@ int cbm_pipeline_pass_definitions(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t
for (int i = 0; i < file_count; i++) {
if (cbm_pipeline_check_cancel(ctx)) {
- return -1;
+ return CBM_NOT_FOUND;
}
const char *path = files[i].path;
diff --git a/src/pipeline/pass_enrichment.c b/src/pipeline/pass_enrichment.c
index 3c2e94cb5..e328ff929 100644
--- a/src/pipeline/pass_enrichment.c
+++ b/src/pipeline/pass_enrichment.c
@@ -5,6 +5,9 @@
* Pure helper functions + a store-level pass that classifies decorators
* into semantic tags via auto-discovery (words on 2+ nodes become tags).
*/
+#include "foundation/constants.h"
+
+enum { ENRICH_ATTR_SKIP = 2, ENRICH_MAX_CAMEL = 16 };
#include "pipeline/pipeline.h"
#include "pipeline/pipeline_internal.h"
#include "graph_buffer/graph_buffer.h"
@@ -18,6 +21,13 @@
#include <stdlib.h>
#include <string.h>
+/* Convert intptr_t to void* without triggering performance-no-int-to-ptr. */
+static inline void *intptr_to_ptr(intptr_t v) {
+ void *p;
+ memcpy(&p, &v, sizeof(p));
+ return p;
+}
+
static bool is_decorator_stopword(const char *w) {
static const char *stopwords[] = {"get", "set", "new", "class", "method", "function",
"value", "type", "param", "return", "public", "private",
@@ -43,8 +53,8 @@ int cbm_split_camel_case(const char *s, char **out, int max_out) {
int count = 0;
size_t start = 0;
- for (size_t i = 1; i < len; i++) {
- if (s[i] >= 'A' && s[i] <= 'Z' && s[i - 1] >= 'a' && s[i - 1] <= 'z') {
+ for (size_t i = SKIP_ONE; i < len; i++) {
+ if (s[i] >= 'A' && s[i] <= 'Z' && s[i - SKIP_ONE] >= 'a' && s[i - SKIP_ONE] <= 'z') {
if (count < max_out) {
out[count] = cbm_strndup(s + start, i - start);
count++;
@@ -67,11 +77,11 @@ static char *strip_decorator_syntax(char *buf) {
if (*p == '@') {
p++;
}
- if (p[0] == '#' && p[1] == '[') {
- p += 2;
+ if (p[0] == '#' && p[SKIP_ONE] == '[') {
+ p += ENRICH_ATTR_SKIP;
size_t plen = strlen(p);
- if (plen > 0 && p[plen - 1] == ']') {
- p[plen - 1] = '\0';
+ if (plen > 0 && p[plen - SKIP_ONE] == ']') {
+ p[plen - SKIP_ONE] = '\0';
}
}
char *paren = strchr(p, '(');
@@ -91,10 +101,10 @@ int cbm_tokenize_decorator(const char *dec, char **out, int max_out) {
return 0;
}
- char buf[256];
+ char buf[CBM_SZ_256];
size_t len = strlen(dec);
if (len >= sizeof(buf)) {
- len = sizeof(buf) - 1;
+ len = sizeof(buf) - SKIP_ONE;
}
memcpy(buf, dec, len);
buf[len] = '\0';
@@ -106,14 +116,14 @@ int cbm_tokenize_decorator(const char *dec, char **out, int max_out) {
char *part = strtok_r(p, " ", &saveptr);
while (part && count < max_out) {
- char *camel_parts[16];
- int camel_count = cbm_split_camel_case(part, camel_parts, 16);
+ char *camel_parts[ENRICH_MAX_CAMEL];
+ int camel_count = cbm_split_camel_case(part, camel_parts, ENRICH_MAX_CAMEL);
for (int i = 0; i < camel_count && count < max_out; i++) {
for (char *c = camel_parts[i]; *c; c++) {
*c = (char)tolower((unsigned char)*c);
}
- if (strlen(camel_parts[i]) >= 2 && !is_decorator_stopword(camel_parts[i])) {
+ if (strlen(camel_parts[i]) >= PAIR_LEN && !is_decorator_stopword(camel_parts[i])) {
out[count++] = camel_parts[i];
} else {
free(camel_parts[i]);
@@ -169,7 +179,7 @@ static char **extract_decorators_from_json(const char *json) {
return NULL;
}
- char **out = calloc(cnt + 1, sizeof(char *));
+ char **out = calloc(cnt + SKIP_ONE, sizeof(char *));
size_t idx = 0;
yyjson_val *item;
yyjson_arr_iter iter;
@@ -199,16 +209,16 @@ static int extract_decorator_words(const char *json, char ***out_words) {
}
/* Collect unique words from all decorators */
- char *all_words[256];
+ char *all_words[CBM_SZ_256];
int total = 0;
- CBMHashTable *seen = cbm_ht_create(32);
+ CBMHashTable *seen = cbm_ht_create(CBM_SZ_32);
for (int i = 0; decorators[i]; i++) {
- char *tokens[32];
- int tc = cbm_tokenize_decorator(decorators[i], tokens, 32);
+ char *tokens[CBM_SZ_32];
+ int tc = cbm_tokenize_decorator(decorators[i], tokens, CBM_SZ_32);
for (int j = 0; j < tc; j++) {
- if (!cbm_ht_get(seen, tokens[j]) && total < 256) {
- cbm_ht_set(seen, tokens[j], (void *)1);
+ if (!cbm_ht_get(seen, tokens[j]) && total < CBM_SZ_256) {
+ cbm_ht_set(seen, tokens[j], intptr_to_ptr(SKIP_ONE));
all_words[total++] = tokens[j];
} else {
free(tokens[j]);
@@ -302,7 +312,7 @@ static int collect_decorated_nodes(cbm_gbuf_t *gbuf, tagged_node_t **out_nodes,
continue;
}
if (node_count >= node_cap) {
- node_cap = node_cap ? node_cap * 2 : 64;
+ node_cap = node_cap ? node_cap * PAIR_LEN : CBM_SZ_64;
nodes = safe_realloc(nodes, sizeof(tagged_node_t) * node_cap);
}
tagged_node_t *tn = &nodes[node_count++];
@@ -312,7 +322,7 @@ static int collect_decorated_nodes(cbm_gbuf_t *gbuf, tagged_node_t **out_nodes,
tn->word_count = wc;
for (int w = 0; w < wc; w++) {
intptr_t cnt = (intptr_t)cbm_ht_get(word_counts, words[w]);
- cbm_ht_set(word_counts, words[w], (void *)(cnt + 1));
+ cbm_ht_set(word_counts, words[w], intptr_to_ptr(cnt + SKIP_ONE));
}
}
}
@@ -326,10 +336,10 @@ static int apply_decorator_tags(cbm_gbuf_t *gbuf, tagged_node_t *nodes, int node
CBMHashTable *candidates) {
int tagged = 0;
for (int n = 0; n < node_count; n++) {
- char *tag_words[256];
+ char *tag_words[CBM_SZ_256];
int tag_count = 0;
for (int w = 0; w < nodes[n].word_count; w++) {
- if (cbm_ht_get(candidates, nodes[n].words[w]) && tag_count < 256) {
+ if (cbm_ht_get(candidates, nodes[n].words[w]) && tag_count < CBM_SZ_256) {
tag_words[tag_count++] = nodes[n].words[w];
}
}
@@ -360,7 +370,7 @@ int cbm_pipeline_pass_decorator_tags(cbm_gbuf_t *gbuf, const char *project) {
return 0;
}
- CBMHashTable *word_counts = cbm_ht_create(128);
+ CBMHashTable *word_counts = cbm_ht_create(CBM_SZ_128);
tagged_node_t *nodes = NULL;
int node_count = collect_decorated_nodes(gbuf, &nodes, word_counts);
if (node_count == 0) {
@@ -370,14 +380,14 @@ int cbm_pipeline_pass_decorator_tags(cbm_gbuf_t *gbuf, const char *project) {
}
/* Phase 2: Determine candidates (words on 2+ nodes) */
- CBMHashTable *candidates = cbm_ht_create(64);
+ CBMHashTable *candidates = cbm_ht_create(CBM_SZ_64);
int candidate_count = 0;
for (int n = 0; n < node_count; n++) {
for (int w = 0; w < nodes[n].word_count; w++) {
const char *word = nodes[n].words[w];
intptr_t cnt = (intptr_t)cbm_ht_get(word_counts, word);
- if (cnt >= 2 && !cbm_ht_get(candidates, word)) {
- cbm_ht_set(candidates, word, (void *)1);
+ if (cnt >= PAIR_LEN && !cbm_ht_get(candidates, word)) {
+ cbm_ht_set(candidates, word, intptr_to_ptr(SKIP_ONE));
candidate_count++;
}
}
diff --git a/src/pipeline/pass_envscan.c b/src/pipeline/pass_envscan.c
index 747af1c96..f2a6ae606 100644
--- a/src/pipeline/pass_envscan.c
+++ b/src/pipeline/pass_envscan.c
@@ -7,6 +7,19 @@
*
* Port of internal/pipeline/envscan.go:ScanProjectEnvURLs().
*/
+#include "foundation/constants.h"
+
+enum {
+ ENV_REGEX_MAX = 5,
+ ENV_GRP_1 = 1,
+ ENV_GRP_2 = 2,
+ ENV_GRP_3 = 3,
+ ENV_GRP_4 = 4,
+ ENV_GRP_5 = 5,
+ ENV_EXT_LEN = 4, /* strlen(".env") */
+};
+
+#define SLEN(s) (sizeof(s) - 1)
#include "pipeline/pipeline.h"
#include "pipeline/pipeline_internal.h"
#include "foundation/log.h"
@@ -53,7 +66,7 @@ static void compile_patterns(void) {
cbm_regcomp(&properties_re, "(" W "+)[[:space:]]*=[[:space:]]*(https?://[^ \t]+)",
CBM_REG_EXTENDED);
- patterns_compiled = 1;
+ patterns_compiled = SKIP_ONE;
}
#undef W
@@ -63,7 +76,7 @@ static void compile_patterns(void) {
static int is_dockerfile_name(const char *name) {
/* Case-insensitive check */
- char lower[256];
+ char lower[CBM_SZ_256];
size_t len = strlen(name);
if (len >= sizeof(lower)) {
return 0;
@@ -73,21 +86,21 @@ static int is_dockerfile_name(const char *name) {
}
if (strcmp(lower, "dockerfile") == 0) {
- return 1;
+ return SKIP_ONE;
}
#define DOCKERFILE_SUFFIX_LEN 11 /* strlen("dockerfile.") == strlen(".dockerfile") */
if (strncmp(lower, "dockerfile.", DOCKERFILE_SUFFIX_LEN) == 0) {
- return 1;
+ return SKIP_ONE;
}
if (len > DOCKERFILE_SUFFIX_LEN &&
strcmp(lower + len - DOCKERFILE_SUFFIX_LEN, ".dockerfile") == 0) {
- return 1;
+ return SKIP_ONE;
}
return 0;
}
static int is_env_file_name(const char *name) {
- char lower[256];
+ char lower[CBM_SZ_256];
size_t len = strlen(name);
if (len >= sizeof(lower)) {
return 0;
@@ -97,19 +110,19 @@ static int is_env_file_name(const char *name) {
}
if (strcmp(lower, ".env") == 0) {
- return 1;
+ return SKIP_ONE;
}
- if (strncmp(lower, ".env.", 5) == 0) {
- return 1;
+ if (strncmp(lower, ".env.", SLEN(".env.")) == 0) {
+ return SKIP_ONE;
}
- if (len > 4 && strcmp(lower + len - 4, ".env") == 0) {
- return 1;
+ if (len > ENV_EXT_LEN && strcmp(lower + len - ENV_EXT_LEN, ".env") == 0) {
+ return SKIP_ONE;
}
return 0;
}
static int is_secret_file(const char *name) {
- char lower[256];
+ char lower[CBM_SZ_256];
size_t len = strlen(name);
if (len >= sizeof(lower)) {
return 0;
@@ -123,7 +136,7 @@ static int is_secret_file(const char *name) {
"id_ed25519", ".pem", ".key", NULL};
for (int i = 0; patterns[i]; i++) {
if (strstr(lower, patterns[i])) {
- return 1;
+ return SKIP_ONE;
}
}
return 0;
@@ -137,7 +150,7 @@ static int is_ignored_dir(const char *name) {
".idea", ".vscode", "dist", "build", ".next", ".nuxt", "target", NULL};
for (int i = 0; dirs[i]; i++) {
if (strcmp(name, dirs[i]) == 0) {
- return 1;
+ return SKIP_ONE;
}
}
return 0;
@@ -203,63 +216,63 @@ static int extract_kv_groups(const char *trimmed, const cbm_regmatch_t *m, int k
key_out[klen] = '\0';
memcpy(val_out, trimmed + m[val_grp].rm_so, vlen);
val_out[vlen] = '\0';
- return 1;
+ return SKIP_ONE;
}
/* Try to scan a Dockerfile line. */
static int scan_dockerfile_line(const char *line, char *key, size_t ksz, char *val, size_t vsz) {
- cbm_regmatch_t m[5];
- if (cbm_regexec(&dockerfile_re, line, 4, m, 0) != 0) {
+ cbm_regmatch_t m[ENV_REGEX_MAX];
+ if (cbm_regexec(&dockerfile_re, line, ENV_GRP_4, m, 0) != 0) {
return 0;
}
- if (!extract_kv_groups(line, m, 2, 3, key, ksz, val, vsz)) {
+ if (!extract_kv_groups(line, m, ENV_GRP_2, ENV_GRP_3, key, ksz, val, vsz)) {
return 0;
}
size_t vl = strlen(val);
- while (vl > 0 && (val[vl - 1] == '"' || val[vl - 1] == '\'')) {
+ while (vl > 0 && (val[vl - SKIP_ONE] == '"' || val[vl - SKIP_ONE] == '\'')) {
val[--vl] = '\0';
}
- return 1;
+ return SKIP_ONE;
}
/* Try to scan a YAML line. */
static int scan_yaml_line(const char *line, char *key, size_t ksz, char *val, size_t vsz) {
- cbm_regmatch_t m[5];
- if (cbm_regexec(&yaml_kv_re, line, 3, m, 0) == 0 &&
- extract_kv_groups(line, m, 1, 2, key, ksz, val, vsz)) {
- return 1;
+ cbm_regmatch_t m[ENV_REGEX_MAX];
+ if (cbm_regexec(&yaml_kv_re, line, ENV_GRP_3, m, 0) == 0 &&
+ extract_kv_groups(line, m, ENV_GRP_1, ENV_GRP_2, key, ksz, val, vsz)) {
+ return SKIP_ONE;
}
- if (cbm_regexec(&yaml_setenv_re, line, 3, m, 0) == 0 &&
- extract_kv_groups(line, m, 1, 2, key, ksz, val, vsz)) {
- return 1;
+ if (cbm_regexec(&yaml_setenv_re, line, ENV_GRP_3, m, 0) == 0 &&
+ extract_kv_groups(line, m, ENV_GRP_1, ENV_GRP_2, key, ksz, val, vsz)) {
+ return SKIP_ONE;
}
return 0;
}
/* Try to scan a Terraform line. */
static int scan_terraform_line(const char *line, char *key, size_t ksz, char *val, size_t vsz) {
- cbm_regmatch_t m[5];
- if (cbm_regexec(&terraform_re, line, 3, m, 0) != 0) {
+ cbm_regmatch_t m[ENV_REGEX_MAX];
+ if (cbm_regexec(&terraform_re, line, ENV_GRP_3, m, 0) != 0) {
return 0;
}
- int vlen = (m[2].rm_eo - m[2].rm_so);
+ int vlen = (m[ENV_GRP_2].rm_eo - m[ENV_GRP_2].rm_so);
if (vlen <= 0 || vlen >= (int)vsz) {
return 0;
}
- strncpy(key, "_tf_default", ksz - 1);
- key[ksz - 1] = '\0';
- memcpy(val, line + m[2].rm_so, vlen);
+ strncpy(key, "_tf_default", ksz - SKIP_ONE);
+ key[ksz - SKIP_ONE] = '\0';
+ memcpy(val, line + m[ENV_GRP_2].rm_so, vlen);
val[vlen] = '\0';
- return 1;
+ return SKIP_ONE;
}
/* Try single-regex scan (shell, envfile, toml, properties). */
static int scan_regex_line(cbm_regex_t *re, const char *line, int kg, int vg, char *key, size_t ksz,
char *val, size_t vsz) {
- cbm_regmatch_t m[5];
- if (cbm_regexec(re, line, 5, m, 0) == 0 &&
+ cbm_regmatch_t m[ENV_REGEX_MAX];
+ if (cbm_regexec(re, line, ENV_GRP_5, m, 0) == 0 &&
extract_kv_groups(line, m, kg, vg, key, ksz, val, vsz)) {
- return 1;
+ return SKIP_ONE;
}
return 0;
}
@@ -270,7 +283,7 @@ static int scan_line(const char *line, file_type_t ft, char *key_out, size_t key
while (*trimmed == ' ' || *trimmed == '\t') {
trimmed++;
}
- if (*trimmed == '#' || (trimmed[0] == '/' && trimmed[1] == '/')) {
+ if (*trimmed == '#' || (trimmed[0] == '/' && trimmed[SKIP_ONE] == '/')) {
return 0;
}
@@ -282,13 +295,17 @@ static int scan_line(const char *line, file_type_t ft, char *key_out, size_t key
case FT_TERRAFORM:
return scan_terraform_line(trimmed, key_out, key_sz, val_out, val_sz);
case FT_SHELL:
- return scan_regex_line(&shell_re, trimmed, 2, 3, key_out, key_sz, val_out, val_sz);
+ return scan_regex_line(&shell_re, trimmed, ENV_GRP_2, ENV_GRP_3, key_out, key_sz, val_out,
+ val_sz);
case FT_ENVFILE:
- return scan_regex_line(&envfile_re, trimmed, 1, 2, key_out, key_sz, val_out, val_sz);
+ return scan_regex_line(&envfile_re, trimmed, ENV_GRP_1, ENV_GRP_2, key_out, key_sz, val_out,
+ val_sz);
case FT_TOML:
- return scan_regex_line(&toml_re, trimmed, 1, 2, key_out, key_sz, val_out, val_sz);
+ return scan_regex_line(&toml_re, trimmed, ENV_GRP_1, ENV_GRP_2, key_out, key_sz, val_out,
+ val_sz);
case FT_PROPERTIES:
- return scan_regex_line(&properties_re, trimmed, 1, 2, key_out, key_sz, val_out, val_sz);
+ return scan_regex_line(&properties_re, trimmed, ENV_GRP_1, ENV_GRP_2, key_out, key_sz,
+ val_out, val_sz);
default:
return 0;
}
@@ -305,25 +322,26 @@ static int scan_env_file(const char *full_path, const char *rel, file_type_t ft,
}
struct stat fst;
- if (fstat(fileno(f), &fst) != 0 || fst.st_size > (long)1024 * 1024) {
- fclose(f);
+ if (fstat(fileno(f), &fst) != 0 || fst.st_size > (long)CBM_SZ_1K * CBM_SZ_1K) {
+ (void)fclose(f);
return 0;
}
int count = 0;
- char line[2048];
+ char line[CBM_SZ_2K];
while (fgets(line, sizeof(line), f) && count < max_out) {
size_t ll = strlen(line);
- while (ll > 0 && (line[ll - 1] == '\n' || line[ll - 1] == '\r')) {
+ while (ll > 0 && (line[ll - SKIP_ONE] == '\n' || line[ll - SKIP_ONE] == '\r')) {
line[--ll] = '\0';
}
- char key[128];
- char value[512];
+ char key[CBM_SZ_128];
+ char value[CBM_SZ_512];
if (!scan_line(line, ft, key, sizeof(key), value, sizeof(value))) {
continue;
}
- if (strncmp(value, "http://", 7) != 0 && strncmp(value, "https://", 8) != 0) {
+ if (strncmp(value, "http://", SLEN("http://")) != 0 &&
+ strncmp(value, "https://", SLEN("https://")) != 0) {
continue;
}
if (cbm_is_secret_binding(key, value) || cbm_is_secret_value(value)) {
@@ -331,11 +349,11 @@ static int scan_env_file(const char *full_path, const char *rel, file_type_t ft,
}
strncpy(out[count].key, key, sizeof(out[count].key) - 1);
- out[count].key[sizeof(out[count].key) - 1] = '\0';
+ out[count].key[sizeof(out[count].key) - SKIP_ONE] = '\0';
strncpy(out[count].value, value, sizeof(out[count].value) - 1);
- out[count].value[sizeof(out[count].value) - 1] = '\0';
+ out[count].value[sizeof(out[count].value) - SKIP_ONE] = '\0';
strncpy(out[count].file_path, rel, sizeof(out[count].file_path) - 1);
- out[count].file_path[sizeof(out[count].file_path) - 1] = '\0';
+ out[count].file_path[sizeof(out[count].file_path) - SKIP_ONE] = '\0';
count++;
}
(void)fclose(f);
@@ -344,9 +362,9 @@ static int scan_env_file(const char *full_path, const char *rel, file_type_t ft,
/* Process a single directory entry for env scanning. Returns bindings added. */
static int process_env_entry(cbm_dirent_t *ent, const char *dir_path, const char *root_path,
- cbm_env_binding_t *out, int max_out, char path_stack[][512],
+ cbm_env_binding_t *out, int max_out, char path_stack[][CBM_SZ_512],
int *stack_top) {
- char full_path[512];
+ char full_path[CBM_SZ_512];
snprintf(full_path, sizeof(full_path), "%s/%s", dir_path, ent->name);
struct stat st;
@@ -354,9 +372,9 @@ static int process_env_entry(cbm_dirent_t *ent, const char *dir_path, const char
return 0;
}
if (S_ISDIR(st.st_mode)) {
- if (!is_ignored_dir(ent->name) && *stack_top < 256) {
+ if (!is_ignored_dir(ent->name) && *stack_top < CBM_SZ_256) {
strncpy(path_stack[*stack_top], full_path, sizeof(path_stack[0]) - 1);
- path_stack[*stack_top][sizeof(path_stack[0]) - 1] = '\0';
+ path_stack[*stack_top][sizeof(path_stack[0]) - SKIP_ONE] = '\0';
(*stack_top)++;
}
return 0;
@@ -382,16 +400,16 @@ int cbm_scan_project_env_urls(const char *root_path, cbm_env_binding_t *out, int
compile_patterns();
int count = 0;
- char path_stack[256][512];
- int stack_top = 1;
+ char path_stack[CBM_SZ_256][CBM_SZ_512];
+ int stack_top = SKIP_ONE;
strncpy(path_stack[0], root_path, sizeof(path_stack[0]) - 1);
- path_stack[0][sizeof(path_stack[0]) - 1] = '\0';
+ path_stack[0][sizeof(path_stack[0]) - SKIP_ONE] = '\0';
while (stack_top > 0 && count < max_out) {
stack_top--;
- char dir_path[512];
- strncpy(dir_path, path_stack[stack_top], sizeof(dir_path) - 1);
- dir_path[sizeof(dir_path) - 1] = '\0';
+ char dir_path[CBM_SZ_512];
+ strncpy(dir_path, path_stack[stack_top], sizeof(dir_path) - SKIP_ONE);
+ dir_path[sizeof(dir_path) - SKIP_ONE] = '\0';
cbm_dir_t *d = cbm_opendir(dir_path);
if (!d) {
diff --git a/src/pipeline/pass_gitdiff.c b/src/pipeline/pass_gitdiff.c
index 75179e96d..f2b8fac61 100644
--- a/src/pipeline/pass_gitdiff.c
+++ b/src/pipeline/pass_gitdiff.c
@@ -4,6 +4,11 @@
* Pure string parsers for git diff --name-status and --unified=0 output.
* No git execution — just parsing pre-captured output strings.
*/
+#include "foundation/constants.h"
+
+enum { GD_STATUS_IDX = 1, GD_PLUS_PREFIX = 6 };
+
+#define SLEN(s) (sizeof(s) - 1)
#include "pipeline/pipeline.h"
#include "pipeline/pipeline_internal.h"
@@ -13,26 +18,26 @@
void cbm_parse_range(const char *s, int *out_start, int *out_count) {
*out_start = 0;
- *out_count = 1;
+ *out_count = SKIP_ONE;
const char *comma = strchr(s, ',');
if (!comma) {
- *out_start = (int)strtol(s, NULL, 10);
+ *out_start = (int)strtol(s, NULL, CBM_DECIMAL_BASE);
return;
}
/* Parse start */
- char buf[32];
+ char buf[CBM_SZ_32];
size_t len = (size_t)(comma - s);
if (len >= sizeof(buf)) {
- len = sizeof(buf) - 1;
+ len = sizeof(buf) - SKIP_ONE;
}
memcpy(buf, s, len);
buf[len] = '\0';
- *out_start = (int)strtol(buf, NULL, 10);
+ *out_start = (int)strtol(buf, NULL, CBM_DECIMAL_BASE);
/* Parse count */
- *out_count = (int)strtol(comma + 1, NULL, 10);
+ *out_count = (int)strtol(comma + SKIP_ONE, NULL, CBM_DECIMAL_BASE);
}
#define HUNK_LINE_BUF 1536
@@ -42,7 +47,7 @@ void cbm_parse_range(const char *s, int *out_start, int *out_count) {
static bool parse_one_name_status(const char *line, size_t line_len, cbm_changed_file_t *out_f) {
char tmp[HUNK_LINE_BUF];
if (line_len >= sizeof(tmp)) {
- line_len = sizeof(tmp) - 1;
+ line_len = sizeof(tmp) - SKIP_ONE;
}
memcpy(tmp, line, line_len);
tmp[line_len] = '\0';
@@ -53,25 +58,25 @@ static bool parse_one_name_status(const char *line, size_t line_len, cbm_changed
return false;
}
*tab1 = '\0';
- char *path1 = tab1 + 1;
+ char *path1 = tab1 + SKIP_ONE;
char *tab2 = strchr(path1, '\t');
char *path2 = NULL;
if (tab2) {
*tab2 = '\0';
- path2 = tab2 + 1;
+ path2 = tab2 + SKIP_ONE;
}
memset(out_f, 0, sizeof(*out_f));
if (status_str[0] == 'R') {
out_f->status[0] = 'R';
- out_f->status[1] = '\0';
+ out_f->status[GD_STATUS_IDX] = '\0';
snprintf(out_f->old_path, sizeof(out_f->old_path), "%s", path1);
snprintf(out_f->path, sizeof(out_f->path), "%s", path2 ? path2 : path1);
} else {
out_f->status[0] = status_str[0];
- out_f->status[1] = '\0';
+ out_f->status[GD_STATUS_IDX] = '\0';
snprintf(out_f->path, sizeof(out_f->path), "%s", path1);
out_f->old_path[0] = '\0';
}
@@ -98,7 +103,7 @@ int cbm_parse_name_status(const char *output, cbm_changed_file_t *out, int max_o
}
}
- line = eol ? eol + 1 : line + line_len;
+ line = eol ? eol + SKIP_ONE : line + line_len;
}
return count;
}
@@ -115,16 +120,16 @@ static bool parse_hunk_line(const char *line, size_t line_len, const char *curre
const char *end_at = strstr(plus, " @@");
size_t range_len;
if (end_at) {
- range_len = (size_t)(end_at - plus - 1);
+ range_len = (size_t)(end_at - plus - SKIP_ONE);
} else {
- range_len = (size_t)(line + line_len - plus - 1);
+ range_len = (size_t)(line + line_len - plus - SKIP_ONE);
}
- char range_str[64];
+ char range_str[CBM_SZ_64];
if (range_len >= sizeof(range_str)) {
- range_len = sizeof(range_str) - 1;
+ range_len = sizeof(range_str) - SKIP_ONE;
}
- memcpy(range_str, plus + 1, range_len);
+ memcpy(range_str, plus + SKIP_ONE, range_len);
range_str[range_len] = '\0';
int start;
@@ -135,7 +140,7 @@ static bool parse_hunk_line(const char *line, size_t line_len, const char *curre
return false;
}
- int end = start + cnt - 1;
+ int end = start + cnt - SKIP_ONE;
if (end < start) {
end = start;
}
@@ -152,7 +157,7 @@ int cbm_parse_hunks(const char *output, cbm_changed_hunk_t *out, int max_out) {
}
int count = 0;
- char current_file[512] = {0};
+ char current_file[CBM_SZ_512] = {0};
const char *line = output;
while (*line && count < max_out) {
@@ -160,25 +165,26 @@ int cbm_parse_hunks(const char *output, cbm_changed_hunk_t *out, int max_out) {
size_t line_len = eol ? (size_t)(eol - line) : strlen(line);
if (line_len == 0) {
- line = eol ? eol + 1 : line + line_len;
+ line = eol ? eol + SKIP_ONE : line + line_len;
continue;
}
- if (line_len > 6 && strncmp(line, "+++ b/", 6) == 0) {
- size_t flen = line_len - 6;
+ if (line_len > GD_PLUS_PREFIX && strncmp(line, "+++ b/", SLEN("+++ b/")) == 0) {
+ size_t flen = line_len - GD_PLUS_PREFIX;
if (flen >= sizeof(current_file)) {
- flen = sizeof(current_file) - 1;
+ flen = sizeof(current_file) - SKIP_ONE;
}
memcpy(current_file, line + 6, flen);
current_file[flen] = '\0';
- } else if (line_len >= 2 && line[0] == '@' && line[1] == '@' && current_file[0]) {
+ } else if (line_len >= PAIR_LEN && line[0] == '@' && line[GD_STATUS_IDX] == '@' &&
+ current_file[0]) {
cbm_changed_hunk_t h;
if (parse_hunk_line(line, line_len, current_file, &h)) {
out[count++] = h;
}
}
- line = eol ? eol + 1 : line + line_len;
+ line = eol ? eol + SKIP_ONE : line + line_len;
}
return count;
}
diff --git a/src/pipeline/pass_githistory.c b/src/pipeline/pass_githistory.c
index f9e9a7d59..36b491f53 100644
--- a/src/pipeline/pass_githistory.c
+++ b/src/pipeline/pass_githistory.c
@@ -10,6 +10,11 @@
*
* Depends on: pass_structure having created File nodes
*/
+#include "foundation/constants.h"
+
+enum { GH_RING = 4, GH_RING_MASK = 3, GH_INIT_CAP = 16, GH_MIN_COMMITS = 3, GH_MAX_FILES = 20 };
+
+#define SLEN(s) (sizeof(s) - 1)
#include "pipeline/pipeline.h"
#include "pipeline/pipeline_internal.h"
#include "graph_buffer/graph_buffer.h"
@@ -28,10 +33,10 @@
#include <string.h>
static const char *itoa_log(int val) {
- static CBM_TLS char bufs[4][32];
+ static CBM_TLS char bufs[GH_RING][CBM_SZ_32];
static CBM_TLS int idx = 0;
int i = idx;
- idx = (idx + 1) & 3;
+ idx = (idx + SKIP_ONE) & GH_RING_MASK;
snprintf(bufs[i], sizeof(bufs[i]), "%d", val);
return bufs[i];
}
@@ -47,15 +52,16 @@ bool cbm_is_trackable_file(const char *path) {
}
/* Skip directory prefixes */
#define LEN_NODE_MODULES_SLASH 13 /* strlen("node_modules/") */
- if (strncmp(path, ".git/", 5) == 0 ||
+ if (strncmp(path, ".git/", SLEN(".git/")) == 0 ||
strncmp(path, "node_modules/", LEN_NODE_MODULES_SLASH) == 0 ||
- strncmp(path, "vendor/", 7) == 0 || strncmp(path, "__pycache__/", 12) == 0 ||
- strncmp(path, ".cache/", 7) == 0) {
+ strncmp(path, "vendor/", SLEN("vendor/")) == 0 ||
+ strncmp(path, "__pycache__/", SLEN("__pycache__/")) == 0 ||
+ strncmp(path, ".cache/", SLEN(".cache/")) == 0) {
return false;
}
/* Skip lock/generated file names */
const char *base = strrchr(path, '/');
- base = base ? base + 1 : path;
+ base = base ? base + SKIP_ONE : path;
if (strcmp(base, "package-lock.json") == 0 || strcmp(base, "yarn.lock") == 0 ||
strcmp(base, "pnpm-lock.yaml") == 0 || strcmp(base, "Cargo.lock") == 0 ||
strcmp(base, "poetry.lock") == 0 || strcmp(base, "composer.lock") == 0 ||
@@ -85,7 +91,7 @@ typedef struct {
static void commit_add_file(commit_t *c, const char *file) {
if (c->count >= c->cap) {
- c->cap = c->cap ? c->cap * 2 : 16;
+ c->cap = c->cap ? c->cap * PAIR_LEN : GH_INIT_CAP;
c->files = safe_realloc(c->files, c->cap * sizeof(char *));
}
c->files[c->count++] = strdup(file);
@@ -113,7 +119,7 @@ static int parse_git_log(const char *repo_path, commit_t **out, int *out_count)
git_repository *repo = NULL;
if (git_repository_open(&repo, repo_path) != 0) {
git_libgit2_shutdown();
- return -1;
+ return CBM_NOT_FOUND;
}
/* Walk from HEAD, sorted chronologically */
@@ -121,7 +127,7 @@ static int parse_git_log(const char *repo_path, commit_t **out, int *out_count)
if (git_revwalk_new(&walker, repo) != 0) {
git_repository_free(repo);
git_libgit2_shutdown();
- return -1;
+ return CBM_NOT_FOUND;
}
git_revwalk_sorting(walker, GIT_SORT_TIME);
git_revwalk_push_head(walker);
@@ -130,7 +136,7 @@ static int parse_git_log(const char *repo_path, commit_t **out, int *out_count)
time_t cutoff = time(NULL) - (365L * 24 * 3600);
int max_commits = 10000;
- int cap = 64;
+ int cap = CBM_SZ_64;
commit_t *commits = malloc(cap * sizeof(commit_t));
int count = 0;
@@ -180,7 +186,7 @@ static int parse_git_log(const char *repo_path, commit_t **out, int *out_count)
if (current.count > 0) {
if (count >= cap) {
- cap *= 2;
+ cap *= PAIR_LEN;
commits = safe_realloc(commits, cap * sizeof(commit_t));
}
commits[count++] = current;
@@ -213,10 +219,10 @@ static int parse_git_log(const char *repo_path, commit_t **out, int *out_count)
*out_count = 0;
if (!cbm_validate_shell_arg(repo_path)) {
- return -1;
+ return CBM_NOT_FOUND;
}
- char cmd[1024];
+ char cmd[CBM_SZ_1K];
snprintf(cmd, sizeof(cmd),
"cd '%s' && git log --name-only --pretty=format:COMMIT:%%H "
"--since='1 year ago' --max-count=10000 2>/dev/null",
@@ -224,28 +230,28 @@ static int parse_git_log(const char *repo_path, commit_t **out, int *out_count)
FILE *fp = cbm_popen(cmd, "r");
if (!fp) {
- return -1;
+ return CBM_NOT_FOUND;
}
- int cap = 64;
+ int cap = CBM_SZ_64;
commit_t *commits = malloc(cap * sizeof(commit_t));
int count = 0;
commit_t current = {0};
- char line[1024];
+ char line[CBM_SZ_1K];
while (fgets(line, sizeof(line), fp)) {
size_t len = strlen(line);
- while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r')) {
+ while (len > 0 && (line[len - SKIP_ONE] == '\n' || line[len - SKIP_ONE] == '\r')) {
line[--len] = '\0';
}
if (len == 0) {
continue;
}
- if (strncmp(line, "COMMIT:", 7) == 0) {
+ if (strncmp(line, "COMMIT:", SLEN("COMMIT:")) == 0) {
if (current.count > 0) {
if (count >= cap) {
- cap *= 2;
+ cap *= PAIR_LEN;
commits = safe_realloc(commits, cap * sizeof(commit_t));
}
commits[count++] = current;
@@ -260,7 +266,7 @@ static int parse_git_log(const char *repo_path, commit_t **out, int *out_count)
}
if (current.count > 0) {
if (count >= cap) {
- cap *= 2;
+ cap *= PAIR_LEN;
commits = safe_realloc(commits, cap * sizeof(commit_t));
}
commits[count++] = current;
@@ -296,7 +302,7 @@ typedef struct {
static void collect_coupling_cb(const char *pair_key, void *val, void *ud) {
collect_coupling_ctx_t *cctx = ud;
int co_count = *(int *)val;
- if (co_count < 3) {
+ if (co_count < GH_MIN_COMMITS) {
return;
}
if (cctx->out_count >= cctx->max_out) {
@@ -308,9 +314,9 @@ static void collect_coupling_cb(const char *pair_key, void *val, void *ud) {
return;
}
size_t la = sep - pair_key;
- const char *file_b = sep + 1;
+ const char *file_b = sep + SKIP_ONE;
- char file_a_buf[512];
+ char file_a_buf[CBM_SZ_512];
if (la >= sizeof(file_a_buf)) {
return;
}
@@ -342,11 +348,11 @@ static void collect_coupling_cb(const char *pair_key, void *val, void *ud) {
int cbm_compute_change_coupling(const cbm_commit_files_t *commits, int commit_count,
cbm_change_coupling_t *out, int max_out) {
- CBMHashTable *file_counts = cbm_ht_create(1024);
- CBMHashTable *pair_counts = cbm_ht_create(2048);
+ CBMHashTable *file_counts = cbm_ht_create(CBM_SZ_1K);
+ CBMHashTable *pair_counts = cbm_ht_create(CBM_SZ_2K);
for (int c = 0; c < commit_count; c++) {
- if (commits[c].count > 20) {
+ if (commits[c].count > GH_MAX_FILES) {
continue;
}
@@ -356,13 +362,13 @@ int cbm_compute_change_coupling(const cbm_commit_files_t *commits, int commit_co
(*val)++;
} else {
int *nv = malloc(sizeof(int));
- *nv = 1;
+ *nv = SKIP_ONE;
cbm_ht_set(file_counts, strdup(commits[c].files[i]), nv);
}
}
for (int i = 0; i < commits[c].count; i++) {
- for (int j = i + 1; j < commits[c].count; j++) {
+ for (int j = i + SKIP_ONE; j < commits[c].count; j++) {
const char *a = commits[c].files[i];
const char *b = commits[c].files[j];
if (strcmp(a, b) > 0) {
@@ -372,10 +378,10 @@ int cbm_compute_change_coupling(const cbm_commit_files_t *commits, int commit_co
}
size_t la = strlen(a);
size_t lb = strlen(b);
- char *pk = malloc(la + 1 + lb + 1);
+ char *pk = malloc(la + SKIP_ONE + lb + SKIP_ONE);
memcpy(pk, a, la);
pk[la] = '\x01';
- memcpy(pk + la + 1, b, lb + 1);
+ memcpy(pk + la + SKIP_ONE, b, lb + SKIP_ONE);
int *val = cbm_ht_get(pair_counts, pk);
if (val) {
@@ -383,7 +389,7 @@ int cbm_compute_change_coupling(const cbm_commit_files_t *commits, int commit_co
free(pk);
} else {
int *nv = malloc(sizeof(int));
- *nv = 1;
+ *nv = SKIP_ONE;
cbm_ht_set(pair_counts, pk, nv);
}
}
@@ -476,7 +482,7 @@ int cbm_pipeline_githistory_apply(cbm_pipeline_ctx_t *ctx, const cbm_githistory_
continue;
}
- char props[128];
+ char props[CBM_SZ_128];
snprintf(props, sizeof(props), "{\"co_changes\":%d,\"coupling_score\":%.2f}",
cc->co_change_count, cc->coupling_score);
diff --git a/src/pipeline/pass_httplinks.c b/src/pipeline/pass_httplinks.c
deleted file mode 100644
index 3a5e8d138..000000000
--- a/src/pipeline/pass_httplinks.c
+++ /dev/null
@@ -1,1483 +0,0 @@
-
-/*
- * pass_httplinks.c — HTTP route discovery and cross-service linking.
- *
- * Port of Go internal/httplink package. Discovers HTTP route registrations
- * (Express, Flask, Gin, Spring, Ktor, Laravel, Actix, ASP.NET) and HTTP
- * call sites (fetch, http.Get, requests.post, etc.). Creates:
- * - Route nodes with method + path
- * - HANDLES edges: handler function → Route
- * - HTTP_CALLS edges: caller → Route (cross-service calls)
- * - ASYNC_CALLS edges: caller → Route (async dispatch)
- * - CALLS edges with via=route_registration (registrar → handler)
- *
- * Operates on graph buffer (pre-flush): reads Function/Method/Module nodes,
- * parses decorator properties via yyjson, reads source from disk, and writes
- * Route nodes + edges back to the graph buffer.
- *
- * Depends on: pass_definitions, pass_calls (for cross-file prefix resolution)
- */
-#include "pipeline/pipeline.h"
-#include "pipeline/pipeline_internal.h"
-#include "pipeline/httplink.h"
-#include "pipeline/worker_pool.h"
-#include "graph_buffer/graph_buffer.h"
-#include "foundation/platform.h"
-#include "foundation/log.h"
-#include "foundation/compat.h"
-#include "foundation/compat_regex.h"
-
-#include "yyjson/yyjson.h"
-
-#include <ctype.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <stdatomic.h>
-
-/* ── Constants ────────────────────────────────────────────────── */
-#define DOTTED_FRAG_BUF 260 /* buffer for slash-to-dot path conversion */
-#define MIN_PATH_CONFIDENCE 0.25 /* minimum score to create HTTP_CALLS edge */
-#define MODULE_WEIGHT 0.85 /* confidence weight for Module-sourced calls */
-
-/* ── Format int to string for logging ──────────────────────────── */
-
-static const char *itoa_hl(int val) {
- static CBM_TLS char bufs[4][32];
- static CBM_TLS int idx = 0;
- int i = idx;
- idx = (idx + 1) & 3;
- snprintf(bufs[i], sizeof(bufs[i]), "%d", val);
- return bufs[i];
-}
-
-/* ── Source cache helpers ──────────────────────────────────────── */
-
-/* Read source lines from disk (used for route discovery which processes
- * few files filtered by language extension). */
-static char *read_source_lines(const cbm_pipeline_ctx_t *ctx, const char *rel_path, int start_line,
- int end_line) {
- return cbm_read_source_lines_disk(ctx->repo_path, rel_path, start_line, end_line);
-}
-
-/* Read full source file, using cache if available. Returns malloc'd copy (caller must free). */
-/* Read full source from disk (used for module route discovery — few files,
- * filtered by .php/.js extension). */
-static char *read_full_source(const cbm_pipeline_ctx_t *ctx, const char *rel_path) {
- char path_buf[2048];
- snprintf(path_buf, sizeof(path_buf), "%s/%s", ctx->repo_path, rel_path);
- FILE *f = fopen(path_buf, "rb");
- if (!f) {
- return NULL;
- }
- (void)fseek(f, 0, SEEK_END);
- long sz = ftell(f);
- (void)fseek(f, 0, SEEK_SET);
- if (sz <= 0 || sz > (long)10 * 1024 * 1024) {
- (void)fclose(f);
- return NULL;
- }
- char *source = malloc((size_t)sz + 1);
- if (!source) {
- (void)fclose(f);
- return NULL;
- }
- size_t nread = fread(source, 1, (size_t)sz, f);
- (void)fclose(f);
- source[nread] = '\0';
- return source;
-}
-
-/* ── JSON helpers ──────────────────────────────────────────────── */
-
-/* Extract the "decorators" array from a properties_json string.
- * Returns a NULL-terminated array of strings. Caller must free array and strings. */
-static char **extract_decorators(const char *json, int *out_count) {
- *out_count = 0;
- if (!json) {
- return NULL;
- }
-
- yyjson_doc *doc = yyjson_read(json, strlen(json), 0);
- if (!doc) {
- return NULL;
- }
-
- yyjson_val *root = yyjson_doc_get_root(doc);
- yyjson_val *decs = yyjson_obj_get(root, "decorators");
- if (!decs || !yyjson_is_arr(decs)) {
- yyjson_doc_free(doc);
- return NULL;
- }
-
- size_t cnt = yyjson_arr_size(decs);
- if (cnt == 0) {
- yyjson_doc_free(doc);
- return NULL;
- }
-
- char **out = calloc(cnt + 1, sizeof(char *));
- int idx = 0;
- yyjson_val *item;
- yyjson_arr_iter iter;
- yyjson_arr_iter_init(decs, &iter);
- while ((item = yyjson_arr_iter_next(&iter))) {
- if (yyjson_is_str(item)) {
- char *s = strdup(yyjson_get_str(item));
- /* Collapse newlines to spaces so regex matches multiline decorators.
- * POSIX regex [[:space:]] may not match \n on all platforms. */
- if (s) {
- for (char *p = s; *p; p++) {
- if (*p == '\n' || *p == '\r') {
- *p = ' ';
- }
- }
- }
- out[idx++] = s;
- }
- }
- out[idx] = NULL;
- *out_count = idx;
-
- yyjson_doc_free(doc);
- if (idx > 0) {
- return out;
- }
- free(out);
- return NULL;
-}
-
-/* Check if a JSON properties string has is_test=true. */
-static bool is_test_from_json(const char *json) {
- if (!json) {
- return false;
- }
- /* Fast path: substring search before full parse */
- if (!strstr(json, "\"is_test\"")) {
- return false;
- }
-
- yyjson_doc *doc = yyjson_read(json, strlen(json), 0);
- if (!doc) {
- return false;
- }
- yyjson_val *root = yyjson_doc_get_root(doc);
- yyjson_val *v = yyjson_obj_get(root, "is_test");
- bool result = v && yyjson_is_bool(v) && yyjson_get_bool(v);
- yyjson_doc_free(doc);
- return result;
-}
-
-/* Check if node is from a test file (file path heuristic + is_test property). */
-static bool is_test_node(const cbm_gbuf_node_t *n) {
- if (is_test_from_json(n->properties_json)) {
- return true;
- }
- if (!n->file_path) {
- return false;
- }
- return cbm_is_test_node_fp(n->file_path, false);
-}
-
-/* Update properties_json to set is_entry_point=true.
- * Returns a newly allocated JSON string. Caller must free(). */
-static char *set_entry_point(const char *json) {
- yyjson_doc *doc = json ? yyjson_read(json, strlen(json), 0) : NULL;
- yyjson_val *root = doc ? yyjson_doc_get_root(doc) : NULL;
-
- yyjson_mut_doc *mdoc = yyjson_mut_doc_new(NULL);
- yyjson_mut_val *mroot;
-
- if (root && yyjson_is_obj(root)) {
- mroot = yyjson_val_mut_copy(mdoc, root);
- } else {
- mroot = yyjson_mut_obj(mdoc);
- }
- yyjson_mut_doc_set_root(mdoc, mroot);
-
- yyjson_mut_obj_remove_key(mroot, "is_entry_point");
- yyjson_mut_obj_add_bool(mdoc, mroot, "is_entry_point", true);
-
- char *result = yyjson_mut_write(mdoc, 0, NULL);
- yyjson_mut_doc_free(mdoc);
- if (doc) {
- yyjson_doc_free(doc);
- }
- return result;
-}
-
-static void free_decorators(char **decs) {
- if (!decs) {
- return;
- }
- for (int i = 0; decs[i]; i++) {
- free(decs[i]);
- }
- free(decs);
-}
-
-/* ── Suffix helpers ────────────────────────────────────────────── */
-
-static bool has_suffix(const char *s, const char *suffix) {
- size_t sl = strlen(s);
- size_t xl = strlen(suffix);
- if (xl > sl) {
- return false;
- }
- return strcmp(s + sl - xl, suffix) == 0;
-}
-
-static bool is_jsts_file(const char *path) {
- return has_suffix(path, ".js") || has_suffix(path, ".ts") || has_suffix(path, ".mjs") ||
- has_suffix(path, ".mts") || has_suffix(path, ".tsx");
-}
-
-/* ── Route discovery ───────────────────────────────────────────── */
-
-/* Max routes per pass */
-#define MAX_ROUTES 4096
-#define MAX_CALL_SITES 4096
-
-/* Discover routes from a single Function/Method node. */
-static int discover_node_routes(const cbm_gbuf_node_t *n, const cbm_pipeline_ctx_t *ctx,
- cbm_route_handler_t *out, int max_out) {
- int total = 0;
-
- /* 1. Decorator-based routes (Python, Java, Rust, ASP.NET) */
- int ndec = 0;
- char **decs = extract_decorators(n->properties_json, &ndec);
- if (decs && ndec > 0) {
- int nr = cbm_extract_python_routes(n->name, n->qualified_name, (const char **)decs, ndec,
- out + total, max_out - total);
- total += nr;
-
- nr = cbm_extract_java_routes(n->name, n->qualified_name, (const char **)decs, ndec,
- out + total, max_out - total);
- total += nr;
-
- /* Rust Actix and C# ASP.NET also use decorator patterns —
- * these are handled by java_routes for similar decorator syntax
- * but we can add specific extractors here if needed */
- }
- free_decorators(decs);
-
- /* 2. Source-based routes — scoped by file extension to avoid
- * cross-framework false positives (e.g. Ktor regex matching PHP Cache::get) */
- if (n->file_path && n->start_line > 0 && n->end_line > 0 && total < max_out) {
- char *source = read_source_lines(ctx, n->file_path, n->start_line, n->end_line);
- if (source) {
- const char *fp = n->file_path;
- int nr;
-
- if (has_suffix(fp, ".go")) {
- nr = cbm_extract_go_routes(n->name, n->qualified_name, source, out + total,
- max_out - total);
- total += nr;
- }
- if (is_jsts_file(fp)) {
- nr = cbm_extract_express_routes(n->name, n->qualified_name, source, out + total,
- max_out - total);
- total += nr;
- }
- if (has_suffix(fp, ".php")) {
- nr = cbm_extract_laravel_routes(n->name, n->qualified_name, source, out + total,
- max_out - total);
- total += nr;
- }
- if (has_suffix(fp, ".kt") || has_suffix(fp, ".kts")) {
- nr = cbm_extract_ktor_routes(n->name, n->qualified_name, source, out + total,
- max_out - total);
- total += nr;
- }
-
- free(source);
- }
- }
-
- return total;
-}
-
-/* Discover module-level routes (PHP Laravel, JS/TS Express at top level). */
-static int discover_module_routes(const cbm_gbuf_node_t *mod, const cbm_pipeline_ctx_t *ctx,
- cbm_route_handler_t *out, int max_out) {
- if (!mod->file_path) {
- return 0;
- }
-
- bool is_php = has_suffix(mod->file_path, ".php");
- bool is_js = is_jsts_file(mod->file_path);
- if (!is_php && !is_js) {
- return 0;
- }
-
- /* Read full file (from cache or disk) */
- char *source = read_full_source(ctx, mod->file_path);
- if (!source) {
- return 0;
- }
-
- int total = 0;
- if (is_php) {
- total += cbm_extract_laravel_routes(mod->name, mod->qualified_name, source, out + total,
- max_out - total);
- }
- if (is_js) {
- total += cbm_extract_express_routes(mod->name, mod->qualified_name, source, out + total,
- max_out - total);
- }
- free(source);
- return total;
-}
-
-/* ── Prefix resolution ─────────────────────────────────────────── */
-
-/* Import map entry for prefix resolution (shared between FastAPI/Express). */
-typedef struct {
- char var[128];
- char module[256];
-} hl_import_entry_t;
-
-/* Build Python import map from "from X import Y" statements. */
-static int fastapi_build_import_map(const char *source, const cbm_regex_t *import_re,
- hl_import_entry_t *imports, int max_imports) {
- int count = 0;
- const char *p = source;
- cbm_regmatch_t pm[3];
- while (count < max_imports && cbm_regexec(import_re, p, 3, pm, 0) == 0) {
- int mlen = (pm[1].rm_eo - pm[1].rm_so);
- int vlen = (pm[2].rm_eo - pm[2].rm_so);
- if (mlen < 256 && vlen < 128) {
- snprintf(imports[count].module, 256, "%.*s", mlen, p + pm[1].rm_so);
- snprintf(imports[count].var, 128, "%.*s", vlen, p + pm[2].rm_so);
- count++;
- }
- p += pm[0].rm_eo;
- }
- return count;
-}
-
-/* Apply a resolved prefix to all routes matching a module path. */
-static void apply_module_prefix(cbm_route_handler_t *routes, int route_count,
- const char *module_path, const char *file_frag, char *prefix) {
- size_t pfx_len = strlen(prefix);
- while (pfx_len > 0 && prefix[pfx_len - 1] == '/') {
- prefix[--pfx_len] = '\0';
- }
-
- for (int r = 0; r < route_count; r++) {
- if (strncmp(routes[r].path, prefix, pfx_len) == 0) {
- continue;
- }
- if (strstr(routes[r].qualified_name, module_path) ||
- (routes[r].function_name[0] && strstr(routes[r].qualified_name, file_frag))) {
- char new_path[256];
- const char *old_path = routes[r].path;
- while (*old_path == '/') {
- old_path++;
- }
- snprintf(new_path, sizeof(new_path), "%s/%s", prefix, old_path);
- snprintf(routes[r].path, sizeof(routes[r].path), "%s", new_path);
- }
- }
-}
-
-/* Look up a variable name in the import map. */
-static const char *hl_import_lookup(const hl_import_entry_t *imports, int count, const char *var) {
- for (int i = 0; i < count; i++) {
- if (strcmp(imports[i].var, var) == 0) {
- return imports[i].module;
- }
- }
- return NULL;
-}
-
-/* Process one Python module for include_router calls. */
-static void fastapi_process_module(cbm_pipeline_ctx_t *ctx, const cbm_gbuf_node_t *mod,
- const cbm_regex_t *include_re, const cbm_regex_t *import_re,
- cbm_route_handler_t *routes, int route_count) {
- char *source = read_full_source(ctx, mod->file_path);
- if (!source) {
- return;
- }
-
- hl_import_entry_t imports[64];
- memset(imports, 0, sizeof(imports));
- int import_count = fastapi_build_import_map(source, import_re, imports, 64);
-
- const char *p = source;
- cbm_regmatch_t pm[3];
- while (cbm_regexec(include_re, p, 3, pm, 0) == 0) {
- char var_name[128] = {0};
- char prefix[256] = {0};
- int vlen = (pm[1].rm_eo - pm[1].rm_so);
- int plen = (pm[2].rm_eo - pm[2].rm_so);
- if (vlen < 128) {
- snprintf(var_name, 128, "%.*s", vlen, p + pm[1].rm_so);
- }
- if (plen < 256) {
- snprintf(prefix, 256, "%.*s", plen, p + pm[2].rm_so);
- }
- p += pm[0].rm_eo;
-
- /* Resolve var → module path */
- const char *module_path = hl_import_lookup(imports, import_count, var_name);
- if (!module_path) {
- continue;
- }
-
- /* Convert dotted module path to file fragment */
- char file_frag[256];
- snprintf(file_frag, sizeof(file_frag), "%s", module_path);
- for (char *c = file_frag; *c; c++) {
- if (*c == '.') {
- *c = '/';
- }
- }
-
- apply_module_prefix(routes, route_count, module_path, file_frag, prefix);
- }
-
- free(source);
-}
-
-/* Resolve FastAPI include_router prefixes.
- * Scans Python Module nodes for: app.include_router(var, prefix="/prefix")
- * and from ... import var. Prepends prefix to routes from matching modules. */
-static void resolve_fastapi_prefixes(cbm_pipeline_ctx_t *ctx, cbm_route_handler_t *routes,
- int route_count) {
- const cbm_gbuf_node_t **modules = NULL;
- int mod_count = 0;
- if (cbm_gbuf_find_by_label(ctx->gbuf, "Module", &modules, &mod_count) != 0) {
- return;
- }
-
- cbm_regex_t include_re;
- cbm_regex_t import_re;
- if (cbm_regcomp(
- &include_re,
- "\\.include_router\\(([[:alnum:]_]+)[[:space:]]*,[[:space:]]*prefix[[:space:]]*=[[:"
- "space:]]*[\"']([^\"']+)[\"']",
- CBM_REG_EXTENDED) != 0) {
- return;
- }
- if (cbm_regcomp(&import_re,
- "from[[:space:]]+([[:alnum:]_.]+)[[:space:]]+import[[:space:]]+([[:alnum:]_]+)",
- CBM_REG_EXTENDED) != 0) {
- cbm_regfree(&include_re);
- return;
- }
-
- for (int m = 0; m < mod_count; m++) {
- const cbm_gbuf_node_t *mod = modules[m];
- if (!mod->file_path || !has_suffix(mod->file_path, ".py")) {
- continue;
- }
- fastapi_process_module(ctx, mod, &include_re, &import_re, routes, route_count);
- }
-
- cbm_regfree(&include_re);
- cbm_regfree(&import_re);
-}
-
-/* Build JS/TS import map from require() and ES import statements. */
-static int express_build_import_map(const char *source, const cbm_regex_t *require_re,
- const cbm_regex_t *esimport_re, hl_import_entry_t *imports,
- int max_imports) {
- int count = 0;
- cbm_regmatch_t pm[4];
-
- const char *p = source;
- while (count < max_imports && cbm_regexec(require_re, p, 4, pm, 0) == 0) {
- int vlen = (pm[2].rm_eo - pm[2].rm_so);
- int mlen = (pm[3].rm_eo - pm[3].rm_so);
- if (vlen < 128 && mlen < 256) {
- snprintf(imports[count].var, 128, "%.*s", vlen, p + pm[2].rm_so);
- snprintf(imports[count].module, 256, "%.*s", mlen, p + pm[3].rm_so);
- count++;
- }
- p += pm[0].rm_eo;
- }
- p = source;
- while (count < max_imports && cbm_regexec(esimport_re, p, 3, pm, 0) == 0) {
- int vlen = (pm[1].rm_eo - pm[1].rm_so);
- int mlen = (pm[2].rm_eo - pm[2].rm_so);
- if (vlen < 128 && mlen < 256) {
- snprintf(imports[count].var, 128, "%.*s", vlen, p + pm[1].rm_so);
- snprintf(imports[count].module, 256, "%.*s", mlen, p + pm[2].rm_so);
- count++;
- }
- p += pm[0].rm_eo;
- }
- return count;
-}
-
-/* Apply Express .use() prefix for one matched var to routes. */
-static void express_apply_use_prefix(cbm_route_handler_t *routes, int route_count,
- const char *module_path, char *prefix) {
- /* Strip leading ./ and ../ from relative import */
- const char *file_frag = module_path;
- if (strncmp(file_frag, "./", 2) == 0) {
- file_frag += 2;
- }
- if (strncmp(file_frag, "../", 3) == 0) {
- file_frag += 3;
- }
-
- /* Strip trailing slash from prefix */
- size_t pfx_len = strlen(prefix);
- while (pfx_len > 0 && prefix[pfx_len - 1] == '/') {
- prefix[--pfx_len] = '\0';
- }
-
- /* Convert slash-based path to dots for QN matching */
- char dotted_frag[DOTTED_FRAG_BUF];
- snprintf(dotted_frag, sizeof(dotted_frag), "%s", file_frag);
- for (char *c = dotted_frag; *c; c++) {
- if (*c == '/') {
- *c = '.';
- }
- }
-
- for (int r = 0; r < route_count; r++) {
- if (strncmp(routes[r].path, prefix, pfx_len) == 0) {
- continue;
- }
- if (strstr(routes[r].qualified_name, dotted_frag) ||
- strstr(routes[r].qualified_name, file_frag)) {
- char new_path[256];
- const char *old_path = routes[r].path;
- while (*old_path == '/') {
- old_path++;
- }
- snprintf(new_path, sizeof(new_path), "%s/%s", prefix, old_path);
- snprintf(routes[r].path, sizeof(routes[r].path), "%s", new_path);
- }
- }
-}
-
-/* Process one JS/TS module for Express .use() prefix resolution. */
-static void express_process_module(cbm_pipeline_ctx_t *ctx, const cbm_gbuf_node_t *mod,
- const cbm_regex_t *use_re, const cbm_regex_t *require_re,
- const cbm_regex_t *esimport_re, cbm_route_handler_t *routes,
- int route_count) {
- char *source = read_full_source(ctx, mod->file_path);
- if (!source) {
- return;
- }
-
- hl_import_entry_t imports[64];
- memset(imports, 0, sizeof(imports));
- int import_count = express_build_import_map(source, require_re, esimport_re, imports, 64);
-
- const char *p = source;
- cbm_regmatch_t pm[3];
- while (cbm_regexec(use_re, p, 3, pm, 0) == 0) {
- char prefix[256] = {0};
- char var_name[128] = {0};
- int plen = (pm[1].rm_eo - pm[1].rm_so);
- int vlen = (pm[2].rm_eo - pm[2].rm_so);
- if (plen < 256) {
- snprintf(prefix, 256, "%.*s", plen, p + pm[1].rm_so);
- }
- if (vlen < 128) {
- snprintf(var_name, 128, "%.*s", vlen, p + pm[2].rm_so);
- }
- p += pm[0].rm_eo;
-
- const char *module_path = NULL;
- for (int i = 0; i < import_count; i++) {
- if (strcmp(imports[i].var, var_name) == 0) {
- module_path = imports[i].module;
- break;
- }
- }
- if (!module_path) {
- continue;
- }
-
- express_apply_use_prefix(routes, route_count, module_path, prefix);
- }
-
- free(source);
-}
-
-/* Resolve Express app.use("/prefix", routerVar) prefixes. */
-static void resolve_express_prefixes(cbm_pipeline_ctx_t *ctx, cbm_route_handler_t *routes,
- int route_count) {
- const cbm_gbuf_node_t **modules = NULL;
- int mod_count = 0;
- if (cbm_gbuf_find_by_label(ctx->gbuf, "Module", &modules, &mod_count) != 0) {
- return;
- }
-
- cbm_regex_t use_re;
- cbm_regex_t require_re;
- cbm_regex_t esimport_re;
- if (cbm_regcomp(
- &use_re,
- "\\.use\\([[:space:]]*[\"'`]([^\"'`]+)[\"'`][[:space:]]*,[[:space:]]*([[:alnum:]_]+)",
- CBM_REG_EXTENDED) != 0) {
- return;
- }
- if (cbm_regcomp(
- &require_re,
- "(const|let|var)[[:space:]]+([[:alnum:]_]+)[[:space:]]*=[[:space:]]*require\\([[:"
- "space:]]*[\"']([^\"']+)[\"']",
- CBM_REG_EXTENDED) != 0) {
- cbm_regfree(&use_re);
- return;
- }
- if (cbm_regcomp(
- &esimport_re,
- "import[[:space:]]+([[:alnum:]_]+)[[:space:]]+from[[:space:]]+[\"']([^\"']+)[\"']",
- CBM_REG_EXTENDED) != 0) {
- cbm_regfree(&use_re);
- cbm_regfree(&require_re);
- return;
- }
-
- for (int m = 0; m < mod_count; m++) {
- const cbm_gbuf_node_t *mod = modules[m];
- if (!mod->file_path || !is_jsts_file(mod->file_path)) {
- continue;
- }
- express_process_module(ctx, mod, &use_re, &require_re, &esimport_re, routes, route_count);
- }
-
- cbm_regfree(&use_re);
- cbm_regfree(&require_re);
- cbm_regfree(&esimport_re);
-}
-
-/* Apply a group prefix to all routes belonging to a function. */
-static void apply_prefix_to_func_routes(cbm_route_handler_t *routes, int route_count,
- const char *func_qn, const char *prefix) {
- size_t pfx_len = strlen(prefix);
- char pfx_buf[256];
- snprintf(pfx_buf, sizeof(pfx_buf), "%s", prefix);
- while (pfx_len > 0 && pfx_buf[pfx_len - 1] == '/') {
- pfx_buf[--pfx_len] = '\0';
- }
- for (int r = 0; r < route_count; r++) {
- if (strcmp(routes[r].qualified_name, func_qn) != 0) {
- continue;
- }
- if (strncmp(routes[r].path, pfx_buf, pfx_len) == 0) {
- continue;
- }
- char new_path[256];
- const char *old = routes[r].path;
- while (*old == '/') {
- old++;
- }
- snprintf(new_path, sizeof(new_path), "%s/%s", pfx_buf, old);
- snprintf(routes[r].path, sizeof(routes[r].path), "%s", new_path);
- }
-}
-
-/* Index of routes grouped by function QN. */
-typedef struct {
- const char *qn;
- int start;
- int count;
-} hl_func_routes_t;
-
-/* Build routesByFunc index: funcQN → (start_index, count) in routes array. */
-static int build_func_route_index(const cbm_route_handler_t *routes, int route_count,
- hl_func_routes_t *func_map, int max_funcs) {
- int func_map_count = 0;
- for (int i = 0; i < route_count && func_map_count < max_funcs; i++) {
- int found = -1;
- for (int j = 0; j < func_map_count; j++) {
- if (strcmp(func_map[j].qn, routes[i].qualified_name) == 0) {
- found = j;
- func_map[j].count++;
- break;
- }
- }
- if (found < 0) {
- func_map[func_map_count].qn = routes[i].qualified_name;
- func_map[func_map_count].start = i;
- func_map[func_map_count].count = 1;
- func_map_count++;
- }
- }
- return func_map_count;
-}
-
-/* Group prefix var→prefix mapping. */
-typedef struct {
- char var[128];
- char prefix[256];
-} hl_var_prefix_t;
-
-/* Try direct Group() pattern: FuncName(router.Group("/prefix")) */
-static bool try_direct_group_prefix(const char *source, const cbm_regex_t *re, const char *name,
- cbm_route_handler_t *routes, int route_count,
- const char *func_qn) {
- cbm_regmatch_t pm[3];
- const char *p = source;
- while (cbm_regexec(re, p, 3, pm, 0) == 0) {
- char called_name[128] = {0};
- char prefix[256] = {0};
- int nlen = (pm[1].rm_eo - pm[1].rm_so);
- int plen = (pm[2].rm_eo - pm[2].rm_so);
- if (nlen < 128) {
- snprintf(called_name, 128, "%.*s", nlen, p + pm[1].rm_so);
- }
- if (plen < 256) {
- snprintf(prefix, 256, "%.*s", plen, p + pm[2].rm_so);
- }
- p += pm[0].rm_eo;
- if (strcmp(called_name, name) == 0) {
- apply_prefix_to_func_routes(routes, route_count, func_qn, prefix);
- return true;
- }
- }
- return false;
-}
-
-/* Collect var := r.Group("/prefix") assignments from source. */
-static int collect_var_group_prefixes(const char *source, const cbm_regex_t *re,
- hl_var_prefix_t *out, int max_out) {
- cbm_regmatch_t pm[3];
- int count = 0;
- const char *p = source;
- while (count < max_out && cbm_regexec(re, p, 3, pm, 0) == 0) {
- int vlen = (pm[1].rm_eo - pm[1].rm_so);
- int plen = (pm[2].rm_eo - pm[2].rm_so);
- if (vlen < 128 && plen < 256) {
- snprintf(out[count].var, 128, "%.*s", vlen, p + pm[1].rm_so);
- snprintf(out[count].prefix, 256, "%.*s", plen, p + pm[2].rm_so);
- count++;
- }
- p += pm[0].rm_eo;
- }
- return count;
-}
-
-/* Try indirect Group() pattern: v1 := r.Group("/api"); FuncName(v1) */
-static void try_indirect_group_prefix(const char *source, const cbm_gbuf_node_t *func_node,
- const hl_var_prefix_t *vars, int var_count,
- cbm_route_handler_t *routes, int route_count,
- const char *func_qn) {
- char call_pat[256];
- snprintf(call_pat, sizeof(call_pat), "%s[[:space:]]*\\([[:space:]]*([[:alnum:]_]+)",
- func_node->name);
- cbm_regex_t call_re;
- if (cbm_regcomp(&call_re, call_pat, CBM_REG_EXTENDED) != 0) {
- return;
- }
- cbm_regmatch_t pm[3];
- const char *p = source;
- while (cbm_regexec(&call_re, p, 2, pm, 0) == 0) {
- char arg_name[128] = {0};
- int alen = (pm[1].rm_eo - pm[1].rm_so);
- if (alen < 128) {
- snprintf(arg_name, 128, "%.*s", alen, p + pm[1].rm_so);
- }
- p += pm[0].rm_eo;
- for (int v = 0; v < var_count; v++) {
- if (strcmp(vars[v].var, arg_name) == 0) {
- apply_prefix_to_func_routes(routes, route_count, func_qn, vars[v].prefix);
- break;
- }
- }
- }
- cbm_regfree(&call_re);
-}
-
-static void resolve_group_from_caller(const char *caller_source, const cbm_gbuf_node_t *func_node,
- const cbm_regex_t *group_direct_re,
- const cbm_regex_t *group_var_re, cbm_route_handler_t *routes,
- int route_count, const char *func_qn) {
- if (try_direct_group_prefix(caller_source, group_direct_re, func_node->name, routes,
- route_count, func_qn)) {
- return;
- }
- hl_var_prefix_t var_pfx[16];
- memset(var_pfx, 0, sizeof(var_pfx));
- int var_count = collect_var_group_prefixes(caller_source, group_var_re, var_pfx, 16);
- if (var_count > 0) {
- try_indirect_group_prefix(caller_source, func_node, var_pfx, var_count, routes, route_count,
- func_qn);
- }
-}
-
-/* Resolve Go gin cross-file Group() prefixes.
- * Pattern: v1 := r.Group("/api"); RegisterRoutes(v1) */
-static void resolve_cross_file_group_prefixes(cbm_pipeline_ctx_t *ctx, cbm_route_handler_t *routes,
- int route_count) {
- hl_func_routes_t func_map[1024];
- memset(func_map, 0, sizeof(func_map));
- int func_map_count = build_func_route_index(routes, route_count, func_map, 1024);
-
- cbm_regex_t group_direct_re;
- cbm_regex_t group_var_re;
- if (cbm_regcomp(
- &group_direct_re,
- "([[:alnum:]_]+)\\([[:space:]]*[[:alnum:]_]+\\.Group\\([[:space:]]*\"([^\"]+)\"",
- CBM_REG_EXTENDED) != 0) {
- return;
- }
- if (cbm_regcomp(
- &group_var_re,
- "([[:alnum:]_]+)[[:space:]]*:?=[[:space:]]*[[:alnum:]_]+\\.Group\\([[:space:]]*\"(["
- "^\"]+)\"",
- CBM_REG_EXTENDED) != 0) {
- cbm_regfree(&group_direct_re);
- return;
- }
-
- for (int fi = 0; fi < func_map_count; fi++) {
- const char *func_qn = func_map[fi].qn;
- const cbm_gbuf_node_t *func_node = cbm_gbuf_find_by_qn(ctx->gbuf, func_qn);
- if (!func_node) {
- continue;
- }
-
- const cbm_gbuf_edge_t **caller_edges = NULL;
- int caller_count = 0;
- if (cbm_gbuf_find_edges_by_target_type(ctx->gbuf, func_node->id, "CALLS", &caller_edges,
- &caller_count) != 0 ||
- caller_count == 0) {
- continue;
- }
-
- for (int ci = 0; ci < caller_count; ci++) {
- const cbm_gbuf_node_t *caller =
- cbm_gbuf_find_by_id(ctx->gbuf, caller_edges[ci]->source_id);
- if (!caller || !caller->file_path || caller->start_line <= 0) {
- continue;
- }
-
- char *caller_source =
- read_source_lines(ctx, caller->file_path, caller->start_line, caller->end_line);
- if (!caller_source) {
- continue;
- }
-
- resolve_group_from_caller(caller_source, func_node, &group_direct_re, &group_var_re,
- routes, route_count, func_qn);
- free(caller_source);
- }
- }
-
- cbm_regfree(&group_direct_re);
- cbm_regfree(&group_var_re);
-}
-
-/* ── Registration call edges ───────────────────────────────────── */
-
-/* Create CALLS edges from route-registering functions to handler functions.
- * e.g., RegisterRoutes has .POST("/path", h.CreateOrder) → CALLS edge to CreateOrder. */
-static int create_registration_call_edges(cbm_pipeline_ctx_t *ctx, cbm_route_handler_t *routes,
- int route_count) {
- int count = 0;
- for (int i = 0; i < route_count; i++) {
- if (routes[i].handler_ref[0] == '\0') {
- continue;
- }
-
- /* Find the registering function node */
- const cbm_gbuf_node_t *registrar = cbm_gbuf_find_by_qn(ctx->gbuf, routes[i].qualified_name);
- if (!registrar) {
- continue;
- }
-
- /* Resolve handler reference — strip receiver prefix (e.g., "h." from "h.CreateOrder") */
- const char *handler_name = routes[i].handler_ref;
- const char *dot = strrchr(handler_name, '.');
- if (dot) {
- handler_name = dot + 1;
- }
-
- /* Search for the handler function/method by name */
- const cbm_gbuf_node_t **handler_nodes = NULL;
- int handler_count = 0;
- if (cbm_gbuf_find_by_name(ctx->gbuf, handler_name, &handler_nodes, &handler_count) != 0) {
- continue;
- }
- if (handler_count == 0) {
- continue;
- }
-
- const cbm_gbuf_node_t *handler = handler_nodes[0];
-
- /* Store resolved handler QN for later use in insertRouteNodes */
- snprintf(routes[i].resolved_handler_qn, sizeof(routes[i].resolved_handler_qn), "%s",
- handler->qualified_name);
-
- /* Create CALLS edge with via=route_registration */
- cbm_gbuf_insert_edge(ctx->gbuf, registrar->id, handler->id, "CALLS",
- "{\"via\":\"route_registration\"}");
- count++;
- }
- return count;
-}
-
-/* ── Route node insertion ──────────────────────────────────────── */
-
-/* Snapshot of handler node fields (gbuf pointers go stale after upsert). */
-typedef struct {
- char file[512];
- char label[32];
- char name[256];
- char qn[512];
- char props_json[2048];
- int start;
- int end;
- int64_t id;
-} hl_handler_snapshot_t;
-
-/* Copy handler node fields into a stable snapshot. */
-static void snapshot_handler_node(const cbm_gbuf_node_t *handler_node, hl_handler_snapshot_t *h) {
- memset(h, 0, sizeof(*h));
- snprintf(h->props_json, sizeof(h->props_json), "{}");
- if (!handler_node) {
- return;
- }
- if (handler_node->file_path) {
- snprintf(h->file, sizeof(h->file), "%s", handler_node->file_path);
- }
- if (handler_node->label) {
- snprintf(h->label, sizeof(h->label), "%s", handler_node->label);
- }
- if (handler_node->name) {
- snprintf(h->name, sizeof(h->name), "%s", handler_node->name);
- }
- if (handler_node->qualified_name) {
- snprintf(h->qn, sizeof(h->qn), "%s", handler_node->qualified_name);
- }
- if (handler_node->properties_json) {
- snprintf(h->props_json, sizeof(h->props_json), "%s", handler_node->properties_json);
- }
- h->start = handler_node->start_line;
- h->end = handler_node->end_line;
- h->id = handler_node->id;
-}
-
-/* Build Route node properties JSON with optional protocol detection. */
-static void build_route_props(char *props, size_t props_size, const cbm_route_handler_t *rh,
- const char *handler_qn, const hl_handler_snapshot_t *h,
- const cbm_pipeline_ctx_t *ctx) {
- int n = snprintf(props, props_size, "{\"method\":\"%s\",\"path\":\"%s\",\"handler\":\"%s\"",
- rh->method, rh->path, handler_qn);
- if (rh->protocol[0]) {
- n += snprintf(props + n, props_size - (size_t)n, ",\"protocol\":\"%s\"", rh->protocol);
- } else if (h->id > 0 && h->file[0] && h->start > 0) {
- char *hsource = read_source_lines(ctx, h->file, h->start, h->end);
- if (hsource) {
- const char *proto = cbm_detect_protocol(hsource);
- if (proto[0]) {
- n += snprintf(props + n, props_size - (size_t)n, ",\"protocol\":\"%s\"", proto);
- }
- free(hsource);
- }
- }
- snprintf(props + n, props_size - (size_t)n, "}");
-}
-
-/* Build normalized Route QN from method and path. */
-static void build_route_qn(char *route_qn, size_t qn_size, const cbm_route_handler_t *rh) {
- char normal_method[16];
- snprintf(normal_method, sizeof(normal_method), "%s", rh->method[0] ? rh->method : "ANY");
-
- char normal_path[256];
- snprintf(normal_path, sizeof(normal_path), "%s", rh->path);
- for (char *c = normal_path; *c; c++) {
- if (*c == '/') {
- *c = '_';
- }
- }
- char *np = normal_path;
- while (*np == '_') {
- np++;
- }
- size_t nplen = strlen(np);
- while (nplen > 0 && np[nplen - 1] == '_') {
- np[--nplen] = '\0';
- }
-
- snprintf(route_qn, qn_size, "%s.route.%s.%s", rh->qualified_name, normal_method, np);
-}
-
-/* Insert Route nodes and HANDLES edges for discovered routes.
- * Uses ResolvedHandlerQN if set (from createRegistrationCallEdges). */
-static int insert_route_nodes(cbm_pipeline_ctx_t *ctx, cbm_route_handler_t *routes,
- int route_count) {
- int count = 0;
- for (int i = 0; i < route_count; i++) {
- cbm_route_handler_t *rh = &routes[i];
-
- char route_qn[1024];
- build_route_qn(route_qn, sizeof(route_qn), rh);
-
- char normal_method[16];
- snprintf(normal_method, sizeof(normal_method), "%s", rh->method[0] ? rh->method : "ANY");
- char route_name[256];
- snprintf(route_name, sizeof(route_name), "%s %s", normal_method, rh->path);
-
- const char *handler_qn = rh->qualified_name;
- if (rh->resolved_handler_qn[0]) {
- handler_qn = rh->resolved_handler_qn;
- }
-
- hl_handler_snapshot_t h;
- snapshot_handler_node(cbm_gbuf_find_by_qn(ctx->gbuf, handler_qn), &h);
-
- char props[512];
- build_route_props(props, sizeof(props), rh, handler_qn, &h, ctx);
-
- int64_t route_id = cbm_gbuf_upsert_node(ctx->gbuf, "Route", route_name, route_qn, h.file,
- h.start, h.end, props);
- if (route_id <= 0) {
- continue;
- }
-
- if (h.id > 0) {
- cbm_gbuf_insert_edge(ctx->gbuf, h.id, route_id, "HANDLES", "{}");
-
- char *new_props = set_entry_point(h.props_json);
- if (new_props) {
- cbm_gbuf_upsert_node(ctx->gbuf, h.label, h.name, h.qn, h.file, h.start, h.end,
- new_props);
- free(new_props);
- }
- }
-
- count++;
- }
- return count;
-}
-
-/* ── Match and link ────────────────────────────────────────────── */
-
-/* Match one call site against all routes and create edges. Returns number of links created. */
-static int match_site_to_routes(cbm_pipeline_ctx_t *ctx, const cbm_http_call_site_t *cs,
- const cbm_gbuf_node_t *caller, const cbm_route_handler_t *routes,
- int route_count) {
- int links = 0;
- for (int ri = 0; ri < route_count; ri++) {
- const cbm_route_handler_t *rh = &routes[ri];
-
- if (cbm_same_service(cs->source_qn, rh->qualified_name)) {
- continue;
- }
- if (cbm_is_path_excluded(rh->path, cbm_default_exclude_paths,
- cbm_default_exclude_paths_count)) {
- continue;
- }
-
- double score = cbm_path_match_score(cs->path, rh->path);
- if (score < MIN_PATH_CONFIDENCE) {
- continue;
- }
-
- double weight = (strcmp(cs->source_label, "Module") == 0) ? MODULE_WEIGHT : 1.0;
- score *= weight;
- if (score > 1.0) {
- score = 1.0;
- }
-
- const char *handler_qn = rh->qualified_name;
- if (rh->resolved_handler_qn[0]) {
- handler_qn = rh->resolved_handler_qn;
- }
- const cbm_gbuf_node_t *handler = cbm_gbuf_find_by_qn(ctx->gbuf, handler_qn);
- if (!handler) {
- continue;
- }
-
- const char *edge_type = cs->is_async ? "ASYNC_CALLS" : "HTTP_CALLS";
- const char *band = cbm_confidence_band(score);
-
- char edge_props[256];
- snprintf(edge_props, sizeof(edge_props),
- "{\"url_path\":\"%s\",\"confidence\":%.3f,\"confidence_band\":\"%s\"}", cs->path,
- score, band);
-
- cbm_gbuf_insert_edge(ctx->gbuf, caller->id, handler->id, edge_type, edge_props);
- links++;
- }
- return links;
-}
-
-/* Match call sites to routes and create HTTP_CALLS/ASYNC_CALLS edges. */
-static int match_and_link(cbm_pipeline_ctx_t *ctx, cbm_route_handler_t *routes, int route_count,
- cbm_http_call_site_t *sites, int site_count) {
- int link_count = 0;
-
- for (int si = 0; si < site_count; si++) {
- const cbm_http_call_site_t *cs = &sites[si];
- const cbm_gbuf_node_t *caller = cbm_gbuf_find_by_qn(ctx->gbuf, cs->source_qn);
- if (!caller) {
- continue;
- }
- link_count += match_site_to_routes(ctx, cs, caller, routes, route_count);
- }
-
- return link_count;
-}
-
-/* ── Parallel route discovery ──────────────────────────────────── */
-
-/* Node entry for flat work array (tagged union of Function/Method/Module). */
-typedef struct {
- const cbm_gbuf_node_t *node;
- bool is_module; /* true = Module, false = Function/Method */
-} hl_work_item_t;
-
-/* Per-worker buffer for route discovery. */
-#define HL_ROUTES_PER_WORKER 512
-typedef struct {
- cbm_route_handler_t routes[HL_ROUTES_PER_WORKER];
- int count;
-} hl_route_buf_t;
-
-/* Context for parallel route discovery. */
-typedef struct {
- const hl_work_item_t *items;
- int item_count;
- const cbm_pipeline_ctx_t *ctx;
- hl_route_buf_t *worker_bufs; /* one per worker */
- int worker_count;
- _Atomic int next_idx;
- _Atomic int *cancelled;
-} hl_route_ctx_t;
-
-static void hl_route_worker(int worker_id, void *arg) {
- hl_route_ctx_t *rc = arg;
- hl_route_buf_t *buf = &rc->worker_bufs[worker_id];
-
- while (1) {
- int idx = atomic_fetch_add_explicit(&rc->next_idx, 1, memory_order_relaxed);
- if (idx >= rc->item_count) {
- break;
- }
- if (atomic_load_explicit(rc->cancelled, memory_order_relaxed)) {
- break;
- }
-
- const hl_work_item_t *item = &rc->items[idx];
-
- /* Skip test nodes */
- if (is_test_node(item->node)) {
- continue;
- }
-
- int space = HL_ROUTES_PER_WORKER - buf->count;
- if (space <= 0) {
- continue; /* worker buffer full */
- }
-
- int nr;
- if (item->is_module) {
- nr = discover_module_routes(item->node, rc->ctx, buf->routes + buf->count, space);
- } else {
- nr = discover_node_routes(item->node, rc->ctx, buf->routes + buf->count, space);
- }
- buf->count += nr;
- }
-}
-
-/* Per-worker buffer for call site discovery. */
-#define HL_SITES_PER_WORKER 512
-typedef struct {
- cbm_http_call_site_t sites[HL_SITES_PER_WORKER];
- int count;
-} hl_site_buf_t;
-
-/* Context for parallel call site discovery. */
-typedef struct {
- const cbm_gbuf_node_t **nodes;
- const char **labels; /* "Function" or "Method" per node */
- int node_count;
- const cbm_pipeline_ctx_t *ctx;
- hl_site_buf_t *worker_bufs;
- int worker_count;
- _Atomic int next_idx;
- _Atomic int *cancelled;
-} hl_site_ctx_t;
-
-/* Check if source contains HTTP client or async dispatch keywords.
- * Returns: 0 = neither, 1 = http only, 2 = async only, 3 = both. */
-static int check_http_async_keywords(const char *source) {
- bool has_http = false;
- for (int k = 0; k < cbm_http_client_keywords_count; k++) {
- if (strstr(source, cbm_http_client_keywords[k])) {
- has_http = true;
- break;
- }
- }
- bool has_async = false;
- for (int k = 0; k < cbm_async_dispatch_keywords_count; k++) {
- if (strstr(source, cbm_async_dispatch_keywords[k])) {
- has_async = true;
- break;
- }
- }
- return (has_http ? 1 : 0) | (has_async ? 2 : 0);
-}
-
-/* Return true if name looks like a Python dunder method (__xxx__). */
-static bool is_dunder_method(const char *name) {
- if (!name) {
- return false;
- }
- size_t len = strlen(name);
- return len > 4 && name[0] == '_' && name[1] == '_' && name[len - 1] == '_' &&
- name[len - 2] == '_';
-}
-
-/* Store extracted URL paths as call sites in the worker buffer. */
-static void store_site_paths(hl_site_buf_t *buf, const char *source, const cbm_gbuf_node_t *n,
- const char *label, bool is_async) {
- char *paths[64];
- int path_count = cbm_extract_url_paths(source, paths, 64);
-
- int space = HL_SITES_PER_WORKER - buf->count;
- for (int p = 0; p < path_count && space > 0; p++) {
- cbm_http_call_site_t *site = &buf->sites[buf->count];
- snprintf(site->path, sizeof(site->path), "%s", paths[p]);
- site->method[0] = '\0';
- snprintf(site->source_name, sizeof(site->source_name), "%s", n->name);
- snprintf(site->source_qn, sizeof(site->source_qn), "%s", n->qualified_name);
- snprintf(site->source_label, sizeof(site->source_label), "%s", label);
- site->is_async = is_async;
- buf->count++;
- space--;
- }
- for (int p = 0; p < path_count; p++) {
- free(paths[p]);
- }
-}
-
-static void hl_site_worker(int worker_id, void *arg) {
- hl_site_ctx_t *sc = arg;
- hl_site_buf_t *buf = &sc->worker_bufs[worker_id];
-
- while (1) {
- int idx = atomic_fetch_add_explicit(&sc->next_idx, 1, memory_order_relaxed);
- if (idx >= sc->node_count) {
- break;
- }
- if (atomic_load_explicit(sc->cancelled, memory_order_relaxed)) {
- break;
- }
-
- const cbm_gbuf_node_t *n = sc->nodes[idx];
- if (!n->file_path || n->start_line <= 0 || n->end_line <= 0) {
- continue;
- }
- if (is_dunder_method(n->name)) {
- continue;
- }
-
- char *source = read_source_lines(sc->ctx, n->file_path, n->start_line, n->end_line);
- if (!source) {
- continue;
- }
-
- int kw = check_http_async_keywords(source);
- if (kw == 0) {
- free(source);
- continue;
- }
-
- bool is_async = (kw & 2) && !(kw & 1);
- store_site_paths(buf, source, n, sc->labels[idx], is_async);
- free(source);
- }
-}
-
-/* ── Main pass entry point ─────────────────────────────────────── */
-
-/* Collect routes from Function/Method/Module nodes via parallel workers. */
-static int collect_routes_parallel(cbm_pipeline_ctx_t *ctx, const cbm_gbuf_node_t **label_nodes[3],
- const int label_counts[3], int worker_count,
- cbm_route_handler_t *routes) {
- int total_route_nodes = 0;
- for (int li = 0; li < 3; li++) {
- total_route_nodes += label_counts[li];
- }
-
- hl_work_item_t *work_items = NULL;
- if (total_route_nodes > 0) {
- work_items = malloc((size_t)total_route_nodes * sizeof(hl_work_item_t));
- }
-
- int wi = 0;
- if (work_items) {
- for (int li = 0; li < 3; li++) {
- for (int i = 0; i < label_counts[li]; i++) {
- work_items[wi].node = label_nodes[li][i];
- work_items[wi].is_module = (li == 2);
- wi++;
- }
- }
- }
-
- int route_count = 0;
- hl_route_buf_t *route_bufs = calloc((size_t)worker_count, sizeof(hl_route_buf_t));
-
- if (work_items && route_bufs && wi > 0) {
- hl_route_ctx_t rc = {
- .items = work_items,
- .item_count = wi,
- .ctx = ctx,
- .worker_bufs = route_bufs,
- .worker_count = worker_count,
- .cancelled = ctx->cancelled,
- };
- atomic_init(&rc.next_idx, 0);
-
- cbm_parallel_for_opts_t opts = {.max_workers = worker_count, .force_pthreads = false};
- cbm_parallel_for(worker_count, hl_route_worker, &rc, opts);
-
- for (int w = 0; w < worker_count; w++) {
- int to_copy = route_bufs[w].count;
- if (to_copy > MAX_ROUTES - route_count) {
- to_copy = MAX_ROUTES - route_count;
- }
- if (to_copy > 0) {
- memcpy(routes + route_count, route_bufs[w].routes,
- (size_t)to_copy * sizeof(cbm_route_handler_t));
- route_count += to_copy;
- }
- }
- }
- free(work_items);
- free(route_bufs);
- return route_count;
-}
-
-/* Collect HTTP/async call sites from Function/Method nodes via parallel workers. */
-static int collect_sites_parallel(const cbm_pipeline_ctx_t *ctx,
- const cbm_gbuf_node_t **label_nodes[3], const int label_counts[3],
- int worker_count, cbm_http_call_site_t *sites) {
- const char *site_labels[] = {"Function", "Method"};
- int total_site_nodes = 0;
- for (int li = 0; li < 2; li++) {
- total_site_nodes += label_counts[li];
- }
- if (total_site_nodes == 0) {
- return 0;
- }
-
- const cbm_gbuf_node_t **all_site_nodes =
- malloc((size_t)total_site_nodes * sizeof(cbm_gbuf_node_t *));
- const char **all_site_labels = malloc((size_t)total_site_nodes * sizeof(const char *));
- if (!all_site_nodes || !all_site_labels) {
- free(all_site_nodes);
- free(all_site_labels);
- return 0;
- }
-
- int si2 = 0;
- for (int li = 0; li < 2; li++) {
- for (int i = 0; i < label_counts[li]; i++) {
- all_site_nodes[si2] = label_nodes[li][i];
- all_site_labels[si2] = site_labels[li];
- si2++;
- }
- }
-
- int site_count = 0;
- hl_site_buf_t *site_bufs = calloc((size_t)worker_count, sizeof(hl_site_buf_t));
- if (site_bufs && si2 > 0) {
- hl_site_ctx_t sc = {
- .nodes = all_site_nodes,
- .labels = all_site_labels,
- .node_count = si2,
- .ctx = ctx,
- .worker_bufs = site_bufs,
- .worker_count = worker_count,
- .cancelled = ctx->cancelled,
- };
- atomic_init(&sc.next_idx, 0);
-
- cbm_parallel_for_opts_t opts = {.max_workers = worker_count, .force_pthreads = false};
- cbm_parallel_for(worker_count, hl_site_worker, &sc, opts);
-
- for (int w = 0; w < worker_count; w++) {
- int to_copy = site_bufs[w].count;
- if (to_copy > MAX_CALL_SITES - site_count) {
- to_copy = MAX_CALL_SITES - site_count;
- }
- if (to_copy > 0) {
- memcpy(sites + site_count, site_bufs[w].sites,
- (size_t)to_copy * sizeof(cbm_http_call_site_t));
- site_count += to_copy;
- }
- }
- }
- free(site_bufs);
- free(all_site_nodes);
- free(all_site_labels);
- return site_count;
-}
-
-int cbm_pipeline_pass_httplinks(cbm_pipeline_ctx_t *ctx) {
- cbm_log_info("pass.start", "pass", "httplinks");
-
- if (cbm_pipeline_check_cancel(ctx)) {
- return -1;
- }
-
- int worker_count = cbm_default_worker_count(true);
- if (worker_count < 1) {
- worker_count = 1;
- }
-
- /* ── Phase 1: Route collection from decorator properties + disk ── */
- const char *route_labels[] = {"Function", "Method", "Module"};
- const cbm_gbuf_node_t **label_nodes[3] = {NULL, NULL, NULL};
- int label_counts[3] = {0, 0, 0};
-
- for (int li = 0; li < 3; li++) {
- cbm_gbuf_find_by_label(ctx->gbuf, route_labels[li], &label_nodes[li], &label_counts[li]);
- }
-
- cbm_route_handler_t *routes = calloc(MAX_ROUTES, sizeof(cbm_route_handler_t));
- if (!routes) {
- return -1;
- }
- int route_count = collect_routes_parallel(ctx, label_nodes, label_counts, worker_count, routes);
- cbm_log_info("httplink.routes", "count", itoa_hl(route_count));
-
- /* ── Phase 2: Resolve cross-file prefixes (serial) ────────── */
- resolve_cross_file_group_prefixes(ctx, routes, route_count);
- resolve_fastapi_prefixes(ctx, routes, route_count);
- resolve_express_prefixes(ctx, routes, route_count);
-
- /* ── Phase 3: Registration edges (serial) ─────────────────── */
- int reg_edges = create_registration_call_edges(ctx, routes, route_count);
- if (reg_edges > 0) {
- cbm_log_info("httplink.registration_edges", "count", itoa_hl(reg_edges));
- }
-
- /* ── Phase 4: Route nodes + HANDLES edges (serial) ────────── */
- int route_nodes = insert_route_nodes(ctx, routes, route_count);
-
- /* ── Phase 5: Call site collection ──────────────────────────── */
- cbm_http_call_site_t *sites = calloc(MAX_CALL_SITES, sizeof(cbm_http_call_site_t));
- int site_count = 0;
- if (sites) {
- site_count = collect_sites_parallel(ctx, label_nodes, label_counts, worker_count, sites);
- }
- cbm_log_info("httplink.callsites", "count", itoa_hl(site_count));
-
- /* ── Phase 6: Match and link (serial) ─────────────────────── */
- int link_count = 0;
- if (sites && site_count > 0 && route_count > 0) {
- link_count = match_and_link(ctx, routes, route_count, sites, site_count);
- }
-
- free(routes);
- free(sites);
-
- cbm_log_info("pass.done", "pass", "httplinks", "routes", itoa_hl(route_nodes), "calls",
- itoa_hl(link_count));
- return 0;
-}
diff --git a/src/pipeline/pass_infrascan.c b/src/pipeline/pass_infrascan.c
index 5dcd21984..d15004b05 100644
--- a/src/pipeline/pass_infrascan.c
+++ b/src/pipeline/pass_infrascan.c
@@ -5,6 +5,31 @@
* secret filtering, and parsing Dockerfiles, .env files, shell scripts,
* and Terraform files.
*/
+#include "foundation/constants.h"
+
+enum {
+ IS_ENV_EXT = 4, /* strlen(".env") */
+ IS_CONTENT_LIMIT = 4096,
+ IS_MAX_STAGES = 16,
+ IS_MAX_PORTS = 16,
+ IS_MAX_SOURCES = 16,
+ IS_TOKEN_MIN_1 = 16, /* min alnum for AWS key */
+ IS_TOKEN_MIN_2 = 20, /* min alnum for GH classic token */
+ IS_FROM_SKIP = 4, /* strlen("FROM") */
+ IS_EXPOSE_SKIP = 6, /* strlen("EXPOSE") */
+ IS_RUN_SKIP = 3, /* strlen("RUN") / strlen("ENV") / strlen("ARG") */
+ IS_CMD_SKIP = 4, /* strlen("CMD ") */
+ IS_USER_SKIP = 5, /* strlen("USER ") */
+ IS_EXPORT_SKIP = 7, /* strlen("export ") */
+ IS_WORKDIR_SKIP = 8, /* strlen("WORKDIR ") */
+ IS_ENTRYPOINT_OFF = 10, /* strlen("ENTRYPOINT") */
+ IS_AS_SKIP = 3, /* strlen("AS ") */
+ IS_SOURCE_DOT = 2, /* strlen(". ") */
+ IS_QUOTE_TRIM = 2, /* strip surrounding quotes */
+};
+#define IS_NOT_FOUND (-1)
+
+#define SLEN(s) (sizeof(s) - 1)
#include "pipeline/pipeline.h"
#include "pipeline/pipeline_internal.h"
@@ -30,7 +55,7 @@ static void to_lower(const char *src, char *dst, size_t dst_sz) {
size_t i;
size_t len = strlen(src);
if (len >= dst_sz) {
- len = dst_sz - 1;
+ len = dst_sz - SKIP_ONE;
}
for (i = 0; i < len; i++) {
dst[i] = (char)tolower((unsigned char)src[i]);
@@ -81,7 +106,7 @@ static const char *skip_ws(const char *p) {
/* Extract a word ([a-zA-Z0-9_]+) into buf. Returns length. */
static int extract_word(const char *p, char *buf, size_t buf_sz) {
int n = 0;
- while ((isalnum((unsigned char)p[n]) || p[n] == '_') && (size_t)n < buf_sz - 1) {
+ while ((isalnum((unsigned char)p[n]) || p[n] == '_') && (size_t)n < buf_sz - SKIP_ONE) {
buf[n] = p[n];
n++;
}
@@ -92,7 +117,7 @@ static int extract_word(const char *p, char *buf, size_t buf_sz) {
/* Extract a non-space token into buf. Returns length. */
static int extract_token(const char *p, char *buf, size_t buf_sz) {
int n = 0;
- while (p[n] && p[n] != ' ' && p[n] != '\t' && (size_t)n < buf_sz - 1) {
+ while (p[n] && p[n] != ' ' && p[n] != '\t' && (size_t)n < buf_sz - SKIP_ONE) {
buf[n] = p[n];
n++;
}
@@ -103,8 +128,8 @@ static int extract_token(const char *p, char *buf, size_t buf_sz) {
/* Trim trailing whitespace in-place */
static void rtrim(char *s) {
size_t len = strlen(s);
- while (len > 0 &&
- (s[len - 1] == ' ' || s[len - 1] == '\t' || s[len - 1] == '\r' || s[len - 1] == '\n')) {
+ while (len > 0 && (s[len - SKIP_ONE] == ' ' || s[len - SKIP_ONE] == '\t' ||
+ s[len - SKIP_ONE] == '\r' || s[len - SKIP_ONE] == '\n')) {
s[--len] = '\0';
}
}
@@ -115,7 +140,7 @@ bool cbm_is_dockerfile(const char *name) {
if (!name) {
return false;
}
- char lower[256];
+ char lower[CBM_SZ_256];
to_lower(name, lower, sizeof(lower));
if (strcmp(lower, "dockerfile") == 0) {
@@ -135,7 +160,7 @@ bool cbm_is_compose_file(const char *name) {
if (!name) {
return false;
}
- char lower[256];
+ char lower[CBM_SZ_256];
to_lower(name, lower, sizeof(lower));
bool prefix_match = (strncmp(lower, "docker-compose", LEN_DOCKER_COMPOSE) == 0) ||
@@ -155,10 +180,10 @@ bool cbm_is_cloudbuild_file(const char *name) {
if (!name) {
return false;
}
- char lower[256];
+ char lower[CBM_SZ_256];
to_lower(name, lower, sizeof(lower));
- if (strncmp(lower, "cloudbuild", 10) != 0) {
+ if (strncmp(lower, "cloudbuild", SLEN("cloudbuild")) != 0) {
return false;
}
const char *ext = strrchr(lower, '.');
@@ -172,17 +197,17 @@ bool cbm_is_env_file(const char *name) {
if (!name) {
return false;
}
- char lower[256];
+ char lower[CBM_SZ_256];
to_lower(name, lower, sizeof(lower));
if (strcmp(lower, ".env") == 0) {
return true;
}
- if (strncmp(lower, ".env.", 5) == 0) {
+ if (strncmp(lower, ".env.", SLEN(".env.")) == 0) {
return true;
}
size_t len = strlen(lower);
- if (len > 4 && strcmp(lower + len - 4, ".env") == 0) {
+ if (len > IS_ENV_EXT && strcmp(lower + len - IS_ENV_EXT, ".env") == 0) {
return true;
}
return false;
@@ -192,7 +217,7 @@ bool cbm_is_kustomize_file(const char *name) {
if (!name) {
return false;
}
- char lower[256];
+ char lower[CBM_SZ_256];
to_lower(name, lower, sizeof(lower));
if (strcmp(lower, "kustomization.yaml") == 0) {
return true;
@@ -206,7 +231,7 @@ bool cbm_is_k8s_manifest(const char *name, const char *content) {
}
enum { K8S_PEEK_SZ = 4097 };
char buf[K8S_PEEK_SZ];
- size_t n = strnlen(content, 4096);
+ size_t n = strnlen(content, IS_CONTENT_LIMIT);
memcpy(buf, content, n);
buf[n] = '\0';
return ci_strstr(buf, "apiVersion:") != NULL;
@@ -251,34 +276,35 @@ bool cbm_is_secret_value(const char *value) {
/* AKIA + 16 alnum (AWS key) */
p = ci_strstr(value, "AKIA");
- if (p && count_alnum(p + 4) >= 16) {
+ if (p && count_alnum(p + IS_CMD_SKIP) >= IS_TOKEN_MIN_1) {
return true;
}
/* sk- + 20 alnum (API key) */
p = ci_strstr(value, "sk-");
- if (p && count_alnum(p + 3) >= 20) {
+ if (p && count_alnum(p + IS_RUN_SKIP) >= IS_TOKEN_MIN_2) {
return true;
}
/* ghp_ + 36 alnum (GitHub PAT) */
p = ci_strstr(value, "ghp_");
- if (p && count_alnum(p + 4) >= GITHUB_PAT_MIN_ALNUM) {
+ if (p && count_alnum(p + IS_CMD_SKIP) >= GITHUB_PAT_MIN_ALNUM) {
return true;
}
/* glpat- + 20 alnum/dash (GitLab PAT) */
p = ci_strstr(value, "glpat-");
- if (p && count_alnum_dash(p + 6) >= 20) {
+ if (p && count_alnum_dash(p + IS_EXPOSE_SKIP) >= IS_TOKEN_MIN_2) {
return true;
}
/* xox[bps]- (Slack token) */
p = ci_strstr(value, "xox");
- if (p && p[3] != '\0' &&
- (tolower((unsigned char)p[3]) == 'b' || tolower((unsigned char)p[3]) == 'p' ||
- tolower((unsigned char)p[3]) == 's') &&
- p[4] == '-' && count_alnum_dash(p + 5) >= 1) {
+ if (p && p[IS_RUN_SKIP] != '\0' &&
+ (tolower((unsigned char)p[IS_RUN_SKIP]) == 'b' ||
+ tolower((unsigned char)p[IS_RUN_SKIP]) == 'p' ||
+ tolower((unsigned char)p[IS_RUN_SKIP]) == 's') &&
+ p[IS_CMD_SKIP] == '-' && count_alnum_dash(p + IS_USER_SKIP) >= SKIP_ONE) {
return true;
}
@@ -301,7 +327,7 @@ bool cbm_is_secret_binding(const char *key, const char *value) {
static void clean_json_array_inner(const char *s, size_t len, char *out, size_t out_sz) {
size_t pos = 0;
bool in_space = false;
- for (size_t i = 1; i < len - 1 && pos < out_sz - 1; i++) {
+ for (size_t i = SKIP_ONE; i < len - SKIP_ONE && pos < out_sz - SKIP_ONE; i++) {
char c = s[i];
if (c == '"') {
continue;
@@ -319,7 +345,7 @@ static void clean_json_array_inner(const char *s, size_t len, char *out, size_t
in_space = false;
}
}
- while (pos > 0 && out[pos - 1] == ' ') {
+ while (pos > 0 && out[pos - SKIP_ONE] == ' ') {
pos--;
}
out[pos] = '\0';
@@ -331,7 +357,7 @@ void cbm_clean_json_brackets(const char *s, char *out, size_t out_sz) {
}
size_t len = strlen(s);
- if (len >= 2 && s[0] == '[' && s[len - 1] == ']') {
+ if (len >= PAIR_LEN && s[0] == '[' && s[len - SKIP_ONE] == ']') {
clean_json_array_inner(s, len, out, out_sz);
} else {
snprintf(out, out_sz, "%s", s);
@@ -341,17 +367,17 @@ void cbm_clean_json_brackets(const char *s, char *out, size_t out_sz) {
/* ── Dockerfile parser ──────────────────────────────────────────── */
static void df_parse_from(const char *line, cbm_dockerfile_result_t *r) {
- if (strncasecmp(line, "FROM", 4) != 0) {
+ if (strncasecmp(line, "FROM", SLEN("FROM")) != 0) {
return;
}
- const char *p = line + 4;
+ const char *p = line + IS_FROM_SKIP;
if (*p != ' ' && *p != '\t') {
return;
}
p = skip_ws(p);
/* Extract image */
- if (r->stage_count >= 16) {
+ if (r->stage_count >= IS_MAX_STAGES) {
return;
}
int idx = r->stage_count;
@@ -365,26 +391,26 @@ static void df_parse_from(const char *line, cbm_dockerfile_result_t *r) {
/* Check for AS <name> */
r->stage_names[idx][0] = '\0';
- if (strncasecmp(p, "AS", 2) == 0 && (p[2] == ' ' || p[2] == '\t')) {
- p = skip_ws(p + 3);
+ if (strncasecmp(p, "AS", SLEN("AS")) == 0 && (p[PAIR_LEN] == ' ' || p[PAIR_LEN] == '\t')) {
+ p = skip_ws(p + IS_AS_SKIP);
extract_word(p, r->stage_names[idx], sizeof(r->stage_names[idx]));
}
r->stage_count++;
}
static void df_parse_expose(const char *line, cbm_dockerfile_result_t *r) {
- if (strncasecmp(line, "EXPOSE", 6) != 0) {
+ if (strncasecmp(line, "EXPOSE", SLEN("EXPOSE")) != 0) {
return;
}
- const char *p = line + 6;
+ const char *p = line + IS_EXPOSE_SKIP;
if (*p != ' ' && *p != '\t') {
return;
}
p = skip_ws(p);
/* Parse space-separated ports */
- while (*p && r->port_count < 16) {
- char port[32];
+ while (*p && r->port_count < IS_MAX_PORTS) {
+ char port[CBM_SZ_32];
int n = extract_token(p, port, sizeof(port));
if (n == 0) {
break;
@@ -405,21 +431,21 @@ static void df_parse_expose(const char *line, cbm_dockerfile_result_t *r) {
}
static void df_parse_env(const char *line, cbm_dockerfile_result_t *r) {
- if (strncasecmp(line, "ENV", 3) != 0) {
+ if (strncasecmp(line, "ENV", SLEN("ENV")) != 0) {
return;
}
- const char *p = line + 3;
+ const char *p = line + IS_RUN_SKIP;
if (*p != ' ' && *p != '\t') {
return;
}
p = skip_ws(p);
- if (r->env_count >= 64) {
+ if (r->env_count >= CBM_SZ_64) {
return;
}
/* Extract key */
- char key[128];
+ char key[CBM_SZ_128];
int klen = extract_word(p, key, sizeof(key));
if (klen == 0) {
return;
@@ -437,7 +463,7 @@ static void df_parse_env(const char *line, cbm_dockerfile_result_t *r) {
}
/* Value is rest of line (trimmed) */
- char value[512];
+ char value[CBM_SZ_512];
snprintf(value, sizeof(value), "%s", p);
rtrim(value);
@@ -452,16 +478,16 @@ static void df_parse_env(const char *line, cbm_dockerfile_result_t *r) {
}
static void df_parse_arg(const char *line, cbm_dockerfile_result_t *r) {
- if (strncasecmp(line, "ARG", 3) != 0) {
+ if (strncasecmp(line, "ARG", SLEN("ARG")) != 0) {
return;
}
- const char *p = line + 3;
+ const char *p = line + IS_RUN_SKIP;
if (*p != ' ' && *p != '\t') {
return;
}
p = skip_ws(p);
- if (r->build_arg_count >= 32) {
+ if (r->build_arg_count >= CBM_SZ_32) {
return;
}
extract_word(p, r->build_args[r->build_arg_count], sizeof(r->build_args[0]));
@@ -473,29 +499,33 @@ static void df_parse_arg(const char *line, cbm_dockerfile_result_t *r) {
/* Parse a Dockerfile CMD/ENTRYPOINT value: strip brackets, trim. */
static void df_parse_json_cmd(const char *line, int prefix_len, char *out, size_t out_sz) {
const char *p = skip_ws(line + prefix_len);
- char raw[512];
+ char raw[CBM_SZ_512];
snprintf(raw, sizeof(raw), "%s", p);
rtrim(raw);
cbm_clean_json_brackets(raw, out, out_sz);
}
static void df_parse_directives(const char *line, cbm_dockerfile_result_t *r) {
- if (strncasecmp(line, "WORKDIR", 7) == 0 && (line[7] == ' ' || line[7] == '\t')) {
- const char *p = skip_ws(line + 8);
+ if (strncasecmp(line, "WORKDIR", SLEN("WORKDIR")) == 0 &&
+ (line[IS_EXPORT_SKIP] == ' ' || line[IS_EXPORT_SKIP] == '\t')) {
+ const char *p = skip_ws(line + IS_WORKDIR_SKIP);
snprintf(r->workdir, sizeof(r->workdir), "%s", p);
rtrim(r->workdir);
return;
}
- if (strncasecmp(line, "CMD", 3) == 0 && (line[3] == ' ' || line[3] == '\t')) {
- df_parse_json_cmd(line, 4, r->cmd, sizeof(r->cmd));
+ if (strncasecmp(line, "CMD", SLEN("CMD")) == 0 &&
+ (line[IS_RUN_SKIP] == ' ' || line[IS_RUN_SKIP] == '\t')) {
+ df_parse_json_cmd(line, IS_CMD_SKIP, r->cmd, sizeof(r->cmd));
return;
}
- if (strncasecmp(line, "ENTRYPOINT", 10) == 0 && (line[10] == ' ' || line[10] == '\t')) {
+ if (strncasecmp(line, "ENTRYPOINT", SLEN("ENTRYPOINT")) == 0 &&
+ (line[IS_ENTRYPOINT_OFF] == ' ' || line[IS_ENTRYPOINT_OFF] == '\t')) {
df_parse_json_cmd(line, LEN_HEALTHCHECK, r->entrypoint, sizeof(r->entrypoint));
return;
}
- if (strncasecmp(line, "USER", 4) == 0 && (line[4] == ' ' || line[4] == '\t')) {
- const char *p = skip_ws(line + 5);
+ if (strncasecmp(line, "USER", SLEN("USER")) == 0 &&
+ (line[IS_CMD_SKIP] == ' ' || line[IS_CMD_SKIP] == '\t')) {
+ const char *p = skip_ws(line + IS_USER_SKIP);
extract_word(p, r->user, sizeof(r->user));
return;
}
@@ -503,7 +533,7 @@ static void df_parse_directives(const char *line, cbm_dockerfile_result_t *r) {
(line[LEN_HEALTHCHECK] == ' ' || line[LEN_HEALTHCHECK] == '\t')) {
const char *cmd_pos = ci_strstr(line + LEN_HEALTHCHECK, "CMD");
if (cmd_pos) {
- cmd_pos = skip_ws(cmd_pos + 3);
+ cmd_pos = skip_ws(cmd_pos + IS_RUN_SKIP);
snprintf(r->healthcheck, sizeof(r->healthcheck), "%s", cmd_pos);
rtrim(r->healthcheck);
}
@@ -512,24 +542,24 @@ static void df_parse_directives(const char *line, cbm_dockerfile_result_t *r) {
int cbm_parse_dockerfile_source(const char *source, cbm_dockerfile_result_t *out) {
if (!source || !out) {
- return -1;
+ return CBM_NOT_FOUND;
}
memset(out, 0, sizeof(*out));
/* Process line by line */
const char *p = source;
- char line[4096];
+ char line[CBM_SZ_4K];
while (*p) {
/* Extract one line */
const char *eol = strchr(p, '\n');
size_t line_len = eol ? (size_t)(eol - p) : strlen(p);
if (line_len >= sizeof(line)) {
- line_len = sizeof(line) - 1;
+ line_len = sizeof(line) - SKIP_ONE;
}
memcpy(line, p, line_len);
line[line_len] = '\0';
- p = eol ? eol + 1 : p + line_len;
+ p = eol ? eol + SKIP_ONE : p + line_len;
/* Trim */
char *trimmed = line;
@@ -552,13 +582,13 @@ int cbm_parse_dockerfile_source(const char *source, cbm_dockerfile_result_t *out
/* No stages = empty/invalid Dockerfile */
if (out->stage_count == 0) {
- return -1;
+ return CBM_NOT_FOUND;
}
/* base_image = last stage's image (use intermediate copy to avoid restrict overlap) */
{
char tmp[sizeof(out->base_image)];
- snprintf(tmp, sizeof(tmp), "%s", out->stage_images[out->stage_count - 1]);
+ snprintf(tmp, sizeof(tmp), "%s", out->stage_images[out->stage_count - SKIP_ONE]);
memcpy(out->base_image, tmp, sizeof(out->base_image));
}
@@ -570,16 +600,16 @@ int cbm_parse_dockerfile_source(const char *source, cbm_dockerfile_result_t *out
/* Strip matching surrounding quotes from a value string in-place. */
static void strip_surrounding_quotes(char *value) {
size_t vlen = strlen(value);
- if (vlen >= 2 && ((value[0] == '"' && value[vlen - 1] == '"') ||
- (value[0] == '\'' && value[vlen - 1] == '\''))) {
- memmove(value, value + 1, vlen - 2);
- value[vlen - 2] = '\0';
+ if (vlen >= CBM_QUOTE_PAIR && ((value[0] == '"' && value[vlen - SKIP_ONE] == '"') ||
+ (value[0] == '\'' && value[vlen - SKIP_ONE] == '\''))) {
+ memmove(value, value + CBM_QUOTE_OFFSET, vlen - CBM_QUOTE_PAIR);
+ value[vlen - IS_QUOTE_TRIM] = '\0';
}
}
/* Parse a single dotenv line: KEY=VALUE. Returns 1 if env var added. */
static int parse_dotenv_line(const char *trimmed, cbm_dotenv_result_t *out) {
- char key[128];
+ char key[CBM_SZ_128];
int klen = 0;
if (isalpha((unsigned char)trimmed[0]) || trimmed[0] == '_') {
klen = extract_word(trimmed, key, sizeof(key));
@@ -588,38 +618,38 @@ static int parse_dotenv_line(const char *trimmed, cbm_dotenv_result_t *out) {
return 0;
}
- char value[512];
- snprintf(value, sizeof(value), "%s", trimmed + klen + 1);
+ char value[CBM_SZ_512];
+ snprintf(value, sizeof(value), "%s", trimmed + klen + SKIP_ONE);
rtrim(value);
strip_surrounding_quotes(value);
- if (cbm_is_secret_binding(key, value) || out->env_count >= 64) {
+ if (cbm_is_secret_binding(key, value) || out->env_count >= CBM_SZ_64) {
return 0;
}
snprintf(out->env_vars[out->env_count].key, sizeof(out->env_vars[0].key), "%s", key);
snprintf(out->env_vars[out->env_count].value, sizeof(out->env_vars[0].value), "%s", value);
out->env_count++;
- return 1;
+ return SKIP_ONE;
}
int cbm_parse_dotenv_source(const char *source, cbm_dotenv_result_t *out) {
if (!source || !out) {
- return -1;
+ return CBM_NOT_FOUND;
}
memset(out, 0, sizeof(*out));
const char *p = source;
- char line[4096];
+ char line[CBM_SZ_4K];
while (*p) {
const char *eol = strchr(p, '\n');
size_t line_len = eol ? (size_t)(eol - p) : strlen(p);
if (line_len >= sizeof(line)) {
- line_len = sizeof(line) - 1;
+ line_len = sizeof(line) - SKIP_ONE;
}
memcpy(line, p, line_len);
line[line_len] = '\0';
- p = eol ? eol + 1 : p + line_len;
+ p = eol ? eol + SKIP_ONE : p + line_len;
char *trimmed = line;
while (*trimmed == ' ' || *trimmed == '\t') {
@@ -634,41 +664,42 @@ int cbm_parse_dotenv_source(const char *source, cbm_dotenv_result_t *out) {
parse_dotenv_line(trimmed, out);
}
- return (out->env_count > 0) ? 0 : -1;
+ return (out->env_count > 0) ? 0 : IS_NOT_FOUND;
}
/* ── Shell script parser ────────────────────────────────────────── */
static void shell_parse_export(const char *line, cbm_shell_result_t *r) {
/* export VAR=VALUE */
- if (strncmp(line, "export", 6) != 0 || (line[6] != ' ' && line[6] != '\t')) {
+ if (strncmp(line, "export", SLEN("export")) != 0 ||
+ (line[IS_EXPOSE_SKIP] != ' ' && line[IS_EXPOSE_SKIP] != '\t')) {
return;
}
- const char *p = skip_ws(line + 7);
+ const char *p = skip_ws(line + IS_EXPORT_SKIP);
- char key[128];
+ char key[CBM_SZ_128];
int klen = extract_word(p, key, sizeof(key));
if (klen == 0 || p[klen] != '=') {
return;
}
- const char *val_start = p + klen + 1;
- char value[512];
+ const char *val_start = p + klen + SKIP_ONE;
+ char value[CBM_SZ_512];
snprintf(value, sizeof(value), "%s", val_start);
rtrim(value);
/* Strip surrounding quotes */
size_t vlen = strlen(value);
- if (vlen >= 2 && ((value[0] == '"' && value[vlen - 1] == '"') ||
- (value[0] == '\'' && value[vlen - 1] == '\''))) {
- memmove(value, value + 1, vlen - 2);
- value[vlen - 2] = '\0';
+ if (vlen >= CBM_QUOTE_PAIR && ((value[0] == '"' && value[vlen - SKIP_ONE] == '"') ||
+ (value[0] == '\'' && value[vlen - SKIP_ONE] == '\''))) {
+ memmove(value, value + CBM_QUOTE_OFFSET, vlen - CBM_QUOTE_PAIR);
+ value[vlen - IS_QUOTE_TRIM] = '\0';
}
if (cbm_is_secret_binding(key, value)) {
return;
}
- if (r->env_count >= 64) {
+ if (r->env_count >= CBM_SZ_64) {
return;
}
snprintf(r->env_vars[r->env_count].key, sizeof(r->env_vars[0].key), "%s", key);
@@ -682,29 +713,29 @@ static void shell_parse_plain_var(const char *line, cbm_shell_result_t *r) {
return;
}
- char key[128];
+ char key[CBM_SZ_128];
int klen = extract_word(line, key, sizeof(key));
if (klen == 0 || line[klen] != '=') {
return;
}
- const char *val_start = line + klen + 1;
- char value[512];
+ const char *val_start = line + klen + SKIP_ONE;
+ char value[CBM_SZ_512];
snprintf(value, sizeof(value), "%s", val_start);
rtrim(value);
/* Strip surrounding quotes */
size_t vlen = strlen(value);
- if (vlen >= 2 && ((value[0] == '"' && value[vlen - 1] == '"') ||
- (value[0] == '\'' && value[vlen - 1] == '\''))) {
- memmove(value, value + 1, vlen - 2);
- value[vlen - 2] = '\0';
+ if (vlen >= CBM_QUOTE_PAIR && ((value[0] == '"' && value[vlen - SKIP_ONE] == '"') ||
+ (value[0] == '\'' && value[vlen - SKIP_ONE] == '\''))) {
+ memmove(value, value + CBM_QUOTE_OFFSET, vlen - CBM_QUOTE_PAIR);
+ value[vlen - IS_QUOTE_TRIM] = '\0';
}
if (cbm_is_secret_binding(key, value)) {
return;
}
- if (r->env_count >= 64) {
+ if (r->env_count >= CBM_SZ_64) {
return;
}
snprintf(r->env_vars[r->env_count].key, sizeof(r->env_vars[0].key), "%s", key);
@@ -715,28 +746,29 @@ static void shell_parse_plain_var(const char *line, cbm_shell_result_t *r) {
static void shell_parse_source(const char *line, cbm_shell_result_t *r) {
/* source <file> or . <file> */
const char *p = NULL;
- if (strncmp(line, "source", 6) == 0 && (line[6] == ' ' || line[6] == '\t')) {
- p = skip_ws(line + 7);
- } else if (line[0] == '.' && (line[1] == ' ' || line[1] == '\t')) {
- p = skip_ws(line + 2);
+ if (strncmp(line, "source", SLEN("source")) == 0 &&
+ (line[IS_EXPOSE_SKIP] == ' ' || line[IS_EXPOSE_SKIP] == '\t')) {
+ p = skip_ws(line + IS_EXPORT_SKIP);
+ } else if (line[0] == '.' && (line[SKIP_ONE] == ' ' || line[SKIP_ONE] == '\t')) {
+ p = skip_ws(line + IS_SOURCE_DOT);
}
if (!p) {
return;
}
- if (r->source_count >= 16) {
+ if (r->source_count >= IS_MAX_SOURCES) {
return;
}
/* Strip surrounding quotes */
- char path[256];
+ char path[CBM_SZ_256];
snprintf(path, sizeof(path), "%s", p);
rtrim(path);
size_t plen = strlen(path);
- if (plen >= 2 && ((path[0] == '"' && path[plen - 1] == '"') ||
- (path[0] == '\'' && path[plen - 1] == '\''))) {
- memmove(path, path + 1, plen - 2);
- path[plen - 2] = '\0';
+ if (plen >= CBM_QUOTE_PAIR && ((path[0] == '"' && path[plen - SKIP_ONE] == '"') ||
+ (path[0] == '\'' && path[plen - SKIP_ONE] == '\''))) {
+ memmove(path, path + CBM_QUOTE_OFFSET, plen - CBM_QUOTE_PAIR);
+ path[plen - IS_QUOTE_TRIM] = '\0';
}
/* Extract just the path token (no trailing args) */
@@ -758,19 +790,20 @@ static void shell_parse_docker(const char *line, cbm_shell_result_t *r) {
(line[LEN_DOCKER_COMPOSE] == ' ' || line[LEN_DOCKER_COMPOSE] == '\t')) {
tool = "docker-compose";
p = skip_ws(line + LEN_DOCKER_COMPOSE_SKIP);
- } else if (strncmp(line, "docker", 6) == 0 && (line[6] == ' ' || line[6] == '\t')) {
+ } else if (strncmp(line, "docker", SLEN("docker")) == 0 &&
+ (line[IS_EXPOSE_SKIP] == ' ' || line[IS_EXPOSE_SKIP] == '\t')) {
tool = "docker";
- p = skip_ws(line + 7);
+ p = skip_ws(line + IS_EXPORT_SKIP);
}
if (!tool || !p || !*p) {
return;
}
- if (r->docker_cmd_count >= 16) {
+ if (r->docker_cmd_count >= IS_MAX_STAGES) {
return;
}
- char subcmd[64];
+ char subcmd[CBM_SZ_64];
extract_word(p, subcmd, sizeof(subcmd));
if (subcmd[0]) {
snprintf(r->docker_cmds[r->docker_cmd_count], sizeof(r->docker_cmds[0]), "%s %s", tool,
@@ -784,8 +817,8 @@ static bool shell_try_shebang(const char *trimmed, cbm_shell_result_t *out, bool
if (*shebang_checked) {
return false;
}
- if (trimmed[0] == '#' && trimmed[1] == '!') {
- const char *sb = trimmed + 2;
+ if (trimmed[0] == '#' && trimmed[SKIP_ONE] == '!') {
+ const char *sb = trimmed + PAIR_LEN;
while (*sb == ' ') {
sb++;
}
@@ -800,15 +833,16 @@ static bool shell_try_shebang(const char *trimmed, cbm_shell_result_t *out, bool
/* Dispatch a single trimmed shell line to the appropriate parser. */
static void shell_dispatch_line(const char *trimmed, cbm_shell_result_t *out) {
- if (strncmp(trimmed, "export", 6) == 0) {
+ if (strncmp(trimmed, "export", SLEN("export")) == 0) {
shell_parse_export(trimmed, out);
return;
}
- if (strncmp(trimmed, "source", 6) == 0 || (trimmed[0] == '.' && trimmed[1] == ' ')) {
+ if (strncmp(trimmed, "source", SLEN("source")) == 0 ||
+ (trimmed[0] == '.' && trimmed[SKIP_ONE] == ' ')) {
shell_parse_source(trimmed, out);
return;
}
- if (strncmp(trimmed, "docker", 6) == 0) {
+ if (strncmp(trimmed, "docker", SLEN("docker")) == 0) {
shell_parse_docker(trimmed, out);
}
shell_parse_plain_var(trimmed, out);
@@ -816,23 +850,23 @@ static void shell_dispatch_line(const char *trimmed, cbm_shell_result_t *out) {
int cbm_parse_shell_source(const char *source, cbm_shell_result_t *out) {
if (!source || !out) {
- return -1;
+ return CBM_NOT_FOUND;
}
memset(out, 0, sizeof(*out));
const char *p = source;
- char line[4096];
+ char line[CBM_SZ_4K];
bool shebang_checked = false;
while (*p) {
const char *eol = strchr(p, '\n');
size_t line_len = eol ? (size_t)(eol - p) : strlen(p);
if (line_len >= sizeof(line)) {
- line_len = sizeof(line) - 1;
+ line_len = sizeof(line) - SKIP_ONE;
}
memcpy(line, p, line_len);
line[line_len] = '\0';
- p = eol ? eol + 1 : p + line_len;
+ p = eol ? eol + SKIP_ONE : p + line_len;
char *trimmed = line;
while (*trimmed == ' ' || *trimmed == '\t') {
@@ -857,7 +891,7 @@ int cbm_parse_shell_source(const char *source, cbm_shell_result_t *out) {
bool has_content = out->shebang[0] != '\0' || out->env_count > 0 || out->source_count > 0 ||
out->docker_cmd_count > 0;
- return has_content ? 0 : -1;
+ return has_content ? 0 : IS_NOT_FOUND;
}
/* ── Terraform parser ───────────────────────────────────────────── */
@@ -881,7 +915,7 @@ static void tf_extract_quoted(const char *line, const char *prefix, char *out, s
if (*p != '=') {
return;
}
- p = skip_ws(p + 1);
+ p = skip_ws(p + SKIP_ONE);
/* Strip optional quotes */
if (*p == '"') {
@@ -889,7 +923,7 @@ static void tf_extract_quoted(const char *line, const char *prefix, char *out, s
const char *end = strchr(p, '"');
size_t vlen = end ? (size_t)(end - p) : strlen(p);
if (vlen >= out_sz) {
- vlen = out_sz - 1;
+ vlen = out_sz - SKIP_ONE;
}
memcpy(out, p, vlen);
out[vlen] = '\0';
@@ -928,11 +962,11 @@ static int tf_extract_ident(const char *p, const char *keyword, char *out, size_
}
size_t ilen = (size_t)(end - after);
if (ilen >= out_sz) {
- ilen = out_sz - 1;
+ ilen = out_sz - SKIP_ONE;
}
memcpy(out, after, ilen);
out[ilen] = '\0';
- return (int)(end - p + 1);
+ return (int)(end - p + SKIP_ONE);
}
/* Parse a second quoted string after the first ident (for resource/data blocks). */
@@ -945,7 +979,7 @@ static void tf_extract_second_quoted(const char *trimmed, int consumed, char *ou
if (end) {
size_t len = (size_t)(end - rest);
if (len >= outsz) {
- len = outsz - 1;
+ len = outsz - SKIP_ONE;
}
memcpy(out, rest, len);
out[len] = '\0';
@@ -956,7 +990,7 @@ static void tf_extract_second_quoted(const char *trimmed, int consumed, char *ou
/* Try to parse a simple "keyword ident" block (variable, output, provider). */
static bool tf_try_simple_block(const char *trimmed, const char *keyword, char *names, int name_sz,
int *count, int max_count) {
- char ident[128];
+ char ident[CBM_SZ_128];
int consumed = tf_extract_ident(trimmed, keyword, ident, sizeof(ident));
if (consumed <= 0 || *count >= max_count) {
return false;
@@ -969,11 +1003,11 @@ static bool tf_try_simple_block(const char *trimmed, const char *keyword, char *
/* Try to match terraform/locals keyword blocks. */
static bool tf_try_keyword_block(const char *trimmed, tf_block_kind_t *cur_block,
cbm_terraform_result_t *out) {
- if (strncmp(trimmed, "terraform", 9) == 0 && strstr(trimmed, "{")) {
+ if (strncmp(trimmed, "terraform", SLEN("terraform")) == 0 && strstr(trimmed, "{")) {
*cur_block = TF_BLOCK_TERRAFORM;
return true;
}
- if (strncmp(trimmed, "locals", 6) == 0 && strstr(trimmed, "{")) {
+ if (strncmp(trimmed, "locals", SLEN("locals")) == 0 && strstr(trimmed, "{")) {
out->has_locals = true;
return true;
}
@@ -983,13 +1017,13 @@ static bool tf_try_keyword_block(const char *trimmed, tf_block_kind_t *cur_block
/* Detect a top-level block header. Returns true if line was consumed as a header. */
static bool tf_detect_block_header(const char *trimmed, cbm_terraform_result_t *out,
tf_block_kind_t *cur_block, int *cur_var_idx, int *cur_mod_idx) {
- char ident1[128];
+ char ident1[CBM_SZ_128];
/* resource "type" "name" */
{
int rc = tf_extract_ident(trimmed, "resource", ident1, sizeof(ident1));
- if (rc > 0 && out->resource_count < 32) {
- char ident2[128];
+ if (rc > 0 && out->resource_count < CBM_SZ_32) {
+ char ident2[CBM_SZ_128];
tf_extract_second_quoted(trimmed, rc, ident2, sizeof(ident2));
snprintf(out->resources[out->resource_count].type, sizeof(out->resources[0].type), "%s",
ident1);
@@ -1002,7 +1036,7 @@ static bool tf_detect_block_header(const char *trimmed, cbm_terraform_result_t *
/* variable "name" */
int consumed = tf_extract_ident(trimmed, "variable", ident1, sizeof(ident1));
- if (consumed > 0 && out->variable_count < 32) {
+ if (consumed > 0 && out->variable_count < CBM_SZ_32) {
*cur_block = TF_BLOCK_VARIABLE;
*cur_var_idx = out->variable_count;
snprintf(out->variables[*cur_var_idx].name, sizeof(out->variables[0].name), "%s", ident1);
@@ -1012,19 +1046,19 @@ static bool tf_detect_block_header(const char *trimmed, cbm_terraform_result_t *
/* output "name" */
if (tf_try_simple_block(trimmed, "output", out->outputs[0], (int)sizeof(out->outputs[0]),
- &out->output_count, 32)) {
+ &out->output_count, CBM_SZ_32)) {
return true;
}
/* provider "name" */
if (tf_try_simple_block(trimmed, "provider", out->providers[0], (int)sizeof(out->providers[0]),
- &out->provider_count, 16)) {
+ &out->provider_count, IS_MAX_STAGES)) {
return true;
}
/* module "name" */
consumed = tf_extract_ident(trimmed, "module", ident1, sizeof(ident1));
- if (consumed > 0 && out->module_count < 16) {
+ if (consumed > 0 && out->module_count < IS_MAX_STAGES) {
*cur_block = TF_BLOCK_MODULE;
*cur_mod_idx = out->module_count;
snprintf(out->modules[*cur_mod_idx].tf_name, sizeof(out->modules[0].tf_name), "%s", ident1);
@@ -1035,8 +1069,8 @@ static bool tf_detect_block_header(const char *trimmed, cbm_terraform_result_t *
/* data "type" "name" */
{
int dc = tf_extract_ident(trimmed, "data", ident1, sizeof(ident1));
- if (dc > 0 && out->data_source_count < 16) {
- char ident2[128];
+ if (dc > 0 && out->data_source_count < IS_MAX_STAGES) {
+ char ident2[CBM_SZ_128];
tf_extract_second_quoted(trimmed, dc, ident2, sizeof(ident2));
snprintf(out->data_sources[out->data_source_count].type,
sizeof(out->data_sources[0].type), "%s", ident1);
@@ -1052,17 +1086,17 @@ static bool tf_detect_block_header(const char *trimmed, cbm_terraform_result_t *
/* Extract attributes from a line inside a variable block. */
static void tf_parse_variable_attrs(const char *trimmed, cbm_tf_variable_t *v) {
- char def_val[256] = {0};
+ char def_val[CBM_SZ_256] = {0};
tf_extract_quoted(trimmed, "default", def_val, sizeof(def_val));
if (def_val[0] && !cbm_is_secret_binding(v->name, def_val)) {
snprintf(v->default_val, sizeof(v->default_val), "%s", def_val);
}
- char type_val[64] = {0};
+ char type_val[CBM_SZ_64] = {0};
tf_extract_quoted(trimmed, "type", type_val, sizeof(type_val));
if (type_val[0]) {
snprintf(v->type, sizeof(v->type), "%s", type_val);
}
- char desc_val[256] = {0};
+ char desc_val[CBM_SZ_256] = {0};
tf_extract_quoted(trimmed, "description", desc_val, sizeof(desc_val));
if (desc_val[0]) {
snprintf(v->description, sizeof(v->description), "%s", desc_val);
@@ -1080,7 +1114,7 @@ static void tf_parse_block_attrs(const char *trimmed, cbm_terraform_result_t *ou
break;
case TF_BLOCK_MODULE:
if (cur_mod_idx >= 0) {
- char src_val[256] = {0};
+ char src_val[CBM_SZ_256] = {0};
tf_extract_quoted(trimmed, "source", src_val, sizeof(src_val));
if (src_val[0]) {
snprintf(out->modules[cur_mod_idx].source, sizeof(out->modules[0].source), "%s",
@@ -1090,7 +1124,7 @@ static void tf_parse_block_attrs(const char *trimmed, cbm_terraform_result_t *ou
break;
case TF_BLOCK_TERRAFORM: {
const char *bp = skip_ws(trimmed);
- char backend_name[128] = {0};
+ char backend_name[CBM_SZ_128] = {0};
tf_extract_ident(bp, "backend", backend_name, sizeof(backend_name));
if (backend_name[0]) {
snprintf(out->backend, sizeof(out->backend), "%s", backend_name);
@@ -1115,18 +1149,18 @@ static char *tf_next_line(const char **pp, char *line, size_t line_sz) {
const char *eol = strchr(p, '\n');
size_t len = eol ? (size_t)(eol - p) : strlen(p);
if (len >= line_sz) {
- len = line_sz - 1;
+ len = line_sz - SKIP_ONE;
}
memcpy(line, p, len);
line[len] = '\0';
- *pp = eol ? eol + 1 : p + len;
+ *pp = eol ? eol + SKIP_ONE : p + len;
char *trimmed = line;
while (*trimmed == ' ' || *trimmed == '\t') {
trimmed++;
}
rtrim(trimmed);
- if (*trimmed == '\0' || *trimmed == '#' || (trimmed[0] == '/' && trimmed[1] == '/')) {
+ if (*trimmed == '\0' || *trimmed == '#' || (trimmed[0] == '/' && trimmed[SKIP_ONE] == '/')) {
return NULL;
}
return trimmed;
@@ -1134,16 +1168,16 @@ static char *tf_next_line(const char **pp, char *line, size_t line_sz) {
int cbm_parse_terraform_source(const char *source, cbm_terraform_result_t *out) {
if (!source || !out) {
- return -1;
+ return CBM_NOT_FOUND;
}
memset(out, 0, sizeof(*out));
const char *p = source;
- char line[4096];
+ char line[CBM_SZ_4K];
int brace_depth = 0;
tf_block_kind_t cur_block = TF_BLOCK_NONE;
- int cur_var_idx = -1;
- int cur_mod_idx = -1;
+ int cur_var_idx = IS_NOT_FOUND;
+ int cur_mod_idx = IS_NOT_FOUND;
while (*p) {
char *trimmed = tf_next_line(&p, line, sizeof(line));
@@ -1153,24 +1187,24 @@ int cbm_parse_terraform_source(const char *source, cbm_terraform_result_t *out)
brace_depth += count_char(trimmed, '{') - count_char(trimmed, '}');
- if (brace_depth <= 1 && cur_block == TF_BLOCK_NONE) {
+ if (brace_depth <= SKIP_ONE && cur_block == TF_BLOCK_NONE) {
if (tf_detect_block_header(trimmed, out, &cur_block, &cur_var_idx, &cur_mod_idx)) {
continue;
}
}
- if (cur_block != TF_BLOCK_NONE && brace_depth >= 1 && brace_depth <= 2) {
+ if (cur_block != TF_BLOCK_NONE && brace_depth >= SKIP_ONE && brace_depth <= PAIR_LEN) {
tf_parse_block_attrs(trimmed, out, cur_block, cur_var_idx, cur_mod_idx);
}
if (brace_depth == 0 && cur_block != TF_BLOCK_NONE) {
cur_block = TF_BLOCK_NONE;
- cur_var_idx = -1;
- cur_mod_idx = -1;
+ cur_var_idx = IS_NOT_FOUND;
+ cur_mod_idx = IS_NOT_FOUND;
}
}
- return tf_result_has_content(out) ? 0 : -1;
+ return tf_result_has_content(out) ? 0 : IS_NOT_FOUND;
}
/* ── Infra QN helper ────────────────────────────────────────────── */
@@ -1182,7 +1216,7 @@ char *cbm_infra_qn(const char *project_name, const char *rel_path, const char *i
return NULL;
}
- char result[1024];
+ char result[CBM_SZ_1K];
if (service_name && service_name[0] && infra_type &&
strcmp(infra_type, "compose-service") == 0) {
snprintf(result, sizeof(result), "%s::%s", base, service_name);
diff --git a/src/pipeline/pass_k8s.c b/src/pipeline/pass_k8s.c
index 8d08da4bf..b6e459ed5 100644
--- a/src/pipeline/pass_k8s.c
+++ b/src/pipeline/pass_k8s.c
@@ -11,6 +11,7 @@
* Depends on: pass_infrascan.c (cbm_is_kustomize_file, cbm_is_k8s_manifest, cbm_infra_qn),
* extraction layer (cbm.h), graph_buffer, pipeline internals.
*/
+#include "foundation/constants.h"
#include "pipeline/pipeline.h"
#include "pipeline/pipeline_internal.h"
#include "graph_buffer/graph_buffer.h"
@@ -37,19 +38,22 @@ static char *k8s_read_file(const char *path, int *out_len) {
long size = ftell(f);
(void)fseek(f, 0, SEEK_SET);
- if (size <= 0 || size > (long)100 * 1024 * 1024) {
+ if (size <= 0 || size > (long)CBM_PERCENT * CBM_SZ_1K * CBM_SZ_1K) {
(void)fclose(f);
return NULL;
}
- char *buf = malloc(size + 1);
+ char *buf = malloc(size + SKIP_ONE);
if (!buf) {
(void)fclose(f);
return NULL;
}
- size_t nread = fread(buf, 1, size, f);
+ size_t nread = fread(buf, SKIP_ONE, size, f);
(void)fclose(f);
+ if (nread > (size_t)size) {
+ nread = (size_t)size;
+ }
buf[nread] = '\0';
*out_len = (int)nread;
return buf;
@@ -57,10 +61,11 @@ static char *k8s_read_file(const char *path, int *out_len) {
/* Format int to string for logging. Thread-safe via TLS. */
static const char *itoa_k8s(int val) {
- static CBM_TLS char bufs[4][32];
+ enum { RING_BUF_COUNT = 4, RING_BUF_MASK = 3 };
+ static CBM_TLS char bufs[RING_BUF_COUNT][CBM_SZ_32];
static CBM_TLS int idx = 0;
int i = idx;
- idx = (idx + 1) & 3;
+ idx = (idx + SKIP_ONE) & RING_BUF_MASK;
snprintf(bufs[i], sizeof(bufs[i]), "%d", val);
return bufs[i];
}
@@ -68,7 +73,7 @@ static const char *itoa_k8s(int val) {
/* Extract the basename of a path (pointer into the string; no allocation). */
static const char *k8s_basename(const char *path) {
const char *p = strrchr(path, '/');
- return p ? p + 1 : path;
+ return p ? p + SKIP_ONE : path;
}
/* ── Kustomize handler ───────────────────────────────────────────── */
@@ -82,7 +87,7 @@ static void handle_kustomize(cbm_pipeline_ctx_t *ctx, const char *path, const ch
}
int64_t mod_id = cbm_gbuf_upsert_node(ctx->gbuf, "Module", k8s_basename(rel_path), mod_qn,
- rel_path, 1, 0, "{\"source\":\"kustomize\"}");
+ rel_path, SKIP_ONE, 0, "{\"source\":\"kustomize\"}");
free(mod_qn);
if (mod_id <= 0) {
@@ -197,7 +202,7 @@ int cbm_pipeline_pass_k8s(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *files,
for (int i = 0; i < file_count; i++) {
if (cbm_pipeline_check_cancel(ctx)) {
- return -1;
+ return CBM_NOT_FOUND;
}
const char *path = files[i].path;
diff --git a/src/pipeline/pass_parallel.c b/src/pipeline/pass_parallel.c
index 722549ce2..ec7df71ad 100644
--- a/src/pipeline/pass_parallel.c
+++ b/src/pipeline/pass_parallel.c
@@ -10,6 +10,22 @@
*
* Depends on: worker_pool, graph_buffer (shared IDs + merge), extraction (cbm.h)
*/
+#include "foundation/constants.h"
+
+enum {
+ PP_RING = 4,
+ PP_RING_MASK = 3,
+ PP_JSON_MARGIN = 10,
+ PP_ESC_MARGIN = 3,
+ PP_ESC_SPACE = 2,
+ PP_ARGS_MARGIN = 20,
+ PP_LOG_THRESH = 24,
+ PP_LOG_INTERVAL = 10,
+ PP_TIMER_THRESH = 1000,
+};
+#define PP_NSEC_PER_SEC 1000000000ULL
+#define PP_USEC_PER_MS 1000000ULL
+#define PP_HALF_CONF 0.5
#include "pipeline/pipeline.h"
#include "pipeline/pipeline_internal.h"
#include "pipeline/worker_pool.h"
@@ -22,7 +38,6 @@
#include "foundation/slab_alloc.h"
#include "foundation/mem.h"
#include "foundation/compat_regex.h"
-#include "pipeline/httplink.h"
#include "cbm.h"
#include <stdatomic.h>
@@ -35,7 +50,7 @@
static uint64_t extract_now_ns(void) {
struct timespec ts;
cbm_clock_gettime(CLOCK_MONOTONIC, &ts);
- return ((uint64_t)ts.tv_sec * 1000000000ULL) + (uint64_t)ts.tv_nsec;
+ return ((uint64_t)ts.tv_sec * PP_NSEC_PER_SEC) + (uint64_t)ts.tv_nsec;
}
/* ── Helpers (duplicated from pass files — kept static for isolation) ── */
@@ -49,16 +64,16 @@ static char *read_file(const char *path, int *out_len) {
(void)fseek(f, 0, SEEK_END);
long size = ftell(f);
(void)fseek(f, 0, SEEK_SET);
- if (size <= 0 || size > (long)100 * 1024 * 1024) {
+ if (size <= 0 || size > (long)CBM_PERCENT * CBM_SZ_1K * CBM_SZ_1K) {
(void)fclose(f);
return NULL;
}
- char *buf = (char *)malloc((size_t)size + 1);
+ char *buf = (char *)malloc((size_t)size + SKIP_ONE);
if (!buf) {
(void)fclose(f);
return NULL;
}
- size_t nread = fread(buf, 1, (size_t)size, f);
+ size_t nread = fread(buf, SKIP_ONE, (size_t)size, f);
(void)fclose(f);
buf[nread] = '\0';
*out_len = (int)nread;
@@ -71,10 +86,10 @@ static void free_source(char *buf) {
}
static const char *itoa_log(int val) {
- static CBM_TLS char bufs[4][32];
+ static CBM_TLS char bufs[PP_RING][CBM_SZ_32];
static CBM_TLS int idx = 0;
int i = idx;
- idx = (idx + 1) & 3;
+ idx = (idx + SKIP_ONE) & PP_RING_MASK;
snprintf(bufs[i], sizeof(bufs[i]), "%d", val);
return bufs[i];
}
@@ -100,16 +115,16 @@ static int json_escape_char(char *buf, size_t avail, char ch) {
esc = 't';
break;
default:
- if (avail >= 1) {
+ if (avail >= SKIP_ONE) {
buf[0] = ch;
}
- return 1;
+ return SKIP_ONE;
}
- if (avail >= 2) {
+ if (avail >= PP_ESC_SPACE) {
buf[0] = '\\';
- buf[1] = esc;
+ buf[SKIP_ONE] = esc;
}
- return 2;
+ return PP_ESC_SPACE;
}
static void append_json_string(char *buf, size_t bufsize, size_t *pos, const char *key,
@@ -117,7 +132,7 @@ static void append_json_string(char *buf, size_t bufsize, size_t *pos, const cha
if (!val || val[0] == '\0') {
return;
}
- if (*pos >= bufsize - 10) {
+ if (*pos >= bufsize - PP_JSON_MARGIN) {
return;
}
size_t p = *pos;
@@ -126,11 +141,11 @@ static void append_json_string(char *buf, size_t bufsize, size_t *pos, const cha
return;
}
p += (size_t)w;
- for (const char *s = val; *s && p < bufsize - 3; s++) {
- int n = json_escape_char(buf + p, bufsize - p - 2, *s);
+ for (const char *s = val; *s && p < bufsize - PP_ESC_MARGIN; s++) {
+ int n = json_escape_char(buf + p, bufsize - p - PP_ESC_SPACE, *s);
p += (size_t)n;
}
- if (p < bufsize - 1) {
+ if (p < bufsize - SKIP_ONE) {
buf[p++] = '"';
}
buf[p] = '\0';
@@ -140,36 +155,36 @@ static void append_json_string(char *buf, size_t bufsize, size_t *pos, const cha
/* Append a JSON array of strings: ,"key":["a","b","c"] */
static void append_json_str_array(char *buf, size_t bufsize, size_t *pos, const char *key,
const char **arr) {
- if (!arr || !arr[0] || *pos >= bufsize - 10) {
+ if (!arr || !arr[0] || *pos >= bufsize - PP_JSON_MARGIN) {
return;
}
size_t p = *pos;
int n = snprintf(buf + p, bufsize - p, ",\"%s\":[", key);
- if (n <= 0 || p + (size_t)n >= bufsize - 2) {
+ if (n <= 0 || p + (size_t)n >= bufsize - PP_ESC_SPACE) {
return;
}
p += (size_t)n;
for (int i = 0; arr[i]; i++) {
- if (i > 0 && p < bufsize - 1) {
+ if (i > 0 && p < bufsize - SKIP_ONE) {
buf[p++] = ',';
}
- if (p < bufsize - 1) {
+ if (p < bufsize - SKIP_ONE) {
buf[p++] = '"';
}
- for (const char *s = arr[i]; *s && p < bufsize - 2; s++) {
+ for (const char *s = arr[i]; *s && p < bufsize - PP_ESC_SPACE; s++) {
if (*s == '"' || *s == '\\') {
buf[p++] = '\\';
- if (p >= bufsize - 2) {
+ if (p >= bufsize - PP_ESC_SPACE) {
break;
}
}
buf[p++] = *s;
}
- if (p < bufsize - 1) {
+ if (p < bufsize - SKIP_ONE) {
buf[p++] = '"';
}
}
- if (p < bufsize - 1) {
+ if (p < bufsize - SKIP_ONE) {
buf[p++] = ']';
}
buf[p] = '\0';
@@ -197,9 +212,9 @@ static void build_def_props(char *buf, size_t bufsize, const CBMDefinition *def)
append_json_str_array(buf, bufsize, &pos, "param_types", def->param_types);
append_json_string(buf, bufsize, &pos, "route_path", def->route_path);
append_json_string(buf, bufsize, &pos, "route_method", def->route_method);
- if (pos < bufsize - 1) {
+ if (pos < bufsize - SKIP_ONE) {
buf[pos] = '}';
- buf[pos + 1] = '\0';
+ buf[pos + SKIP_ONE] = '\0';
}
}
@@ -324,23 +339,23 @@ static int compare_by_size_desc(const void *a, const void *b) {
const file_sort_entry_t *fa = a;
const file_sort_entry_t *fb = b;
if (fb->size > fa->size) {
- return 1;
+ return SKIP_ONE;
}
if (fb->size < fa->size) {
- return -1;
+ return CBM_NOT_FOUND;
}
return 0;
}
/* ── Phase 3A: Parallel Extract ──────────────────────────────────── */
-#define CBM_CACHE_LINE 128
+#define CBM_CACHE_LINE CBM_SZ_128
typedef struct __attribute__((aligned(CBM_CACHE_LINE))) {
cbm_gbuf_t *local_gbuf;
int nodes_created;
int errors;
- char _pad[CBM_CACHE_LINE - sizeof(cbm_gbuf_t *) - (2 * sizeof(int))];
+ char _pad[CBM_CACHE_LINE - sizeof(cbm_gbuf_t *) - (PP_ESC_SPACE * sizeof(int))];
} extract_worker_state_t;
typedef struct {
@@ -363,7 +378,7 @@ typedef struct {
/* Insert one definition node (and its route if present) into the local gbuf. */
static void insert_def_into_gbuf(extract_worker_state_t *ws, const cbm_file_info_t *fi,
CBMDefinition *def) {
- char props[2048];
+ char props[CBM_SZ_2K];
build_def_props(props, sizeof(props), def);
int64_t func_id =
cbm_gbuf_upsert_node(ws->local_gbuf, def->label ? def->label : "Function", def->name,
@@ -374,26 +389,26 @@ static void insert_def_into_gbuf(extract_worker_state_t *ws, const cbm_file_info
const char *rm = def->route_method ? def->route_method : "ANY";
char route_qn[CBM_ROUTE_QN_SIZE];
snprintf(route_qn, sizeof(route_qn), "__route__%s__%s", rm, def->route_path);
- char rprops[256];
+ char rprops[CBM_SZ_256];
snprintf(rprops, sizeof(rprops), "{\"method\":\"%s\",\"source\":\"decorator\"}", rm);
int64_t route_id =
cbm_gbuf_upsert_node(ws->local_gbuf, "Route", def->route_path, route_qn,
def->file_path ? def->file_path : fi->rel_path, 0, 0, rprops);
- char hprops[512];
+ char hprops[CBM_SZ_512];
snprintf(hprops, sizeof(hprops), "{\"handler\":\"%s\"}", def->qualified_name);
cbm_gbuf_insert_edge(ws->local_gbuf, func_id, route_id, "HANDLES", hprops);
}
}
static void log_extract_fail(int pos, uint64_t ms, const char *path) {
- if (pos < 24) {
+ if (pos < PP_LOG_THRESH) {
cbm_log_warn("parallel.extract.file.fail", "pos", itoa_log(pos), "elapsed_ms",
itoa_log((int)ms), "path", path);
}
}
static void log_extract_done(int pos, uint64_t ms, int defs, const char *path) {
- if (pos < 24 || ms > 1000) {
+ if (pos < PP_LOG_THRESH || ms > PP_TIMER_THRESH) {
cbm_log_info("parallel.extract.file.done", "pos", itoa_log(pos), "elapsed_ms",
itoa_log((int)ms), "defs", itoa_log(defs), "path", path);
}
@@ -409,8 +424,9 @@ static void extract_worker(int worker_id, void *ctx_ptr) {
}
/* Pull files from shared atomic counter */
- while (1) {
- int sort_pos = atomic_fetch_add_explicit(&ec->next_file_idx, 1, memory_order_relaxed);
+ while (SKIP_ONE) {
+ int sort_pos =
+ atomic_fetch_add_explicit(&ec->next_file_idx, SKIP_ONE, memory_order_relaxed);
if (sort_pos >= ec->file_count) {
break;
}
@@ -431,9 +447,9 @@ static void extract_worker(int worker_id, void *ctx_ptr) {
/* Per-file start log: shows which file each worker is processing.
* Critical for diagnosing stuck workers on large vendored files. */
- if (sort_pos < 24) { /* first 2 rounds of workers = most interesting */
+ if (sort_pos < PP_LOG_THRESH) { /* first 2 rounds of workers = most interesting */
cbm_log_info("parallel.extract.file.start", "pos", itoa_log(sort_pos), "size_kb",
- itoa_log(source_len / 1024), "path", fi->rel_path);
+ itoa_log(source_len / CBM_SZ_1K), "path", fi->rel_path);
}
uint64_t file_t0 = extract_now_ns();
@@ -441,7 +457,7 @@ static void extract_worker(int worker_id, void *ctx_ptr) {
CBMFileResult *result = cbm_extract_file(source, source_len, fi->language, ec->project_name,
fi->rel_path, CBM_EXTRACT_BUDGET, NULL, NULL);
- uint64_t file_elapsed_ms = (extract_now_ns() - file_t0) / 1000000ULL;
+ uint64_t file_elapsed_ms = (extract_now_ns() - file_t0) / PP_USEC_PER_MS;
if (!result) {
log_extract_fail(sort_pos, file_elapsed_ms, fi->rel_path);
@@ -471,9 +487,9 @@ static void extract_worker(int worker_id, void *ctx_ptr) {
ec->result_cache[file_idx] = result;
/* Progress logging: log every 10 files (atomic read, no contention) */
- if ((sort_pos + 1) % 10 == 0 || sort_pos + 1 == ec->file_count) {
- cbm_log_info("parallel.extract.progress", "done", itoa_log(sort_pos + 1), "total",
- itoa_log(ec->file_count));
+ if ((sort_pos + SKIP_ONE) % PP_LOG_INTERVAL == 0 || sort_pos + SKIP_ONE == ec->file_count) {
+ cbm_log_info("parallel.extract.progress", "done", itoa_log(sort_pos + SKIP_ONE),
+ "total", itoa_log(ec->file_count));
}
/* Reclaim all slab + tier2 memory between files.
@@ -511,8 +527,9 @@ int cbm_parallel_extract(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *files,
if (cbm_mem_budget() > 0) {
size_t worker_budget = cbm_mem_worker_budget(worker_count);
cbm_log_info("parallel.mem.budget", "total_mb",
- itoa_log((int)(cbm_mem_budget() / (1024 * 1024))), "per_worker_mb",
- itoa_log((int)(worker_budget / (1024 * 1024))));
+ itoa_log((int)(cbm_mem_budget() / ((size_t)CBM_SZ_1K * CBM_SZ_1K))),
+ "per_worker_mb",
+ itoa_log((int)(worker_budget / ((size_t)CBM_SZ_1K * CBM_SZ_1K))));
}
/* Ensure extraction library is initialized */
@@ -536,7 +553,7 @@ int cbm_parallel_extract(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *files,
if (cbm_aligned_alloc((void **)&workers, CBM_CACHE_LINE,
(size_t)worker_count * sizeof(extract_worker_state_t)) != 0) {
free(sorted);
- return -1;
+ return CBM_NOT_FOUND;
}
memset(workers, 0, (size_t)worker_count * sizeof(extract_worker_state_t));
@@ -575,15 +592,15 @@ int cbm_parallel_extract(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *files,
free(sorted);
if (atomic_load(ctx->cancelled)) {
- return -1;
+ return CBM_NOT_FOUND;
}
/* RSS-based memory stats after extraction */
if (cbm_mem_budget() > 0) {
- size_t rss_mb = cbm_mem_rss() / (1024 * 1024);
- size_t peak_mb = cbm_mem_peak_rss() / (1024 * 1024);
- size_t budget_mb = cbm_mem_budget() / (1024 * 1024);
- size_t worker_mb = cbm_mem_worker_budget(worker_count) / (1024 * 1024);
+ size_t rss_mb = cbm_mem_rss() / ((size_t)CBM_SZ_1K * CBM_SZ_1K);
+ size_t peak_mb = cbm_mem_peak_rss() / ((size_t)CBM_SZ_1K * CBM_SZ_1K);
+ size_t budget_mb = cbm_mem_budget() / ((size_t)CBM_SZ_1K * CBM_SZ_1K);
+ size_t worker_mb = cbm_mem_worker_budget(worker_count) / ((size_t)CBM_SZ_1K * CBM_SZ_1K);
cbm_log_info("parallel.extract.mem", "rss_mb", itoa_log((int)rss_mb), "peak_mb",
itoa_log((int)peak_mb), "budget_mb", itoa_log((int)budget_mb), "per_worker_mb",
itoa_log((int)worker_mb));
@@ -635,7 +652,7 @@ int cbm_build_registry_from_cache(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t
for (int i = 0; i < file_count; i++) {
if (cbm_pipeline_check_cancel(ctx)) {
- return -1;
+ return CBM_NOT_FOUND;
}
CBMFileResult *result = result_cache[i];
@@ -664,7 +681,7 @@ int cbm_build_registry_from_cache(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t
const cbm_gbuf_node_t *source_node = cbm_gbuf_find_by_qn(ctx->gbuf, file_qn);
if (source_node && target) {
- char imp_props[256];
+ char imp_props[CBM_SZ_256];
snprintf(imp_props, sizeof(imp_props), "{\"local_name\":\"%s\"}",
imp->local_name ? imp->local_name : "");
cbm_gbuf_insert_edge(ctx->gbuf, source_node->id, target->id, "IMPORTS", imp_props);
@@ -688,7 +705,7 @@ typedef struct __attribute__((aligned(CBM_CACHE_LINE))) {
int usages_resolved;
int semantic_resolved;
int errors;
- char _pad[CBM_CACHE_LINE - sizeof(cbm_gbuf_t *) - (4 * sizeof(int))];
+ char _pad[CBM_CACHE_LINE - sizeof(cbm_gbuf_t *) - (PP_RING * sizeof(int))];
} resolve_worker_state_t;
typedef struct {
@@ -709,7 +726,7 @@ typedef struct {
} resolve_ctx_t;
/* Minimum buffer space needed per arg JSON object */
-#define CBM_ARG_JSON_GUARD 32
+#define CBM_ARG_JSON_GUARD CBM_SZ_32
/* Append arg data as JSON to edge properties: ,"args":[{"i":0,"e":"x","v":"val"},...]
* Returns new position in buffer. */
@@ -748,7 +765,7 @@ static int format_call_arg(char *buf, size_t bufsize, const CBMCallArg *a, const
}
static size_t append_args_json(char *buf, size_t bufsize, size_t pos, const CBMCall *call) {
- if (call->arg_count == 0 || pos >= bufsize - 20) {
+ if (call->arg_count == 0 || pos >= bufsize - PP_ARGS_MARGIN) {
return pos;
}
int n = snprintf(buf + pos, bufsize - pos, ",\"args\":[");
@@ -758,17 +775,17 @@ static size_t append_args_json(char *buf, size_t bufsize, size_t pos, const CBMC
pos += (size_t)n;
for (int i = 0; i < call->arg_count && pos < bufsize - CBM_ARG_JSON_GUARD; i++) {
const CBMCallArg *a = &call->args[i];
- if (i > 0 && pos < bufsize - 1) {
+ if (i > 0 && pos < bufsize - SKIP_ONE) {
buf[pos++] = ',';
}
- char expr_buf[128];
+ char expr_buf[CBM_SZ_128];
sanitize_expr(expr_buf, a->expr);
n = format_call_arg(buf + pos, bufsize - pos, a, expr_buf);
if (n > 0) {
pos += (size_t)n;
}
}
- if (pos < bufsize - 1) {
+ if (pos < bufsize - SKIP_ONE) {
buf[pos++] = ']';
}
buf[pos] = '\0';
@@ -803,9 +820,7 @@ static const char *find_route_path_in_args(const CBMCall *call, const char **out
if (!val || val[0] != '/') {
continue;
}
- if (ca->keyword && is_path_keyword(ca->keyword)) {
- found = val;
- } else if (!ca->keyword && ca->index == 0) {
+ if ((ca->keyword && is_path_keyword(ca->keyword)) || (!ca->keyword && ca->index == 0)) {
found = val;
}
}
@@ -831,16 +846,38 @@ static const char *find_route_path_in_args(const CBMCall *call, const char **out
/* Build props JSON, append args, close brace, emit edge. */
static void finalize_and_emit(cbm_gbuf_t *gbuf, int64_t src_id, int64_t tgt_id,
const char *edge_type, char *props, int n, const CBMCall *call) {
- if (n > 0 && (size_t)n < sizeof(props) - 2) {
- size_t pos = append_args_json(props, 2048, (size_t)n, call);
- if (pos < sizeof(props) - 1) {
+ if (n > 0 && (size_t)n < sizeof(props) - PP_ESC_SPACE) {
+ size_t pos = append_args_json(props, CBM_SZ_2K, (size_t)n, call);
+ if (pos < sizeof(props) - SKIP_ONE) {
props[pos] = '}';
- props[pos + 1] = '\0';
+ props[pos + SKIP_ONE] = '\0';
}
}
cbm_gbuf_insert_edge(gbuf, src_id, tgt_id, edge_type, props);
}
+/* Build Route node QN and properties for HTTP/async service edges. */
+static int64_t build_service_route(cbm_gbuf_t *gbuf, const char *arg, const char *method,
+ const char *broker, cbm_svc_kind_t svc) {
+ char route_qn[CBM_ROUTE_QN_SIZE];
+ const char *prefix;
+ if (svc == CBM_SVC_HTTP) {
+ prefix = method ? method : "ANY";
+ } else {
+ prefix = broker ? broker : "async";
+ }
+ snprintf(route_qn, sizeof(route_qn), "__route__%s__%s", prefix, arg);
+ char route_props[CBM_SZ_256];
+ if (method) {
+ snprintf(route_props, sizeof(route_props), "{\"method\":\"%s\"}", method);
+ } else if (broker) {
+ snprintf(route_props, sizeof(route_props), "{\"broker\":\"%s\"}", broker);
+ } else {
+ snprintf(route_props, sizeof(route_props), "{}");
+ }
+ return cbm_gbuf_upsert_node(gbuf, "Route", arg, route_qn, "", 0, 0, route_props);
+}
+
/* Emit HTTP_CALLS or ASYNC_CALLS edge via Route node. */
static void emit_http_async_service_edge(cbm_gbuf_t *gbuf, const cbm_gbuf_node_t *source,
const CBMCall *call, const cbm_resolution_t *res,
@@ -851,21 +888,17 @@ static void emit_http_async_service_edge(cbm_gbuf_t *gbuf, const cbm_gbuf_node_t
const char *broker =
(svc == CBM_SVC_ASYNC) ? cbm_service_pattern_broker(res->qualified_name) : NULL;
- char route_qn[CBM_ROUTE_QN_SIZE];
- const char *prefix =
- (svc == CBM_SVC_HTTP) ? (method ? method : "ANY") : (broker ? broker : "async");
- snprintf(route_qn, sizeof(route_qn), "__route__%s__%s", prefix, arg);
- char route_props[256];
- snprintf(route_props, sizeof(route_props), "%s%s%s",
- method ? "{\"method\":\"" : (broker ? "{\"broker\":\"" : "{}"),
- method ? method : (broker ? broker : ""), (method || broker) ? "\"}" : "");
- int64_t route_id = cbm_gbuf_upsert_node(gbuf, "Route", arg, route_qn, "", 0, 0, route_props);
-
- char props[2048];
- int n = snprintf(props, sizeof(props), "{\"callee\":\"%s\",\"url_path\":\"%s\"%s%s%s%s%s%s",
- call->callee_name, arg, method ? ",\"method\":\"" : "", method ? method : "",
- method ? "\"" : "", broker ? ",\"broker\":\"" : "", broker ? broker : "",
- broker ? "\"" : "");
+ int64_t route_id = build_service_route(gbuf, arg, method, broker, svc);
+
+ char props[CBM_SZ_2K];
+ int n = snprintf(props, sizeof(props), "{\"callee\":\"%s\",\"url_path\":\"%s\"",
+ call->callee_name, arg);
+ if (method) {
+ n += snprintf(props + n, sizeof(props) - (size_t)n, ",\"method\":\"%s\"", method);
+ }
+ if (broker) {
+ n += snprintf(props + n, sizeof(props) - (size_t)n, ",\"broker\":\"%s\"", broker);
+ }
finalize_and_emit(gbuf, source->id, route_id, edge_type, props, n, call);
}
@@ -873,7 +906,7 @@ static void emit_http_async_service_edge(cbm_gbuf_t *gbuf, const cbm_gbuf_node_t
static void emit_config_edge(cbm_gbuf_t *gbuf, const cbm_gbuf_node_t *source,
const cbm_gbuf_node_t *target, const CBMCall *call,
const cbm_resolution_t *res, const char *arg) {
- char props[2048];
+ char props[CBM_SZ_2K];
int n = snprintf(props, sizeof(props), "{\"callee\":\"%s\",\"key\":\"%s\",\"confidence\":%.2f",
call->callee_name, arg ? arg : "", res->confidence);
finalize_and_emit(gbuf, source->id, target->id, "CONFIGURES", props, n, call);
@@ -883,7 +916,7 @@ static void emit_config_edge(cbm_gbuf_t *gbuf, const cbm_gbuf_node_t *source,
static void emit_normal_calls_edge(cbm_gbuf_t *gbuf, const cbm_gbuf_node_t *source,
const cbm_gbuf_node_t *target, const CBMCall *call,
const cbm_resolution_t *res) {
- char props[2048];
+ char props[CBM_SZ_2K];
int n = snprintf(props, sizeof(props),
"{\"callee\":\"%s\",\"confidence\":%.2f,\"strategy\":\"%s\",\"candidates\":%d",
call->callee_name, res->confidence, res->strategy ? res->strategy : "unknown",
@@ -901,10 +934,10 @@ static void emit_route_registration(cbm_gbuf_t *gbuf, const cbm_gbuf_node_t *sou
const char *method = cbm_service_pattern_route_method(call->callee_name);
char rqn[CBM_ROUTE_QN_SIZE];
snprintf(rqn, sizeof(rqn), "__route__%s__%s", method ? method : "ANY", route_path);
- char rp[256];
+ char rp[CBM_SZ_256];
snprintf(rp, sizeof(rp), "{\"method\":\"%s\"}", method ? method : "ANY");
int64_t rid = cbm_gbuf_upsert_node(gbuf, "Route", route_path, rqn, "", 0, 0, rp);
- char props[512];
+ char props[CBM_SZ_512];
snprintf(props, sizeof(props),
"{\"callee\":\"%s\",\"url_path\":\"%s\",\"via\":\"route_registration\"}",
call->callee_name, route_path);
@@ -914,7 +947,7 @@ static void emit_route_registration(cbm_gbuf_t *gbuf, const cbm_gbuf_node_t *sou
if (hres.qualified_name && hres.qualified_name[0] != '\0') {
const cbm_gbuf_node_t *h = cbm_gbuf_find_by_qn(main_gbuf, hres.qualified_name);
if (h) {
- char hp[256];
+ char hp[CBM_SZ_256];
snprintf(hp, sizeof(hp), "{\"handler\":\"%s\"}", hres.qualified_name);
cbm_gbuf_insert_edge(gbuf, h->id, rid, "HANDLES", hp);
}
@@ -948,7 +981,7 @@ static void emit_service_edge(cbm_gbuf_t *gbuf, const cbm_gbuf_node_t *source,
}
bool has_url = (arg && arg[0] != '\0' && (arg[0] == '/' || strstr(arg, "://") != NULL));
- bool has_topic = (arg && arg[0] != '\0' && svc == CBM_SVC_ASYNC && strlen(arg) > 2);
+ bool has_topic = (arg && arg[0] != '\0' && svc == CBM_SVC_ASYNC && strlen(arg) > PP_ESC_SPACE);
if ((svc == CBM_SVC_HTTP || svc == CBM_SVC_ASYNC) && (has_url || has_topic)) {
emit_http_async_service_edge(gbuf, source, call, res, svc, arg);
@@ -957,6 +990,76 @@ static void emit_service_edge(cbm_gbuf_t *gbuf, const cbm_gbuf_node_t *source,
} else {
emit_normal_calls_edge(gbuf, source, target, call, res);
}
+
+ /* URL-in-args detection: if any arg contains an API path, also create
+ * HTTP_CALLS → Route. Handles wrapper functions (apiFetch, apiClient)
+ * and any call that passes a URL as argument. */
+ for (int ai = 0; ai < call->arg_count; ai++) {
+ const CBMCallArg *ca = &call->args[ai];
+ const char *url = ca->value ? ca->value : ca->expr;
+ if (!url || (url[0] != '/' && url[0] != '`')) {
+ continue;
+ }
+ /* Normalize template literals: `/api/x/${id}` → /api/x/:id */
+ char norm[CBM_SZ_256];
+ int ni = 0;
+ const char *p = url;
+ if (*p == '`' || *p == '"' || *p == '\'') {
+ p++;
+ }
+ if (*p != '/') {
+ continue;
+ }
+ while (*p && ni < (int)sizeof(norm) - PAIR_LEN) {
+ if (*p == '$' && *(p + SKIP_ONE) == '{') {
+ norm[ni++] = ':';
+ p += PAIR_LEN;
+ while (*p && *p != '}' && ni < (int)sizeof(norm) - PAIR_LEN) {
+ norm[ni++] = *p++;
+ }
+ if (*p == '}') {
+ p++;
+ }
+ } else if (*p == '`' || *p == '"' || *p == '\'') {
+ break;
+ } else if (*p == '?') {
+ break;
+ } else {
+ norm[ni++] = *p++;
+ }
+ }
+ norm[ni] = '\0';
+ enum { MIN_URL_LEN = 4 };
+ if (ni < MIN_URL_LEN || !strchr(norm + SKIP_ONE, '/')) {
+ continue;
+ }
+ /* Reject regex, comments, prose */
+ bool is_junk = false;
+ for (int ri = 0; norm[ri] && !is_junk; ri++) {
+ char ch = norm[ri];
+ if (ch == '\\' || ch == '^' || ch == '$' || ch == '*' || ch == '+' || ch == '(' ||
+ ch == ')' || ch == '[' || ch == ']' || ch == '|' || ch == ' ') {
+ is_junk = true;
+ }
+ if (ch == '/' && ri > 0 && norm[ri - SKIP_ONE] == '/') {
+ is_junk = true;
+ }
+ }
+ if (is_junk) {
+ continue;
+ }
+
+ char route_qn[CBM_ROUTE_QN_SIZE];
+ snprintf(route_qn, sizeof(route_qn), "__route__ANY__%s", norm);
+ int64_t route_id = cbm_gbuf_upsert_node(gbuf, "Route", norm, route_qn, "", 0, 0,
+ "{\"source\":\"arg_url\"}");
+ char eprops[CBM_SZ_512];
+ snprintf(eprops, sizeof(eprops),
+ "{\"callee\":\"%s\",\"url_path\":\"%s\",\"via\":\"arg_url\"}", call->callee_name,
+ norm);
+ cbm_gbuf_insert_edge(gbuf, source->id, route_id, "HTTP_CALLS", eprops);
+ break; /* one URL per call is enough */
+ }
}
/* Find the source node for an edge: enclosing function or file node. */
@@ -994,7 +1097,7 @@ static void resolve_file_calls(resolve_ctx_t *rc, resolve_worker_state_t *ws, CB
if (!res.qualified_name || res.qualified_name[0] == '\0') {
if (cbm_service_pattern_route_method(call->callee_name) != NULL) {
cbm_resolution_t fake_res = {.qualified_name = call->callee_name,
- .confidence = 0.5,
+ .confidence = PP_HALF_CONF,
.strategy = "callee_suffix"};
emit_service_edge(ws->local_edge_buf, source_node, source_node, call, &fake_res,
module_qn, rc->registry, rc->main_gbuf, imp_keys, imp_vals,
@@ -1035,7 +1138,7 @@ static void resolve_file_usages(resolve_ctx_t *rc, resolve_worker_state_t *ws,
if (!tgt || src->id == tgt->id) {
continue;
}
- char uprops[256];
+ char uprops[CBM_SZ_256];
snprintf(uprops, sizeof(uprops), "{\"callee\":\"%s\"}", usage->ref_name);
cbm_gbuf_insert_edge(ws->local_edge_buf, src->id, tgt->id, "USAGE", uprops);
ws->usages_resolved++;
@@ -1125,7 +1228,7 @@ static void resolve_def_decorators(resolve_ctx_t *rc, resolve_worker_state_t *ws
return;
}
for (int dc = 0; def->decorators[dc]; dc++) {
- char fn[256];
+ char fn[CBM_SZ_256];
extract_decorator_func(def->decorators[dc], fn, sizeof(fn));
if (fn[0] == '\0') {
continue;
@@ -1136,7 +1239,7 @@ static void resolve_def_decorators(resolve_ctx_t *rc, resolve_worker_state_t *ws
}
const cbm_gbuf_node_t *dn = cbm_gbuf_find_by_qn(rc->main_gbuf, res.qualified_name);
if (dn && node->id != dn->id) {
- char dp[256];
+ char dp[CBM_SZ_256];
snprintf(dp, sizeof(dp), "{\"decorator\":\"%s\"}", def->decorators[dc]);
cbm_gbuf_insert_edge(ws->local_edge_buf, node->id, dn->id, "DECORATES", dp);
ws->semantic_resolved++;
@@ -1190,8 +1293,9 @@ static void resolve_worker(int worker_id, void *ctx_ptr) {
cbm_gbuf_new_shared_ids(rc->project_name, rc->repo_path, rc->shared_ids);
}
- while (1) {
- int file_idx = atomic_fetch_add_explicit(&rc->next_file_idx, 1, memory_order_relaxed);
+ while (SKIP_ONE) {
+ int file_idx =
+ atomic_fetch_add_explicit(&rc->next_file_idx, SKIP_ONE, memory_order_relaxed);
if (file_idx >= rc->file_count) {
break;
}
@@ -1253,7 +1357,7 @@ int cbm_parallel_resolve(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *files,
resolve_worker_state_t *workers = NULL;
if (cbm_aligned_alloc((void **)&workers, CBM_CACHE_LINE,
(size_t)worker_count * sizeof(resolve_worker_state_t)) != 0) {
- return -1;
+ return CBM_NOT_FOUND;
}
memset(workers, 0, (size_t)worker_count * sizeof(resolve_worker_state_t));
@@ -1295,7 +1399,7 @@ int cbm_parallel_resolve(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *files,
int go_impl = cbm_pipeline_implements_go(ctx);
if (atomic_load(ctx->cancelled)) {
- return -1;
+ return CBM_NOT_FOUND;
}
cbm_log_info("parallel.resolve.done", "calls", itoa_log(total_calls), "usages",
diff --git a/src/pipeline/pass_route_nodes.c b/src/pipeline/pass_route_nodes.c
index 79ed21680..588fa7990 100644
--- a/src/pipeline/pass_route_nodes.c
+++ b/src/pipeline/pass_route_nodes.c
@@ -14,6 +14,19 @@
* Service A: checkout() → HTTP_CALLS → Route("POST /api/orders")
* Service B: create_order() → HANDLES → Route("POST /api/orders")
*/
+#include "foundation/constants.h"
+
+enum {
+ RN_MAX_SCHEME = 12,
+ RN_MIN_SCHEME = 3,
+ RN_STRIP_PASSES = 2,
+ RN_SCHEME_SKIP = 3,
+ RN_ARGS_SKIP = 7,
+ RN_PROPS_MARGIN = 100,
+ RN_CALLEE_SKIP = 14, /* strlen('"callee_args":[') - 1 */
+};
+
+#define SLEN(s) (sizeof(s) - 1)
#include "pipeline/pipeline_internal.h"
#include "graph_buffer/graph_buffer.h"
#include "foundation/log.h"
@@ -28,7 +41,7 @@ static const char *json_extract(const char *json, const char *key, char *buf, in
return NULL;
}
/* Build "key":" pattern */
- char pattern[128];
+ char pattern[CBM_SZ_128];
snprintf(pattern, sizeof(pattern), "\"%s\":\"", key);
const char *start = strstr(json, pattern);
if (!start) {
@@ -41,7 +54,7 @@ static const char *json_extract(const char *json, const char *key, char *buf, in
}
int len = (int)(end - start);
if (len >= bufsz) {
- len = bufsz - 1;
+ len = bufsz - SKIP_ONE;
}
memcpy(buf, start, (size_t)len);
buf[len] = '\0';
@@ -63,15 +76,15 @@ static void route_edge_visitor(const cbm_gbuf_edge_t *edge, void *userdata) {
}
/* Extract url_path from properties */
- char url_buf[512];
+ char url_buf[CBM_SZ_512];
const char *url = json_extract(edge->properties_json, "url_path", url_buf, sizeof(url_buf));
if (!url || !url[0]) {
return;
}
/* Extract method or broker */
- char method_buf[16];
- char broker_buf[64];
+ char method_buf[CBM_SZ_16];
+ char broker_buf[CBM_SZ_64];
const char *method =
json_extract(edge->properties_json, "method", method_buf, sizeof(method_buf));
const char *broker =
@@ -86,7 +99,7 @@ static void route_edge_visitor(const cbm_gbuf_edge_t *edge, void *userdata) {
}
/* Build properties for Route node */
- char route_props[256];
+ char route_props[CBM_SZ_256];
if (method) {
snprintf(route_props, sizeof(route_props), "{\"method\":\"%s\"}", method);
} else if (broker) {
@@ -101,7 +114,7 @@ static void route_edge_visitor(const cbm_gbuf_edge_t *edge, void *userdata) {
/* Note: we do NOT re-target the edge here because modifying edges during
* iteration is unsafe. The edge stays pointing to the library function.
- * The httplink URL matching pass will create the Route→handler HANDLES
+ * The URL-in-args detection in pass_parallel will create Route→handler HANDLES
* edge separately. The caller→Route edge is created by pass_calls for
* the sequential path; for the parallel path, the caller→library edge
* with url_path in properties is sufficient for query_graph to find
@@ -117,14 +130,14 @@ static const char *url_path(const char *url) {
if (!scheme_end) {
return url; /* Already a path */
}
- const char *path = strchr(scheme_end + 3, '/');
+ const char *path = strchr(scheme_end + RN_SCHEME_SKIP, '/');
return path ? path : "/";
}
/* Check if a trailing dash-segment is a hash/project-number (strippable).
* Returns true if the segment is short alphanumeric but not a meaningful word. */
static bool is_hash_segment(const char *seg, size_t slen) {
- if (slen > 12 || slen == 0) {
+ if (slen > RN_MAX_SCHEME || slen == 0) {
return false;
}
int has_letter = 0;
@@ -133,21 +146,21 @@ static bool is_hash_segment(const char *seg, size_t slen) {
return false;
}
if (seg[si] >= 'a' && seg[si] <= 'z') {
- has_letter = 1;
+ has_letter = SKIP_ONE;
}
}
/* Don't strip meaningful words (>=3 chars with letters like "api", "endpoint") */
- return !(has_letter && slen >= 3);
+ return !(has_letter && slen >= RN_MIN_SCHEME);
}
/* Strip up to 2 trailing hash/project-number segments from a Cloud Run hostname. */
static void strip_cloud_run_suffixes(char *hostname) {
- for (int strip = 0; strip < 2; strip++) {
+ for (int strip = 0; strip < RN_STRIP_PASSES; strip++) {
char *last_dash = strrchr(hostname, '-');
if (!last_dash) {
break;
}
- if (!is_hash_segment(last_dash + 1, strlen(last_dash + 1))) {
+ if (!is_hash_segment(last_dash + SKIP_ONE, strlen(last_dash + SKIP_ONE))) {
break;
}
*last_dash = '\0';
@@ -164,7 +177,7 @@ static const char *extract_service_name(const char *url, char *buf, int bufsz) {
if (!scheme_end) {
return NULL;
}
- const char *host_start = scheme_end + 3;
+ const char *host_start = scheme_end + RN_SCHEME_SKIP;
const char *end = host_start;
while (*end && *end != '.' && *end != '/') {
end++;
@@ -174,7 +187,7 @@ static const char *extract_service_name(const char *url, char *buf, int bufsz) {
return NULL;
}
- char tmp[256];
+ char tmp[CBM_SZ_256];
if (hlen >= (int)sizeof(tmp)) {
return NULL;
}
@@ -217,8 +230,9 @@ static int match_one_infra_route(cbm_gbuf_t *gb, const cbm_gbuf_node_t *infra,
}
int file_matches = (handler_route->file_path != NULL &&
strstr(handler_route->file_path, svc_name) != NULL);
- int is_prefix_route = (handler_route->qualified_name != NULL &&
- strncmp(handler_route->qualified_name, "__route__ANY__", 14) == 0);
+ int is_prefix_route =
+ (handler_route->qualified_name != NULL &&
+ strncmp(handler_route->qualified_name, "__route__ANY__", SLEN("__route__ANY__")) == 0);
if (!file_matches && !is_prefix_route) {
continue;
}
@@ -231,8 +245,9 @@ static int match_one_infra_route(cbm_gbuf_t *gb, const cbm_gbuf_node_t *infra,
continue;
}
- int path_match = (strlen(handler_path) > 1 && (strstr(infra_path, handler_path) != NULL ||
- strstr(handler_path, infra_path) != NULL));
+ int path_match =
+ (strlen(handler_path) > SKIP_ONE && (strstr(infra_path, handler_path) != NULL ||
+ strstr(handler_path, infra_path) != NULL));
int root_svc_match = (strcmp(handler_path, "/") == 0);
if (path_match || root_svc_match) {
const cbm_gbuf_edge_t **fn_handles = NULL;
@@ -243,7 +258,7 @@ static int match_one_infra_route(cbm_gbuf_t *gb, const cbm_gbuf_node_t *infra,
cbm_gbuf_insert_edge(gb, fn_handles[fh]->source_id, infra->id, "HANDLES",
"{\"source\":\"infra_match\"}");
}
- return 1;
+ return SKIP_ONE;
}
}
return 0;
@@ -261,7 +276,8 @@ static void match_infra_routes(cbm_gbuf_t *gb) {
for (int i = 0; i < route_count; i++) {
const cbm_gbuf_node_t *infra = all_routes[i];
- if (!infra->qualified_name || strncmp(infra->qualified_name, "__route__infra__", 16) != 0) {
+ if (!infra->qualified_name ||
+ strncmp(infra->qualified_name, "__route__infra__", SLEN("__route__infra__")) != 0) {
continue;
}
if (!infra->name || !strstr(infra->name, "://")) {
@@ -269,7 +285,7 @@ static void match_infra_routes(cbm_gbuf_t *gb) {
}
const char *infra_path = url_path(infra->name);
- char svc_buf[128];
+ char svc_buf[CBM_SZ_128];
const char *svc_name = extract_service_name(infra->name, svc_buf, sizeof(svc_buf));
if (!infra_path || !svc_name) {
continue;
@@ -279,7 +295,7 @@ static void match_infra_routes(cbm_gbuf_t *gb) {
}
if (matched > 0) {
- char buf[16];
+ char buf[CBM_SZ_16];
snprintf(buf, sizeof(buf), "%d", matched);
cbm_log_info("pass.route_match", "infra_matched", buf);
}
@@ -293,7 +309,7 @@ static bool extract_json_prop(const char *json, const char *key, char *buf, int
if (!json) {
return false;
}
- char pattern[64];
+ char pattern[CBM_SZ_64];
snprintf(pattern, sizeof(pattern), "\"%s\":\"", key);
const char *p = strstr(json, pattern);
if (!p) {
@@ -320,7 +336,7 @@ static int ensure_one_decorator_route(cbm_gbuf_t *gb, const cbm_gbuf_node_t *fun
return 0;
}
- char path[256];
+ char path[CBM_SZ_256];
if (!extract_json_prop(func->properties_json, "route_path", path, sizeof(path))) {
return 0;
}
@@ -328,14 +344,14 @@ static int ensure_one_decorator_route(cbm_gbuf_t *gb, const cbm_gbuf_node_t *fun
return 0;
}
- char method[16] = "ANY";
+ char method[CBM_SZ_16] = "ANY";
extract_json_prop(func->properties_json, "route_method", method, sizeof(method));
char route_qn[CBM_ROUTE_QN_SIZE];
snprintf(route_qn, sizeof(route_qn), "__route__%s__%s", method, path);
const cbm_gbuf_node_t *existing = cbm_gbuf_find_by_qn(gb, route_qn);
- char rprops[256];
+ char rprops[CBM_SZ_256];
snprintf(rprops, sizeof(rprops), "{\"method\":\"%s\",\"source\":\"decorator\"}", method);
int64_t route_id = cbm_gbuf_upsert_node(gb, "Route", path, route_qn,
func->file_path ? func->file_path : "", 0, 0, rprops);
@@ -351,11 +367,11 @@ static int ensure_one_decorator_route(cbm_gbuf_t *gb, const cbm_gbuf_node_t *fun
}
}
- char hprops[512];
+ char hprops[CBM_SZ_512];
snprintf(hprops, sizeof(hprops), "{\"handler\":\"%s\"}",
func->qualified_name ? func->qualified_name : "");
cbm_gbuf_insert_edge(gb, func->id, route_id, "HANDLES", hprops);
- return 1;
+ return SKIP_ONE;
}
/* Phase 2a: Ensure all functions with route_path properties have Route+HANDLES edges. */
@@ -363,7 +379,7 @@ static void ensure_decorator_routes(cbm_gbuf_t *gb) {
const char *labels[] = {"Function", "Method"};
int created = 0;
- for (int li = 0; li < 2; li++) {
+ for (int li = 0; li < RN_STRIP_PASSES; li++) {
const cbm_gbuf_node_t **nodes = NULL;
int count = 0;
if (cbm_gbuf_find_by_label(gb, labels[li], &nodes, &count) != 0) {
@@ -375,7 +391,7 @@ static void ensure_decorator_routes(cbm_gbuf_t *gb) {
}
if (created > 0) {
- char buf[16];
+ char buf[CBM_SZ_16];
snprintf(buf, sizeof(buf), "%d", created);
cbm_log_info("pass.ensure_decorator_routes", "created", buf);
}
@@ -429,7 +445,8 @@ static void connect_prefix_to_decorators(cbm_gbuf_t *gb) {
for (int ri = 0; ri < route_count; ri++) {
const cbm_gbuf_node_t *prefix_route = routes[ri];
if (!prefix_route->qualified_name ||
- strncmp(prefix_route->qualified_name, "__route__ANY__/", 15) != 0) {
+ strncmp(prefix_route->qualified_name, "__route__ANY__/", SLEN("__route__ANY__/")) !=
+ 0) {
continue;
}
@@ -448,18 +465,18 @@ static void connect_prefix_to_decorators(cbm_gbuf_t *gb) {
if (!last_slash) {
continue;
}
- int dir_len = (int)(last_slash - registrar->file_path) + 1;
+ int dir_len = (int)(last_slash - registrar->file_path) + SKIP_ONE;
const char *prefix_path = prefix_route->name;
const char *prefix_segs =
- (prefix_path && prefix_path[0] == '/') ? prefix_path + 1 : prefix_path;
+ (prefix_path && prefix_path[0] == '/') ? prefix_path + SKIP_ONE : prefix_path;
connected +=
bridge_funcs_to_prefix(gb, prefix_route, registrar->file_path, dir_len, prefix_segs);
}
if (connected > 0) {
- char buf[16];
+ char buf[CBM_SZ_16];
snprintf(buf, sizeof(buf), "%d", connected);
cbm_log_info("pass.prefix_bridge", "connected", buf);
}
@@ -475,7 +492,7 @@ static int has_direct_call(const cbm_gbuf_t *gb, int64_t source, int64_t target)
cbm_gbuf_find_edges_by_source_type(gb, source, "CALLS", &edges, &count);
for (int i = 0; i < count; i++) {
if (edges[i]->target_id == target) {
- return 1;
+ return SKIP_ONE;
}
}
return 0;
@@ -503,7 +520,7 @@ static void extract_param_names(const cbm_gbuf_node_t *node, char *buf, int bufs
}
int len = (int)(end - p);
if (len >= bufsize) {
- len = bufsize - 1;
+ len = bufsize - SKIP_ONE;
}
memcpy(buf, p, (size_t)len);
buf[len] = '\0';
@@ -519,7 +536,7 @@ static const char *find_args_in_props(const char *props) {
if (!p) {
return NULL;
}
- return p + 7; /* skip "args":[ , points to first { or ] */
+ return p + RN_ARGS_SKIP; /* skip "args":[ , points to first { or ] */
}
/* Append handler_params and caller_args to DATA_FLOWS props. Closes with '}'. */
@@ -535,15 +552,15 @@ static void finish_data_flow_props(char *props, size_t propsz, size_t pos,
int w = snprintf(props + pos, propsz - pos, ",\"caller_args\":[%.*s", 400, args_json);
if (w > 0) {
pos += (size_t)w;
- char *close = strchr(props + (pos - (size_t)w) + 14, ']');
- if (close && close < props + propsz - 2) {
- pos = (size_t)(close - props) + 1;
+ char *close = strchr(props + (pos - (size_t)w) + RN_CALLEE_SKIP, ']');
+ if (close && close < props + propsz - PAIR_LEN) {
+ pos = (size_t)(close - props) + SKIP_ONE;
}
}
}
- if (pos < propsz - 1) {
+ if (pos < propsz - SKIP_ONE) {
props[pos] = '}';
- props[pos + 1] = '\0';
+ props[pos + SKIP_ONE] = '\0';
}
}
@@ -562,15 +579,15 @@ static int try_create_data_flow(cbm_gbuf_t *gb, int64_t caller_id, int64_t handl
return 0;
}
if (has_direct_call(gb, caller_id, handler_id)) {
- return -1;
+ return CBM_NOT_FOUND;
}
const char *args_json = find_args_in_props(caller_props);
const cbm_gbuf_node_t *handler_node = cbm_gbuf_find_by_id(gb, handler_id);
- char handler_params[512];
+ char handler_params[CBM_SZ_512];
extract_param_names(handler_node, handler_params, sizeof(handler_params));
- char props[2048];
+ char props[CBM_SZ_2K];
int n;
if (via_infra) {
n = snprintf(props, sizeof(props),
@@ -583,11 +600,11 @@ static int try_create_data_flow(cbm_gbuf_t *gb, int64_t caller_id, int64_t handl
route->qualified_name ? route->qualified_name : "", edge_type);
}
- if (n > 0 && (size_t)n < sizeof(props) - 100) {
+ if (n > 0 && (size_t)n < sizeof(props) - RN_PROPS_MARGIN) {
finish_data_flow_props(props, sizeof(props), (size_t)n, handler_params, args_json);
}
cbm_gbuf_insert_edge(gb, caller_id, handler_id, "DATA_FLOWS", props);
- return 1;
+ return SKIP_ONE;
}
/* Collect extra handler IDs reachable via INFRA_MAPS chain from a route. */
@@ -642,8 +659,8 @@ static void create_route_data_flows(cbm_gbuf_t *gb, const cbm_gbuf_node_t *route
int handles_count = 0;
cbm_gbuf_find_edges_by_target_type(gb, route->id, "HANDLES", &handles_edges, &handles_count);
- int64_t extra_handlers[32];
- int n_extra = collect_infra_handlers(gb, route->id, extra_handlers, 32);
+ int64_t extra_handlers[CBM_SZ_32];
+ int n_extra = collect_infra_handlers(gb, route->id, extra_handlers, CBM_SZ_32);
for (int ci = 0; ci < n_callers; ci++) {
for (int hi = 0; hi < handles_count; hi++) {
@@ -679,14 +696,14 @@ static void create_data_flows(cbm_gbuf_t *gb) {
int skipped = 0;
for (int ri = 0; ri < route_count; ri++) {
- caller_edge_ref_t caller_edges[64];
- int n_callers = collect_caller_edges(gb, routes[ri]->id, caller_edges, 64);
+ caller_edge_ref_t caller_edges[CBM_SZ_64];
+ int n_callers = collect_caller_edges(gb, routes[ri]->id, caller_edges, CBM_SZ_64);
create_route_data_flows(gb, routes[ri], caller_edges, n_callers, &flows, &skipped);
}
if (flows > 0 || skipped > 0) {
- char buf1[16];
- char buf2[16];
+ char buf1[CBM_SZ_16];
+ char buf2[CBM_SZ_16];
snprintf(buf1, sizeof(buf1), "%d", flows);
snprintf(buf2, sizeof(buf2), "%d", skipped);
cbm_log_info("pass.data_flows", "created", buf1, "skipped_has_call", buf2);
@@ -702,7 +719,7 @@ void cbm_pipeline_create_route_nodes(cbm_gbuf_t *gb) {
cbm_gbuf_foreach_edge(gb, route_edge_visitor, &ctx);
if (ctx.created > 0) {
- char buf[16];
+ char buf[CBM_SZ_16];
snprintf(buf, sizeof(buf), "%d", ctx.created);
cbm_log_info("pass.route_nodes", "created", buf);
}
diff --git a/src/pipeline/pass_semantic.c b/src/pipeline/pass_semantic.c
index fa9788a11..e709b4e4e 100644
--- a/src/pipeline/pass_semantic.c
+++ b/src/pipeline/pass_semantic.c
@@ -11,6 +11,7 @@
*
* Depends on: pass_definitions having populated the registry and graph buffer
*/
+#include "foundation/constants.h"
#include "pipeline/pipeline.h"
#include "pipeline/pipeline_internal.h"
#include "graph_buffer/graph_buffer.h"
@@ -30,27 +31,31 @@ static char *read_file(const char *path, int *out_len) {
(void)fseek(f, 0, SEEK_END);
long size = ftell(f);
(void)fseek(f, 0, SEEK_SET);
- if (size <= 0 || size > (long)100 * 1024 * 1024) {
+ if (size <= 0 || size > (long)CBM_PERCENT * CBM_SZ_1K * CBM_SZ_1K) {
(void)fclose(f);
return NULL;
}
- char *buf = malloc(size + 1);
+ char *buf = malloc(size + SKIP_ONE);
if (!buf) {
(void)fclose(f);
return NULL;
}
- size_t nread = fread(buf, 1, size, f);
+ size_t nread = fread(buf, SKIP_ONE, size, f);
(void)fclose(f);
+ if (nread > (size_t)size) {
+ nread = (size_t)size;
+ }
buf[nread] = '\0';
*out_len = (int)nread;
return buf;
}
static const char *itoa_log(int val) {
- static CBM_TLS char bufs[4][32];
+ enum { RING_BUF_COUNT = 4, RING_BUF_MASK = 3 };
+ static CBM_TLS char bufs[RING_BUF_COUNT][CBM_SZ_32];
static CBM_TLS int idx = 0;
int i = idx;
- idx = (idx + 1) & 3;
+ idx = (idx + SKIP_ONE) & RING_BUF_MASK;
snprintf(bufs[i], sizeof(bufs[i]), "%d", val);
return bufs[i];
}
@@ -218,19 +223,19 @@ static int check_go_class_implements(cbm_pipeline_ctx_t *ctx, const cbm_gbuf_nod
if (!fp_ends_with(cls->file_path, ".go")) {
return 0;
}
- char prefix[512];
+ char prefix[CBM_SZ_512];
snprintf(prefix, sizeof(prefix), "%s.", cls->qualified_name);
for (int m = 0; m < im_count; m++) {
- char method_qn[512];
+ char method_qn[CBM_SZ_512];
snprintf(method_qn, sizeof(method_qn), "%s%s", prefix, imethods[m].name);
if (!cbm_gbuf_find_by_qn(ctx->gbuf, method_qn)) {
return 0;
}
}
cbm_gbuf_insert_edge(ctx->gbuf, cls->id, iface->id, "IMPLEMENTS", "{}");
- int edges = 1;
+ int edges = SKIP_ONE;
for (int m = 0; m < im_count; m++) {
- char method_qn[512];
+ char method_qn[CBM_SZ_512];
snprintf(method_qn, sizeof(method_qn), "%s%s", prefix, imethods[m].name);
const cbm_gbuf_node_t *cm = cbm_gbuf_find_by_qn(ctx->gbuf, method_qn);
if (cm) {
@@ -275,9 +280,9 @@ int cbm_pipeline_implements_go(cbm_pipeline_ctx_t *ctx) {
}
/* Collect interface method info */
- go_imethod_t imethods[128];
+ go_imethod_t imethods[CBM_SZ_128];
int im_count = 0;
- for (int j = 0; j < dm_count && im_count < 128; j++) {
+ for (int j = 0; j < dm_count && im_count < CBM_SZ_128; j++) {
const cbm_gbuf_node_t *m = cbm_gbuf_find_by_id(ctx->gbuf, dm_edges[j]->target_id);
if (m && m->name) {
imethods[im_count++] = (go_imethod_t){m->name, m->id};
@@ -300,7 +305,7 @@ int cbm_pipeline_implements_go(cbm_pipeline_ctx_t *ctx) {
static void resolve_decorator(cbm_pipeline_ctx_t *ctx, const cbm_gbuf_node_t *node,
const char *decorator, const char *module_qn, const char **imp_keys,
const char **imp_vals, int imp_count, int *count) {
- char func_name[256];
+ char func_name[CBM_SZ_256];
extract_decorator_func(decorator, func_name, sizeof(func_name));
if (func_name[0] == '\0') {
return;
@@ -312,7 +317,7 @@ static void resolve_decorator(cbm_pipeline_ctx_t *ctx, const cbm_gbuf_node_t *no
}
const cbm_gbuf_node_t *dec = cbm_gbuf_find_by_qn(ctx->gbuf, res.qualified_name);
if (dec && node->id != dec->id) {
- char props[256];
+ char props[CBM_SZ_256];
snprintf(props, sizeof(props), "{\"decorator\":\"%s\"}", decorator);
cbm_gbuf_insert_edge(ctx->gbuf, node->id, dec->id, "DECORATES", props);
(*count)++;
@@ -414,7 +419,7 @@ int cbm_pipeline_pass_semantic(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *f
for (int i = 0; i < file_count; i++) {
if (cbm_pipeline_check_cancel(ctx)) {
- return -1;
+ return CBM_NOT_FOUND;
}
const char *rel = files[i].rel_path;
diff --git a/src/pipeline/pass_tests.c b/src/pipeline/pass_tests.c
index 27283cc90..9cade02a0 100644
--- a/src/pipeline/pass_tests.c
+++ b/src/pipeline/pass_tests.c
@@ -9,6 +9,22 @@
*
* Depends on: pass_calls having populated CALLS edges
*/
+#include "foundation/constants.h"
+
+enum {
+ PT_RING = 4,
+ PT_RING_MASK = 3,
+ PT_TEST_LEN = 4, /* strlen("Test") */
+ PT_DESCRIBE_LEN = 9, /* strlen("Describe") + 1... actually strlen("describe_") */
+ PT_CONTEXT_LEN = 7, /* strlen("context") */
+ PT_SUFFIX_LEN = 8, /* strlen("_test.go") */
+ PT_EXT_PY = 3, /* strlen(".py") / strlen(".go") */
+ PT_PYTEST_PREFIX = 5, /* strlen("test_") */
+ PT_SEARCH_COUNT = 2, /* number of search passes */
+ PT_FOUND_SKIP = 5, /* strlen("_test") + 1 or strlen("_spec") + 1 */
+};
+
+#define SLEN(s) (sizeof(s) - 1)
#include "pipeline/pipeline.h"
#include "pipeline/pipeline_internal.h"
#include "graph_buffer/graph_buffer.h"
@@ -19,10 +35,10 @@
#include <string.h>
static const char *itoa_log(int val) {
- static char bufs[4][32];
+ static char bufs[PT_RING][CBM_SZ_32];
static int idx = 0;
int i = idx;
- idx = (idx + 1) & 3;
+ idx = (idx + SKIP_ONE) & PT_RING_MASK;
snprintf(bufs[i], sizeof(bufs[i]), "%d", val);
return bufs[i];
}
@@ -47,11 +63,11 @@ bool cbm_is_test_path(const char *path) {
return false;
}
const char *base = strrchr(path, '/');
- base = base ? base + 1 : path;
+ base = base ? base + SKIP_ONE : path;
size_t len = strlen(path);
/* Prefix-based: Python test_*.py */
- if (strncmp(base, "test_", 5) == 0) {
+ if (strncmp(base, "test_", SLEN("test_")) == 0) {
return true;
}
@@ -81,8 +97,9 @@ bool cbm_is_test_path(const char *path) {
return true;
}
/* Also match if path STARTS with these directories */
- if (strncmp(path, "tests/", 6) == 0 || strncmp(path, "test/", 5) == 0 ||
- strncmp(path, "spec/", 5) == 0 || strncmp(path, "__tests__/", 10) == 0) {
+ if (strncmp(path, "tests/", SLEN("tests/")) == 0 ||
+ strncmp(path, "test/", SLEN("test/")) == 0 || strncmp(path, "spec/", SLEN("spec/")) == 0 ||
+ strncmp(path, "__tests__/", SLEN("__tests__/")) == 0) {
return true;
}
@@ -101,22 +118,26 @@ bool cbm_is_test_func_name(const char *name) {
}
/* Go: Test/Benchmark/Example + uppercase letter or end-of-string.
* "TestFoo" = test, "Testable" = not test (lowercase after prefix). */
- if (strncmp(name, "Test", 4) == 0 && (name[4] == '\0' || (name[4] >= 'A' && name[4] <= 'Z'))) {
+ if (strncmp(name, "Test", SLEN("Test")) == 0 &&
+ (name[PT_TEST_LEN] == '\0' || (name[PT_TEST_LEN] >= 'A' && name[PT_TEST_LEN] <= 'Z'))) {
return true;
}
- if (strncmp(name, "Benchmark", 9) == 0 &&
- (name[9] == '\0' || (name[9] >= 'A' && name[9] <= 'Z'))) {
+ if (strncmp(name, "Benchmark", SLEN("Benchmark")) == 0 &&
+ (name[PT_DESCRIBE_LEN] == '\0' ||
+ (name[PT_DESCRIBE_LEN] >= 'A' && name[PT_DESCRIBE_LEN] <= 'Z'))) {
return true;
}
- if (strncmp(name, "Example", 7) == 0 &&
- (name[7] == '\0' || (name[7] >= 'A' && name[7] <= 'Z'))) {
+ if (strncmp(name, "Example", SLEN("Example")) == 0 &&
+ (name[PT_CONTEXT_LEN] == '\0' ||
+ (name[PT_CONTEXT_LEN] >= 'A' && name[PT_CONTEXT_LEN] <= 'Z'))) {
return true;
}
/* Python/Rust/C++/Lua/Java: test_ or test prefix (lowercase) */
- if (strncmp(name, "test_", 5) == 0) {
+ if (strncmp(name, "test_", SLEN("test_")) == 0) {
return true;
}
- if (strncmp(name, "test", 4) == 0 && name[4] >= 'A' && name[4] <= 'Z') {
+ if (strncmp(name, "test", SLEN("test")) == 0 && name[PT_TEST_LEN] >= 'A' &&
+ name[PT_TEST_LEN] <= 'Z') {
return true;
}
/* JS/TS: test/it/describe + lifecycle hooks */
@@ -135,15 +156,15 @@ bool cbm_is_test_func_name(const char *name) {
/* Assemble dir/name+ext into a heap-allocated path. */
static char *build_path(const char *test_path, size_t dir_len, const char *name, size_t name_len,
const char *ext, size_t ext_len) {
- char *result = malloc(dir_len + 1 + name_len + ext_len + 1);
+ char *result = malloc(dir_len + SKIP_ONE + name_len + ext_len + SKIP_ONE);
if (dir_len > 0) {
memcpy(result, test_path, dir_len);
result[dir_len] = '/';
- memcpy(result + dir_len + 1, name, name_len);
- memcpy(result + dir_len + 1 + name_len, ext, ext_len + 1);
+ memcpy(result + dir_len + SKIP_ONE, name, name_len);
+ memcpy(result + dir_len + SKIP_ONE + name_len, ext, ext_len + SKIP_ONE);
} else {
memcpy(result, name, name_len);
- memcpy(result + name_len, ext, ext_len + 1);
+ memcpy(result + name_len, ext, ext_len + SKIP_ONE);
}
return result;
}
@@ -157,28 +178,29 @@ static char *test_to_prod_path(const char *test_path) {
const char *base = strrchr(test_path, '/');
size_t dir_len = base ? (size_t)(base - test_path) : 0;
- base = base ? base + 1 : test_path;
+ base = base ? base + SKIP_ONE : test_path;
/* Go: foo_test.go → foo.go */
const char *suffix = strstr(base, "_test.go");
- if (suffix && suffix[8] == '\0') {
- return build_path(test_path, dir_len, base, (size_t)(suffix - base), ".go", 3);
+ if (suffix && suffix[PT_SUFFIX_LEN] == '\0') {
+ return build_path(test_path, dir_len, base, (size_t)(suffix - base), ".go", PT_EXT_PY);
}
/* Python: test_foo.py → foo.py */
- if (strncmp(base, "test_", 5) == 0) {
+ if (strncmp(base, "test_", SLEN("test_")) == 0) {
const char *ext = strstr(base, ".py");
- if (ext && ext[3] == '\0') {
- return build_path(test_path, dir_len, base + 5, (size_t)(ext - base - 5), ".py", 3);
+ if (ext && ext[PT_EXT_PY] == '\0') {
+ return build_path(test_path, dir_len, base + PT_PYTEST_PREFIX,
+ (size_t)(ext - base - PT_PYTEST_PREFIX), ".py", PT_EXT_PY);
}
}
/* JS/TS: foo.test.ts → foo.ts, foo.spec.ts → foo.ts */
- for (int s = 0; s < 2; s++) {
+ for (int s = 0; s < PT_SEARCH_COUNT; s++) {
const char *pat = s == 0 ? ".test." : ".spec.";
const char *found = strstr(base, pat);
if (found) {
- const char *ext = found + 5;
+ const char *ext = found + PT_FOUND_SKIP;
return build_path(test_path, dir_len, base, (size_t)(found - base), ext, strlen(ext));
}
}
diff --git a/src/pipeline/pass_usages.c b/src/pipeline/pass_usages.c
index d09912c71..f5b2df971 100644
--- a/src/pipeline/pass_usages.c
+++ b/src/pipeline/pass_usages.c
@@ -11,6 +11,7 @@
*
* Depends on: pass_definitions having populated the registry and graph buffer
*/
+#include "foundation/constants.h"
#include "pipeline/pipeline.h"
#include "pipeline/pipeline_internal.h"
#include "graph_buffer/graph_buffer.h"
@@ -31,27 +32,31 @@ static char *read_file(const char *path, int *out_len) {
(void)fseek(f, 0, SEEK_END);
long size = ftell(f);
(void)fseek(f, 0, SEEK_SET);
- if (size <= 0 || size > (long)100 * 1024 * 1024) {
+ if (size <= 0 || size > (long)CBM_PERCENT * CBM_SZ_1K * CBM_SZ_1K) {
(void)fclose(f);
return NULL;
}
- char *buf = malloc(size + 1);
+ char *buf = malloc(size + SKIP_ONE);
if (!buf) {
(void)fclose(f);
return NULL;
}
- size_t nread = fread(buf, 1, size, f);
+ size_t nread = fread(buf, SKIP_ONE, size, f);
(void)fclose(f);
+ if (nread > (size_t)size) {
+ nread = (size_t)size;
+ }
buf[nread] = '\0';
*out_len = (int)nread;
return buf;
}
static const char *itoa_log(int val) {
- static CBM_TLS char bufs[4][32];
+ enum { RING_BUF_COUNT = 4, RING_BUF_MASK = 3 };
+ static CBM_TLS char bufs[RING_BUF_COUNT][CBM_SZ_32];
static CBM_TLS int idx = 0;
int i = idx;
- idx = (idx + 1) & 3;
+ idx = (idx + SKIP_ONE) & RING_BUF_MASK;
snprintf(bufs[i], sizeof(bufs[i]), "%d", val);
return bufs[i];
}
@@ -216,7 +221,7 @@ static int resolve_usage_edges(cbm_pipeline_ctx_t *ctx, const CBMFileResult *res
continue;
}
- char uprops[256];
+ char uprops[CBM_SZ_256];
snprintf(uprops, sizeof(uprops), "{\"callee\":\"%s\"}", usage->ref_name);
cbm_gbuf_insert_edge(ctx->gbuf, src->id, tgt->id, "USAGE", uprops);
resolved++;
@@ -303,7 +308,7 @@ int cbm_pipeline_pass_usages(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *fil
for (int i = 0; i < file_count; i++) {
if (cbm_pipeline_check_cancel(ctx)) {
- return -1;
+ return CBM_NOT_FOUND;
}
const char *path = files[i].path;
diff --git a/src/pipeline/pipeline.c b/src/pipeline/pipeline.c
index 15680514a..3524f65ac 100644
--- a/src/pipeline/pipeline.c
+++ b/src/pipeline/pipeline.c
@@ -10,6 +10,10 @@
* 6. Post-passes: tests, communities, HTTP links, git history
* 7. Dump graph buffer to SQLite
*/
+#include "foundation/constants.h"
+
+enum { CBM_DIR_PERMS = 0755, PL_RING = 4, PL_RING_MASK = 3, PL_SEQ_PASSES = 5, PL_WAL_BUF = 1040 };
+#define PL_NSEC_PER_SEC 1000000000LL
#include "pipeline/pipeline.h"
#include "pipeline/pipeline_internal.h"
#include "pipeline/worker_pool.h"
@@ -32,6 +36,12 @@
#include <sys/stat.h>
#include <time.h>
+static inline void *intptr_to_ptr(intptr_t v) {
+ void *p;
+ memcpy(&p, &v, sizeof(p));
+ return p;
+}
+
/* ── Global index lock ─────────────────────────────────────────── */
/* Prevents concurrent pipeline runs on the same DB file.
* Atomic spinlock: 0 = free, 1 = locked. */
@@ -82,10 +92,10 @@ static double elapsed_ms(struct timespec start) {
/* Format int to string for logging. Thread-safe via TLS rotating buffers. */
static const char *itoa_buf(int val) {
- static CBM_TLS char bufs[4][32];
+ static CBM_TLS char bufs[PL_RING][CBM_SZ_32];
static CBM_TLS int idx = 0;
int i = idx;
- idx = (idx + 1) & 3;
+ idx = (idx + SKIP_ONE) & PL_RING_MASK;
snprintf(bufs[i], sizeof(bufs[i]), "%d", val);
return bufs[i];
}
@@ -98,7 +108,7 @@ cbm_pipeline_t *cbm_pipeline_new(const char *repo_path, const char *db_path,
return NULL;
}
- cbm_pipeline_t *p = calloc(1, sizeof(cbm_pipeline_t));
+ cbm_pipeline_t *p = calloc(CBM_ALLOC_ONE, sizeof(cbm_pipeline_t));
if (!p) {
return NULL;
}
@@ -149,7 +159,7 @@ atomic_int *cbm_pipeline_cancelled_ptr(cbm_pipeline_t *p) {
/* Resolve the DB path for this pipeline. Caller must free(). */
static char *resolve_db_path(const cbm_pipeline_t *p) {
- char *path = malloc(1024);
+ char *path = malloc(CBM_SZ_1K);
if (!path) {
return NULL;
}
@@ -166,7 +176,7 @@ static char *resolve_db_path(const cbm_pipeline_t *p) {
}
static int check_cancel(const cbm_pipeline_t *p) {
- return atomic_load(&p->cancelled) ? -1 : 0;
+ return atomic_load(&p->cancelled) ? CBM_NOT_FOUND : 0;
}
/* ── Hash table cleanup callback ─────────────────────────────────── */
@@ -184,10 +194,10 @@ static void free_seen_dir_key(const char *key, void *val, void *ud) {
static void create_folder_chain(cbm_pipeline_t *p, const char *dir, CBMHashTable *seen_dirs) {
char *walk = strdup(dir);
while (walk[0] != '\0' && !cbm_ht_get(seen_dirs, walk)) {
- cbm_ht_set(seen_dirs, strdup(walk), (void *)1);
+ cbm_ht_set(seen_dirs, strdup(walk), intptr_to_ptr(SKIP_ONE));
char *folder_qn = cbm_pipeline_fqn_folder(p->project_name, walk);
const char *dir_base = strrchr(walk, '/');
- dir_base = dir_base ? dir_base + 1 : walk;
+ dir_base = dir_base ? dir_base + SKIP_ONE : walk;
cbm_gbuf_upsert_node(p->gbuf, "Folder", dir_base, folder_qn, walk, 0, 0, "{}");
char *pdir = strdup(walk);
@@ -231,7 +241,7 @@ static int pass_structure(cbm_pipeline_t *p, const cbm_file_info_t *files, int f
cbm_gbuf_upsert_node(p->gbuf, "Project", p->project_name, p->project_name, NULL, 0, 0, "{}");
/* Collect unique directories and create Folder/Package nodes */
- CBMHashTable *seen_dirs = cbm_ht_create(256);
+ CBMHashTable *seen_dirs = cbm_ht_create(CBM_SZ_256);
for (int i = 0; i < file_count; i++) {
const char *rel = files[i].rel_path;
@@ -243,9 +253,9 @@ static int pass_structure(cbm_pipeline_t *p, const cbm_file_info_t *files, int f
char *file_qn = cbm_pipeline_fqn_compute(p->project_name, rel, "__file__");
/* Extract basename */
const char *slash = strrchr(rel, '/');
- const char *basename = slash ? slash + 1 : rel;
+ const char *basename = slash ? slash + SKIP_ONE : rel;
- char props[256];
+ char props[CBM_SZ_256];
const char *ext = strrchr(basename, '.');
snprintf(props, sizeof(props), "{\"extension\":\"%s\"}", ext ? ext : "");
@@ -334,11 +344,11 @@ static int process_one_infra_binding(cbm_gbuf_t *gbuf, const CBMInfraBinding *ib
if (!topic_route) {
return 0;
}
- char props[512];
+ char props[CBM_SZ_512];
snprintf(props, sizeof(props), "{\"broker\":\"%s\",\"topic\":\"%s\",\"endpoint\":\"%s\"}",
ib->broker ? ib->broker : "async", ib->source_name, ib->target_url);
cbm_gbuf_insert_edge(gbuf, topic_route->id, url_route_id, "INFRA_MAPS", props);
- return 1;
+ return SKIP_ONE;
}
static void cbm_pipeline_process_infra_bindings(cbm_gbuf_t *gbuf, const cbm_file_info_t *files,
@@ -356,7 +366,7 @@ static void cbm_pipeline_process_infra_bindings(cbm_gbuf_t *gbuf, const cbm_file
}
}
if (bindings > 0) {
- char buf[16];
+ char buf[CBM_SZ_16];
snprintf(buf, sizeof(buf), "%d", bindings);
cbm_log_info("pass.infra_bindings", "linked", buf);
}
@@ -375,7 +385,7 @@ static void try_upsert_infra_route(cbm_gbuf_t *gbuf, const CBMStringRef *sr, con
}
char route_qn[CBM_ROUTE_QN_SIZE];
snprintf(route_qn, sizeof(route_qn), "__route__infra__%s", sr->value);
- char route_props[512];
+ char route_props[CBM_SZ_512];
if (sr->key_path) {
snprintf(route_props, sizeof(route_props), "{\"source\":\"infra\",\"key_path\":\"%s\"}",
sr->key_path);
@@ -443,7 +453,7 @@ static int run_sequential_pipeline(cbm_pipeline_t *p, cbm_pipeline_ctx_t *ctx,
{cbm_pipeline_pass_semantic, "semantic", false},
};
int rc = 0;
- for (int si = 0; si < 5 && rc == 0; si++) {
+ for (int si = 0; si < PL_SEQ_PASSES && rc == 0; si++) {
cbm_clock_gettime(CLOCK_MONOTONIC, t);
int pr = seq_passes[si].fn(ctx, files, file_count);
if (pr != 0 && !seq_passes[si].ignore_err) {
@@ -452,7 +462,7 @@ static int run_sequential_pipeline(cbm_pipeline_t *p, cbm_pipeline_ctx_t *ctx,
cbm_log_info("pass.timing", "pass", seq_passes[si].name, "elapsed_ms",
itoa_buf((int)elapsed_ms(*t)));
if (check_cancel(p)) {
- rc = -1;
+ rc = CBM_NOT_FOUND;
}
}
if (seq_cache) {
@@ -478,7 +488,7 @@ static int run_parallel_pipeline(cbm_pipeline_t *p, cbm_pipeline_ctx_t *ctx,
CBMFileResult **cache = (CBMFileResult **)calloc(file_count, sizeof(CBMFileResult *));
if (!cache) {
cbm_log_error("pipeline.err", "phase", "cache_alloc");
- return -1;
+ return CBM_NOT_FOUND;
}
cbm_clock_gettime(CLOCK_MONOTONIC, t);
int rc = cbm_parallel_extract(ctx, files, file_count, cache, &shared_ids, worker_count);
@@ -486,7 +496,7 @@ static int run_parallel_pipeline(cbm_pipeline_t *p, cbm_pipeline_ctx_t *ctx,
itoa_buf((int)elapsed_ms(*t)));
if (rc != 0 || check_cancel(p)) {
free(cache);
- return rc != 0 ? rc : -1;
+ return rc != 0 ? rc : CBM_NOT_FOUND;
}
cbm_gbuf_set_next_id(p->gbuf, atomic_load(&shared_ids));
cbm_clock_gettime(CLOCK_MONOTONIC, t);
@@ -500,7 +510,7 @@ static int run_parallel_pipeline(cbm_pipeline_t *p, cbm_pipeline_ctx_t *ctx,
}
}
free(cache);
- return rc != 0 ? rc : -1;
+ return rc != 0 ? rc : CBM_NOT_FOUND;
}
cbm_clock_gettime(CLOCK_MONOTONIC, t);
rc = cbm_parallel_resolve(ctx, files, file_count, cache, &shared_ids, worker_count);
@@ -521,7 +531,7 @@ static int run_parallel_pipeline(cbm_pipeline_t *p, cbm_pipeline_ctx_t *ctx,
cbm_clock_gettime(CLOCK_MONOTONIC, t);
cbm_pipeline_pass_k8s(ctx, files, file_count);
cbm_log_info("pass.timing", "pass", "k8s", "elapsed_ms", itoa_buf((int)elapsed_ms(*t)));
- return check_cancel(p) ? -1 : 0;
+ return check_cancel(p) ? CBM_NOT_FOUND : 0;
}
/* Try incremental pipeline or delete old DB for reindex.
@@ -529,12 +539,12 @@ static int run_parallel_pipeline(cbm_pipeline_t *p, cbm_pipeline_ctx_t *ctx,
static int try_incremental_or_delete_db(cbm_pipeline_t *p, cbm_file_info_t *files, int file_count) {
char *db_path = resolve_db_path(p);
if (!db_path) {
- return -1;
+ return CBM_NOT_FOUND;
}
struct stat db_st;
if (stat(db_path, &db_st) != 0) {
free(db_path);
- return -1;
+ return CBM_NOT_FOUND;
}
cbm_store_t *check_store = cbm_store_open_path(db_path);
if (check_store && cbm_store_check_integrity(check_store)) {
@@ -543,7 +553,7 @@ static int try_incremental_or_delete_db(cbm_pipeline_t *p, cbm_file_info_t *file
cbm_store_get_file_hashes(check_store, p->project_name, &hashes, &hash_count);
cbm_store_free_file_hashes(hashes, hash_count);
cbm_store_close(check_store);
- if (hash_count > 0 && file_count <= hash_count + (hash_count / 2)) {
+ if (hash_count > 0 && file_count <= hash_count + (hash_count / PAIR_LEN)) {
cbm_log_info("pipeline.route", "path", "incremental", "stored_hashes",
itoa_buf(hash_count));
int rc = cbm_pipeline_run_incremental(p, db_path, files, file_count);
@@ -559,24 +569,25 @@ static int try_incremental_or_delete_db(cbm_pipeline_t *p, cbm_file_info_t *file
}
cbm_log_info("pipeline.route", "path", "reindex", "action", "deleting old db");
cbm_unlink(db_path);
- char wal[1040];
- char shm[1040];
+ char wal[PL_WAL_BUF];
+ char shm[PL_WAL_BUF];
snprintf(wal, sizeof(wal), "%s-wal", db_path);
snprintf(shm, sizeof(shm), "%s-shm", db_path);
cbm_unlink(wal);
cbm_unlink(shm);
free(db_path);
- return -1;
+ return CBM_NOT_FOUND;
}
/* Get platform-specific mtime in nanoseconds. */
static int64_t stat_mtime_ns(const struct stat *fst) {
#ifdef __APPLE__
- return ((int64_t)fst->st_mtimespec.tv_sec * 1000000000LL) + (int64_t)fst->st_mtimespec.tv_nsec;
+ return ((int64_t)fst->st_mtimespec.tv_sec * PL_NSEC_PER_SEC) +
+ (int64_t)fst->st_mtimespec.tv_nsec;
#elif defined(_WIN32)
return (int64_t)fst->st_mtime * 1000000000LL;
#else
- return ((int64_t)fst->st_mtim.tv_sec * 1000000000LL) + (int64_t)fst->st_mtim.tv_nsec;
+ return ((int64_t)fst->st_mtim.tv_sec * PL_NSEC_PER_SEC) + (int64_t)fst->st_mtim.tv_nsec;
#endif
}
@@ -585,7 +596,7 @@ static int dump_and_persist_hashes(cbm_pipeline_t *p, const cbm_file_info_t *fil
struct timespec *t) {
cbm_clock_gettime(CLOCK_MONOTONIC, t);
const char *home = cbm_get_home_dir();
- char db_path[1024];
+ char db_path[CBM_SZ_1K];
if (p->db_path) {
snprintf(db_path, sizeof(db_path), "%s", p->db_path);
} else {
@@ -595,12 +606,12 @@ static int dump_and_persist_hashes(cbm_pipeline_t *p, const cbm_file_info_t *fil
snprintf(db_path, sizeof(db_path), "%s/.cache/codebase-memory-mcp/%s.db", home,
p->project_name);
}
- char db_dir[1024];
+ char db_dir[CBM_SZ_1K];
snprintf(db_dir, sizeof(db_dir), "%s", db_path);
char *last_slash = strrchr(db_dir, '/');
if (last_slash) {
*last_slash = '\0';
- cbm_mkdir_p(db_dir, 0755);
+ cbm_mkdir_p(db_dir, CBM_DIR_PERMS);
}
int rc = cbm_gbuf_dump_to_sqlite(p->gbuf, db_path);
if (rc != 0) {
@@ -624,12 +635,10 @@ static int dump_and_persist_hashes(cbm_pipeline_t *p, const cbm_file_info_t *fil
return 0;
}
-/* Run githistory (I/O) + httplinks (CPU) in parallel, then apply edges. */
-static int run_githistory_and_httplinks(cbm_pipeline_t *p, cbm_pipeline_ctx_t *ctx) {
+/* Run githistory pass. */
+static int run_githistory(cbm_pipeline_t *p, cbm_pipeline_ctx_t *ctx) {
struct timespec t_gh;
- struct timespec t_hl;
cbm_clock_gettime(CLOCK_MONOTONIC, &t_gh);
- cbm_clock_gettime(CLOCK_MONOTONIC, &t_hl);
cbm_githistory_result_t gh_result = {0};
cbm_thread_t gh_thread;
@@ -637,7 +646,7 @@ static int run_githistory_and_httplinks(cbm_pipeline_t *p, cbm_pipeline_ctx_t *c
gh_compute_arg_t gh_arg = {.repo_path = ctx->repo_path, .result = &gh_result};
if (p->mode != CBM_MODE_FAST) {
- if (cbm_default_worker_count(true) > 1) {
+ if (cbm_default_worker_count(true) > SKIP_ONE) {
if (cbm_thread_create(&gh_thread, 0, gh_compute_thread_fn, &gh_arg) == 0) {
gh_threaded = true;
}
@@ -651,8 +660,7 @@ static int run_githistory_and_httplinks(cbm_pipeline_t *p, cbm_pipeline_ctx_t *c
cbm_log_info("pass.skip", "pass", "githistory", "reason", "fast_mode");
}
- int rc = cbm_pipeline_pass_httplinks(ctx);
- cbm_log_info("pass.timing", "pass", "httplinks", "elapsed_ms", itoa_buf((int)elapsed_ms(t_hl)));
+ int rc = 0;
if (gh_threaded) {
cbm_thread_join(&gh_thread);
@@ -679,7 +687,7 @@ static int run_githistory_and_httplinks(cbm_pipeline_t *p, cbm_pipeline_ctx_t *c
int cbm_pipeline_run(cbm_pipeline_t *p) {
if (!p) {
- return -1;
+ return CBM_NOT_FOUND;
}
struct timespec t0;
@@ -704,7 +712,7 @@ int cbm_pipeline_run(cbm_pipeline_t *p) {
cbm_log_info("pipeline.discover", "files", itoa_buf(file_count), "elapsed_ms",
itoa_buf((int)elapsed_ms(t0)));
if (rc != 0 || check_cancel(p)) {
- rc = -1;
+ rc = CBM_NOT_FOUND;
goto cleanup;
}
@@ -736,18 +744,18 @@ int cbm_pipeline_run(cbm_pipeline_t *p) {
pass_structure(p, files, file_count);
cbm_log_info("pass.timing", "pass", "structure", "elapsed_ms", itoa_buf((int)elapsed_ms(t)));
if (check_cancel(p)) {
- rc = -1;
+ rc = CBM_NOT_FOUND;
goto cleanup;
}
/* Run extraction passes (parallel or sequential) */
int worker_count = cbm_default_worker_count(true);
#define MIN_FILES_FOR_PARALLEL 50
- rc = (worker_count > 1 && file_count > MIN_FILES_FOR_PARALLEL)
+ rc = (worker_count > SKIP_ONE && file_count > MIN_FILES_FOR_PARALLEL)
? run_parallel_pipeline(p, &ctx, files, file_count, worker_count, &t)
: run_sequential_pipeline(p, &ctx, files, file_count, &t);
if (check_cancel(p)) {
- rc = -1;
+ rc = CBM_NOT_FOUND;
}
if (rc != 0) {
goto cleanup;
@@ -758,10 +766,10 @@ int cbm_pipeline_run(cbm_pipeline_t *p) {
rc = cbm_pipeline_pass_tests(&ctx, files, file_count);
cbm_log_info("pass.timing", "pass", "tests", "elapsed_ms", itoa_buf((int)elapsed_ms(t)));
if (rc == 0 && !check_cancel(p)) {
- rc = run_githistory_and_httplinks(p, &ctx);
+ rc = run_githistory(p, &ctx);
}
if (check_cancel(p)) {
- rc = -1;
+ rc = CBM_NOT_FOUND;
}
if (rc != 0) {
goto cleanup;
diff --git a/src/pipeline/pipeline.h b/src/pipeline/pipeline.h
index 203f4374e..9454f9320 100644
--- a/src/pipeline/pipeline.h
+++ b/src/pipeline/pipeline.h
@@ -149,4 +149,6 @@ cbm_fuzzy_result_t cbm_registry_fuzzy_resolve(const cbm_registry_t *r, const cha
const char *module_qn, const char **import_map_keys,
const char **import_map_vals, int import_map_count);
+const char *cbm_confidence_band(double score);
+
#endif /* CBM_PIPELINE_H */
diff --git a/src/pipeline/pipeline_incremental.c b/src/pipeline/pipeline_incremental.c
index 10881e9f9..9715c91a7 100644
--- a/src/pipeline/pipeline_incremental.c
+++ b/src/pipeline/pipeline_incremental.c
@@ -1,403 +1,402 @@
-/*
- * pipeline_incremental.c — Disk-based incremental re-indexing.
- *
- * Operates on the existing SQLite DB directly (not RAM-first graph buffer).
- * Compares file mtime+size against stored hashes to classify changed/unchanged.
- * Deletes changed files' nodes (edges cascade via ON DELETE CASCADE),
- * re-parses only changed files through passes into a temp graph buffer,
- * then merges new nodes/edges into the disk DB. Persists updated hashes.
- *
- * Called from pipeline.c when a DB with stored hashes already exists.
- */
-#include "pipeline/pipeline.h"
-#include "pipeline/pipeline_internal.h"
-#include "store/store.h"
-#include "graph_buffer/graph_buffer.h"
-#include "discover/discover.h"
-#include "foundation/log.h"
-#include "foundation/hash_table.h"
-#include "foundation/compat.h"
-#include "foundation/compat_fs.h"
-#include "foundation/platform.h"
-
-#include <stdlib.h>
-#include <string.h>
-#include <sys/stat.h>
-#include <stdatomic.h>
-#include <stdint.h>
-
-/* ── Constants ───────────────────────────────────────────────────── */
-
-#define CBM_MS_PER_SEC 1000.0
-#define CBM_NS_PER_MS 1000000.0
-#define CBM_NS_PER_SEC 1000000000LL
-
-/* ── Timing helper (same as pipeline.c) ──────────────────────────── */
-
-static double elapsed_ms(struct timespec start) {
- struct timespec now;
- cbm_clock_gettime(CLOCK_MONOTONIC, &now);
- double s = (double)(now.tv_sec - start.tv_sec);
- double ns = (double)(now.tv_nsec - start.tv_nsec);
- return (s * CBM_MS_PER_SEC) + (ns / CBM_NS_PER_MS);
-}
-
-/* itoa into static buffer — matches pipeline.c helper */
-static const char *itoa_buf(int v) {
- static _Thread_local char buf[4][24];
- static _Thread_local int idx = 0;
- idx = (idx + 1) & 3;
- snprintf(buf[idx], sizeof(buf[idx]), "%d", v);
- return buf[idx];
-}
-
-/* ── Platform-portable mtime_ns ──────────────────────────────────── */
-
-static int64_t stat_mtime_ns(const struct stat *st) {
-#ifdef __APPLE__
- return ((int64_t)st->st_mtimespec.tv_sec * CBM_NS_PER_SEC) + (int64_t)st->st_mtimespec.tv_nsec;
-#elif defined(_WIN32)
- return (int64_t)st->st_mtime * CBM_NS_PER_SEC;
-#else
- return ((int64_t)st->st_mtim.tv_sec * CBM_NS_PER_SEC) + (int64_t)st->st_mtim.tv_nsec;
-#endif
-}
-
-/* ── File classification ─────────────────────────────────────────── */
-
-/* Classify discovered files against stored hashes using mtime+size.
- * Returns a boolean array: changed[i] = true if files[i] needs re-parsing.
- * Caller must free the returned array. */
-static bool *classify_files(cbm_file_info_t *files, int file_count, cbm_file_hash_t *stored,
- int stored_count, int *out_changed, int *out_unchanged) {
- bool *changed = calloc((size_t)file_count, sizeof(bool));
- if (!changed) {
- return NULL;
- }
-
- int n_changed = 0;
- int n_unchanged = 0;
-
- /* Build lookup: rel_path -> stored hash */
- CBMHashTable *ht = cbm_ht_create(stored_count > 0 ? (size_t)stored_count * 2 : 64);
- for (int i = 0; i < stored_count; i++) {
- cbm_ht_set(ht, stored[i].rel_path, &stored[i]);
- }
-
- for (int i = 0; i < file_count; i++) {
- cbm_file_hash_t *h = cbm_ht_get(ht, files[i].rel_path);
- if (!h) {
- /* New file */
- changed[i] = true;
- n_changed++;
- continue;
- }
-
- struct stat st;
- if (stat(files[i].path, &st) != 0) {
- changed[i] = true;
- n_changed++;
- continue;
- }
-
- if (stat_mtime_ns(&st) != h->mtime_ns || st.st_size != h->size) {
- changed[i] = true;
- n_changed++;
- } else {
- n_unchanged++;
- }
- }
-
- cbm_ht_free(ht);
- *out_changed = n_changed;
- *out_unchanged = n_unchanged;
- return changed;
-}
-
-/* Find stored files that no longer exist on disk. Returns count. */
-static int find_deleted_files(cbm_file_info_t *files, int file_count, cbm_file_hash_t *stored,
- int stored_count, char ***out_deleted) {
- CBMHashTable *current = cbm_ht_create((size_t)file_count * 2);
- for (int i = 0; i < file_count; i++) {
- cbm_ht_set(current, files[i].rel_path, &files[i]);
- }
-
- int count = 0;
- int cap = 64;
- char **deleted = malloc((size_t)cap * sizeof(char *));
-
- for (int i = 0; i < stored_count; i++) {
- if (!cbm_ht_get(current, stored[i].rel_path)) {
- if (count >= cap) {
- cap *= 2;
- char **tmp = realloc(deleted, (size_t)cap * sizeof(char *));
- if (!tmp) {
- break;
- }
- deleted = tmp;
- }
- deleted[count++] = strdup(stored[i].rel_path);
- }
- }
-
- cbm_ht_free(current);
- *out_deleted = deleted;
- return count;
-}
-
-/* ── Persist file hashes ─────────────────────────────────────────── */
-
-static void persist_hashes(cbm_store_t *store, const char *project, cbm_file_info_t *files,
- int file_count) {
- for (int i = 0; i < file_count; i++) {
- struct stat st;
- if (stat(files[i].path, &st) != 0) {
- continue;
- }
- cbm_store_upsert_file_hash(store, project, files[i].rel_path, "", stat_mtime_ns(&st),
- st.st_size);
- }
-}
-
-/* ── Registry seed visitor ────────────────────────────────────────── */
-
-/* Callback for cbm_gbuf_foreach_node: add each node to the registry
- * so the resolver can find cross-file symbols during incremental. */
-static void registry_visitor(const cbm_gbuf_node_t *node, void *userdata) {
- cbm_registry_t *r = (cbm_registry_t *)userdata;
- cbm_registry_add(r, node->name, node->qualified_name, node->label);
-}
-
-/* Run parallel or sequential extract+resolve for changed files. */
-static void run_extract_resolve(cbm_pipeline_ctx_t *ctx, cbm_file_info_t *changed_files, int ci) {
- struct timespec t;
-
-#define MIN_FILES_FOR_PARALLEL_INCR 50
- int worker_count = cbm_default_worker_count(true);
- bool use_parallel = (worker_count > 1 && ci > MIN_FILES_FOR_PARALLEL_INCR);
-
- if (use_parallel) {
- cbm_log_info("incremental.mode", "mode", "parallel", "workers", itoa_buf(worker_count),
- "changed", itoa_buf(ci));
-
- _Atomic int64_t shared_ids;
- atomic_init(&shared_ids, cbm_gbuf_next_id(ctx->gbuf));
-
- CBMFileResult **cache = (CBMFileResult **)calloc(ci, sizeof(CBMFileResult *));
- if (cache) {
- cbm_clock_gettime(CLOCK_MONOTONIC, &t);
- cbm_parallel_extract(ctx, changed_files, ci, cache, &shared_ids, worker_count);
- cbm_gbuf_set_next_id(ctx->gbuf, atomic_load(&shared_ids));
- cbm_log_info("pass.timing", "pass", "incr_extract", "elapsed_ms",
- itoa_buf((int)elapsed_ms(t)));
-
- cbm_clock_gettime(CLOCK_MONOTONIC, &t);
- cbm_build_registry_from_cache(ctx, changed_files, ci, cache);
- cbm_log_info("pass.timing", "pass", "incr_registry", "elapsed_ms",
- itoa_buf((int)elapsed_ms(t)));
-
- cbm_clock_gettime(CLOCK_MONOTONIC, &t);
- cbm_parallel_resolve(ctx, changed_files, ci, cache, &shared_ids, worker_count);
- cbm_gbuf_set_next_id(ctx->gbuf, atomic_load(&shared_ids));
- cbm_log_info("pass.timing", "pass", "incr_resolve", "elapsed_ms",
- itoa_buf((int)elapsed_ms(t)));
-
- for (int j = 0; j < ci; j++) {
- if (cache[j]) {
- cbm_free_result(cache[j]);
- }
- }
- free(cache);
- }
- } else {
- cbm_log_info("incremental.mode", "mode", "sequential", "changed", itoa_buf(ci));
- cbm_pipeline_pass_definitions(ctx, changed_files, ci);
- cbm_pipeline_pass_calls(ctx, changed_files, ci);
- cbm_pipeline_pass_usages(ctx, changed_files, ci);
- cbm_pipeline_pass_semantic(ctx, changed_files, ci);
- }
-}
-
-/* Run post-extraction passes (tests, decorator tags, configlink, httplinks). */
-static void run_postpasses(cbm_pipeline_ctx_t *ctx, cbm_file_info_t *changed_files, int ci,
- const char *project) {
- struct timespec t;
-
- cbm_clock_gettime(CLOCK_MONOTONIC, &t);
- cbm_pipeline_pass_tests(ctx, changed_files, ci);
- cbm_log_info("pass.timing", "pass", "incr_tests", "elapsed_ms", itoa_buf((int)elapsed_ms(t)));
-
- cbm_clock_gettime(CLOCK_MONOTONIC, &t);
- cbm_pipeline_pass_decorator_tags(ctx->gbuf, project);
- cbm_log_info("pass.timing", "pass", "incr_decorator_tags", "elapsed_ms",
- itoa_buf((int)elapsed_ms(t)));
-
- cbm_clock_gettime(CLOCK_MONOTONIC, &t);
- cbm_pipeline_pass_configlink(ctx);
- cbm_log_info("pass.timing", "pass", "incr_configlink", "elapsed_ms",
- itoa_buf((int)elapsed_ms(t)));
-
- cbm_clock_gettime(CLOCK_MONOTONIC, &t);
- cbm_pipeline_pass_httplinks(ctx);
- cbm_log_info("pass.timing", "pass", "incr_httplinks", "elapsed_ms",
- itoa_buf((int)elapsed_ms(t)));
-}
-
-/* Delete old DB and dump merged graph + hashes to disk. */
-static void dump_and_persist(cbm_gbuf_t *gbuf, const char *db_path, const char *project,
- cbm_file_info_t *files, int file_count) {
- struct timespec t;
- cbm_clock_gettime(CLOCK_MONOTONIC, &t);
-
- cbm_unlink(db_path);
- char wal[1040];
- char shm[1040];
- snprintf(wal, sizeof(wal), "%s-wal", db_path);
- snprintf(shm, sizeof(shm), "%s-shm", db_path);
- cbm_unlink(wal);
- cbm_unlink(shm);
-
- int dump_rc = cbm_gbuf_dump_to_sqlite(gbuf, db_path);
- cbm_log_info("incremental.dump", "rc", itoa_buf(dump_rc), "elapsed_ms",
- itoa_buf((int)elapsed_ms(t)));
-
- cbm_store_t *hash_store = cbm_store_open_path(db_path);
- if (hash_store) {
- persist_hashes(hash_store, project, files, file_count);
- cbm_store_close(hash_store);
- }
-}
-
-/* ── Incremental pipeline entry point ────────────────────────────── */
-
-int cbm_pipeline_run_incremental(cbm_pipeline_t *p, const char *db_path, cbm_file_info_t *files,
- int file_count) {
- struct timespec t0;
- cbm_clock_gettime(CLOCK_MONOTONIC, &t0);
-
- const char *project = cbm_pipeline_project_name(p);
-
- /* Open existing disk DB */
- cbm_store_t *store = cbm_store_open_path(db_path);
- if (!store) {
- cbm_log_error("incremental.err", "msg", "open_db_failed", "path", db_path);
- return -1;
- }
-
- /* Load stored file hashes */
- cbm_file_hash_t *stored = NULL;
- int stored_count = 0;
- cbm_store_get_file_hashes(store, project, &stored, &stored_count);
-
- /* Classify files */
- int n_changed = 0;
- int n_unchanged = 0;
- bool *is_changed =
- classify_files(files, file_count, stored, stored_count, &n_changed, &n_unchanged);
-
- /* Find deleted files */
- char **deleted = NULL;
- int deleted_count = find_deleted_files(files, file_count, stored, stored_count, &deleted);
-
- cbm_log_info("incremental.classify", "changed", itoa_buf(n_changed), "unchanged",
- itoa_buf(n_unchanged), "deleted", itoa_buf(deleted_count));
-
- /* Fast path: nothing changed → skip */
- if (n_changed == 0 && deleted_count == 0) {
- cbm_log_info("incremental.noop", "reason", "no_changes");
- free(is_changed);
- free(deleted);
- cbm_store_free_file_hashes(stored, stored_count);
- cbm_store_close(store);
- return 0;
- }
-
- cbm_store_free_file_hashes(stored, stored_count);
-
- /* Build list of changed files */
- cbm_file_info_t *changed_files = malloc((size_t)n_changed * sizeof(cbm_file_info_t));
- int ci = 0;
- for (int i = 0; i < file_count; i++) {
- if (is_changed[i]) {
- changed_files[ci++] = files[i];
- }
- }
- free(is_changed);
-
- cbm_log_info("incremental.reparse", "files", itoa_buf(ci));
-
- struct timespec t;
-
- /* Step 1: Load existing graph into RAM */
- cbm_clock_gettime(CLOCK_MONOTONIC, &t);
- cbm_gbuf_t *existing = cbm_gbuf_new(project, cbm_pipeline_repo_path(p));
- int load_rc = cbm_gbuf_load_from_db(existing, db_path, project);
- cbm_log_info("incremental.load_db", "rc", itoa_buf(load_rc), "nodes",
- itoa_buf(cbm_gbuf_node_count(existing)), "edges",
- itoa_buf(cbm_gbuf_edge_count(existing)), "elapsed_ms",
- itoa_buf((int)elapsed_ms(t)));
-
- if (load_rc != 0) {
- cbm_log_error("incremental.err", "msg", "load_db_failed");
- cbm_gbuf_free(existing);
- free(changed_files);
- for (int i = 0; i < deleted_count; i++) {
- free(deleted[i]);
- }
- free(deleted);
- cbm_store_close(store);
- return -1;
- }
-
- cbm_store_close(store);
-
- /* Step 2: Purge stale nodes */
- cbm_clock_gettime(CLOCK_MONOTONIC, &t);
- for (int i = 0; i < ci; i++) {
- cbm_gbuf_delete_by_file(existing, changed_files[i].rel_path);
- }
- for (int i = 0; i < deleted_count; i++) {
- cbm_gbuf_delete_by_file(existing, deleted[i]);
- free(deleted[i]);
- }
- free(deleted);
- cbm_log_info("incremental.purge", "elapsed_ms", itoa_buf((int)elapsed_ms(t)));
-
- /* Step 3-5: Registry + extract + resolve */
- cbm_registry_t *registry = cbm_registry_new();
- cbm_clock_gettime(CLOCK_MONOTONIC, &t);
- cbm_gbuf_foreach_node(existing, registry_visitor, registry);
- cbm_log_info("incremental.registry_seed", "symbols", itoa_buf(cbm_registry_size(registry)),
- "elapsed_ms", itoa_buf((int)elapsed_ms(t)));
-
- cbm_pipeline_ctx_t ctx = {
- .project_name = project,
- .repo_path = cbm_pipeline_repo_path(p),
- .gbuf = existing,
- .registry = registry,
- .cancelled = cbm_pipeline_cancelled_ptr(p),
- };
-
- for (int i = 0; i < ci; i++) {
- char *file_qn = cbm_pipeline_fqn_compute(project, changed_files[i].rel_path, "__file__");
- if (file_qn) {
- cbm_gbuf_upsert_node(existing, "File", changed_files[i].rel_path, file_qn,
- changed_files[i].rel_path, 0, 0, "{}");
- free(file_qn);
- }
- }
-
- run_extract_resolve(&ctx, changed_files, ci);
- cbm_pipeline_pass_k8s(&ctx, changed_files, ci);
- run_postpasses(&ctx, changed_files, ci, project);
-
- free(changed_files);
- cbm_registry_free(registry);
-
- /* Step 7: Dump to disk */
- dump_and_persist(existing, db_path, project, files, file_count);
- cbm_gbuf_free(existing);
-
- cbm_log_info("incremental.done", "elapsed_ms", itoa_buf((int)elapsed_ms(t0)));
- return 0;
-}
+/*
+ * pipeline_incremental.c — Disk-based incremental re-indexing.
+ *
+ * Operates on the existing SQLite DB directly (not RAM-first graph buffer).
+ * Compares file mtime+size against stored hashes to classify changed/unchanged.
+ * Deletes changed files' nodes (edges cascade via ON DELETE CASCADE),
+ * re-parses only changed files through passes into a temp graph buffer,
+ * then merges new nodes/edges into the disk DB. Persists updated hashes.
+ *
+ * Called from pipeline.c when a DB with stored hashes already exists.
+ */
+#include "foundation/constants.h"
+
+enum { INCR_RING_BUF = 4, INCR_RING_MASK = 3, INCR_TS_BUF = 24, INCR_WAL_BUF = 1040 };
+#include "pipeline/pipeline.h"
+#include "pipeline/pipeline_internal.h"
+#include "store/store.h"
+#include "graph_buffer/graph_buffer.h"
+#include "discover/discover.h"
+#include "foundation/log.h"
+#include "foundation/hash_table.h"
+#include "foundation/compat.h"
+#include "foundation/compat_fs.h"
+#include "foundation/platform.h"
+
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <stdatomic.h>
+#include <stdint.h>
+
+/* ── Constants ───────────────────────────────────────────────────── */
+
+#define CBM_MS_PER_SEC 1000.0
+#define CBM_NS_PER_MS 1000000.0
+#define CBM_NS_PER_SEC 1000000000LL
+
+/* ── Timing helper (same as pipeline.c) ──────────────────────────── */
+
+static double elapsed_ms(struct timespec start) {
+ struct timespec now;
+ cbm_clock_gettime(CLOCK_MONOTONIC, &now);
+ double s = (double)(now.tv_sec - start.tv_sec);
+ double ns = (double)(now.tv_nsec - start.tv_nsec);
+ return (s * CBM_MS_PER_SEC) + (ns / CBM_NS_PER_MS);
+}
+
+/* itoa into static buffer — matches pipeline.c helper */
+static const char *itoa_buf(int v) {
+ static _Thread_local char buf[INCR_RING_BUF][INCR_TS_BUF];
+ static _Thread_local int idx = 0;
+ idx = (idx + SKIP_ONE) & INCR_RING_MASK;
+ snprintf(buf[idx], sizeof(buf[idx]), "%d", v);
+ return buf[idx];
+}
+
+/* ── Platform-portable mtime_ns ──────────────────────────────────── */
+
+static int64_t stat_mtime_ns(const struct stat *st) {
+#ifdef __APPLE__
+ return ((int64_t)st->st_mtimespec.tv_sec * CBM_NS_PER_SEC) + (int64_t)st->st_mtimespec.tv_nsec;
+#elif defined(_WIN32)
+ return (int64_t)st->st_mtime * CBM_NS_PER_SEC;
+#else
+ return ((int64_t)st->st_mtim.tv_sec * CBM_NS_PER_SEC) + (int64_t)st->st_mtim.tv_nsec;
+#endif
+}
+
+/* ── File classification ─────────────────────────────────────────── */
+
+/* Classify discovered files against stored hashes using mtime+size.
+ * Returns a boolean array: changed[i] = true if files[i] needs re-parsing.
+ * Caller must free the returned array. */
+static bool *classify_files(cbm_file_info_t *files, int file_count, cbm_file_hash_t *stored,
+ int stored_count, int *out_changed, int *out_unchanged) {
+ bool *changed = calloc((size_t)file_count, sizeof(bool));
+ if (!changed) {
+ return NULL;
+ }
+
+ int n_changed = 0;
+ int n_unchanged = 0;
+
+ /* Build lookup: rel_path -> stored hash */
+ CBMHashTable *ht =
+ cbm_ht_create(stored_count > 0 ? (size_t)stored_count * PAIR_LEN : CBM_SZ_64);
+ for (int i = 0; i < stored_count; i++) {
+ cbm_ht_set(ht, stored[i].rel_path, &stored[i]);
+ }
+
+ for (int i = 0; i < file_count; i++) {
+ cbm_file_hash_t *h = cbm_ht_get(ht, files[i].rel_path);
+ if (!h) {
+ /* New file */
+ changed[i] = true;
+ n_changed++;
+ continue;
+ }
+
+ struct stat st;
+ if (stat(files[i].path, &st) != 0) {
+ changed[i] = true;
+ n_changed++;
+ continue;
+ }
+
+ if (stat_mtime_ns(&st) != h->mtime_ns || st.st_size != h->size) {
+ changed[i] = true;
+ n_changed++;
+ } else {
+ n_unchanged++;
+ }
+ }
+
+ cbm_ht_free(ht);
+ *out_changed = n_changed;
+ *out_unchanged = n_unchanged;
+ return changed;
+}
+
+/* Find stored files that no longer exist on disk. Returns count. */
+static int find_deleted_files(cbm_file_info_t *files, int file_count, cbm_file_hash_t *stored,
+ int stored_count, char ***out_deleted) {
+ CBMHashTable *current = cbm_ht_create((size_t)file_count * PAIR_LEN);
+ for (int i = 0; i < file_count; i++) {
+ cbm_ht_set(current, files[i].rel_path, &files[i]);
+ }
+
+ int count = 0;
+ int cap = CBM_SZ_64;
+ char **deleted = malloc((size_t)cap * sizeof(char *));
+
+ for (int i = 0; i < stored_count; i++) {
+ if (!cbm_ht_get(current, stored[i].rel_path)) {
+ if (count >= cap) {
+ cap *= PAIR_LEN;
+ char **tmp = realloc(deleted, (size_t)cap * sizeof(char *));
+ if (!tmp) {
+ break;
+ }
+ deleted = tmp;
+ }
+ deleted[count++] = strdup(stored[i].rel_path);
+ }
+ }
+
+ cbm_ht_free(current);
+ *out_deleted = deleted;
+ return count;
+}
+
+/* ── Persist file hashes ─────────────────────────────────────────── */
+
+static void persist_hashes(cbm_store_t *store, const char *project, cbm_file_info_t *files,
+ int file_count) {
+ for (int i = 0; i < file_count; i++) {
+ struct stat st;
+ if (stat(files[i].path, &st) != 0) {
+ continue;
+ }
+ cbm_store_upsert_file_hash(store, project, files[i].rel_path, "", stat_mtime_ns(&st),
+ st.st_size);
+ }
+}
+
+/* ── Registry seed visitor ────────────────────────────────────────── */
+
+/* Callback for cbm_gbuf_foreach_node: add each node to the registry
+ * so the resolver can find cross-file symbols during incremental. */
+static void registry_visitor(const cbm_gbuf_node_t *node, void *userdata) {
+ cbm_registry_t *r = (cbm_registry_t *)userdata;
+ cbm_registry_add(r, node->name, node->qualified_name, node->label);
+}
+
+/* Run parallel or sequential extract+resolve for changed files. */
+static void run_extract_resolve(cbm_pipeline_ctx_t *ctx, cbm_file_info_t *changed_files, int ci) {
+ struct timespec t;
+
+#define MIN_FILES_FOR_PARALLEL_INCR 50
+ int worker_count = cbm_default_worker_count(true);
+ bool use_parallel = (worker_count > SKIP_ONE && ci > MIN_FILES_FOR_PARALLEL_INCR);
+
+ if (use_parallel) {
+ cbm_log_info("incremental.mode", "mode", "parallel", "workers", itoa_buf(worker_count),
+ "changed", itoa_buf(ci));
+
+ _Atomic int64_t shared_ids;
+ atomic_init(&shared_ids, cbm_gbuf_next_id(ctx->gbuf));
+
+ CBMFileResult **cache = (CBMFileResult **)calloc(ci, sizeof(CBMFileResult *));
+ if (cache) {
+ cbm_clock_gettime(CLOCK_MONOTONIC, &t);
+ cbm_parallel_extract(ctx, changed_files, ci, cache, &shared_ids, worker_count);
+ cbm_gbuf_set_next_id(ctx->gbuf, atomic_load(&shared_ids));
+ cbm_log_info("pass.timing", "pass", "incr_extract", "elapsed_ms",
+ itoa_buf((int)elapsed_ms(t)));
+
+ cbm_clock_gettime(CLOCK_MONOTONIC, &t);
+ cbm_build_registry_from_cache(ctx, changed_files, ci, cache);
+ cbm_log_info("pass.timing", "pass", "incr_registry", "elapsed_ms",
+ itoa_buf((int)elapsed_ms(t)));
+
+ cbm_clock_gettime(CLOCK_MONOTONIC, &t);
+ cbm_parallel_resolve(ctx, changed_files, ci, cache, &shared_ids, worker_count);
+ cbm_gbuf_set_next_id(ctx->gbuf, atomic_load(&shared_ids));
+ cbm_log_info("pass.timing", "pass", "incr_resolve", "elapsed_ms",
+ itoa_buf((int)elapsed_ms(t)));
+
+ for (int j = 0; j < ci; j++) {
+ if (cache[j]) {
+ cbm_free_result(cache[j]);
+ }
+ }
+ free(cache);
+ }
+ } else {
+ cbm_log_info("incremental.mode", "mode", "sequential", "changed", itoa_buf(ci));
+ cbm_pipeline_pass_definitions(ctx, changed_files, ci);
+ cbm_pipeline_pass_calls(ctx, changed_files, ci);
+ cbm_pipeline_pass_usages(ctx, changed_files, ci);
+ cbm_pipeline_pass_semantic(ctx, changed_files, ci);
+ }
+}
+
+/* Run post-extraction passes (tests, decorator tags, configlink). */
+static void run_postpasses(cbm_pipeline_ctx_t *ctx, cbm_file_info_t *changed_files, int ci,
+ const char *project) {
+ struct timespec t;
+
+ cbm_clock_gettime(CLOCK_MONOTONIC, &t);
+ cbm_pipeline_pass_tests(ctx, changed_files, ci);
+ cbm_log_info("pass.timing", "pass", "incr_tests", "elapsed_ms", itoa_buf((int)elapsed_ms(t)));
+
+ cbm_clock_gettime(CLOCK_MONOTONIC, &t);
+ cbm_pipeline_pass_decorator_tags(ctx->gbuf, project);
+ cbm_log_info("pass.timing", "pass", "incr_decorator_tags", "elapsed_ms",
+ itoa_buf((int)elapsed_ms(t)));
+
+ cbm_clock_gettime(CLOCK_MONOTONIC, &t);
+ cbm_pipeline_pass_configlink(ctx);
+ cbm_log_info("pass.timing", "pass", "incr_configlink", "elapsed_ms",
+ itoa_buf((int)elapsed_ms(t)));
+}
+/* Delete old DB and dump merged graph + hashes to disk. */
+static void dump_and_persist(cbm_gbuf_t *gbuf, const char *db_path, const char *project,
+ cbm_file_info_t *files, int file_count) {
+ struct timespec t;
+ cbm_clock_gettime(CLOCK_MONOTONIC, &t);
+
+ cbm_unlink(db_path);
+ char wal[INCR_WAL_BUF];
+ char shm[INCR_WAL_BUF];
+ snprintf(wal, sizeof(wal), "%s-wal", db_path);
+ snprintf(shm, sizeof(shm), "%s-shm", db_path);
+ cbm_unlink(wal);
+ cbm_unlink(shm);
+
+ int dump_rc = cbm_gbuf_dump_to_sqlite(gbuf, db_path);
+ cbm_log_info("incremental.dump", "rc", itoa_buf(dump_rc), "elapsed_ms",
+ itoa_buf((int)elapsed_ms(t)));
+
+ cbm_store_t *hash_store = cbm_store_open_path(db_path);
+ if (hash_store) {
+ persist_hashes(hash_store, project, files, file_count);
+ cbm_store_close(hash_store);
+ }
+}
+
+/* ── Incremental pipeline entry point ────────────────────────────── */
+
+int cbm_pipeline_run_incremental(cbm_pipeline_t *p, const char *db_path, cbm_file_info_t *files,
+ int file_count) {
+ struct timespec t0;
+ cbm_clock_gettime(CLOCK_MONOTONIC, &t0);
+
+ const char *project = cbm_pipeline_project_name(p);
+
+ /* Open existing disk DB */
+ cbm_store_t *store = cbm_store_open_path(db_path);
+ if (!store) {
+ cbm_log_error("incremental.err", "msg", "open_db_failed", "path", db_path);
+ return CBM_NOT_FOUND;
+ }
+
+ /* Load stored file hashes */
+ cbm_file_hash_t *stored = NULL;
+ int stored_count = 0;
+ cbm_store_get_file_hashes(store, project, &stored, &stored_count);
+
+ /* Classify files */
+ int n_changed = 0;
+ int n_unchanged = 0;
+ bool *is_changed =
+ classify_files(files, file_count, stored, stored_count, &n_changed, &n_unchanged);
+
+ /* Find deleted files */
+ char **deleted = NULL;
+ int deleted_count = find_deleted_files(files, file_count, stored, stored_count, &deleted);
+
+ cbm_log_info("incremental.classify", "changed", itoa_buf(n_changed), "unchanged",
+ itoa_buf(n_unchanged), "deleted", itoa_buf(deleted_count));
+
+ /* Fast path: nothing changed → skip */
+ if (n_changed == 0 && deleted_count == 0) {
+ cbm_log_info("incremental.noop", "reason", "no_changes");
+ free(is_changed);
+ free(deleted);
+ cbm_store_free_file_hashes(stored, stored_count);
+ cbm_store_close(store);
+ return 0;
+ }
+
+ cbm_store_free_file_hashes(stored, stored_count);
+
+ /* Build list of changed files */
+ cbm_file_info_t *changed_files =
+ (n_changed > 0) ? malloc((size_t)n_changed * sizeof(cbm_file_info_t)) : NULL;
+ int ci = 0;
+ for (int i = 0; i < file_count; i++) {
+ if (is_changed[i]) {
+ changed_files[ci++] = files[i];
+ }
+ }
+ free(is_changed);
+
+ cbm_log_info("incremental.reparse", "files", itoa_buf(ci));
+
+ struct timespec t;
+
+ /* Step 1: Load existing graph into RAM */
+ cbm_clock_gettime(CLOCK_MONOTONIC, &t);
+ cbm_gbuf_t *existing = cbm_gbuf_new(project, cbm_pipeline_repo_path(p));
+ int load_rc = cbm_gbuf_load_from_db(existing, db_path, project);
+ cbm_log_info("incremental.load_db", "rc", itoa_buf(load_rc), "nodes",
+ itoa_buf(cbm_gbuf_node_count(existing)), "edges",
+ itoa_buf(cbm_gbuf_edge_count(existing)), "elapsed_ms",
+ itoa_buf((int)elapsed_ms(t)));
+
+ if (load_rc != 0) {
+ cbm_log_error("incremental.err", "msg", "load_db_failed");
+ cbm_gbuf_free(existing);
+ free(changed_files);
+ for (int i = 0; i < deleted_count; i++) {
+ free(deleted[i]);
+ }
+ free(deleted);
+ cbm_store_close(store);
+ return CBM_NOT_FOUND;
+ }
+
+ cbm_store_close(store);
+
+ /* Step 2: Purge stale nodes */
+ cbm_clock_gettime(CLOCK_MONOTONIC, &t);
+ for (int i = 0; i < ci; i++) {
+ cbm_gbuf_delete_by_file(existing, changed_files[i].rel_path);
+ }
+ for (int i = 0; i < deleted_count; i++) {
+ cbm_gbuf_delete_by_file(existing, deleted[i]);
+ free(deleted[i]);
+ }
+ free(deleted);
+ cbm_log_info("incremental.purge", "elapsed_ms", itoa_buf((int)elapsed_ms(t)));
+
+ /* Step 3-5: Registry + extract + resolve */
+ cbm_registry_t *registry = cbm_registry_new();
+ cbm_clock_gettime(CLOCK_MONOTONIC, &t);
+ cbm_gbuf_foreach_node(existing, registry_visitor, registry);
+ cbm_log_info("incremental.registry_seed", "symbols", itoa_buf(cbm_registry_size(registry)),
+ "elapsed_ms", itoa_buf((int)elapsed_ms(t)));
+
+ cbm_pipeline_ctx_t ctx = {
+ .project_name = project,
+ .repo_path = cbm_pipeline_repo_path(p),
+ .gbuf = existing,
+ .registry = registry,
+ .cancelled = cbm_pipeline_cancelled_ptr(p),
+ };
+
+ for (int i = 0; i < ci; i++) {
+ char *file_qn = cbm_pipeline_fqn_compute(project, changed_files[i].rel_path, "__file__");
+ if (file_qn) {
+ cbm_gbuf_upsert_node(existing, "File", changed_files[i].rel_path, file_qn,
+ changed_files[i].rel_path, 0, 0, "{}");
+ free(file_qn);
+ }
+ }
+
+ run_extract_resolve(&ctx, changed_files, ci);
+ cbm_pipeline_pass_k8s(&ctx, changed_files, ci);
+ run_postpasses(&ctx, changed_files, ci, project);
+
+ free(changed_files);
+ cbm_registry_free(registry);
+
+ /* Step 7: Dump to disk */
+ dump_and_persist(existing, db_path, project, files, file_count);
+ cbm_gbuf_free(existing);
+
+ cbm_log_info("incremental.done", "elapsed_ms", itoa_buf((int)elapsed_ms(t0)));
+ return 0;
+}
diff --git a/src/pipeline/pipeline_internal.h b/src/pipeline/pipeline_internal.h
index eeec6b542..2fa4f4338 100644
--- a/src/pipeline/pipeline_internal.h
+++ b/src/pipeline/pipeline_internal.h
@@ -1,3 +1,4 @@
+#include "foundation/constants.h"
/*
* pipeline_internal.h — Internal pipeline state shared between pass files.
*
@@ -48,7 +49,7 @@ typedef struct {
/* Check cancellation. Returns non-zero if cancelled. */
static inline int cbm_pipeline_check_cancel(const cbm_pipeline_ctx_t *ctx) {
- return atomic_load(ctx->cancelled) ? -1 : 0;
+ return atomic_load(ctx->cancelled) ? CBM_NOT_FOUND : 0;
}
/* ── Testable helpers ────────────────────────────────────────────── */
@@ -64,8 +65,8 @@ bool cbm_is_test_func_name(const char *name);
/* Coupling result from computeChangeCoupling */
typedef struct {
- char file_a[512];
- char file_b[512];
+ char file_a[CBM_SZ_512];
+ char file_b[CBM_SZ_512];
int co_change_count;
double coupling_score;
} cbm_change_coupling_t;
@@ -90,13 +91,13 @@ int cbm_pipeline_implements_go(cbm_pipeline_ctx_t *ctx);
/* ── Git diff helpers (pass_gitdiff.c) ───────────────────────────── */
typedef struct {
- char status[4]; /* "M", "A", "D", "R" */
- char path[512];
- char old_path[512]; /* non-empty only for renames */
+ char status[CBM_SZ_4]; /* M/A/D/R */ /* "M", "A", "D", "R" */
+ char path[CBM_SZ_512];
+ char old_path[CBM_SZ_512]; /* non-empty only for renames */
} cbm_changed_file_t;
typedef struct {
- char path[512];
+ char path[CBM_SZ_512];
int start_line;
int end_line;
} cbm_changed_hunk_t;
@@ -142,7 +143,7 @@ typedef struct {
int include_count;
char **defines;
int define_count;
- char standard[32];
+ char standard[CBM_SZ_32];
} cbm_compile_flags_t;
/* Split a shell command string into arguments (handles quoting).
@@ -184,81 +185,81 @@ void cbm_clean_json_brackets(const char *s, char *out, size_t out_sz);
/* Key-value pair for environment variables / config entries */
typedef struct {
- char key[128];
- char value[512];
+ char key[CBM_SZ_128];
+ char value[CBM_SZ_512];
} cbm_env_kv_t;
/* Dockerfile parsing result */
typedef struct {
- char base_image[256];
- char stage_images[16][256];
- char stage_names[16][128];
+ char base_image[CBM_SZ_256];
+ char stage_images[CBM_SZ_16][CBM_SZ_256];
+ char stage_names[CBM_SZ_16][CBM_SZ_128];
int stage_count;
- char exposed_ports[16][32];
+ char exposed_ports[CBM_SZ_16][CBM_SZ_32];
int port_count;
- cbm_env_kv_t env_vars[64];
+ cbm_env_kv_t env_vars[CBM_SZ_64];
int env_count;
- char build_args[32][128];
+ char build_args[CBM_SZ_32][CBM_SZ_128];
int build_arg_count;
- char workdir[256];
- char cmd[512];
- char entrypoint[512];
- char healthcheck[512];
- char user[64];
+ char workdir[CBM_SZ_256];
+ char cmd[CBM_SZ_512];
+ char entrypoint[CBM_SZ_512];
+ char healthcheck[CBM_SZ_512];
+ char user[CBM_SZ_64];
} cbm_dockerfile_result_t;
/* Dotenv parsing result */
typedef struct {
- cbm_env_kv_t env_vars[64];
+ cbm_env_kv_t env_vars[CBM_SZ_64];
int env_count;
} cbm_dotenv_result_t;
/* Shell script parsing result */
typedef struct {
- char shebang[256];
- cbm_env_kv_t env_vars[64];
+ char shebang[CBM_SZ_256];
+ cbm_env_kv_t env_vars[CBM_SZ_64];
int env_count;
- char sources[16][256];
+ char sources[CBM_SZ_16][CBM_SZ_256];
int source_count;
- char docker_cmds[16][256];
+ char docker_cmds[CBM_SZ_16][CBM_SZ_256];
int docker_cmd_count;
} cbm_shell_result_t;
/* Terraform variable */
typedef struct {
- char name[128];
- char type[64];
- char default_val[256];
- char description[256];
+ char name[CBM_SZ_128];
+ char type[CBM_SZ_64];
+ char default_val[CBM_SZ_256];
+ char description[CBM_SZ_256];
} cbm_tf_variable_t;
/* Terraform resource / data source */
typedef struct {
- char type[128];
- char name[128];
+ char type[CBM_SZ_128];
+ char name[CBM_SZ_128];
} cbm_tf_resource_t;
/* Terraform module */
typedef struct {
- char tf_name[128];
- char source[256];
+ char tf_name[CBM_SZ_128];
+ char source[CBM_SZ_256];
} cbm_tf_module_t;
/* Terraform parsing result */
typedef struct {
- cbm_tf_resource_t resources[32];
+ cbm_tf_resource_t resources[CBM_SZ_32];
int resource_count;
- cbm_tf_variable_t variables[32];
+ cbm_tf_variable_t variables[CBM_SZ_32];
int variable_count;
- char outputs[32][128];
+ char outputs[CBM_SZ_32][CBM_SZ_128];
int output_count;
- char providers[16][128];
+ char providers[CBM_SZ_16][CBM_SZ_128];
int provider_count;
- cbm_tf_module_t modules[16];
+ cbm_tf_module_t modules[CBM_SZ_16];
int module_count;
- cbm_tf_resource_t data_sources[16];
+ cbm_tf_resource_t data_sources[CBM_SZ_16];
int data_source_count;
- char backend[128];
+ char backend[CBM_SZ_128];
bool has_locals;
} cbm_terraform_result_t;
@@ -343,8 +344,6 @@ int cbm_pipeline_githistory_compute(const char *repo_path, cbm_githistory_result
/* Apply pre-computed couplings to the graph buffer (main thread only). */
int cbm_pipeline_githistory_apply(cbm_pipeline_ctx_t *ctx, const cbm_githistory_result_t *result);
-int cbm_pipeline_pass_httplinks(cbm_pipeline_ctx_t *ctx);
-
/* Pre-dump pass: decorator tags enrichment (operates on gbuf). */
int cbm_pipeline_pass_decorator_tags(cbm_gbuf_t *gbuf, const char *project);
@@ -354,9 +353,9 @@ int cbm_pipeline_pass_configlink(cbm_pipeline_ctx_t *ctx);
/* ── Env URL scanner (pass_envscan.c) ────────────────────────────── */
typedef struct {
- char key[128];
- char value[512];
- char file_path[256];
+ char key[CBM_SZ_128];
+ char value[CBM_SZ_512];
+ char file_path[CBM_SZ_256];
} cbm_env_binding_t;
/* Scan a project directory for environment variable assignments with URL values.
diff --git a/src/pipeline/registry.c b/src/pipeline/registry.c
index 8ba603d91..e0b94194e 100644
--- a/src/pipeline/registry.c
+++ b/src/pipeline/registry.c
@@ -9,6 +9,13 @@
* 3. Unique name (single candidate project-wide)
* 4. Suffix match with import distance scoring
*/
+#include "foundation/constants.h"
+
+enum { REG_INIT_CAP = 16, REG_MIN_CANDIDATES = 3, REG_RESOLVED = 1, REG_SUFFIX_ALLOC = 2 };
+#define REG_FULL_CONF 1.0
+#define REG_HALF_PENALTY 0.5
+
+#define DEFAULT_CONFIDENCE 0.5
#include "pipeline/pipeline.h"
#include "foundation/hash_table.h"
#include "foundation/dyn_array.h"
@@ -19,6 +26,24 @@
#include <stdlib.h>
#include <string.h>
+/* Confidence score → human-readable band label. */
+#define CONF_BAND_HIGH 0.7
+#define CONF_BAND_MEDIUM 0.45
+#define CONF_BAND_SPECULATIVE 0.25
+
+const char *cbm_confidence_band(double score) {
+ if (score >= CONF_BAND_HIGH) {
+ return "high";
+ }
+ if (score >= CONF_BAND_MEDIUM) {
+ return "medium";
+ }
+ if (score >= CONF_BAND_SPECULATIVE) {
+ return "speculative";
+ }
+ return "";
+}
+
/* ── Resolution confidence scores ────────────────────────────────── */
/* Strategy 1: import_map — direct import → high confidence */
#define CONF_IMPORT_MAP 0.95
@@ -53,7 +78,7 @@ struct cbm_registry {
/* Extract last dot-separated segment from a QN. Returns pointer into s. */
static const char *simple_name(const char *qn) {
const char *last = strrchr(qn, '.');
- return last ? last + 1 : qn;
+ return last ? last + SKIP_ONE : qn;
}
/* Extract everything before the last dot. Returns heap-allocated string. */
@@ -74,8 +99,8 @@ static int common_prefix_len(const char *a, const char *b) {
break;
}
count++;
- a += alen + (adot ? 1 : 0);
- b += blen + (bdot ? 1 : 0);
+ a += alen + (adot ? SKIP_ONE : 0);
+ b += blen + (bdot ? SKIP_ONE : 0);
if (!adot || !bdot) {
break;
}
@@ -87,7 +112,7 @@ static int common_prefix_len(const char *a, const char *b) {
static const char *best_by_import_distance(const char **candidates, int count,
const char *module_qn) {
const char *best = NULL;
- int best_len = -1;
+ int best_len = CBM_NOT_FOUND;
for (int i = 0; i < count; i++) {
int plen = common_prefix_len(candidates[i], module_qn);
if (plen > best_len) {
@@ -102,12 +127,12 @@ static const char *best_by_import_distance(const char **candidates, int count,
* Uses stack buffer to avoid malloc/free per call in hot resolution loop. */
static bool is_import_reachable(const char *candidate_qn, const char **import_vals,
int import_count) {
- char cand_mod[512];
+ char cand_mod[CBM_SZ_512];
const char *last = strrchr(candidate_qn, '.');
if (last) {
size_t len = (size_t)(last - candidate_qn);
if (len >= sizeof(cand_mod)) {
- len = sizeof(cand_mod) - 1;
+ len = sizeof(cand_mod) - SKIP_ONE;
}
memcpy(cand_mod, candidate_qn, len);
cand_mod[len] = '\0';
@@ -124,10 +149,10 @@ static bool is_import_reachable(const char *candidate_qn, const char **import_va
/* Scale confidence inversely with candidate count. */
static double candidate_count_penalty(double base, int count) {
- if (count <= 3) {
+ if (count <= REG_MIN_CANDIDATES) {
return base;
}
- return base * fmin(1.0, CANDIDATE_PENALTY_CAP / (double)count);
+ return base * fmin(REG_FULL_CONF, CANDIDATE_PENALTY_CAP / (double)count);
}
static cbm_resolution_t empty_result(void) {
@@ -138,12 +163,12 @@ static cbm_resolution_t empty_result(void) {
/* ── Lifecycle ──────────────────────────────────────────────────── */
cbm_registry_t *cbm_registry_new(void) {
- cbm_registry_t *r = calloc(1, sizeof(cbm_registry_t));
+ cbm_registry_t *r = calloc(CBM_ALLOC_ONE, sizeof(cbm_registry_t));
if (!r) {
return NULL;
}
- r->exact = cbm_ht_create(1024);
- r->by_name = cbm_ht_create(512);
+ r->exact = cbm_ht_create(CBM_SZ_1K);
+ r->by_name = cbm_ht_create(CBM_SZ_512);
return r;
}
@@ -199,7 +224,7 @@ void cbm_registry_add(cbm_registry_t *r, const char *name, const char *qualified
const char *simple = simple_name(qualified_name);
qn_array_t *arr = cbm_ht_get(r->by_name, simple);
if (!arr) {
- arr = calloc(1, sizeof(qn_array_t));
+ arr = calloc(CBM_ALLOC_ONE, sizeof(qn_array_t));
cbm_ht_set(r->by_name, strdup(simple), arr);
}
cbm_da_push(arr, strdup(qualified_name));
@@ -224,7 +249,7 @@ const char *cbm_registry_label_of(const cbm_registry_t *r, const char *qn) {
int cbm_registry_find_by_name(const cbm_registry_t *r, const char *name, const char ***out,
int *count) {
if (!r || !out || !count) {
- return -1;
+ return CBM_NOT_FOUND;
}
qn_array_t *arr = cbm_ht_get(r->by_name, name);
if (arr && arr->count > 0) {
@@ -287,7 +312,7 @@ static cbm_resolution_t resolve_import_map(const cbm_registry_t *r, const char *
}
/* Build candidate: resolved.suffix or just resolved */
- char candidate[512];
+ char candidate[CBM_SZ_512];
if (suffix && suffix[0]) {
snprintf(candidate, sizeof(candidate), "%s.%s", resolved, suffix);
} else {
@@ -296,14 +321,14 @@ static cbm_resolution_t resolve_import_map(const cbm_registry_t *r, const char *
/* Use cbm_ht_get_key to get the persistent heap-owned key string */
const char *stored_key = cbm_ht_get_key(r->exact, candidate);
if (stored_key) {
- return (cbm_resolution_t){stored_key, "import_map", CONF_IMPORT_MAP, 1};
+ return (cbm_resolution_t){stored_key, "import_map", CONF_IMPORT_MAP, REG_RESOLVED};
}
/* import_map_suffix fallback: scan for QNs starting with resolved+"."
* and ending with "."+suffix */
if (suffix && suffix[0]) {
- char resolved_dot[512];
- char dot_suffix[256];
+ char resolved_dot[CBM_SZ_512];
+ char dot_suffix[CBM_SZ_256];
snprintf(resolved_dot, sizeof(resolved_dot), "%s.", resolved);
snprintf(dot_suffix, sizeof(dot_suffix), ".%s", suffix);
struct ims_ctx ctx = {
@@ -316,7 +341,7 @@ static cbm_resolution_t resolve_import_map(const cbm_registry_t *r, const char *
cbm_ht_foreach(r->exact, ims_scan, &ctx);
if (ctx.found_key) {
return (cbm_resolution_t){ctx.found_key, "import_map_suffix", CONF_IMPORT_MAP_SUFFIX,
- 1};
+ REG_RESOLVED};
}
}
return empty_result();
@@ -325,17 +350,17 @@ static cbm_resolution_t resolve_import_map(const cbm_registry_t *r, const char *
/* Strategy 2: Same-module match */
static cbm_resolution_t resolve_same_module(const cbm_registry_t *r, const char *callee_name,
const char *suffix, const char *module_qn) {
- char candidate[512];
+ char candidate[CBM_SZ_512];
snprintf(candidate, sizeof(candidate), "%s.%s", module_qn, callee_name);
const char *stored_key = cbm_ht_get_key(r->exact, candidate);
if (stored_key) {
- return (cbm_resolution_t){stored_key, "same_module", CONF_SAME_MODULE, 1};
+ return (cbm_resolution_t){stored_key, "same_module", CONF_SAME_MODULE, REG_RESOLVED};
}
if (suffix && suffix[0]) {
snprintf(candidate, sizeof(candidate), "%s.%s", module_qn, suffix);
stored_key = cbm_ht_get_key(r->exact, candidate);
if (stored_key) {
- return (cbm_resolution_t){stored_key, "same_module", CONF_SAME_MODULE, 1};
+ return (cbm_resolution_t){stored_key, "same_module", CONF_SAME_MODULE, REG_RESOLVED};
}
}
return empty_result();
@@ -344,18 +369,18 @@ static cbm_resolution_t resolve_same_module(const cbm_registry_t *r, const char
/* Strategy 4: multiple candidates with import filtering. */
static cbm_resolution_t resolve_multi_with_imports(const qn_array_t *arr, const char *module_qn,
const char **import_vals, int import_count) {
- const char *filtered[256];
+ const char *filtered[CBM_SZ_256];
int fcount = 0;
- for (int i = 0; i < arr->count && fcount < 256; i++) {
+ for (int i = 0; i < arr->count && fcount < CBM_SZ_256; i++) {
if (is_import_reachable(arr->items[i], import_vals, import_count)) {
filtered[fcount++] = arr->items[i];
}
}
- if (fcount == 1) {
+ if (fcount == SKIP_ONE) {
double conf = candidate_count_penalty(CONF_SUFFIX_MATCH, arr->count);
return (cbm_resolution_t){filtered[0], "suffix_match", conf, arr->count};
}
- if (fcount > 1) {
+ if (fcount > SKIP_ONE) {
const char *best = best_by_import_distance(filtered, fcount, module_qn);
if (best) {
double conf = candidate_count_penalty(CONF_SUFFIX_MATCH, fcount);
@@ -365,7 +390,7 @@ static cbm_resolution_t resolve_multi_with_imports(const qn_array_t *arr, const
/* No import-reachable — use all candidates with penalty */
const char *best = best_by_import_distance((const char **)arr->items, arr->count, module_qn);
if (best) {
- double conf = candidate_count_penalty(CONF_SUFFIX_MATCH * 0.5, arr->count);
+ double conf = candidate_count_penalty(CONF_SUFFIX_MATCH * REG_HALF_PENALTY, arr->count);
return (cbm_resolution_t){best, "suffix_match", conf, arr->count};
}
return empty_result();
@@ -382,13 +407,13 @@ static cbm_resolution_t resolve_name_lookup(const cbm_registry_t *r, const char
}
/* Strategy 3: unique name */
- if (arr->count == 1) {
+ if (arr->count == SKIP_ONE) {
double conf = CONF_UNIQUE_NAME;
if (import_vals && import_count > 0 &&
!is_import_reachable(arr->items[0], import_vals, import_count)) {
- conf *= 0.5;
+ conf *= DEFAULT_CONFIDENCE;
}
- return (cbm_resolution_t){arr->items[0], "unique_name", conf, 1};
+ return (cbm_resolution_t){arr->items[0], "unique_name", conf, REG_RESOLVED};
}
/* Strategy 4: multiple candidates */
@@ -411,17 +436,17 @@ cbm_resolution_t cbm_registry_resolve(const cbm_registry_t *r, const char *calle
}
/* Split callee: "pkg.Func" → prefix="pkg", suffix="Func" */
- char prefix[256] = {0};
+ char prefix[CBM_SZ_256] = {0};
const char *suffix = NULL;
const char *dot = strchr(callee_name, '.');
if (dot) {
size_t plen = dot - callee_name;
if (plen >= sizeof(prefix)) {
- plen = sizeof(prefix) - 1;
+ plen = sizeof(prefix) - SKIP_ONE;
}
memcpy(prefix, callee_name, plen);
prefix[plen] = '\0';
- suffix = dot + 1;
+ suffix = dot + SKIP_ONE;
} else {
snprintf(prefix, sizeof(prefix), "%s", callee_name);
}
@@ -476,23 +501,23 @@ cbm_fuzzy_result_t cbm_registry_fuzzy_resolve(const cbm_registry_t *r, const cha
bool have_imports = (import_map_vals && import_map_count > 0);
/* Single candidate */
- if (arr->count == 1) {
+ if (arr->count == SKIP_ONE) {
double conf = CONF_FUZZY_SINGLE;
if (have_imports &&
!is_import_reachable(arr->items[0], import_map_vals, import_map_count)) {
- conf *= 0.5;
+ conf *= DEFAULT_CONFIDENCE;
}
- return (cbm_fuzzy_result_t){{arr->items[0], "fuzzy", conf, 1}, true};
+ return (cbm_fuzzy_result_t){{arr->items[0], "fuzzy", conf, REG_RESOLVED}, true};
}
/* Multiple candidates: filter by import reachability */
- const char *filtered[256];
+ const char *filtered[CBM_SZ_256];
int fcount = arr->count;
const char **fptr = (const char **)arr->items;
if (have_imports) {
fcount = filter_import_reachable((const char **)arr->items, arr->count, import_map_vals,
- import_map_count, filtered, 256);
+ import_map_count, filtered, CBM_SZ_256);
fptr = filtered;
}
@@ -503,12 +528,12 @@ cbm_fuzzy_result_t cbm_registry_fuzzy_resolve(const cbm_registry_t *r, const cha
if (!best) {
return no_match;
}
- return (cbm_fuzzy_result_t){{best, "fuzzy",
- candidate_count_penalty(CONF_FUZZY_MULTI * 0.5, arr->count),
- arr->count},
- true};
+ return (cbm_fuzzy_result_t){
+ {best, "fuzzy",
+ candidate_count_penalty(CONF_FUZZY_MULTI * REG_HALF_PENALTY, arr->count), arr->count},
+ true};
}
- if (fcount == 1) {
+ if (fcount == SKIP_ONE) {
return (cbm_fuzzy_result_t){
{fptr[0], "fuzzy", candidate_count_penalty(CONF_FUZZY_SINGLE, arr->count), arr->count},
true};
@@ -537,7 +562,7 @@ static void few_scan(const char *key, void *value, void *ud) {
size_t klen = strlen(key);
if (klen >= ctx->target_len && strcmp(key + klen - ctx->target_len, ctx->target) == 0) {
if (ctx->count >= ctx->cap) {
- ctx->cap = ctx->cap ? ctx->cap * 2 : 16;
+ ctx->cap = ctx->cap ? ctx->cap * PAIR_LEN : REG_INIT_CAP;
ctx->results = safe_realloc(ctx->results, (size_t)ctx->cap * sizeof(char *));
}
ctx->results[ctx->count++] = key;
@@ -554,11 +579,11 @@ int cbm_registry_find_ending_with(const cbm_registry_t *r, const char *suffix, c
/* Build ".suffix" target */
size_t slen = strlen(suffix);
- char *target = malloc(slen + 2);
+ char *target = malloc(slen + REG_SUFFIX_ALLOC);
target[0] = '.';
- memcpy(target + 1, suffix, slen + 1);
+ memcpy(target + SKIP_ONE, suffix, slen + SKIP_ONE);
- struct few_ctx ctx = {target, slen + 1, NULL, 0, 0};
+ struct few_ctx ctx = {target, slen + SKIP_ONE, NULL, 0, 0};
cbm_ht_foreach(r->exact, few_scan, &ctx);
free(target);
@@ -571,5 +596,3 @@ bool cbm_registry_is_import_reachable(const char *candidate_qn, const char **imp
int import_count) {
return is_import_reachable(candidate_qn, import_vals, import_count);
}
-
-/* cbm_confidence_band() is defined in httplink.c */
diff --git a/src/pipeline/worker_pool.c b/src/pipeline/worker_pool.c
index 63976b8cc..9cde541a4 100644
--- a/src/pipeline/worker_pool.c
+++ b/src/pipeline/worker_pool.c
@@ -9,6 +9,9 @@
* contention, natural load balancing across heterogeneous cores.
*/
#include "pipeline/worker_pool.h"
+#include "foundation/constants.h"
+
+enum { WP_TRUE = 1, WP_MIN = 1, WP_STEP = 1 };
#include "foundation/platform.h"
#include "foundation/compat_thread.h"
@@ -17,7 +20,7 @@
/* 8 MB stack per worker — matches main thread default.
* Required for deep AST recursion (tree-sitter + walk_defs). */
-#define CBM_WORKER_STACK_SIZE (8 * 1024 * 1024)
+#define CBM_WORKER_STACK_SIZE ((size_t)8 * CBM_SZ_1K * CBM_SZ_1K)
/* ── Serial fallback ─────────────────────────────────────────────── */
@@ -38,8 +41,8 @@ typedef struct {
static void *pthread_worker(void *arg) {
pthread_worker_arg_t *wa = arg;
- while (1) {
- int idx = atomic_fetch_add_explicit(wa->next_idx, 1, memory_order_relaxed);
+ while (WP_TRUE) {
+ int idx = atomic_fetch_add_explicit(wa->next_idx, WP_STEP, memory_order_relaxed);
if (idx >= wa->count) {
break;
}
@@ -73,8 +76,8 @@ static void run_pthreads(int count, cbm_parallel_fn fn, void *ctx, int nworkers)
}
/* Main thread also participates */
- while (1) {
- int idx = atomic_fetch_add_explicit(&next_idx, 1, memory_order_relaxed);
+ while (WP_TRUE) {
+ int idx = atomic_fetch_add_explicit(&next_idx, WP_STEP, memory_order_relaxed);
if (idx >= count) {
break;
}
@@ -100,12 +103,12 @@ void cbm_parallel_for(int count, cbm_parallel_fn fn, void *ctx, cbm_parallel_for
if (nworkers <= 0) {
nworkers = cbm_default_worker_count(true);
}
- if (nworkers < 1) {
- nworkers = 1;
+ if (nworkers < WP_MIN) {
+ nworkers = SKIP_ONE;
}
/* Serial fallback: single worker or trivially small workload */
- if (nworkers <= 1 || count <= 1) {
+ if (nworkers <= WP_MIN || count <= WP_MIN) {
run_serial(count, fn, ctx);
return;
}
diff --git a/src/store/store.c b/src/store/store.c
index 0a8269696..650b2e783 100644
--- a/src/store/store.c
+++ b/src/store/store.c
@@ -8,6 +8,51 @@
// for ISO timestamp
+#include "foundation/constants.h"
+
+enum {
+ ST_COL_1 = 1,
+ ST_COL_2 = 2,
+ ST_COL_3 = 3,
+ ST_COL_4 = 4,
+ ST_COL_5 = 5,
+ ST_COL_6 = 6,
+ ST_COL_7 = 7,
+ ST_COL_8 = 8,
+ ST_COL_9 = 9,
+ ST_FOUND = -1,
+ ST_BUF_16 = 16,
+ ST_BUF_64 = 64,
+ ST_GROWTH = 2,
+ ST_MAX_DEGREE = 8192,
+ ST_HALF_SEC = 500000,
+ ST_RETRY_WAIT_US = 1000,
+ ST_INIT_CAP_8 = 8,
+ ST_INIT_CAP_16 = 16,
+ ST_SQL_BUF = 8192,
+ ST_MAX_ROW_CHECK = 5,
+ ST_QN_MAX_DOTS = 5,
+ ST_QN_MIN_DOTS = 3,
+ ST_IN_CLAUSE_MARGIN = 4,
+ ST_GLOB_MIN_LEN = 3,
+ ST_GLOB_SKIP = 2,
+ ST_MAX_LANG = 10,
+ ST_SEARCH_MAX_BINDS = 16,
+ ST_MAX_PKGS = 64,
+ ST_INIT_CAP_4 = 4,
+ ST_HEADER_PREFIX = 3,
+ ST_MIN_INDEGREE = 3,
+ ST_MAX_PATH_DEPTH = 3,
+ ST_MAX_ITERATIONS = 10,
+ ST_GRAPH_SEED_MULT = 1000,
+ ST_MAX_SECTIONS = 16,
+ ST_METHOD_PROP_LEN = 8,
+ ST_PATH_PROP_LEN = 6,
+ ST_HANDLER_PROP_LEN = 9,
+};
+#define ST_WEIGHT_2 2.0
+
+#define SLEN(s) (sizeof(s) - 1)
#include "store/store.h"
#include "foundation/platform.h"
#include "foundation/compat.h"
@@ -23,12 +68,20 @@
/* ── SQLite bind helpers ───────────────────────────────────────── */
-/* Wrap sqlite3_bind_text with SQLITE_TRANSIENT to isolate the platform
- int-to-pointer cast ((void*)-1) in one place. */
-static const sqlite3_destructor_type BIND_TRANSIENT = SQLITE_TRANSIENT;
+/* Isolate the int-to-ptr cast that SQLITE_TRANSIENT expands to.
+ A union type-pun avoids the performance-no-int-to-ptr diagnostic. */
+static sqlite3_destructor_type make_transient(void) {
+ union {
+ uintptr_t i;
+ sqlite3_destructor_type fn;
+ } u;
+ u.i = (uintptr_t)CBM_NOT_FOUND;
+ return u.fn;
+}
+#define BIND_TRANSIENT (make_transient())
static int bind_text(sqlite3_stmt *s, int col, const char *v) {
- return sqlite3_bind_text(s, col, v, -1, BIND_TRANSIENT);
+ return sqlite3_bind_text(s, col, v, CBM_NOT_FOUND, BIND_TRANSIENT);
}
/* ── Internal store structure ───────────────────────────────────── */
@@ -36,7 +89,7 @@ static int bind_text(sqlite3_stmt *s, int col, const char *v) {
struct cbm_store {
sqlite3 *db;
const char *db_path; /* heap-allocated, or NULL for :memory: */
- char errbuf[512];
+ char errbuf[CBM_SZ_512];
/* Prepared statements (lazily initialized, cached for lifetime) */
sqlite3_stmt *stmt_upsert_node;
@@ -114,9 +167,9 @@ static char *heap_strdup(const char *s) {
return NULL;
}
size_t len = strlen(s);
- char *d = malloc(len + 1);
+ char *d = malloc(len + SKIP_ONE);
if (d) {
- memcpy(d, s, len + 1);
+ memcpy(d, s, len + SKIP_ONE);
}
return d;
}
@@ -131,7 +184,7 @@ static sqlite3_stmt *prepare_cached(cbm_store_t *s, sqlite3_stmt **slot, const c
sqlite3_clear_bindings(*slot);
return *slot;
}
- int rc = sqlite3_prepare_v2(s->db, sql, -1, slot, NULL);
+ int rc = sqlite3_prepare_v2(s->db, sql, CBM_NOT_FOUND, slot, NULL);
if (rc != SQLITE_OK) {
store_set_error_sqlite(s, "prepare");
return NULL;
@@ -240,7 +293,7 @@ static int configure_pragmas(cbm_store_t *s, bool in_memory) {
if (rc != CBM_STORE_OK) {
return rc;
}
- rc = exec_sql(s, "PRAGMA mmap_size = 67108864;"); /* 64 MB */
+ rc = exec_sql(s, "PRAGMA mmap_size = 67108864;"); /* CBM_SZ_64 MB */
}
return rc;
}
@@ -250,7 +303,7 @@ static int configure_pragmas(cbm_store_t *s, bool in_memory) {
static void sqlite_regexp(sqlite3_context *ctx, int argc, sqlite3_value **argv) {
(void)argc;
const char *pattern = (const char *)sqlite3_value_text(argv[0]);
- const char *text = (const char *)sqlite3_value_text(argv[1]);
+ const char *text = (const char *)sqlite3_value_text(argv[SKIP_ONE]);
if (!pattern || !text) {
sqlite3_result_int(ctx, 0);
return;
@@ -259,20 +312,20 @@ static void sqlite_regexp(sqlite3_context *ctx, int argc, sqlite3_value **argv)
cbm_regex_t re;
int rc = cbm_regcomp(&re, pattern, CBM_REG_EXTENDED | CBM_REG_NOSUB);
if (rc != 0) {
- sqlite3_result_error(ctx, "invalid regex", -1);
+ sqlite3_result_error(ctx, "invalid regex", CBM_NOT_FOUND);
return;
}
rc = cbm_regexec(&re, text, 0, NULL, 0);
cbm_regfree(&re);
- sqlite3_result_int(ctx, rc == 0 ? 1 : 0);
+ sqlite3_result_int(ctx, rc == 0 ? SKIP_ONE : 0);
}
/* Case-insensitive REGEXP variant */
static void sqlite_iregexp(sqlite3_context *ctx, int argc, sqlite3_value **argv) {
(void)argc;
const char *pattern = (const char *)sqlite3_value_text(argv[0]);
- const char *text = (const char *)sqlite3_value_text(argv[1]);
+ const char *text = (const char *)sqlite3_value_text(argv[SKIP_ONE]);
if (!pattern || !text) {
sqlite3_result_int(ctx, 0);
return;
@@ -281,13 +334,13 @@ static void sqlite_iregexp(sqlite3_context *ctx, int argc, sqlite3_value **argv)
cbm_regex_t re;
int rc = cbm_regcomp(&re, pattern, CBM_REG_EXTENDED | CBM_REG_NOSUB | CBM_REG_ICASE);
if (rc != 0) {
- sqlite3_result_error(ctx, "invalid regex", -1);
+ sqlite3_result_error(ctx, "invalid regex", CBM_NOT_FOUND);
return;
}
rc = cbm_regexec(&re, text, 0, NULL, 0);
cbm_regfree(&re);
- sqlite3_result_int(ctx, rc == 0 ? 1 : 0);
+ sqlite3_result_int(ctx, rc == 0 ? SKIP_ONE : 0);
}
/* ── Lifecycle ──────────────────────────────────────────────────── */
@@ -311,7 +364,7 @@ static int store_authorizer(void *user_data, int action, const char *p3, const c
}
static cbm_store_t *store_open_internal(const char *path, bool in_memory) {
- cbm_store_t *s = calloc(1, sizeof(cbm_store_t));
+ cbm_store_t *s = calloc(CBM_ALLOC_ONE, sizeof(cbm_store_t));
if (!s) {
return NULL;
}
@@ -336,10 +389,10 @@ static cbm_store_t *store_open_internal(const char *path, bool in_memory) {
sqlite3_set_authorizer(s->db, store_authorizer, NULL);
/* Register REGEXP function (SQLite doesn't have one built-in) */
- sqlite3_create_function(s->db, "regexp", 2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL,
+ sqlite3_create_function(s->db, "regexp", ST_COL_2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL,
sqlite_regexp, NULL, NULL);
/* Case-insensitive variant for search with case_sensitive=false */
- sqlite3_create_function(s->db, "iregexp", 2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL,
+ sqlite3_create_function(s->db, "iregexp", ST_COL_2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL,
sqlite_iregexp, NULL, NULL);
if (configure_pragmas(s, in_memory) != CBM_STORE_OK || init_schema(s) != CBM_STORE_OK ||
@@ -369,7 +422,7 @@ cbm_store_t *cbm_store_open_path_query(const char *db_path) {
return NULL;
}
- cbm_store_t *s = calloc(1, sizeof(cbm_store_t));
+ cbm_store_t *s = calloc(CBM_ALLOC_ONE, sizeof(cbm_store_t));
if (!s) {
return NULL;
}
@@ -389,9 +442,9 @@ cbm_store_t *cbm_store_open_path_query(const char *db_path) {
sqlite3_set_authorizer(s->db, store_authorizer, NULL);
/* Register REGEXP functions. */
- sqlite3_create_function(s->db, "regexp", 2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL,
+ sqlite3_create_function(s->db, "regexp", ST_COL_2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL,
sqlite_regexp, NULL, NULL);
- sqlite3_create_function(s->db, "iregexp", 2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL,
+ sqlite3_create_function(s->db, "iregexp", ST_COL_2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL,
sqlite_iregexp, NULL, NULL);
if (configure_pragmas(s, false) != CBM_STORE_OK) {
@@ -415,7 +468,8 @@ bool cbm_store_check_integrity(cbm_store_t *s) {
* exactly 1 row. More than 5 rows is definitely corrupt (allows some slack
* for edge cases). Also check that root_path looks like a real path. */
sqlite3_stmt *stmt = NULL;
- int rc = sqlite3_prepare_v2(s->db, "SELECT count(*) FROM projects;", -1, &stmt, NULL);
+ int rc =
+ sqlite3_prepare_v2(s->db, "SELECT count(*) FROM projects;", CBM_NOT_FOUND, &stmt, NULL);
if (rc != SQLITE_OK) {
return false;
}
@@ -423,8 +477,9 @@ bool cbm_store_check_integrity(cbm_store_t *s) {
bool ok = true;
if (sqlite3_step(stmt) == SQLITE_ROW) {
int row_count = sqlite3_column_int(stmt, 0);
- if (row_count > 5) {
- fprintf(stderr, "ERROR store.corrupt table=projects rows=%d (expected 1)\n", row_count);
+ if (row_count > ST_MAX_ROW_CHECK) {
+ (void)fprintf(stderr, "ERROR store.corrupt table=projects rows=%d (expected 1)\n",
+ row_count);
ok = false;
}
}
@@ -437,12 +492,12 @@ bool cbm_store_check_integrity(cbm_store_t *s) {
s->db,
"SELECT root_path FROM projects WHERE root_path != '' "
"AND substr(root_path, 1, 1) NOT IN ('/', 'A','B','C','D','E','F','G','H') LIMIT 1;",
- -1, &stmt, NULL);
+ CBM_NOT_FOUND, &stmt, NULL);
if (rc == SQLITE_OK) {
if (sqlite3_step(stmt) == SQLITE_ROW) {
const char *bad_path = (const char *)sqlite3_column_text(stmt, 0);
- fprintf(stderr, "ERROR store.corrupt table=projects bad_root_path=%s\n",
- bad_path ? bad_path : "(null)");
+ (void)fprintf(stderr, "ERROR store.corrupt table=projects bad_root_path=%s\n",
+ bad_path ? bad_path : "(null)");
ok = false;
}
sqlite3_finalize(stmt);
@@ -461,7 +516,7 @@ cbm_store_t *cbm_store_open(const char *project) {
if (!home) {
home = cbm_tmpdir();
}
- char path[1024];
+ char path[CBM_SZ_1K];
snprintf(path, sizeof(path), "%s/.cache/codebase-memory-mcp/%s.db", home, project);
return store_open_internal(path, false);
}
@@ -555,7 +610,7 @@ int cbm_store_begin_bulk(cbm_store_t *s) {
if (rc != CBM_STORE_OK) {
return rc;
}
- return exec_sql(s, "PRAGMA cache_size = -65536;"); /* 64 MB */
+ return exec_sql(s, "PRAGMA cache_size = -65536;"); /* CBM_SZ_64 MB */
}
int cbm_store_end_bulk(cbm_store_t *s) {
@@ -604,7 +659,7 @@ int cbm_store_dump_to_file(cbm_store_t *s, const char *dest_path) {
}
/* Ensure parent directory exists */
- char dir[1024];
+ char dir[CBM_SZ_1K];
snprintf(dir, sizeof(dir), "%s", dest_path);
char *sl = strrchr(dir, '/');
if (sl) {
@@ -613,7 +668,7 @@ int cbm_store_dump_to_file(cbm_store_t *s, const char *dest_path) {
}
/* Write to temp file for atomic swap */
- char tmp_path[1024];
+ char tmp_path[CBM_SZ_1K];
snprintf(tmp_path, sizeof(tmp_path), "%s.tmp", dest_path);
(void)unlink(tmp_path);
@@ -632,7 +687,7 @@ int cbm_store_dump_to_file(cbm_store_t *s, const char *dest_path) {
return CBM_STORE_ERR;
}
- rc = sqlite3_backup_step(bk, -1); /* copy ALL pages in one shot */
+ rc = sqlite3_backup_step(bk, CBM_NOT_FOUND); /* copy ALL pages in one shot */
sqlite3_backup_finish(bk);
if (rc != SQLITE_DONE) {
@@ -668,12 +723,12 @@ int cbm_store_upsert_project(cbm_store_t *s, const char *name, const char *root_
return CBM_STORE_ERR;
}
- char ts[64];
+ char ts[CBM_SZ_64];
iso_now(ts, sizeof(ts));
- bind_text(stmt, 1, name);
- bind_text(stmt, 2, ts);
- bind_text(stmt, 3, root_path);
+ bind_text(stmt, SKIP_ONE, name);
+ bind_text(stmt, ST_COL_2, ts);
+ bind_text(stmt, ST_COL_3, root_path);
int rc = sqlite3_step(stmt);
if (rc != SQLITE_DONE) {
@@ -691,12 +746,12 @@ int cbm_store_get_project(cbm_store_t *s, const char *name, cbm_project_t *out)
return CBM_STORE_ERR;
}
- bind_text(stmt, 1, name);
+ bind_text(stmt, SKIP_ONE, name);
int rc = sqlite3_step(stmt);
if (rc == SQLITE_ROW) {
out->name = heap_strdup((const char *)sqlite3_column_text(stmt, 0));
- out->indexed_at = heap_strdup((const char *)sqlite3_column_text(stmt, 1));
- out->root_path = heap_strdup((const char *)sqlite3_column_text(stmt, 2));
+ out->indexed_at = heap_strdup((const char *)sqlite3_column_text(stmt, SKIP_ONE));
+ out->root_path = heap_strdup((const char *)sqlite3_column_text(stmt, CBM_SZ_2));
return CBM_STORE_OK;
}
return CBM_STORE_NOT_FOUND;
@@ -711,18 +766,18 @@ int cbm_store_list_projects(cbm_store_t *s, cbm_project_t **out, int *count) {
}
/* Collect into dynamic array */
- int cap = 8;
+ int cap = ST_INIT_CAP_8;
int n = 0;
cbm_project_t *arr = malloc(cap * sizeof(cbm_project_t));
while (sqlite3_step(stmt) == SQLITE_ROW) {
if (n >= cap) {
- cap *= 2;
+ cap *= ST_GROWTH;
arr = safe_realloc(arr, cap * sizeof(cbm_project_t));
}
arr[n].name = heap_strdup((const char *)sqlite3_column_text(stmt, 0));
- arr[n].indexed_at = heap_strdup((const char *)sqlite3_column_text(stmt, 1));
- arr[n].root_path = heap_strdup((const char *)sqlite3_column_text(stmt, 2));
+ arr[n].indexed_at = heap_strdup((const char *)sqlite3_column_text(stmt, SKIP_ONE));
+ arr[n].root_path = heap_strdup((const char *)sqlite3_column_text(stmt, CBM_SZ_2));
n++;
}
@@ -738,7 +793,7 @@ int cbm_store_delete_project(cbm_store_t *s, const char *name) {
return CBM_STORE_ERR;
}
- bind_text(stmt, 1, name);
+ bind_text(stmt, SKIP_ONE, name);
int rc = sqlite3_step(stmt);
if (rc != SQLITE_DONE) {
store_set_error_sqlite(s, "delete_project");
@@ -762,14 +817,14 @@ int64_t cbm_store_upsert_node(cbm_store_t *s, const cbm_node_t *n) {
return CBM_STORE_ERR;
}
- bind_text(stmt, 1, safe_str(n->project));
- bind_text(stmt, 2, safe_str(n->label));
- bind_text(stmt, 3, safe_str(n->name));
- bind_text(stmt, 4, safe_str(n->qualified_name));
- bind_text(stmt, 5, safe_str(n->file_path));
- sqlite3_bind_int(stmt, 6, n->start_line);
- sqlite3_bind_int(stmt, 7, n->end_line);
- bind_text(stmt, 8, safe_props(n->properties_json));
+ bind_text(stmt, SKIP_ONE, safe_str(n->project));
+ bind_text(stmt, ST_COL_2, safe_str(n->label));
+ bind_text(stmt, ST_COL_3, safe_str(n->name));
+ bind_text(stmt, ST_COL_4, safe_str(n->qualified_name));
+ bind_text(stmt, ST_COL_5, safe_str(n->file_path));
+ sqlite3_bind_int(stmt, ST_COL_6, n->start_line);
+ sqlite3_bind_int(stmt, ST_COL_7, n->end_line);
+ bind_text(stmt, ST_COL_8, safe_props(n->properties_json));
int rc = sqlite3_step(stmt);
if (rc == SQLITE_ROW) {
@@ -785,14 +840,14 @@ int64_t cbm_store_upsert_node(cbm_store_t *s, const cbm_node_t *n) {
/* Scan a node from current row of stmt. Heap-allocates strings. */
static void scan_node(sqlite3_stmt *stmt, cbm_node_t *n) {
n->id = sqlite3_column_int64(stmt, 0);
- n->project = heap_strdup((const char *)sqlite3_column_text(stmt, 1));
- n->label = heap_strdup((const char *)sqlite3_column_text(stmt, 2));
- n->name = heap_strdup((const char *)sqlite3_column_text(stmt, 3));
- n->qualified_name = heap_strdup((const char *)sqlite3_column_text(stmt, 4));
- n->file_path = heap_strdup((const char *)sqlite3_column_text(stmt, 5));
- n->start_line = sqlite3_column_int(stmt, 6);
- n->end_line = sqlite3_column_int(stmt, 7);
- n->properties_json = heap_strdup((const char *)sqlite3_column_text(stmt, 8));
+ n->project = heap_strdup((const char *)sqlite3_column_text(stmt, SKIP_ONE));
+ n->label = heap_strdup((const char *)sqlite3_column_text(stmt, CBM_SZ_2));
+ n->name = heap_strdup((const char *)sqlite3_column_text(stmt, CBM_SZ_3));
+ n->qualified_name = heap_strdup((const char *)sqlite3_column_text(stmt, CBM_SZ_4));
+ n->file_path = heap_strdup((const char *)sqlite3_column_text(stmt, CBM_SZ_5));
+ n->start_line = sqlite3_column_int(stmt, CBM_SZ_6);
+ n->end_line = sqlite3_column_int(stmt, CBM_SZ_7);
+ n->properties_json = heap_strdup((const char *)sqlite3_column_text(stmt, ST_COL_8));
}
int cbm_store_find_node_by_id(cbm_store_t *s, int64_t id, cbm_node_t *out) {
@@ -804,7 +859,7 @@ int cbm_store_find_node_by_id(cbm_store_t *s, int64_t id, cbm_node_t *out) {
return CBM_STORE_ERR;
}
- sqlite3_bind_int64(stmt, 1, id);
+ sqlite3_bind_int64(stmt, SKIP_ONE, id);
int rc = sqlite3_step(stmt);
if (rc == SQLITE_ROW) {
scan_node(stmt, out);
@@ -827,8 +882,8 @@ int cbm_store_find_node_by_qn(cbm_store_t *s, const char *project, const char *q
return CBM_STORE_ERR;
}
- bind_text(stmt, 1, project);
- bind_text(stmt, 2, qn);
+ bind_text(stmt, SKIP_ONE, project);
+ bind_text(stmt, ST_COL_2, qn);
int rc = sqlite3_step(stmt);
if (rc == SQLITE_ROW) {
scan_node(stmt, out);
@@ -850,7 +905,7 @@ int cbm_store_find_node_by_qn_any(cbm_store_t *s, const char *qn, cbm_node_t *ou
return CBM_STORE_ERR;
}
- bind_text(stmt, 1, qn);
+ bind_text(stmt, SKIP_ONE, qn);
int rc = sqlite3_step(stmt);
if (rc == SQLITE_ROW) {
scan_node(stmt, out);
@@ -877,14 +932,14 @@ int cbm_store_find_nodes_by_name_any(cbm_store_t *s, const char *name, cbm_node_
return CBM_STORE_ERR;
}
- bind_text(stmt, 1, name);
+ bind_text(stmt, SKIP_ONE, name);
- int cap = 16;
+ int cap = ST_INIT_CAP_16;
int n = 0;
cbm_node_t *arr = malloc(cap * sizeof(cbm_node_t));
while (sqlite3_step(stmt) == SQLITE_ROW) {
if (n >= cap) {
- cap *= 2;
+ cap *= ST_GROWTH;
arr = safe_realloc(arr, cap * sizeof(cbm_node_t));
}
scan_node(stmt, &arr[n]);
@@ -934,16 +989,16 @@ static int find_nodes_generic(cbm_store_t *s, sqlite3_stmt **slot, const char *s
return CBM_STORE_ERR;
}
- bind_text(stmt, 1, project);
- bind_text(stmt, 2, val);
+ bind_text(stmt, SKIP_ONE, project);
+ bind_text(stmt, ST_COL_2, val);
- int cap = 16;
+ int cap = ST_INIT_CAP_16;
int n = 0;
cbm_node_t *arr = malloc(cap * sizeof(cbm_node_t));
while (sqlite3_step(stmt) == SQLITE_ROW) {
if (n >= cap) {
- cap *= 2;
+ cap *= ST_GROWTH;
arr = safe_realloc(arr, cap * sizeof(cbm_node_t));
}
scan_node(stmt, &arr[n]);
@@ -992,7 +1047,7 @@ int cbm_store_count_nodes(cbm_store_t *s, const char *project) {
return CBM_STORE_ERR;
}
- bind_text(stmt, 1, project);
+ bind_text(stmt, SKIP_ONE, project);
if (sqlite3_step(stmt) == SQLITE_ROW) {
return sqlite3_column_int(stmt, 0);
}
@@ -1006,7 +1061,7 @@ int cbm_store_delete_nodes_by_project(cbm_store_t *s, const char *project) {
return CBM_STORE_ERR;
}
- bind_text(stmt, 1, project);
+ bind_text(stmt, SKIP_ONE, project);
if (sqlite3_step(stmt) != SQLITE_DONE) {
store_set_error_sqlite(s, "delete_nodes_by_project");
return CBM_STORE_ERR;
@@ -1021,8 +1076,8 @@ int cbm_store_delete_nodes_by_file(cbm_store_t *s, const char *project, const ch
return CBM_STORE_ERR;
}
- bind_text(stmt, 1, project);
- bind_text(stmt, 2, file_path);
+ bind_text(stmt, SKIP_ONE, project);
+ bind_text(stmt, ST_COL_2, file_path);
if (sqlite3_step(stmt) != SQLITE_DONE) {
store_set_error_sqlite(s, "delete_nodes_by_file");
return CBM_STORE_ERR;
@@ -1037,8 +1092,8 @@ int cbm_store_delete_nodes_by_label(cbm_store_t *s, const char *project, const c
return CBM_STORE_ERR;
}
- bind_text(stmt, 1, project);
- bind_text(stmt, 2, label);
+ bind_text(stmt, SKIP_ONE, project);
+ bind_text(stmt, ST_COL_2, label);
if (sqlite3_step(stmt) != SQLITE_DONE) {
store_set_error_sqlite(s, "delete_nodes_by_label");
return CBM_STORE_ERR;
@@ -1083,11 +1138,11 @@ int64_t cbm_store_insert_edge(cbm_store_t *s, const cbm_edge_t *e) {
return CBM_STORE_ERR;
}
- bind_text(stmt, 1, safe_str(e->project));
- sqlite3_bind_int64(stmt, 2, e->source_id);
- sqlite3_bind_int64(stmt, 3, e->target_id);
- bind_text(stmt, 4, safe_str(e->type));
- bind_text(stmt, 5, safe_props(e->properties_json));
+ bind_text(stmt, SKIP_ONE, safe_str(e->project));
+ sqlite3_bind_int64(stmt, PAIR_LEN, e->source_id);
+ sqlite3_bind_int64(stmt, CBM_SZ_3, e->target_id);
+ bind_text(stmt, ST_COL_4, safe_str(e->type));
+ bind_text(stmt, ST_COL_5, safe_props(e->properties_json));
int rc = sqlite3_step(stmt);
if (rc == SQLITE_ROW) {
@@ -1103,11 +1158,11 @@ int64_t cbm_store_insert_edge(cbm_store_t *s, const cbm_edge_t *e) {
/* Scan an edge from current row of stmt. */
static void scan_edge(sqlite3_stmt *stmt, cbm_edge_t *e) {
e->id = sqlite3_column_int64(stmt, 0);
- e->project = heap_strdup((const char *)sqlite3_column_text(stmt, 1));
- e->source_id = sqlite3_column_int64(stmt, 2);
- e->target_id = sqlite3_column_int64(stmt, 3);
- e->type = heap_strdup((const char *)sqlite3_column_text(stmt, 4));
- e->properties_json = heap_strdup((const char *)sqlite3_column_text(stmt, 5));
+ e->project = heap_strdup((const char *)sqlite3_column_text(stmt, SKIP_ONE));
+ e->source_id = sqlite3_column_int64(stmt, CBM_SZ_2);
+ e->target_id = sqlite3_column_int64(stmt, CBM_SZ_3);
+ e->type = heap_strdup((const char *)sqlite3_column_text(stmt, CBM_SZ_4));
+ e->properties_json = heap_strdup((const char *)sqlite3_column_text(stmt, CBM_SZ_5));
}
/* Generic: find multiple edges by a filter. */
@@ -1126,13 +1181,13 @@ static int find_edges_generic(cbm_store_t *s, sqlite3_stmt **slot, const char *s
bind_fn(stmt, bind_data);
- int cap = 16;
+ int cap = ST_INIT_CAP_16;
int n = 0;
cbm_edge_t *arr = malloc(cap * sizeof(cbm_edge_t));
while (sqlite3_step(stmt) == SQLITE_ROW) {
if (n >= cap) {
- cap *= 2;
+ cap *= ST_GROWTH;
arr = safe_realloc(arr, cap * sizeof(cbm_edge_t));
}
scan_edge(stmt, &arr[n]);
@@ -1159,19 +1214,19 @@ typedef struct {
static void bind_source_id(sqlite3_stmt *stmt, const void *data) {
const bind_id_t *b = data;
- sqlite3_bind_int64(stmt, 1, b->id);
+ sqlite3_bind_int64(stmt, SKIP_ONE, b->id);
}
static void bind_id_and_type(sqlite3_stmt *stmt, const void *data) {
const bind_id_type_t *b = data;
- sqlite3_bind_int64(stmt, 1, b->id);
- bind_text(stmt, 2, b->type);
+ sqlite3_bind_int64(stmt, SKIP_ONE, b->id);
+ bind_text(stmt, ST_COL_2, b->type);
}
static void bind_proj_and_type(sqlite3_stmt *stmt, const void *data) {
const bind_proj_type_t *b = data;
- bind_text(stmt, 1, b->project);
- bind_text(stmt, 2, b->type);
+ bind_text(stmt, SKIP_ONE, b->project);
+ bind_text(stmt, ST_COL_2, b->type);
}
int cbm_store_find_edges_by_source(cbm_store_t *s, int64_t source_id, cbm_edge_t **out,
@@ -1229,7 +1284,7 @@ int cbm_store_count_edges(cbm_store_t *s, const char *project) {
return CBM_STORE_ERR;
}
- bind_text(stmt, 1, project);
+ bind_text(stmt, SKIP_ONE, project);
if (sqlite3_step(stmt) == SQLITE_ROW) {
return sqlite3_column_int(stmt, 0);
}
@@ -1244,8 +1299,8 @@ int cbm_store_count_edges_by_type(cbm_store_t *s, const char *project, const cha
return CBM_STORE_ERR;
}
- bind_text(stmt, 1, project);
- bind_text(stmt, 2, type);
+ bind_text(stmt, SKIP_ONE, project);
+ bind_text(stmt, ST_COL_2, type);
if (sqlite3_step(stmt) == SQLITE_ROW) {
return sqlite3_column_int(stmt, 0);
}
@@ -1259,7 +1314,7 @@ int cbm_store_delete_edges_by_project(cbm_store_t *s, const char *project) {
return CBM_STORE_ERR;
}
- bind_text(stmt, 1, project);
+ bind_text(stmt, SKIP_ONE, project);
if (sqlite3_step(stmt) != SQLITE_DONE) {
store_set_error_sqlite(s, "delete_edges_by_project");
return CBM_STORE_ERR;
@@ -1274,8 +1329,8 @@ int cbm_store_delete_edges_by_type(cbm_store_t *s, const char *project, const ch
return CBM_STORE_ERR;
}
- bind_text(stmt, 1, project);
- bind_text(stmt, 2, type);
+ bind_text(stmt, SKIP_ONE, project);
+ bind_text(stmt, ST_COL_2, type);
if (sqlite3_step(stmt) != SQLITE_DONE) {
store_set_error_sqlite(s, "delete_edges_by_type");
return CBM_STORE_ERR;
@@ -1316,11 +1371,11 @@ int cbm_store_upsert_file_hash(cbm_store_t *s, const char *project, const char *
return CBM_STORE_ERR;
}
- bind_text(stmt, 1, project);
- bind_text(stmt, 2, rel_path);
- bind_text(stmt, 3, sha256);
- sqlite3_bind_int64(stmt, 4, mtime_ns);
- sqlite3_bind_int64(stmt, 5, size);
+ bind_text(stmt, SKIP_ONE, project);
+ bind_text(stmt, ST_COL_2, rel_path);
+ bind_text(stmt, ST_COL_3, sha256);
+ sqlite3_bind_int64(stmt, CBM_SZ_4, mtime_ns);
+ sqlite3_bind_int64(stmt, CBM_SZ_5, size);
if (sqlite3_step(stmt) != SQLITE_DONE) {
store_set_error_sqlite(s, "upsert_file_hash");
@@ -1338,22 +1393,22 @@ int cbm_store_get_file_hashes(cbm_store_t *s, const char *project, cbm_file_hash
return CBM_STORE_ERR;
}
- bind_text(stmt, 1, project);
+ bind_text(stmt, SKIP_ONE, project);
- int cap = 16;
+ int cap = ST_INIT_CAP_16;
int n = 0;
cbm_file_hash_t *arr = malloc(cap * sizeof(cbm_file_hash_t));
while (sqlite3_step(stmt) == SQLITE_ROW) {
if (n >= cap) {
- cap *= 2;
+ cap *= ST_GROWTH;
arr = safe_realloc(arr, cap * sizeof(cbm_file_hash_t));
}
arr[n].project = heap_strdup((const char *)sqlite3_column_text(stmt, 0));
- arr[n].rel_path = heap_strdup((const char *)sqlite3_column_text(stmt, 1));
- arr[n].sha256 = heap_strdup((const char *)sqlite3_column_text(stmt, 2));
- arr[n].mtime_ns = sqlite3_column_int64(stmt, 3);
- arr[n].size = sqlite3_column_int64(stmt, 4);
+ arr[n].rel_path = heap_strdup((const char *)sqlite3_column_text(stmt, SKIP_ONE));
+ arr[n].sha256 = heap_strdup((const char *)sqlite3_column_text(stmt, CBM_SZ_2));
+ arr[n].mtime_ns = sqlite3_column_int64(stmt, CBM_SZ_3);
+ arr[n].size = sqlite3_column_int64(stmt, CBM_SZ_4);
n++;
}
@@ -1370,8 +1425,8 @@ int cbm_store_delete_file_hash(cbm_store_t *s, const char *project, const char *
return CBM_STORE_ERR;
}
- bind_text(stmt, 1, project);
- bind_text(stmt, 2, rel_path);
+ bind_text(stmt, SKIP_ONE, project);
+ bind_text(stmt, ST_COL_2, rel_path);
if (sqlite3_step(stmt) != SQLITE_DONE) {
store_set_error_sqlite(s, "delete_file_hash");
return CBM_STORE_ERR;
@@ -1386,7 +1441,7 @@ int cbm_store_delete_file_hashes(cbm_store_t *s, const char *project) {
return CBM_STORE_ERR;
}
- bind_text(stmt, 1, project);
+ bind_text(stmt, SKIP_ONE, project);
if (sqlite3_step(stmt) != SQLITE_DONE) {
store_set_error_sqlite(s, "delete_file_hashes");
return CBM_STORE_ERR;
@@ -1409,23 +1464,23 @@ int cbm_store_find_nodes_by_file_overlap(cbm_store_t *s, const char *project, co
"ORDER BY start_line";
sqlite3_stmt *stmt = NULL;
- int rc = sqlite3_prepare_v2(s->db, sql, -1, &stmt, NULL);
+ int rc = sqlite3_prepare_v2(s->db, sql, CBM_NOT_FOUND, &stmt, NULL);
if (rc != SQLITE_OK) {
store_set_error_sqlite(s, "overlap prepare");
return CBM_STORE_ERR;
}
- bind_text(stmt, 1, project);
- bind_text(stmt, 2, file_path);
- sqlite3_bind_int(stmt, 3, start_line);
- sqlite3_bind_int(stmt, 4, end_line);
+ bind_text(stmt, SKIP_ONE, project);
+ bind_text(stmt, ST_COL_2, file_path);
+ sqlite3_bind_int(stmt, ST_COL_3, start_line);
+ sqlite3_bind_int(stmt, ST_COL_4, end_line);
- int cap = 8;
+ int cap = ST_INIT_CAP_8;
int n = 0;
cbm_node_t *nodes = malloc(cap * sizeof(cbm_node_t));
while (sqlite3_step(stmt) == SQLITE_ROW) {
if (n >= cap) {
- cap *= 2;
+ cap *= ST_GROWTH;
nodes = safe_realloc(nodes, cap * sizeof(cbm_node_t));
}
memset(&nodes[n], 0, sizeof(cbm_node_t));
@@ -1448,7 +1503,7 @@ int cbm_store_find_nodes_by_qn_suffix(cbm_store_t *s, const char *project, const
return CBM_STORE_ERR;
}
/* Match QNs ending with ".suffix" or exactly equal to suffix */
- char like_pattern[512];
+ char like_pattern[CBM_SZ_512];
snprintf(like_pattern, sizeof(like_pattern), "%%.%s", suffix);
const char *sql_with_project =
@@ -1460,27 +1515,28 @@ int cbm_store_find_nodes_by_qn_suffix(cbm_store_t *s, const char *project, const
"WHERE (qualified_name LIKE ?1 OR qualified_name = ?2)";
sqlite3_stmt *stmt = NULL;
- int rc = sqlite3_prepare_v2(s->db, project ? sql_with_project : sql_any, -1, &stmt, NULL);
+ int rc =
+ sqlite3_prepare_v2(s->db, project ? sql_with_project : sql_any, CBM_NOT_FOUND, &stmt, NULL);
if (rc != SQLITE_OK) {
store_set_error_sqlite(s, "qn_suffix prepare");
return CBM_STORE_ERR;
}
if (project) {
- bind_text(stmt, 1, project);
- bind_text(stmt, 2, like_pattern);
- bind_text(stmt, 3, suffix);
+ bind_text(stmt, SKIP_ONE, project);
+ bind_text(stmt, ST_COL_2, like_pattern);
+ bind_text(stmt, ST_COL_3, suffix);
} else {
- bind_text(stmt, 1, like_pattern);
- bind_text(stmt, 2, suffix);
+ bind_text(stmt, SKIP_ONE, like_pattern);
+ bind_text(stmt, ST_COL_2, suffix);
}
- int cap = 8;
+ int cap = ST_INIT_CAP_8;
int n = 0;
cbm_node_t *nodes = malloc(cap * sizeof(cbm_node_t));
while (sqlite3_step(stmt) == SQLITE_ROW) {
if (n >= cap) {
- cap *= 2;
+ cap *= ST_GROWTH;
nodes = safe_realloc(nodes, cap * sizeof(cbm_node_t));
}
memset(&nodes[n], 0, sizeof(cbm_node_t));
@@ -1501,8 +1557,8 @@ void cbm_store_node_degree(cbm_store_t *s, int64_t node_id, int *in_deg, int *ou
const char *in_sql = "SELECT COUNT(*) FROM edges WHERE target_id = ?1 AND type = 'CALLS'";
sqlite3_stmt *stmt = NULL;
- if (sqlite3_prepare_v2(s->db, in_sql, -1, &stmt, NULL) == SQLITE_OK) {
- sqlite3_bind_int64(stmt, 1, node_id);
+ if (sqlite3_prepare_v2(s->db, in_sql, CBM_NOT_FOUND, &stmt, NULL) == SQLITE_OK) {
+ sqlite3_bind_int64(stmt, SKIP_ONE, node_id);
if (sqlite3_step(stmt) == SQLITE_ROW) {
*in_deg = sqlite3_column_int(stmt, 0);
}
@@ -1510,8 +1566,8 @@ void cbm_store_node_degree(cbm_store_t *s, int64_t node_id, int *in_deg, int *ou
}
const char *out_sql = "SELECT COUNT(*) FROM edges WHERE source_id = ?1 AND type = 'CALLS'";
- if (sqlite3_prepare_v2(s->db, out_sql, -1, &stmt, NULL) == SQLITE_OK) {
- sqlite3_bind_int64(stmt, 1, node_id);
+ if (sqlite3_prepare_v2(s->db, out_sql, CBM_NOT_FOUND, &stmt, NULL) == SQLITE_OK) {
+ sqlite3_bind_int64(stmt, SKIP_ONE, node_id);
if (sqlite3_step(stmt) == SQLITE_ROW) {
*out_deg = sqlite3_column_int(stmt, 0);
}
@@ -1531,12 +1587,12 @@ int cbm_store_list_files(cbm_store_t *s, const char *project, char ***out, int *
const char *sql = "SELECT DISTINCT file_path FROM nodes "
"WHERE project = ?1 AND file_path IS NOT NULL AND file_path != ''";
sqlite3_stmt *stmt = NULL;
- if (sqlite3_prepare_v2(s->db, sql, -1, &stmt, NULL) != SQLITE_OK) {
+ if (sqlite3_prepare_v2(s->db, sql, CBM_NOT_FOUND, &stmt, NULL) != SQLITE_OK) {
return CBM_STORE_ERR;
}
- sqlite3_bind_text(stmt, 1, project, -1, SQLITE_STATIC);
+ sqlite3_bind_text(stmt, SKIP_ONE, project, CBM_NOT_FOUND, SQLITE_STATIC);
- int cap = 64;
+ int cap = CBM_SZ_64;
int n = 0;
char **files = malloc(cap * sizeof(char *));
while (sqlite3_step(stmt) == SQLITE_ROW) {
@@ -1545,7 +1601,7 @@ int cbm_store_list_files(cbm_store_t *s, const char *project, char ***out, int *
continue;
}
if (n >= cap) {
- cap *= 2;
+ cap *= ST_GROWTH;
files = safe_realloc(files, cap * sizeof(char *));
}
files[n++] = heap_strdup(fp);
@@ -1563,13 +1619,13 @@ static int query_neighbor_names(sqlite3 *db, const char *sql, int64_t node_id, i
*out = NULL;
*out_count = 0;
sqlite3_stmt *stmt = NULL;
- if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) {
- return -1;
+ if (sqlite3_prepare_v2(db, sql, CBM_NOT_FOUND, &stmt, NULL) != SQLITE_OK) {
+ return CBM_NOT_FOUND;
}
- sqlite3_bind_int64(stmt, 1, node_id);
- sqlite3_bind_int(stmt, 2, limit);
+ sqlite3_bind_int64(stmt, SKIP_ONE, node_id);
+ sqlite3_bind_int(stmt, ST_COL_2, limit);
- int cap = 8;
+ int cap = ST_INIT_CAP_8;
char **names = malloc((size_t)cap * sizeof(char *));
int count = 0;
while (sqlite3_step(stmt) == SQLITE_ROW) {
@@ -1578,7 +1634,7 @@ static int query_neighbor_names(sqlite3 *db, const char *sql, int64_t node_id, i
continue;
}
if (count >= cap) {
- cap *= 2;
+ cap *= ST_GROWTH;
names = safe_realloc(names, (size_t)cap * sizeof(char *));
}
names[count++] = strdup(name);
@@ -1592,7 +1648,7 @@ static int query_neighbor_names(sqlite3 *db, const char *sql, int64_t node_id, i
int cbm_store_node_neighbor_names(cbm_store_t *s, int64_t node_id, int limit, char ***out_callers,
int *caller_count, char ***out_callees, int *callee_count) {
if (!s) {
- return -1;
+ return CBM_NOT_FOUND;
}
*out_callers = NULL;
*caller_count = 0;
@@ -1619,7 +1675,7 @@ int cbm_store_node_neighbor_names(cbm_store_t *s, int64_t node_id, int limit, ch
static int count_degrees_direction(cbm_store_t *s, const int64_t *node_ids, int id_count,
const char *in_clause, bool has_type, const char *edge_type,
bool inbound, int *out_counts) {
- char sql[8192];
+ char sql[ST_SQL_BUF];
const char *id_col = inbound ? "target_id" : "source_id";
if (has_type) {
snprintf(sql, sizeof(sql),
@@ -1634,20 +1690,20 @@ static int count_degrees_direction(cbm_store_t *s, const int64_t *node_ids, int
}
sqlite3_stmt *stmt = NULL;
- if (sqlite3_prepare_v2(s->db, sql, -1, &stmt, NULL) != SQLITE_OK) {
+ if (sqlite3_prepare_v2(s->db, sql, CBM_NOT_FOUND, &stmt, NULL) != SQLITE_OK) {
return CBM_STORE_ERR;
}
for (int i = 0; i < id_count; i++) {
- sqlite3_bind_int64(stmt, i + 1, node_ids[i]);
+ sqlite3_bind_int64(stmt, i + SKIP_ONE, node_ids[i]);
}
if (has_type) {
- bind_text(stmt, id_count + 1, edge_type);
+ bind_text(stmt, id_count + SKIP_ONE, edge_type);
}
while (sqlite3_step(stmt) == SQLITE_ROW) {
int64_t nid = sqlite3_column_int64(stmt, 0);
- int cnt = sqlite3_column_int(stmt, 1);
+ int cnt = sqlite3_column_int(stmt, SKIP_ONE);
for (int i = 0; i < id_count; i++) {
if (node_ids[i] == nid) {
out_counts[i] = cnt;
@@ -1669,9 +1725,9 @@ int cbm_store_batch_count_degrees(cbm_store_t *s, const int64_t *node_ids, int i
memset(out_out, 0, (size_t)id_count * sizeof(int));
/* Build IN clause: (?,?,?) */
- char in_clause[4096];
+ char in_clause[CBM_SZ_4K];
int pos = 0;
- for (int i = 0; i < id_count && pos < (int)sizeof(in_clause) - 4; i++) {
+ for (int i = 0; i < id_count && pos < (int)sizeof(in_clause) - ST_IN_CLAUSE_MARGIN; i++) {
if (i > 0) {
in_clause[pos++] = ',';
}
@@ -1723,28 +1779,28 @@ int cbm_store_find_edges_by_url_path(cbm_store_t *s, const char *project, const
*count = 0;
/* Search properties JSON for url_path containing keyword */
- char like_pattern[512];
+ char like_pattern[CBM_SZ_512];
snprintf(like_pattern, sizeof(like_pattern), "%%\"url_path\":\"%%%%%s%%%%\"%%", keyword);
const char *sql = "SELECT id, project, source_id, target_id, type, properties FROM edges "
"WHERE project = ?1 AND properties LIKE ?2";
sqlite3_stmt *stmt = NULL;
- int rc = sqlite3_prepare_v2(s->db, sql, -1, &stmt, NULL);
+ int rc = sqlite3_prepare_v2(s->db, sql, CBM_NOT_FOUND, &stmt, NULL);
if (rc != SQLITE_OK) {
store_set_error_sqlite(s, "url_path prepare");
return CBM_STORE_ERR;
}
- bind_text(stmt, 1, project);
- bind_text(stmt, 2, like_pattern);
+ bind_text(stmt, SKIP_ONE, project);
+ bind_text(stmt, ST_COL_2, like_pattern);
- int cap = 8;
+ int cap = ST_INIT_CAP_8;
int n = 0;
cbm_edge_t *edges = malloc(cap * sizeof(cbm_edge_t));
while (sqlite3_step(stmt) == SQLITE_ROW) {
if (n >= cap) {
- cap *= 2;
+ cap *= ST_GROWTH;
edges = safe_realloc(edges, cap * sizeof(cbm_edge_t));
}
memset(&edges[n], 0, sizeof(cbm_edge_t));
@@ -1765,7 +1821,7 @@ int cbm_store_restore_from(cbm_store_t *dst, cbm_store_t *src) {
store_set_error_sqlite(dst, "backup init");
return CBM_STORE_ERR;
}
- int rc = sqlite3_backup_step(bk, -1); /* copy all pages */
+ int rc = sqlite3_backup_step(bk, CBM_NOT_FOUND); /* copy all pages */
sqlite3_backup_finish(bk);
if (rc != SQLITE_DONE) {
@@ -1783,18 +1839,18 @@ char *cbm_glob_to_like(const char *pattern) {
return NULL;
}
size_t len = strlen(pattern);
- char *out = malloc((len * 2) + 1);
+ char *out = malloc((len * ST_GROWTH) + SKIP_ONE);
size_t j = 0;
for (size_t i = 0; i < len; i++) {
- if (pattern[i] == '*' && i + 1 < len && pattern[i + 1] == '*') {
+ if (pattern[i] == '*' && i + SKIP_ONE < len && pattern[i + SKIP_ONE] == '*') {
/* Remove leading / from output if present (handles glob dir-star) */
- if (j > 0 && out[j - 1] == '/') {
+ if (j > 0 && out[j - SKIP_ONE] == '/') {
j--;
}
out[j++] = '%';
i++; /* skip second * */
- if (i + 1 < len && pattern[i + 1] == '/') {
+ if (i + SKIP_ONE < len && pattern[i + SKIP_ONE] == '/') {
i++; /* skip trailing / */
}
} else if (pattern[i] == '*') {
@@ -1824,7 +1880,7 @@ int cbm_extract_like_hints(const char *pattern, char **out, int max_out) {
}
int count = 0;
- char buf[256];
+ char buf[CBM_SZ_256];
int blen = 0;
int i = 0;
@@ -1833,11 +1889,11 @@ int cbm_extract_like_hints(const char *pattern, char **out, int max_out) {
switch (ch) {
case '\\':
/* Escaped char — the next char is literal */
- if (pattern[i + 1]) {
- if (blen < (int)sizeof(buf) - 1) {
- buf[blen++] = pattern[i + 1];
+ if (pattern[i + SKIP_ONE]) {
+ if (blen < (int)sizeof(buf) - SKIP_ONE) {
+ buf[blen++] = pattern[i + SKIP_ONE];
}
- i += 2;
+ i += ST_GLOB_SKIP;
} else {
i++;
}
@@ -1855,7 +1911,7 @@ int cbm_extract_like_hints(const char *pattern, char **out, int max_out) {
case '{':
case '}':
/* Meta character — flush current literal segment */
- if (blen >= 3 && count < max_out) {
+ if (blen >= ST_GLOB_MIN_LEN && count < max_out) {
buf[blen] = '\0';
out[count++] = strdup(buf);
}
@@ -1863,7 +1919,7 @@ int cbm_extract_like_hints(const char *pattern, char **out, int max_out) {
i++;
break;
default:
- if (blen < (int)sizeof(buf) - 1) {
+ if (blen < (int)sizeof(buf) - SKIP_ONE) {
buf[blen++] = ch;
}
i++;
@@ -1871,7 +1927,7 @@ int cbm_extract_like_hints(const char *pattern, char **out, int max_out) {
}
}
/* Flush trailing segment */
- if (blen >= 3 && count < max_out) {
+ if (blen >= ST_GLOB_MIN_LEN && count < max_out) {
buf[blen] = '\0';
out[count++] = strdup(buf);
}
@@ -1881,13 +1937,13 @@ int cbm_extract_like_hints(const char *pattern, char **out, int max_out) {
/* ── ensureCaseInsensitive / stripCaseFlag ────────────────────── */
const char *cbm_ensure_case_insensitive(const char *pattern) {
- static char buf[2048];
+ static char buf[CBM_SZ_2K];
if (!pattern) {
buf[0] = '\0';
return buf;
}
/* Already has (?i) prefix? Return as-is. */
- if (strncmp(pattern, "(?i)", 4) == 0) {
+ if (strncmp(pattern, "(?i)", SLEN("(?i)")) == 0) {
snprintf(buf, sizeof(buf), "%s", pattern);
} else {
snprintf(buf, sizeof(buf), "(?i)%s", pattern);
@@ -1896,12 +1952,12 @@ const char *cbm_ensure_case_insensitive(const char *pattern) {
}
const char *cbm_strip_case_flag(const char *pattern) {
- static char buf[2048];
+ static char buf[CBM_SZ_2K];
if (!pattern) {
buf[0] = '\0';
return buf;
}
- if (strncmp(pattern, "(?i)", 4) == 0) {
+ if (strncmp(pattern, "(?i)", SLEN("(?i)")) == 0) {
snprintf(buf, sizeof(buf), "%s", pattern + 4);
} else {
snprintf(buf, sizeof(buf), "%s", pattern);
@@ -1919,7 +1975,7 @@ static void search_apply_degree_filter(char *sql, size_t sql_sz, const cbm_searc
if (!has_degree_filter) {
return;
}
- char inner_sql[4096];
+ char inner_sql[CBM_SZ_4K];
snprintf(inner_sql, sizeof(inner_sql), "%s", sql);
if (p->min_degree >= 0 && p->max_degree >= 0) {
snprintf(sql, sql_sz,
@@ -1958,12 +2014,12 @@ static void search_build_exclude_labels(const char **labels, search_bind_t *bind
if (i > 0) {
elen += snprintf(clause + elen, clause_sz - elen, ",");
if (elen >= clause_sz) {
- elen = clause_sz - 1;
+ elen = clause_sz - SKIP_ONE;
}
}
- elen += snprintf(clause + elen, clause_sz - elen, "?%d", *bind_idx + 1);
+ elen += snprintf(clause + elen, clause_sz - elen, "?%d", *bind_idx + SKIP_ONE);
if (elen >= clause_sz) {
- elen = clause_sz - 1;
+ elen = clause_sz - SKIP_ONE;
}
where_bind_text(binds, bind_idx, labels[i]);
}
@@ -1976,35 +2032,35 @@ static int search_build_where(const cbm_search_params_t *params, char *where, in
int nparams = 0;
*like_pattern_out = NULL;
- char bind_buf[64];
+ char bind_buf[CBM_SZ_64];
if (params->project) {
- snprintf(bind_buf, sizeof(bind_buf), "n.project = ?%d", *bind_idx + 1);
+ snprintf(bind_buf, sizeof(bind_buf), "n.project = ?%d", *bind_idx + SKIP_ONE);
wlen = where_append(where, where_sz, wlen, &nparams, bind_buf);
where_bind_text(binds, bind_idx, params->project);
}
if (params->label) {
- snprintf(bind_buf, sizeof(bind_buf), "n.label = ?%d", *bind_idx + 1);
+ snprintf(bind_buf, sizeof(bind_buf), "n.label = ?%d", *bind_idx + SKIP_ONE);
wlen = where_append(where, where_sz, wlen, &nparams, bind_buf);
where_bind_text(binds, bind_idx, params->label);
}
if (params->name_pattern) {
if (params->case_sensitive) {
- snprintf(bind_buf, sizeof(bind_buf), "n.name REGEXP ?%d", *bind_idx + 1);
+ snprintf(bind_buf, sizeof(bind_buf), "n.name REGEXP ?%d", *bind_idx + SKIP_ONE);
} else {
- snprintf(bind_buf, sizeof(bind_buf), "iregexp(?%d, n.name)", *bind_idx + 1);
+ snprintf(bind_buf, sizeof(bind_buf), "iregexp(?%d, n.name)", *bind_idx + SKIP_ONE);
}
wlen = where_append(where, where_sz, wlen, &nparams, bind_buf);
where_bind_text(binds, bind_idx, params->name_pattern);
}
if (params->file_pattern) {
*like_pattern_out = cbm_glob_to_like(params->file_pattern);
- snprintf(bind_buf, sizeof(bind_buf), "n.file_path LIKE ?%d", *bind_idx + 1);
+ snprintf(bind_buf, sizeof(bind_buf), "n.file_path LIKE ?%d", *bind_idx + SKIP_ONE);
wlen = where_append(where, where_sz, wlen, &nparams, bind_buf);
where_bind_text(binds, bind_idx, *like_pattern_out);
}
if (params->exclude_labels) {
- char excl_clause[512];
+ char excl_clause[CBM_SZ_512];
search_build_exclude_labels(params->exclude_labels, binds, bind_idx, excl_clause,
(int)sizeof(excl_clause));
(void)where_append(where, where_sz, wlen, &nparams, excl_clause);
@@ -2019,8 +2075,8 @@ int cbm_store_search(cbm_store_t *s, const cbm_search_params_t *params, cbm_sear
return CBM_STORE_ERR;
}
- char sql[4096];
- char count_sql[4096];
+ char sql[CBM_SZ_4K];
+ char count_sql[CBM_SZ_4K];
int bind_idx = 0;
const char *select_cols =
@@ -2029,8 +2085,8 @@ int cbm_store_search(cbm_store_t *s, const cbm_search_params_t *params, cbm_sear
"(SELECT COUNT(*) FROM edges e WHERE e.target_id = n.id AND e.type = 'CALLS') AS in_deg, "
"(SELECT COUNT(*) FROM edges e WHERE e.source_id = n.id AND e.type = 'CALLS') AS out_deg ";
- char where[2048] = "";
- search_bind_t binds[16];
+ char where[CBM_SZ_2K] = "";
+ search_bind_t binds[ST_SEARCH_MAX_BINDS];
char *like_pattern = NULL;
int nparams =
@@ -2051,20 +2107,20 @@ int cbm_store_search(cbm_store_t *s, const cbm_search_params_t *params, cbm_sear
snprintf(count_sql, sizeof(count_sql), "SELECT COUNT(*) FROM (%s)", sql);
/* Add ORDER BY + LIMIT */
- int limit = params->limit > 0 ? params->limit : 500000;
+ int limit = params->limit > 0 ? params->limit : ST_HALF_SEC;
int offset = params->offset;
const char *name_col = has_degree_filter ? "name" : "n.name";
- char order_limit[128];
+ char order_limit[CBM_SZ_128];
snprintf(order_limit, sizeof(order_limit), " ORDER BY %s LIMIT %d OFFSET %d", name_col, limit,
offset);
strncat(sql, order_limit, sizeof(sql) - strlen(sql) - 1);
/* Execute count query */
sqlite3_stmt *cnt_stmt = NULL;
- int rc = sqlite3_prepare_v2(s->db, count_sql, -1, &cnt_stmt, NULL);
+ int rc = sqlite3_prepare_v2(s->db, count_sql, CBM_NOT_FOUND, &cnt_stmt, NULL);
if (rc == SQLITE_OK) {
for (int i = 0; i < bind_idx; i++) {
- bind_text(cnt_stmt, i + 1, binds[i].text);
+ bind_text(cnt_stmt, i + SKIP_ONE, binds[i].text);
}
if (sqlite3_step(cnt_stmt) == SQLITE_ROW) {
out->total = sqlite3_column_int(cnt_stmt, 0);
@@ -2074,7 +2130,7 @@ int cbm_store_search(cbm_store_t *s, const cbm_search_params_t *params, cbm_sear
/* Execute main query */
sqlite3_stmt *main_stmt = NULL;
- rc = sqlite3_prepare_v2(s->db, sql, -1, &main_stmt, NULL);
+ rc = sqlite3_prepare_v2(s->db, sql, CBM_NOT_FOUND, &main_stmt, NULL);
if (rc != SQLITE_OK) {
store_set_error_sqlite(s, "search prepare");
free(like_pattern);
@@ -2082,22 +2138,22 @@ int cbm_store_search(cbm_store_t *s, const cbm_search_params_t *params, cbm_sear
}
for (int i = 0; i < bind_idx; i++) {
- bind_text(main_stmt, i + 1, binds[i].text);
+ bind_text(main_stmt, i + SKIP_ONE, binds[i].text);
}
- int cap = 16;
+ int cap = ST_INIT_CAP_16;
int n = 0;
cbm_search_result_t *results = malloc(cap * sizeof(cbm_search_result_t));
while (sqlite3_step(main_stmt) == SQLITE_ROW) {
if (n >= cap) {
- cap *= 2;
+ cap *= ST_GROWTH;
results = safe_realloc(results, cap * sizeof(cbm_search_result_t));
}
memset(&results[n], 0, sizeof(cbm_search_result_t));
scan_node(main_stmt, &results[n].node);
- results[n].in_degree = sqlite3_column_int(main_stmt, 9);
- results[n].out_degree = sqlite3_column_int(main_stmt, 10);
+ results[n].in_degree = sqlite3_column_int(main_stmt, ST_COL_9);
+ results[n].out_degree = sqlite3_column_int(main_stmt, CBM_DECIMAL_BASE);
n++;
}
@@ -2137,20 +2193,20 @@ static int bfs_collect_edges(cbm_store_t *s, int64_t start_id, const cbm_node_ho
int edge_type_count, cbm_edge_info_t **out_edges,
int *out_edge_count) {
/* Build ID set: root + all visited */
- char id_set[4096];
+ char id_set[CBM_SZ_4K];
int ilen = snprintf(id_set, sizeof(id_set), "%lld", (long long)start_id);
if (ilen >= (int)sizeof(id_set)) {
- ilen = (int)sizeof(id_set) - 1;
+ ilen = (int)sizeof(id_set) - SKIP_ONE;
}
for (int i = 0; i < visited_count; i++) {
ilen += snprintf(id_set + ilen, sizeof(id_set) - (size_t)ilen, ",%lld",
(long long)visited[i].node.id);
if (ilen >= (int)sizeof(id_set)) {
- ilen = (int)sizeof(id_set) - 1;
+ ilen = (int)sizeof(id_set) - SKIP_ONE;
}
}
- char edge_sql[8192];
+ char edge_sql[ST_SQL_BUF];
snprintf(edge_sql, sizeof(edge_sql),
"SELECT n1.name, n2.name, e.type "
"FROM edges e "
@@ -2161,7 +2217,7 @@ static int bfs_collect_edges(cbm_store_t *s, int64_t start_id, const cbm_node_ho
id_set, id_set, types_clause);
sqlite3_stmt *estmt = NULL;
- int rc = sqlite3_prepare_v2(s->db, edge_sql, -1, &estmt, NULL);
+ int rc = sqlite3_prepare_v2(s->db, edge_sql, CBM_NOT_FOUND, &estmt, NULL);
if (rc != SQLITE_OK) {
*out_edges = NULL;
*out_edge_count = 0;
@@ -2170,25 +2226,25 @@ static int bfs_collect_edges(cbm_store_t *s, int64_t start_id, const cbm_node_ho
if (edge_type_count > 0) {
for (int i = 0; i < edge_type_count; i++) {
- bind_text(estmt, i + 1, edge_types[i]);
+ bind_text(estmt, i + SKIP_ONE, edge_types[i]);
}
} else {
- bind_text(estmt, 1, "CALLS");
+ bind_text(estmt, SKIP_ONE, "CALLS");
}
- int ecap = 8;
+ int ecap = ST_INIT_CAP_8;
int en = 0;
cbm_edge_info_t *edges = malloc(ecap * sizeof(cbm_edge_info_t));
while (sqlite3_step(estmt) == SQLITE_ROW) {
if (en >= ecap) {
- ecap *= 2;
+ ecap *= ST_GROWTH;
edges = safe_realloc(edges, ecap * sizeof(cbm_edge_info_t));
}
edges[en].from_name = heap_strdup((const char *)sqlite3_column_text(estmt, 0));
- edges[en].to_name = heap_strdup((const char *)sqlite3_column_text(estmt, 1));
- edges[en].type = heap_strdup((const char *)sqlite3_column_text(estmt, 2));
- edges[en].confidence = 1.0;
+ edges[en].to_name = heap_strdup((const char *)sqlite3_column_text(estmt, SKIP_ONE));
+ edges[en].type = heap_strdup((const char *)sqlite3_column_text(estmt, CBM_SZ_2));
+ edges[en].confidence = (double)SKIP_ONE;
en++;
}
sqlite3_finalize(estmt);
@@ -2209,12 +2265,12 @@ static void bfs_build_types_clause(int edge_type_count, char *buf, int buf_sz) {
if (i > 0) {
tlen += snprintf(buf + tlen, buf_sz - tlen, ",");
if (tlen >= buf_sz) {
- tlen = buf_sz - 1;
+ tlen = buf_sz - SKIP_ONE;
}
}
- tlen += snprintf(buf + tlen, buf_sz - tlen, "?%d", i + 1);
+ tlen += snprintf(buf + tlen, buf_sz - tlen, "?%d", i + SKIP_ONE);
if (tlen >= buf_sz) {
- tlen = buf_sz - 1;
+ tlen = buf_sz - SKIP_ONE;
}
}
}
@@ -2230,11 +2286,11 @@ int cbm_store_bfs(cbm_store_t *s, int64_t start_id, const char *direction, const
}
out->root = root;
- char types_clause[512];
+ char types_clause[CBM_SZ_512];
bfs_build_types_clause(edge_type_count, types_clause, (int)sizeof(types_clause));
/* Build recursive CTE for BFS */
- char sql[4096];
+ char sql[CBM_SZ_4K];
const char *join_cond;
const char *next_id;
bool is_inbound = (direction != NULL) && (strcmp(direction, "inbound") == 0);
@@ -2266,7 +2322,7 @@ int cbm_store_bfs(cbm_store_t *s, int64_t start_id, const char *direction, const
(long long)start_id, next_id, join_cond, types_clause, max_depth, max_results);
sqlite3_stmt *stmt = NULL;
- rc = sqlite3_prepare_v2(s->db, sql, -1, &stmt, NULL);
+ rc = sqlite3_prepare_v2(s->db, sql, CBM_NOT_FOUND, &stmt, NULL);
if (rc != SQLITE_OK) {
store_set_error_sqlite(s, "bfs prepare");
return CBM_STORE_ERR;
@@ -2275,23 +2331,23 @@ int cbm_store_bfs(cbm_store_t *s, int64_t start_id, const char *direction, const
/* Bind edge type parameters */
if (edge_type_count > 0) {
for (int i = 0; i < edge_type_count; i++) {
- bind_text(stmt, i + 1, edge_types[i]);
+ bind_text(stmt, i + SKIP_ONE, edge_types[i]);
}
} else {
- bind_text(stmt, 1, "CALLS");
+ bind_text(stmt, SKIP_ONE, "CALLS");
}
- int cap = 16;
+ int cap = ST_INIT_CAP_16;
int n = 0;
cbm_node_hop_t *visited = malloc(cap * sizeof(cbm_node_hop_t));
while (sqlite3_step(stmt) == SQLITE_ROW) {
if (n >= cap) {
- cap *= 2;
+ cap *= ST_GROWTH;
visited = safe_realloc(visited, cap * sizeof(cbm_node_hop_t));
}
scan_node(stmt, &visited[n].node);
- visited[n].hop = sqlite3_column_int(stmt, 9);
+ visited[n].hop = sqlite3_column_int(stmt, ST_COL_9);
n++;
}
@@ -2351,11 +2407,11 @@ void cbm_store_traverse_free(cbm_traverse_result_t *out) {
cbm_risk_level_t cbm_hop_to_risk(int hop) {
switch (hop) {
- case 1:
+ case SKIP_ONE:
return CBM_RISK_CRITICAL;
- case 2:
+ case ST_COL_2:
return CBM_RISK_HIGH;
- case 3:
+ case ST_COL_3:
return CBM_RISK_MEDIUM;
default:
return CBM_RISK_LOW;
@@ -2419,7 +2475,7 @@ int cbm_deduplicate_hops(const cbm_node_hop_t *hops, int hop_count, cbm_node_hop
int n = 0;
for (int i = 0; i < hop_count; i++) {
- int found = -1;
+ int found = ST_FOUND;
for (int j = 0; j < n; j++) {
if (result[j].node.id == hops[i].node.id) {
found = j;
@@ -2446,7 +2502,7 @@ int cbm_deduplicate_hops(const cbm_node_hop_t *hops, int hop_count, cbm_node_hop
int cbm_store_get_schema(cbm_store_t *s, const char *project, cbm_schema_info_t *out) {
memset(out, 0, sizeof(*out));
if (!s || !s->db) {
- return -1;
+ return CBM_NOT_FOUND;
}
/* Node labels */
@@ -2454,19 +2510,19 @@ int cbm_store_get_schema(cbm_store_t *s, const char *project, cbm_schema_info_t
const char *sql = "SELECT label, COUNT(*) FROM nodes WHERE project = ?1 GROUP BY label "
"ORDER BY COUNT(*) DESC;";
sqlite3_stmt *stmt = NULL;
- sqlite3_prepare_v2(s->db, sql, -1, &stmt, NULL);
- bind_text(stmt, 1, project);
+ sqlite3_prepare_v2(s->db, sql, CBM_NOT_FOUND, &stmt, NULL);
+ bind_text(stmt, SKIP_ONE, project);
- int cap = 8;
+ int cap = ST_INIT_CAP_8;
int n = 0;
cbm_label_count_t *arr = malloc(cap * sizeof(cbm_label_count_t));
while (sqlite3_step(stmt) == SQLITE_ROW) {
if (n >= cap) {
- cap *= 2;
+ cap *= ST_GROWTH;
arr = safe_realloc(arr, cap * sizeof(cbm_label_count_t));
}
arr[n].label = heap_strdup((const char *)sqlite3_column_text(stmt, 0));
- arr[n].count = sqlite3_column_int(stmt, 1);
+ arr[n].count = sqlite3_column_int(stmt, SKIP_ONE);
n++;
}
sqlite3_finalize(stmt);
@@ -2479,19 +2535,19 @@ int cbm_store_get_schema(cbm_store_t *s, const char *project, cbm_schema_info_t
const char *sql = "SELECT type, COUNT(*) FROM edges WHERE project = ?1 GROUP BY type ORDER "
"BY COUNT(*) DESC;";
sqlite3_stmt *stmt = NULL;
- sqlite3_prepare_v2(s->db, sql, -1, &stmt, NULL);
- bind_text(stmt, 1, project);
+ sqlite3_prepare_v2(s->db, sql, CBM_NOT_FOUND, &stmt, NULL);
+ bind_text(stmt, SKIP_ONE, project);
- int cap = 8;
+ int cap = ST_INIT_CAP_8;
int n = 0;
cbm_type_count_t *arr = malloc(cap * sizeof(cbm_type_count_t));
while (sqlite3_step(stmt) == SQLITE_ROW) {
if (n >= cap) {
- cap *= 2;
+ cap *= ST_GROWTH;
arr = safe_realloc(arr, cap * sizeof(cbm_type_count_t));
}
arr[n].type = heap_strdup((const char *)sqlite3_column_text(stmt, 0));
- arr[n].count = sqlite3_column_int(stmt, 1);
+ arr[n].count = sqlite3_column_int(stmt, SKIP_ONE);
n++;
}
sqlite3_finalize(stmt);
@@ -2546,19 +2602,19 @@ const char *cbm_qn_to_package(const char *qn) {
if (!qn || !qn[0]) {
return "";
}
- static CBM_TLS char buf[256];
+ static CBM_TLS char buf[CBM_SZ_256];
/* Find dots and extract segment */
- const char *dots[5] = {NULL};
+ const char *dots[ST_QN_MAX_DOTS] = {NULL};
int ndots = 0;
- for (const char *p = qn; *p && ndots < 5; p++) {
+ for (const char *p = qn; *p && ndots < ST_QN_MAX_DOTS; p++) {
if (*p == '.') {
dots[ndots++] = p;
}
}
/* 4+ segments: return segment[2] */
- if (ndots >= 3) {
- const char *start = dots[1] + 1;
- int len = (int)(dots[2] - start);
+ if (ndots >= ST_QN_MIN_DOTS) {
+ const char *start = dots[SKIP_ONE] + SKIP_ONE;
+ int len = (int)(dots[ST_COL_2] - start);
if (len > 0 && len < (int)sizeof(buf)) {
memcpy(buf, start, len);
buf[len] = '\0';
@@ -2566,9 +2622,9 @@ const char *cbm_qn_to_package(const char *qn) {
}
}
/* 2+ segments: return segment[1] */
- if (ndots >= 1) {
- const char *start = dots[0] + 1;
- const char *end = (ndots >= 2) ? dots[1] : qn + strlen(qn);
+ if (ndots >= SKIP_ONE) {
+ const char *start = dots[0] + SKIP_ONE;
+ const char *end = (ndots >= ST_COL_2) ? dots[SKIP_ONE] : qn + strlen(qn);
int len = (int)(end - start);
if (len > 0 && len < (int)sizeof(buf)) {
memcpy(buf, start, len);
@@ -2584,12 +2640,12 @@ const char *cbm_qn_to_top_package(const char *qn) {
if (!qn || !qn[0]) {
return "";
}
- static CBM_TLS char buf[256];
+ static CBM_TLS char buf[CBM_SZ_256];
const char *first_dot = strchr(qn, '.');
if (!first_dot) {
return "";
}
- const char *start = first_dot + 1;
+ const char *start = first_dot + SKIP_ONE;
const char *second_dot = strchr(start, '.');
const char *end = second_dot ? second_dot : qn + strlen(qn);
int len = (int)(end - start);
@@ -2650,13 +2706,13 @@ static const char *file_ext(const char *path) {
if (!dot) {
return NULL;
}
- static CBM_TLS char buf[16];
+ static CBM_TLS char buf[CBM_SZ_16];
int len = (int)strlen(dot);
if (len >= (int)sizeof(buf)) {
return NULL;
}
for (int i = 0; i < len; i++) {
- buf[i] = (char)((dot[i] >= 'A' && dot[i] <= 'Z') ? dot[i] + 32 : dot[i]);
+ buf[i] = (char)((dot[i] >= 'A' && dot[i] <= 'Z') ? dot[i] + CBM_SZ_32 : dot[i]);
}
buf[len] = '\0';
return buf;
@@ -2667,15 +2723,15 @@ static const char *file_ext(const char *path) {
static int arch_languages(cbm_store_t *s, const char *project, cbm_architecture_info_t *out) {
const char *sql = "SELECT file_path FROM nodes WHERE project=?1 AND label='File'";
sqlite3_stmt *stmt = NULL;
- if (sqlite3_prepare_v2(s->db, sql, -1, &stmt, NULL) != SQLITE_OK) {
+ if (sqlite3_prepare_v2(s->db, sql, CBM_NOT_FOUND, &stmt, NULL) != SQLITE_OK) {
store_set_error_sqlite(s, "arch_languages");
return CBM_STORE_ERR;
}
- bind_text(stmt, 1, project);
+ bind_text(stmt, SKIP_ONE, project);
/* Count per language using a simple parallel array */
- const char *lang_names[64];
- int lang_counts[64];
+ const char *lang_names[CBM_SZ_64];
+ int lang_counts[CBM_SZ_64];
int nlang = 0;
while (sqlite3_step(stmt) == SQLITE_ROW) {
@@ -2685,7 +2741,7 @@ static int arch_languages(cbm_store_t *s, const char *project, cbm_architecture_
if (!lang) {
continue;
}
- int found = -1;
+ int found = ST_FOUND;
for (int i = 0; i < nlang; i++) {
if (strcmp(lang_names[i], lang) == 0) {
found = i;
@@ -2694,32 +2750,32 @@ static int arch_languages(cbm_store_t *s, const char *project, cbm_architecture_
}
if (found >= 0) {
lang_counts[found]++;
- } else if (nlang < 64) {
+ } else if (nlang < CBM_SZ_64) {
lang_names[nlang] = lang;
- lang_counts[nlang] = 1;
+ lang_counts[nlang] = SKIP_ONE;
nlang++;
}
}
sqlite3_finalize(stmt);
/* Sort by count descending (simple insertion sort) */
- for (int i = 1; i < nlang; i++) {
+ for (int i = SKIP_ONE; i < nlang; i++) {
int j = i;
- while (j > 0 && lang_counts[j] > lang_counts[j - 1]) {
+ while (j > 0 && lang_counts[j] > lang_counts[j - SKIP_ONE]) {
int tc = lang_counts[j];
- lang_counts[j] = lang_counts[j - 1];
- lang_counts[j - 1] = tc;
+ lang_counts[j] = lang_counts[j - SKIP_ONE];
+ lang_counts[j - SKIP_ONE] = tc;
const char *tn = lang_names[j];
- lang_names[j] = lang_names[j - 1];
- lang_names[j - 1] = tn;
+ lang_names[j] = lang_names[j - SKIP_ONE];
+ lang_names[j - SKIP_ONE] = tn;
j--;
}
}
- if (nlang > 10) {
- nlang = 10;
+ if (nlang > CBM_DECIMAL_BASE) {
+ nlang = ST_MAX_LANG;
}
- out->languages = calloc(nlang, sizeof(cbm_language_count_t));
+ out->languages = (nlang > 0) ? calloc(nlang, sizeof(cbm_language_count_t)) : NULL;
out->language_count = nlang;
for (int i = 0; i < nlang; i++) {
out->languages[i].language = heap_strdup(lang_names[i]);
@@ -2735,23 +2791,23 @@ static int arch_entry_points(cbm_store_t *s, const char *project, cbm_architectu
"json_extract(properties, '$.is_test') != 1) "
"AND file_path NOT LIKE '%test%' LIMIT 20";
sqlite3_stmt *stmt = NULL;
- if (sqlite3_prepare_v2(s->db, sql, -1, &stmt, NULL) != SQLITE_OK) {
+ if (sqlite3_prepare_v2(s->db, sql, CBM_NOT_FOUND, &stmt, NULL) != SQLITE_OK) {
store_set_error_sqlite(s, "arch_entry_points");
return CBM_STORE_ERR;
}
- bind_text(stmt, 1, project);
+ bind_text(stmt, SKIP_ONE, project);
- int cap = 8;
+ int cap = ST_INIT_CAP_8;
int n = 0;
cbm_entry_point_t *arr = calloc(cap, sizeof(cbm_entry_point_t));
while (sqlite3_step(stmt) == SQLITE_ROW) {
if (n >= cap) {
- cap *= 2;
+ cap *= ST_GROWTH;
arr = safe_realloc(arr, cap * sizeof(cbm_entry_point_t));
}
arr[n].name = heap_strdup((const char *)sqlite3_column_text(stmt, 0));
- arr[n].qualified_name = heap_strdup((const char *)sqlite3_column_text(stmt, 1));
- arr[n].file = heap_strdup((const char *)sqlite3_column_text(stmt, 2));
+ arr[n].qualified_name = heap_strdup((const char *)sqlite3_column_text(stmt, SKIP_ONE));
+ arr[n].file = heap_strdup((const char *)sqlite3_column_text(stmt, CBM_SZ_2));
n++;
}
sqlite3_finalize(stmt);
@@ -2775,10 +2831,10 @@ static char *extract_json_string_prop(const char *json, const char *key, int key
}
m++;
const char *end = strchr(m, '"');
- if (!end || end - m >= 256) {
+ if (!end || end - m >= CBM_SZ_256) {
return NULL;
}
- char vbuf[256];
+ char vbuf[CBM_SZ_256];
memcpy(vbuf, m, end - m);
vbuf[end - m] = '\0';
return heap_strdup(vbuf);
@@ -2791,24 +2847,24 @@ static int arch_routes(cbm_store_t *s, const char *project, cbm_architecture_inf
"json_extract(properties, '$.is_test') != 1) "
"LIMIT 20";
sqlite3_stmt *stmt = NULL;
- if (sqlite3_prepare_v2(s->db, sql, -1, &stmt, NULL) != SQLITE_OK) {
+ if (sqlite3_prepare_v2(s->db, sql, CBM_NOT_FOUND, &stmt, NULL) != SQLITE_OK) {
store_set_error_sqlite(s, "arch_routes");
return CBM_STORE_ERR;
}
- bind_text(stmt, 1, project);
+ bind_text(stmt, SKIP_ONE, project);
- int cap = 8;
+ int cap = ST_INIT_CAP_8;
int n = 0;
cbm_route_info_t *arr = calloc(cap, sizeof(cbm_route_info_t));
while (sqlite3_step(stmt) == SQLITE_ROW) {
const char *name = (const char *)sqlite3_column_text(stmt, 0);
- const char *props = (const char *)sqlite3_column_text(stmt, 1);
- const char *fp = (const char *)sqlite3_column_text(stmt, 2);
+ const char *props = (const char *)sqlite3_column_text(stmt, SKIP_ONE);
+ const char *fp = (const char *)sqlite3_column_text(stmt, CBM_SZ_2);
if (cbm_is_test_file_path(fp)) {
continue;
}
if (n >= cap) {
- cap *= 2;
+ cap *= ST_GROWTH;
arr = safe_realloc(arr, cap * sizeof(cbm_route_info_t));
}
@@ -2817,17 +2873,17 @@ static int arch_routes(cbm_store_t *s, const char *project, cbm_architecture_inf
arr[n].handler = heap_strdup("");
char *val;
- val = extract_json_string_prop(props, "\"method\"", 8);
+ val = extract_json_string_prop(props, "\"method\"", ST_METHOD_PROP_LEN);
if (val) {
free((void *)arr[n].method);
arr[n].method = val;
}
- val = extract_json_string_prop(props, "\"path\"", 6);
+ val = extract_json_string_prop(props, "\"path\"", ST_PATH_PROP_LEN);
if (val) {
free((void *)arr[n].path);
arr[n].path = val;
}
- val = extract_json_string_prop(props, "\"handler\"", 9);
+ val = extract_json_string_prop(props, "\"handler\"", ST_HANDLER_PROP_LEN);
if (val) {
free((void *)arr[n].handler);
arr[n].handler = val;
@@ -2849,23 +2905,23 @@ static int arch_hotspots(cbm_store_t *s, const char *project, cbm_architecture_i
"AND n.file_path NOT LIKE '%test%' "
"GROUP BY n.id ORDER BY fan_in DESC LIMIT 10";
sqlite3_stmt *stmt = NULL;
- if (sqlite3_prepare_v2(s->db, sql, -1, &stmt, NULL) != SQLITE_OK) {
+ if (sqlite3_prepare_v2(s->db, sql, CBM_NOT_FOUND, &stmt, NULL) != SQLITE_OK) {
store_set_error_sqlite(s, "arch_hotspots");
return CBM_STORE_ERR;
}
- bind_text(stmt, 1, project);
+ bind_text(stmt, SKIP_ONE, project);
- int cap = 8;
+ int cap = ST_INIT_CAP_8;
int n = 0;
cbm_hotspot_t *arr = calloc(cap, sizeof(cbm_hotspot_t));
while (sqlite3_step(stmt) == SQLITE_ROW) {
if (n >= cap) {
- cap *= 2;
+ cap *= ST_GROWTH;
arr = safe_realloc(arr, cap * sizeof(cbm_hotspot_t));
}
arr[n].name = heap_strdup((const char *)sqlite3_column_text(stmt, 0));
- arr[n].qualified_name = heap_strdup((const char *)sqlite3_column_text(stmt, 1));
- arr[n].fan_in = sqlite3_column_int(stmt, 2);
+ arr[n].qualified_name = heap_strdup((const char *)sqlite3_column_text(stmt, SKIP_ONE));
+ arr[n].fan_in = sqlite3_column_int(stmt, CBM_SZ_2);
n++;
}
sqlite3_finalize(stmt);
@@ -2887,7 +2943,7 @@ static const char *lookup_pkg(const int64_t *nids, char **npkgs, int nn, int64_t
/* Accumulate a cross-package boundary into parallel arrays. */
static void accum_boundary(const char *src_pkg, const char *tgt_pkg, char **bfroms, char **btos,
int *bcounts, int *bn, int bcap) {
- int found = -1;
+ int found = ST_FOUND;
for (int i = 0; i < *bn; i++) {
if (strcmp(bfroms[i], src_pkg) == 0 && strcmp(btos[i], tgt_pkg) == 0) {
found = i;
@@ -2899,7 +2955,7 @@ static void accum_boundary(const char *src_pkg, const char *tgt_pkg, char **bfro
} else if (*bn < bcap) {
bfroms[*bn] = heap_strdup(src_pkg);
btos[*bn] = heap_strdup(tgt_pkg);
- bcounts[*bn] = 1;
+ bcounts[*bn] = SKIP_ONE;
(*bn)++;
}
}
@@ -2910,25 +2966,25 @@ static int arch_boundaries(cbm_store_t *s, const char *project, cbm_cross_pkg_bo
const char *nsql = "SELECT id, qualified_name FROM nodes WHERE project=?1 AND label IN "
"('Function','Method','Class')";
sqlite3_stmt *nstmt = NULL;
- if (sqlite3_prepare_v2(s->db, nsql, -1, &nstmt, NULL) != SQLITE_OK) {
+ if (sqlite3_prepare_v2(s->db, nsql, CBM_NOT_FOUND, &nstmt, NULL) != SQLITE_OK) {
store_set_error_sqlite(s, "arch_boundaries_nodes");
return CBM_STORE_ERR;
}
- bind_text(nstmt, 1, project);
+ bind_text(nstmt, SKIP_ONE, project);
- int ncap = 256;
+ int ncap = CBM_SZ_256;
int nn = 0;
int64_t *nids = malloc(ncap * sizeof(int64_t));
char **npkgs = malloc(ncap * sizeof(char *));
while (sqlite3_step(nstmt) == SQLITE_ROW) {
if (nn >= ncap) {
- ncap *= 2;
+ ncap *= ST_GROWTH;
nids = safe_realloc(nids, ncap * sizeof(int64_t));
npkgs = safe_realloc(npkgs, ncap * sizeof(char *));
}
nids[nn] = sqlite3_column_int64(nstmt, 0);
- const char *qn = (const char *)sqlite3_column_text(nstmt, 1);
+ const char *qn = (const char *)sqlite3_column_text(nstmt, SKIP_ONE);
npkgs[nn] = heap_strdup(cbm_qn_to_package(qn));
nn++;
}
@@ -2937,7 +2993,7 @@ static int arch_boundaries(cbm_store_t *s, const char *project, cbm_cross_pkg_bo
/* Scan edges, count cross-package calls */
const char *esql = "SELECT source_id, target_id FROM edges WHERE project=?1 AND type='CALLS'";
sqlite3_stmt *estmt = NULL;
- if (sqlite3_prepare_v2(s->db, esql, -1, &estmt, NULL) != SQLITE_OK) {
+ if (sqlite3_prepare_v2(s->db, esql, CBM_NOT_FOUND, &estmt, NULL) != SQLITE_OK) {
for (int i = 0; i < nn; i++) {
free(npkgs[i]);
}
@@ -2946,9 +3002,9 @@ static int arch_boundaries(cbm_store_t *s, const char *project, cbm_cross_pkg_bo
store_set_error_sqlite(s, "arch_boundaries_edges");
return CBM_STORE_ERR;
}
- bind_text(estmt, 1, project);
+ bind_text(estmt, SKIP_ONE, project);
- int bcap = 32;
+ int bcap = CBM_SZ_32;
int bn = 0;
char **bfroms = malloc(bcap * sizeof(char *));
char **btos = malloc(bcap * sizeof(char *));
@@ -2956,7 +3012,7 @@ static int arch_boundaries(cbm_store_t *s, const char *project, cbm_cross_pkg_bo
while (sqlite3_step(estmt) == SQLITE_ROW) {
int64_t src_id = sqlite3_column_int64(estmt, 0);
- int64_t tgt_id = sqlite3_column_int64(estmt, 1);
+ int64_t tgt_id = sqlite3_column_int64(estmt, SKIP_ONE);
const char *src_pkg = lookup_pkg(nids, npkgs, nn, src_id);
const char *tgt_pkg = lookup_pkg(nids, npkgs, nn, tgt_id);
if (!src_pkg || !tgt_pkg || !src_pkg[0] || !tgt_pkg[0] || strcmp(src_pkg, tgt_pkg) == 0) {
@@ -2972,30 +3028,31 @@ static int arch_boundaries(cbm_store_t *s, const char *project, cbm_cross_pkg_bo
free(npkgs);
/* Sort by count descending */
- for (int i = 1; i < bn; i++) {
+ for (int i = SKIP_ONE; i < bn; i++) {
int j = i;
- while (j > 0 && bcounts[j] > bcounts[j - 1]) {
+ while (j > 0 && bcounts[j] > bcounts[j - SKIP_ONE]) {
int tc = bcounts[j];
- bcounts[j] = bcounts[j - 1];
- bcounts[j - 1] = tc;
+ bcounts[j] = bcounts[j - SKIP_ONE];
+ bcounts[j - SKIP_ONE] = tc;
char *tf = bfroms[j];
- bfroms[j] = bfroms[j - 1];
- bfroms[j - 1] = tf;
+ bfroms[j] = bfroms[j - SKIP_ONE];
+ bfroms[j - SKIP_ONE] = tf;
char *tt = btos[j];
- btos[j] = btos[j - 1];
- btos[j - 1] = tt;
+ btos[j] = btos[j - SKIP_ONE];
+ btos[j - SKIP_ONE] = tt;
j--;
}
}
- if (bn > 10) {
- for (int i = 10; i < bn; i++) {
+ if (bn > CBM_DECIMAL_BASE) {
+ for (int i = ST_MAX_ITERATIONS; i < bn; i++) {
free(bfroms[i]);
free(btos[i]);
}
- bn = 10;
+ bn = ST_MAX_ITERATIONS;
}
- cbm_cross_pkg_boundary_t *result = calloc(bn, sizeof(cbm_cross_pkg_boundary_t));
+ cbm_cross_pkg_boundary_t *result =
+ (bn > 0) ? calloc(bn, sizeof(cbm_cross_pkg_boundary_t)) : NULL;
for (int i = 0; i < bn; i++) {
result[i].from = bfroms[i];
result[i].to = btos[i];
@@ -3017,14 +3074,14 @@ static int arch_packages_from_qn(cbm_store_t *s, const char *project,
const char *qsql = "SELECT qualified_name FROM nodes WHERE project=?1 AND label IN "
"('Function','Method','Class')";
sqlite3_stmt *stmt = NULL;
- if (sqlite3_prepare_v2(s->db, qsql, -1, &stmt, NULL) != SQLITE_OK) {
+ if (sqlite3_prepare_v2(s->db, qsql, CBM_NOT_FOUND, &stmt, NULL) != SQLITE_OK) {
store_set_error_sqlite(s, "arch_packages_qn");
return CBM_STORE_ERR;
}
- bind_text(stmt, 1, project);
+ bind_text(stmt, SKIP_ONE, project);
- char *pnames[64];
- int pcounts[64];
+ char *pnames[CBM_SZ_64];
+ int pcounts[CBM_SZ_64];
int np = 0;
while (sqlite3_step(stmt) == SQLITE_ROW) {
const char *qn = (const char *)sqlite3_column_text(stmt, 0);
@@ -3032,7 +3089,7 @@ static int arch_packages_from_qn(cbm_store_t *s, const char *project,
if (!pkg[0]) {
continue;
}
- int found = -1;
+ int found = ST_FOUND;
for (int i = 0; i < np; i++) {
if (strcmp(pnames[i], pkg) == 0) {
found = i;
@@ -3041,24 +3098,24 @@ static int arch_packages_from_qn(cbm_store_t *s, const char *project,
}
if (found >= 0) {
pcounts[found]++;
- } else if (np < 64) {
+ } else if (np < CBM_SZ_64) {
pnames[np] = heap_strdup(pkg);
- pcounts[np] = 1;
+ pcounts[np] = SKIP_ONE;
np++;
}
}
sqlite3_finalize(stmt);
/* Sort by count desc */
- for (int i = 1; i < np; i++) {
+ for (int i = SKIP_ONE; i < np; i++) {
int j = i;
- while (j > 0 && pcounts[j] > pcounts[j - 1]) {
+ while (j > 0 && pcounts[j] > pcounts[j - SKIP_ONE]) {
int tc = pcounts[j];
- pcounts[j] = pcounts[j - 1];
- pcounts[j - 1] = tc;
+ pcounts[j] = pcounts[j - SKIP_ONE];
+ pcounts[j - SKIP_ONE] = tc;
char *tn = pnames[j];
- pnames[j] = pnames[j - 1];
- pnames[j - 1] = tn;
+ pnames[j] = pnames[j - SKIP_ONE];
+ pnames[j - SKIP_ONE] = tn;
j--;
}
}
@@ -3069,7 +3126,7 @@ static int arch_packages_from_qn(cbm_store_t *s, const char *project,
np = MAX_PREVIEW_NAMES;
}
- cbm_package_summary_t *arr = calloc(np, sizeof(cbm_package_summary_t));
+ cbm_package_summary_t *arr = (np > 0) ? calloc(np, sizeof(cbm_package_summary_t)) : NULL;
for (int i = 0; i < np; i++) {
arr[i].name = pnames[i];
arr[i].node_count = pcounts[i];
@@ -3085,22 +3142,22 @@ static int arch_packages(cbm_store_t *s, const char *project, cbm_architecture_i
"SELECT n.name, COUNT(*) as cnt FROM nodes n "
"WHERE n.project=?1 AND n.label='Package' GROUP BY n.name ORDER BY cnt DESC LIMIT 15";
sqlite3_stmt *stmt = NULL;
- if (sqlite3_prepare_v2(s->db, sql, -1, &stmt, NULL) != SQLITE_OK) {
+ if (sqlite3_prepare_v2(s->db, sql, CBM_NOT_FOUND, &stmt, NULL) != SQLITE_OK) {
store_set_error_sqlite(s, "arch_packages");
return CBM_STORE_ERR;
}
- bind_text(stmt, 1, project);
+ bind_text(stmt, SKIP_ONE, project);
- int cap = 16;
+ int cap = ST_INIT_CAP_16;
int n = 0;
cbm_package_summary_t *arr = calloc(cap, sizeof(cbm_package_summary_t));
while (sqlite3_step(stmt) == SQLITE_ROW) {
if (n >= cap) {
- cap *= 2;
+ cap *= ST_GROWTH;
arr = safe_realloc(arr, cap * sizeof(cbm_package_summary_t));
}
arr[n].name = heap_strdup((const char *)sqlite3_column_text(stmt, 0));
- arr[n].node_count = sqlite3_column_int(stmt, 1);
+ arr[n].node_count = sqlite3_column_int(stmt, SKIP_ONE);
n++;
}
sqlite3_finalize(stmt);
@@ -3121,7 +3178,7 @@ static int arch_packages(cbm_store_t *s, const char *project, cbm_architecture_i
static void classify_layer(const char *pkg, int in, int out_deg, bool has_routes,
bool has_entry_points, const char **layer, const char **reason) {
- static CBM_TLS char reason_buf[128];
+ static CBM_TLS char reason_buf[CBM_SZ_128];
if (has_entry_points && out_deg > 0 && in == 0) {
*layer = "entry";
*reason = "has entry points, only outbound calls";
@@ -3132,7 +3189,7 @@ static void classify_layer(const char *pkg, int in, int out_deg, bool has_routes
*reason = "has HTTP route definitions";
return;
}
- if (in > out_deg && in > 3) {
+ if (in > out_deg && in > ST_MIN_INDEGREE) {
snprintf(reason_buf, sizeof(reason_buf), "high fan-in (%d in, %d out)", in, out_deg);
*layer = "core";
*reason = reason_buf;
@@ -3167,7 +3224,7 @@ static int find_or_add_pkg(char **all_pkgs, int *npkgs, int max_pkgs, const char
(*npkgs)++;
return idx;
}
- return -1;
+ return CBM_NOT_FOUND;
}
/* Check if a package name appears in an array. */
@@ -3184,8 +3241,8 @@ static bool pkg_in_list(const char *pkg, char **list, int count) {
static int collect_pkg_names(cbm_store_t *s, const char *sql, const char *project, char **pkgs,
int max_pkgs) {
sqlite3_stmt *stmt = NULL;
- sqlite3_prepare_v2(s->db, sql, -1, &stmt, NULL);
- bind_text(stmt, 1, project);
+ sqlite3_prepare_v2(s->db, sql, CBM_NOT_FOUND, &stmt, NULL);
+ bind_text(stmt, SKIP_ONE, project);
int count = 0;
while (sqlite3_step(stmt) == SQLITE_ROW && count < max_pkgs) {
const char *qn = (const char *)sqlite3_column_text(stmt, 0);
@@ -3205,31 +3262,31 @@ static int arch_layers(cbm_store_t *s, const char *project, cbm_architecture_inf
}
/* Collect route and entry point packages */
- char *route_pkgs[32];
+ char *route_pkgs[CBM_SZ_32];
int nrpkgs =
collect_pkg_names(s, "SELECT qualified_name FROM nodes WHERE project=?1 AND label='Route'",
- project, route_pkgs, 32);
+ project, route_pkgs, CBM_SZ_32);
- char *entry_pkgs[32];
+ char *entry_pkgs[CBM_SZ_32];
int nepkgs = collect_pkg_names(s,
"SELECT qualified_name FROM nodes WHERE project=?1 AND "
"json_extract(properties, '$.is_entry_point') = 1",
- project, entry_pkgs, 32);
+ project, entry_pkgs, CBM_SZ_32);
/* Compute fan-in/out per package */
- char *all_pkgs[64];
- int fan_in[64];
- int fan_out[64];
+ char *all_pkgs[CBM_SZ_64];
+ int fan_in[CBM_SZ_64];
+ int fan_out[CBM_SZ_64];
int npkgs = 0;
memset(fan_in, 0, sizeof(fan_in));
memset(fan_out, 0, sizeof(fan_out));
for (int i = 0; i < bcount; i++) {
- int fi = find_or_add_pkg(all_pkgs, &npkgs, 64, boundaries[i].from);
+ int fi = find_or_add_pkg(all_pkgs, &npkgs, ST_MAX_PKGS, boundaries[i].from);
if (fi >= 0) {
fan_out[fi] += boundaries[i].call_count;
}
- int ti = find_or_add_pkg(all_pkgs, &npkgs, 64, boundaries[i].to);
+ int ti = find_or_add_pkg(all_pkgs, &npkgs, ST_MAX_PKGS, boundaries[i].to);
if (ti >= 0) {
fan_in[ti] += boundaries[i].call_count;
}
@@ -3237,14 +3294,14 @@ static int arch_layers(cbm_store_t *s, const char *project, cbm_architecture_inf
/* Also include route/entry packages */
for (int i = 0; i < nrpkgs; i++) {
- find_or_add_pkg(all_pkgs, &npkgs, 64, route_pkgs[i]);
+ find_or_add_pkg(all_pkgs, &npkgs, ST_MAX_PKGS, route_pkgs[i]);
}
for (int i = 0; i < nepkgs; i++) {
- find_or_add_pkg(all_pkgs, &npkgs, 64, entry_pkgs[i]);
+ find_or_add_pkg(all_pkgs, &npkgs, ST_MAX_PKGS, entry_pkgs[i]);
}
/* Classify each package */
- out->layers = calloc(npkgs, sizeof(cbm_package_layer_t));
+ out->layers = (npkgs > 0) ? calloc(npkgs, sizeof(cbm_package_layer_t)) : NULL;
out->layer_count = npkgs;
for (int i = 0; i < npkgs; i++) {
bool has_route = pkg_in_list(all_pkgs[i], route_pkgs, nrpkgs);
@@ -3258,12 +3315,12 @@ static int arch_layers(cbm_store_t *s, const char *project, cbm_architecture_inf
}
/* Sort layers by name */
- for (int i = 1; i < npkgs; i++) {
+ for (int i = SKIP_ONE; i < npkgs; i++) {
int j = i;
- while (j > 0 && strcmp(out->layers[j].name, out->layers[j - 1].name) < 0) {
+ while (j > 0 && strcmp(out->layers[j].name, out->layers[j - SKIP_ONE].name) < 0) {
cbm_package_layer_t tmp = out->layers[j];
- out->layers[j] = out->layers[j - 1];
- out->layers[j - 1] = tmp;
+ out->layers[j] = out->layers[j - SKIP_ONE];
+ out->layers[j - SKIP_ONE] = tmp;
j--;
}
}
@@ -3292,7 +3349,7 @@ static void dir_add_child(char ***children, int *child_count, int *child_cap, co
}
}
if (*child_count >= *child_cap) {
- *child_cap = *child_cap ? *child_cap * 2 : 4;
+ *child_cap = *child_cap ? *child_cap * PAIR_LEN : ST_INIT_CAP_4;
*children = realloc(*children, *child_cap * sizeof(char *));
}
(*children)[(*child_count)++] = heap_strdup(child);
@@ -3315,7 +3372,7 @@ static int dir_find_or_create(char **dir_paths, int *dir_child_counts, char ***d
(*dn)++;
return idx;
}
- return -1;
+ return CBM_NOT_FOUND;
}
/* Create a file tree entry by checking if a path is a file and counting dir children. */
@@ -3343,15 +3400,15 @@ static cbm_file_tree_entry_t make_tree_entry(const char *path, char **files, int
/* Split a path by '/' into parts. Returns number of parts. */
static int split_path_parts(const char *fp, char *buf, int buf_sz, char **parts, int max_parts) {
- strncpy(buf, fp, buf_sz - 1);
- buf[buf_sz - 1] = '\0';
+ strncpy(buf, fp, buf_sz - SKIP_ONE);
+ buf[buf_sz - SKIP_ONE] = '\0';
int nparts = 0;
char *p = buf;
parts[nparts++] = p;
while (*p && nparts < max_parts) {
if (*p == '/') {
*p = '\0';
- parts[nparts++] = p + 1;
+ parts[nparts++] = p + SKIP_ONE;
}
p++;
}
@@ -3362,9 +3419,9 @@ static int split_path_parts(const char *fp, char *buf, int buf_sz, char **parts,
static void arch_register_file_dirs(const char *fp, char **dir_paths, int *dir_child_counts,
char ***dir_children, int *dir_children_caps, int *dn,
int dcap) {
- char tmp[512];
- char *parts[16];
- int nparts = split_path_parts(fp, tmp, (int)sizeof(tmp), parts, 16);
+ char tmp[CBM_SZ_512];
+ char *parts[ST_SEARCH_MAX_BINDS];
+ int nparts = split_path_parts(fp, tmp, (int)sizeof(tmp), parts, ST_SEARCH_MAX_BINDS);
int ri = dir_find_or_create(dir_paths, dir_child_counts, dir_children, dir_children_caps, dn,
dcap, "");
@@ -3372,15 +3429,15 @@ static void arch_register_file_dirs(const char *fp, char **dir_paths, int *dir_c
dir_add_child(&dir_children[ri], &dir_child_counts[ri], &dir_children_caps[ri], parts[0]);
}
- for (int depth = 0; depth < nparts - 1 && depth < 3; depth++) {
- char dir[512] = "";
+ for (int depth = 0; depth < nparts - SKIP_ONE && depth < ST_MAX_PATH_DEPTH; depth++) {
+ char dir[CBM_SZ_512] = "";
for (int k = 0; k <= depth; k++) {
if (k > 0) {
strcat(dir, "/");
}
strcat(dir, parts[k]);
}
- const char *child = (depth + 1 < nparts) ? parts[depth + 1] : NULL;
+ const char *child = (depth + SKIP_ONE < nparts) ? parts[depth + SKIP_ONE] : NULL;
if (!child) {
continue;
}
@@ -3407,7 +3464,7 @@ static int count_slashes(const char *s) {
static void push_tree_entry(cbm_file_tree_entry_t **entries, int *en, int *ecap,
cbm_file_tree_entry_t e) {
if (*en >= *ecap) {
- *ecap *= 2;
+ *ecap *= ST_GROWTH;
*entries = safe_realloc(*entries, *ecap * sizeof(cbm_file_tree_entry_t));
}
(*entries)[(*en)++] = e;
@@ -3417,7 +3474,7 @@ static void push_tree_entry(cbm_file_tree_entry_t **entries, int *en, int *ecap,
static void arch_collect_entries(char **dir_paths, int *dir_child_counts, char ***dir_children,
int dn, char **files, int fn, cbm_file_tree_entry_t **entries_out,
int *en_out) {
- int ecap = 64;
+ int ecap = CBM_SZ_64;
int en = 0;
cbm_file_tree_entry_t *entries = calloc(ecap, sizeof(cbm_file_tree_entry_t));
@@ -3433,13 +3490,13 @@ static void arch_collect_entries(char **dir_paths, int *dir_child_counts, char *
}
}
- /* Non-root dir children (depth < 3) */
+ /* Non-root dir children (depth < ST_COL_3) */
for (int i = 0; i < dn; i++) {
- if (strcmp(dir_paths[i], "") == 0 || count_slashes(dir_paths[i]) >= 3) {
+ if (strcmp(dir_paths[i], "") == 0 || count_slashes(dir_paths[i]) >= ST_MAX_PATH_DEPTH) {
continue;
}
for (int k = 0; k < dir_child_counts[i]; k++) {
- char path[512];
+ char path[CBM_SZ_512];
snprintf(path, sizeof(path), "%s/%s", dir_paths[i], dir_children[i][k]);
push_tree_entry(&entries, &en, &ecap,
make_tree_entry(path, files, fn, dir_paths, dir_child_counts, dn));
@@ -3447,12 +3504,12 @@ static void arch_collect_entries(char **dir_paths, int *dir_child_counts, char *
}
/* Sort by path */
- for (int i = 1; i < en; i++) {
+ for (int i = SKIP_ONE; i < en; i++) {
int j = i;
- while (j > 0 && strcmp(entries[j].path, entries[j - 1].path) < 0) {
+ while (j > 0 && strcmp(entries[j].path, entries[j - SKIP_ONE].path) < 0) {
cbm_file_tree_entry_t tmp = entries[j];
- entries[j] = entries[j - 1];
- entries[j - 1] = tmp;
+ entries[j] = entries[j - SKIP_ONE];
+ entries[j - SKIP_ONE] = tmp;
j--;
}
}
@@ -3484,17 +3541,17 @@ static void arch_free_dirs(char **dir_paths, int *dir_child_counts, char ***dir_
static int arch_file_tree(cbm_store_t *s, const char *project, cbm_architecture_info_t *out) {
const char *sql = "SELECT file_path FROM nodes WHERE project=?1 AND label='File'";
sqlite3_stmt *stmt = NULL;
- if (sqlite3_prepare_v2(s->db, sql, -1, &stmt, NULL) != SQLITE_OK) {
+ if (sqlite3_prepare_v2(s->db, sql, CBM_NOT_FOUND, &stmt, NULL) != SQLITE_OK) {
store_set_error_sqlite(s, "arch_file_tree");
return CBM_STORE_ERR;
}
- bind_text(stmt, 1, project);
+ bind_text(stmt, SKIP_ONE, project);
- int fcap = 32;
+ int fcap = CBM_SZ_32;
int fn = 0;
char **files = malloc(fcap * sizeof(char *));
- int dcap = 64;
+ int dcap = CBM_SZ_64;
int dn = 0;
char **dir_paths = calloc(dcap, sizeof(char *));
int *dir_child_counts = calloc(dcap, sizeof(int));
@@ -3507,7 +3564,7 @@ static int arch_file_tree(cbm_store_t *s, const char *project, cbm_architecture_
continue;
}
if (fn >= fcap) {
- fcap *= 2;
+ fcap *= ST_GROWTH;
files = safe_realloc(files, fcap * sizeof(char *));
}
files[fn++] = heap_strdup(fp);
@@ -3534,13 +3591,13 @@ static int louvain_node_index(const int64_t *nodes, int n, int64_t id) {
return i;
}
}
- return -1;
+ return CBM_NOT_FOUND;
}
static void louvain_build_weights(const int64_t *nodes, int n, const cbm_louvain_edge_t *edges,
int edge_count, int **out_wsi, int **out_wdi, double **out_ww,
int *out_wn) {
- int wcap = edge_count > 0 ? edge_count : 1;
+ int wcap = edge_count > 0 ? edge_count : SKIP_ONE;
int wn = 0;
int *wsi = malloc(wcap * sizeof(int));
int *wdi = malloc(wcap * sizeof(int));
@@ -3557,7 +3614,7 @@ static void louvain_build_weights(const int64_t *nodes, int n, const cbm_louvain
si = di;
di = tmp;
}
- int found = -1;
+ int found = ST_FOUND;
for (int i = 0; i < wn; i++) {
if (wsi[i] == si && wdi[i] == di) {
found = i;
@@ -3565,17 +3622,17 @@ static void louvain_build_weights(const int64_t *nodes, int n, const cbm_louvain
}
}
if (found >= 0) {
- ww[found] += 1.0;
+ ww[found] += (double)SKIP_ONE;
} else {
if (wn >= wcap) {
- wcap *= 2;
+ wcap *= ST_GROWTH;
wsi = safe_realloc(wsi, wcap * sizeof(int));
wdi = safe_realloc(wdi, wcap * sizeof(int));
ww = safe_realloc(ww, wcap * sizeof(double));
}
wsi[wn] = si;
wdi[wn] = di;
- ww[wn] = 1.0;
+ ww[wn] = (double)SKIP_ONE;
wn++;
}
}
@@ -3589,7 +3646,7 @@ static void louvain_build_weights(const int64_t *nodes, int n, const cbm_louvain
static void adj_add_edge(int **adj, double **adj_w, int *adj_n, int *adj_cap, int si, int di,
double w) {
if (adj_n[si] >= adj_cap[si]) {
- int new_cap = adj_cap[si] ? adj_cap[si] * 2 : 4;
+ int new_cap = adj_cap[si] ? adj_cap[si] * ST_GROWTH : ST_INIT_CAP_4;
int *new_adj = safe_realloc(adj[si], new_cap * sizeof(int));
double *new_w = safe_realloc(adj_w[si], new_cap * sizeof(double));
/* Zero-init new slots to satisfy static analyzer */
@@ -3606,7 +3663,7 @@ static void adj_add_edge(int **adj, double **adj_w, int *adj_n, int *adj_cap, in
adj_n[si]++;
if (adj_n[di] >= adj_cap[di]) {
- adj_cap[di] = adj_cap[di] ? adj_cap[di] * 2 : 4;
+ adj_cap[di] = adj_cap[di] ? adj_cap[di] * ST_GROWTH : ST_INIT_CAP_4;
adj[di] = safe_realloc(adj[di], adj_cap[di] * sizeof(int));
adj_w[di] = safe_realloc(adj_w[di], adj_cap[di] * sizeof(double));
}
@@ -3633,10 +3690,10 @@ static bool louvain_iteration(int n, int **adj, double **adj_w, const int *adj_n
for (int i = 0; i < n; i++) {
order[i] = i;
}
- unsigned int seed = (unsigned int)((iter * 1000) + n);
- for (int i = n - 1; i > 0; i--) {
+ unsigned int seed = (unsigned int)((iter * ST_GRAPH_SEED_MULT) + n);
+ for (int i = n - SKIP_ONE; i > 0; i--) {
seed = (seed * LCG_MULTIPLIER) + LCG_INCREMENT;
- int j = (int)((seed >> 16) % (unsigned int)(i + 1));
+ int j = (int)((seed >> ST_BUF_16) % (unsigned int)(i + SKIP_ONE));
int tmp = order[i];
order[i] = order[j];
order[j] = tmp;
@@ -3662,15 +3719,16 @@ static bool louvain_iteration(int n, int **adj, double **adj_w, const int *adj_n
if (!nc_seen[c]) {
continue;
}
- double gain = nc_weight[c] - (degree[i] * comm_degree[c] / (2.0 * total_weight));
+ double gain =
+ nc_weight[c] - (degree[i] * comm_degree[c] / (ST_WEIGHT_2 * total_weight));
if (gain > best_gain) {
best_gain = gain;
best_comm = c;
}
}
- double cur_gain =
- nc_weight[cur_comm] - (degree[i] * comm_degree[cur_comm] / (2.0 * total_weight));
+ double cur_gain = nc_weight[cur_comm] -
+ (degree[i] * comm_degree[cur_comm] / (ST_WEIGHT_2 * total_weight));
if (cur_gain >= best_gain) {
best_comm = cur_comm;
}
@@ -3731,7 +3789,7 @@ int cbm_louvain(const int64_t *nodes, int node_count, const cbm_louvain_edge_t *
free(wsi);
free(wdi);
free(ww);
- return -1;
+ return CBM_NOT_FOUND;
}
double total_weight = 0;
@@ -3766,14 +3824,8 @@ int cbm_louvain(const int64_t *nodes, int node_count, const cbm_louvain_edge_t *
double *degree = calloc(n, sizeof(double));
if (!degree) {
free(community);
- for (int i = 0; i < n; i++) {
- free(adj[i]);
- free(adj_w[i]);
- }
- free(adj);
- free(adj_w);
- free(adj_n);
- return -1;
+ louvain_free_adj(adj, adj_w, adj_n, adj_cap, n);
+ return CBM_NOT_FOUND;
}
for (int i = 0; i < n; i++) {
if (adj_w[i]) {
@@ -3784,7 +3836,7 @@ int cbm_louvain(const int64_t *nodes, int node_count, const cbm_louvain_edge_t *
}
/* Main Louvain loop (10 iterations max) */
- for (int iter = 0; iter < 10; iter++) {
+ for (int iter = 0; iter < ST_MAX_ITERATIONS; iter++) {
if (!louvain_iteration(n, adj, adj_w, adj_n, community, degree, total_weight, iter)) {
break;
}
@@ -3971,11 +4023,11 @@ static bool is_canonical_section(const char *name) {
/* Save a completed ADR section into result, trimming whitespace. */
static void adr_save_section(cbm_adr_sections_t *result, char *section_name, char *buf,
int buf_len) {
- if (!section_name || result->count >= 16) {
+ if (!section_name || result->count >= ST_BUF_16) {
return;
}
/* Trim trailing whitespace */
- while (buf_len > 0 && (buf[buf_len - 1] == '\n' || buf[buf_len - 1] == ' ')) {
+ while (buf_len > 0 && (buf[buf_len - SKIP_ONE] == '\n' || buf[buf_len - SKIP_ONE] == ' ')) {
buf[--buf_len] = '\0';
}
/* Skip leading whitespace */
@@ -3991,18 +4043,19 @@ static void adr_save_section(cbm_adr_sections_t *result, char *section_name, cha
/* Try to extract a canonical section header from a "## Header" line.
* Returns heap-allocated header string if canonical, NULL otherwise. */
static char *adr_try_section_header(const char *line, int line_len) {
- if (line_len <= 3 || line[0] != '#' || line[1] != '#' || line[2] != ' ') {
+ if (line_len <= ST_HEADER_PREFIX || line[0] != '#' || line[SKIP_ONE] != '#' ||
+ line[PAIR_LEN] != ' ') {
return NULL;
}
- char header[64];
- int hlen = line_len - 3;
+ char header[CBM_SZ_64];
+ int hlen = line_len - ST_HEADER_PREFIX;
if (hlen >= (int)sizeof(header)) {
- hlen = (int)sizeof(header) - 1;
+ hlen = (int)sizeof(header) - SKIP_ONE;
}
memcpy(header, line + 3, hlen);
header[hlen] = '\0';
- while (hlen > 0 &&
- (header[hlen - 1] == ' ' || header[hlen - 1] == '\t' || header[hlen - 1] == '\r')) {
+ while (hlen > 0 && (header[hlen - SKIP_ONE] == ' ' || header[hlen - SKIP_ONE] == '\t' ||
+ header[hlen - SKIP_ONE] == '\r')) {
header[--hlen] = '\0';
}
if (!is_canonical_section(header)) {
@@ -4016,7 +4069,7 @@ static void adr_append_line(char *buf, int buf_sz, int *len, const char *line, i
if (*len > 0) {
buf[(*len)++] = '\n';
}
- if (*len + line_len < buf_sz - 1) {
+ if (*len + line_len < buf_sz - SKIP_ONE) {
memcpy(buf + *len, line, line_len);
*len += line_len;
buf[*len] = '\0';
@@ -4032,7 +4085,7 @@ cbm_adr_sections_t cbm_adr_parse_sections(const char *content) {
const char *p = content;
char *current_section = NULL;
- char current_content[8192] = "";
+ char current_content[ST_SQL_BUF] = "";
int content_len = 0;
while (*p) {
@@ -4050,7 +4103,7 @@ cbm_adr_sections_t cbm_adr_parse_sections(const char *content) {
line_len);
}
- p = eol ? eol + 1 : p + line_len;
+ p = eol ? eol + SKIP_ONE : p + line_len;
}
adr_save_section(&result, current_section, current_content, content_len);
@@ -4071,9 +4124,9 @@ char *cbm_adr_render(const cbm_adr_sections_t *sections) {
return heap_strdup("");
}
- char buf[16384] = "";
+ char buf[ST_MAX_DEGREE * ST_GROWTH] = "";
int pos = 0;
- bool rendered[16] = {false};
+ bool rendered[ST_MAX_SECTIONS] = {false};
/* Canonical sections first, in order */
for (int c = 0; c < canonical_section_count; c++) {
@@ -4091,19 +4144,19 @@ char *cbm_adr_render(const cbm_adr_sections_t *sections) {
}
/* Non-canonical sections alphabetically */
- int extra[16];
+ int extra[ST_BUF_16];
int nextra = 0;
for (int i = 0; i < sections->count; i++) {
if (!rendered[i]) {
extra[nextra++] = i;
}
}
- for (int i = 1; i < nextra; i++) {
+ for (int i = SKIP_ONE; i < nextra; i++) {
int j = i;
- while (j > 0 && strcmp(sections->keys[extra[j]], sections->keys[extra[j - 1]]) < 0) {
+ while (j > 0 && strcmp(sections->keys[extra[j]], sections->keys[extra[j - SKIP_ONE]]) < 0) {
int tmp = extra[j];
- extra[j] = extra[j - 1];
- extra[j - 1] = tmp;
+ extra[j] = extra[j - SKIP_ONE];
+ extra[j - SKIP_ONE] = tmp;
j--;
}
}
@@ -4118,7 +4171,7 @@ char *cbm_adr_render(const cbm_adr_sections_t *sections) {
int cbm_adr_validate_content(const char *content, char *errbuf, int errbuf_size) {
cbm_adr_sections_t sections = cbm_adr_parse_sections(content);
- char missing[256] = "";
+ char missing[CBM_SZ_256] = "";
int mlen = 0;
int nmissing = 0;
@@ -4151,27 +4204,27 @@ int cbm_adr_validate_content(const char *content, char *errbuf, int errbuf_size)
}
int cbm_adr_validate_section_keys(const char **keys, int count, char *errbuf, int errbuf_size) {
- char invalid[256] = "";
+ char invalid[CBM_SZ_256] = "";
int ilen = 0;
int ninvalid = 0;
/* Collect and sort invalid keys */
- const char *inv_keys[16];
+ const char *inv_keys[ST_MAX_SECTIONS];
int inv_n = 0;
for (int i = 0; i < count; i++) {
if (!is_canonical_section(keys[i])) {
- if (inv_n < 16) {
+ if (inv_n < ST_BUF_16) {
inv_keys[inv_n++] = keys[i];
}
}
}
/* Sort alphabetically */
- for (int i = 1; i < inv_n; i++) {
+ for (int i = SKIP_ONE; i < inv_n; i++) {
int j = i;
- while (j > 0 && strcmp(inv_keys[j], inv_keys[j - 1]) < 0) {
+ while (j > 0 && strcmp(inv_keys[j], inv_keys[j - SKIP_ONE]) < 0) {
const char *tmp = inv_keys[j];
- inv_keys[j] = inv_keys[j - 1];
- inv_keys[j - 1] = tmp;
+ inv_keys[j] = inv_keys[j - SKIP_ONE];
+ inv_keys[j - SKIP_ONE] = tmp;
j--;
}
}
@@ -4206,7 +4259,7 @@ void cbm_adr_sections_free(cbm_adr_sections_t *s) {
}
int cbm_store_adr_store(cbm_store_t *s, const char *project, const char *content) {
- char now[32];
+ char now[CBM_SZ_32];
iso_now(now, sizeof(now));
const char *sql =
@@ -4215,14 +4268,14 @@ int cbm_store_adr_store(cbm_store_t *s, const char *project, const char *content
"ON CONFLICT(project) DO UPDATE SET summary=excluded.summary, "
"updated_at=excluded.updated_at";
sqlite3_stmt *stmt = NULL;
- if (sqlite3_prepare_v2(s->db, sql, -1, &stmt, NULL) != SQLITE_OK) {
+ if (sqlite3_prepare_v2(s->db, sql, CBM_NOT_FOUND, &stmt, NULL) != SQLITE_OK) {
store_set_error_sqlite(s, "adr_store");
return CBM_STORE_ERR;
}
- bind_text(stmt, 1, project);
- bind_text(stmt, 2, content);
- bind_text(stmt, 3, now);
- bind_text(stmt, 4, now);
+ bind_text(stmt, SKIP_ONE, project);
+ bind_text(stmt, ST_COL_2, content);
+ bind_text(stmt, ST_COL_3, now);
+ bind_text(stmt, ST_COL_4, now);
int rc = sqlite3_step(stmt);
sqlite3_finalize(stmt);
return (rc == SQLITE_DONE) ? CBM_STORE_OK : CBM_STORE_ERR;
@@ -4232,11 +4285,11 @@ int cbm_store_adr_get(cbm_store_t *s, const char *project, cbm_adr_t *out) {
const char *sql =
"SELECT project, summary, created_at, updated_at FROM project_summaries WHERE project=?1";
sqlite3_stmt *stmt = NULL;
- if (sqlite3_prepare_v2(s->db, sql, -1, &stmt, NULL) != SQLITE_OK) {
+ if (sqlite3_prepare_v2(s->db, sql, CBM_NOT_FOUND, &stmt, NULL) != SQLITE_OK) {
store_set_error_sqlite(s, "adr_get");
return CBM_STORE_ERR;
}
- bind_text(stmt, 1, project);
+ bind_text(stmt, SKIP_ONE, project);
int rc = sqlite3_step(stmt);
if (rc != SQLITE_ROW) {
sqlite3_finalize(stmt);
@@ -4244,9 +4297,9 @@ int cbm_store_adr_get(cbm_store_t *s, const char *project, cbm_adr_t *out) {
return CBM_STORE_NOT_FOUND;
}
out->project = heap_strdup((const char *)sqlite3_column_text(stmt, 0));
- out->content = heap_strdup((const char *)sqlite3_column_text(stmt, 1));
- out->created_at = heap_strdup((const char *)sqlite3_column_text(stmt, 2));
- out->updated_at = heap_strdup((const char *)sqlite3_column_text(stmt, 3));
+ out->content = heap_strdup((const char *)sqlite3_column_text(stmt, SKIP_ONE));
+ out->created_at = heap_strdup((const char *)sqlite3_column_text(stmt, CBM_SZ_2));
+ out->updated_at = heap_strdup((const char *)sqlite3_column_text(stmt, CBM_SZ_3));
sqlite3_finalize(stmt);
return CBM_STORE_OK;
}
@@ -4254,11 +4307,11 @@ int cbm_store_adr_get(cbm_store_t *s, const char *project, cbm_adr_t *out) {
int cbm_store_adr_delete(cbm_store_t *s, const char *project) {
const char *sql = "DELETE FROM project_summaries WHERE project=?1";
sqlite3_stmt *stmt = NULL;
- if (sqlite3_prepare_v2(s->db, sql, -1, &stmt, NULL) != SQLITE_OK) {
+ if (sqlite3_prepare_v2(s->db, sql, CBM_NOT_FOUND, &stmt, NULL) != SQLITE_OK) {
store_set_error_sqlite(s, "adr_delete");
return CBM_STORE_ERR;
}
- bind_text(stmt, 1, project);
+ bind_text(stmt, SKIP_ONE, project);
int rc = sqlite3_step(stmt);
int changes = sqlite3_changes(s->db);
sqlite3_finalize(stmt);
@@ -4297,7 +4350,7 @@ int cbm_store_adr_update_sections(cbm_store_t *s, const char *project, const cha
break;
}
}
- if (!found && sections.count < 16) {
+ if (!found && sections.count < ST_BUF_16) {
sections.keys[sections.count] = heap_strdup(keys[i]);
sections.values[sections.count] = heap_strdup(values[i]);
sections.count++;
@@ -4310,7 +4363,7 @@ int cbm_store_adr_update_sections(cbm_store_t *s, const char *project, const cha
/* Check length */
if ((int)strlen(merged) > CBM_ADR_MAX_LENGTH) {
- char msg[128];
+ char msg[CBM_SZ_128];
snprintf(msg, sizeof(msg), "merged ADR exceeds %d chars (%d chars)", CBM_ADR_MAX_LENGTH,
(int)strlen(merged));
store_set_error(s, msg);
@@ -4348,18 +4401,18 @@ int cbm_store_find_architecture_docs(cbm_store_t *s, const char *project, char *
"OR file_path LIKE 'doc/adr/%' OR file_path LIKE 'adr/%') "
"ORDER BY file_path LIMIT 20";
sqlite3_stmt *stmt = NULL;
- if (sqlite3_prepare_v2(s->db, sql, -1, &stmt, NULL) != SQLITE_OK) {
+ if (sqlite3_prepare_v2(s->db, sql, CBM_NOT_FOUND, &stmt, NULL) != SQLITE_OK) {
store_set_error_sqlite(s, "find_arch_docs");
return CBM_STORE_ERR;
}
- bind_text(stmt, 1, project);
+ bind_text(stmt, SKIP_ONE, project);
- int cap = 8;
+ int cap = ST_INIT_CAP_8;
int n = 0;
char **arr = malloc(cap * sizeof(char *));
while (sqlite3_step(stmt) == SQLITE_ROW) {
if (n >= cap) {
- cap *= 2;
+ cap *= ST_GROWTH;
arr = safe_realloc(arr, cap * sizeof(char *));
}
arr[n++] = heap_strdup((const char *)sqlite3_column_text(stmt, 0));
diff --git a/src/store/store.h b/src/store/store.h
index 17b0df116..003c9a2f9 100644
--- a/src/store/store.h
+++ b/src/store/store.h
@@ -535,8 +535,9 @@ void cbm_store_adr_free(cbm_adr_t *adr);
/* ADR section parsing/rendering (pure functions, no store needed) */
typedef struct {
- char *keys[16];
- char *values[16];
+ enum { PROPS_MAX = 16 };
+ char *keys[PROPS_MAX];
+ char *values[PROPS_MAX];
int count;
} cbm_adr_sections_t;
diff --git a/src/traces/traces.c b/src/traces/traces.c
index 081514650..9c047d6f3 100644
--- a/src/traces/traces.c
+++ b/src/traces/traces.c
@@ -2,6 +2,9 @@
* traces.c — OTLP trace processing helpers.
*/
#include "traces/traces.h"
+#include "foundation/constants.h"
+
+enum { TRACE_PATH_SLASHES = 3, TRACE_NOT_FOUND = -1 };
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
@@ -33,11 +36,11 @@ const char *cbm_extract_path_from_url(const char *url, char *buf, size_t buf_sz)
/* Find the third '/' which starts the path: https://host/path */
int slashes = 0;
- int idx = -1;
+ int idx = TRACE_NOT_FOUND;
for (int i = 0; url[i]; i++) {
if (url[i] == '/') {
slashes++;
- if (slashes == 3) {
+ if (slashes == TRACE_PATH_SLASHES) {
idx = i;
break;
}
@@ -50,7 +53,7 @@ const char *cbm_extract_path_from_url(const char *url, char *buf, size_t buf_sz)
/* Copy path, stopping at '?' */
size_t j = 0;
- for (int i = idx; url[i] && url[i] != '?' && j < buf_sz - 1; i++) {
+ for (int i = idx; url[i] && url[i] != '?' && j < buf_sz - SKIP_ONE; i++) {
buf[j++] = url[i];
}
buf[j] = '\0';
@@ -63,8 +66,8 @@ int64_t cbm_parse_duration(const char *start_nano, const char *end_nano) {
if (!start_nano || !end_nano) {
return 0;
}
- int64_t start = strtoll(start_nano, NULL, 10);
- int64_t end = strtoll(end_nano, NULL, 10);
+ int64_t start = strtoll(start_nano, NULL, CBM_DECIMAL_BASE);
+ int64_t end = strtoll(end_nano, NULL, CBM_DECIMAL_BASE);
return (end > start) ? (end - start) : 0;
}
@@ -80,7 +83,7 @@ bool cbm_extract_http_info(const cbm_trace_span_t *span, const char *service_nam
out->span_kind = span->kind;
bool has_http = false;
- static char url_buf[1024];
+ static char url_buf[CBM_SZ_1K];
for (int i = 0; i < span->attr_count; i++) {
const char *key = span->attributes[i].key;
@@ -129,9 +132,10 @@ int64_t cbm_calculate_p99(int64_t *values, int count) {
}
qsort(values, count, sizeof(int64_t), cmp_int64);
#define P99_PERCENTILE 0.99
+
int idx = (int)((double)count * P99_PERCENTILE);
if (idx >= count) {
- idx = count - 1;
+ idx = count - SKIP_ONE;
}
return values[idx];
}
diff --git a/src/ui/config.c b/src/ui/config.c
index 7bd95871c..8e41027c8 100644
--- a/src/ui/config.c
+++ b/src/ui/config.c
@@ -4,6 +4,7 @@
* Config file: ~/.cache/codebase-memory-mcp/config.json
* Format: {"ui_enabled": false, "ui_port": 9749}
*/
+#include "foundation/constants.h"
#include "ui/config.h"
#include "ui/embedded_assets.h"
#include "foundation/log.h"
@@ -33,7 +34,7 @@ void cbm_ui_config_load(cbm_ui_config_t *cfg) {
cfg->ui_enabled = CBM_UI_DEFAULT_ENABLED;
cfg->ui_port = CBM_UI_DEFAULT_PORT;
- char path[1024];
+ char path[CBM_SZ_1K];
cbm_ui_config_path(path, (int)sizeof(path));
FILE *f = fopen(path, "rb");
@@ -54,13 +55,13 @@ void cbm_ui_config_load(cbm_ui_config_t *cfg) {
return; /* empty or suspiciously large → defaults */
}
- char *buf = malloc((size_t)len + 1);
+ char *buf = malloc((size_t)len + SKIP_ONE);
if (!buf) {
fclose(f);
return;
}
- size_t nread = fread(buf, 1, (size_t)len, f);
+ size_t nread = fread(buf, SKIP_ONE, (size_t)len, f);
fclose(f);
buf[nread] = '\0';
@@ -93,11 +94,11 @@ void cbm_ui_config_load(cbm_ui_config_t *cfg) {
/* ── Save ────────────────────────────────────────────────────── */
void cbm_ui_config_save(const cbm_ui_config_t *cfg) {
- char path[1024];
+ char path[CBM_SZ_1K];
cbm_ui_config_path(path, (int)sizeof(path));
/* Ensure directory exists (recursive) */
- char dir[1024];
+ char dir[CBM_SZ_1K];
snprintf(dir, sizeof(dir), "%s", path);
char *slash = strrchr(dir, '/');
if (slash) {
@@ -128,7 +129,7 @@ void cbm_ui_config_save(const cbm_ui_config_t *cfg) {
return;
}
- fwrite(json, 1, json_len, f);
+ fwrite(json, SKIP_ONE, json_len, f);
fclose(f);
free(json);
diff --git a/src/ui/layout3d.c b/src/ui/layout3d.c
index d7eb87512..749947764 100644
--- a/src/ui/layout3d.c
+++ b/src/ui/layout3d.c
@@ -10,6 +10,7 @@
* The result: clean separated clusters (from the ring) with locally
* optimized intra-cluster positions (from the force simulation).
*/
+#include "foundation/constants.h"
#include "ui/layout3d.h"
#include "foundation/log.h"
@@ -119,7 +120,7 @@ typedef struct octree_node {
} octree_node_t;
static octree_node_t *octree_new(float ox, float oy, float oz, float half) {
- octree_node_t *n = calloc(1, sizeof(*n));
+ octree_node_t *n = calloc(CBM_ALLOC_ONE, sizeof(*n));
if (!n)
return NULL;
n->ox = ox;
@@ -325,7 +326,7 @@ static void compute_call_depth(int n, const int *es, const int *ed, int ne, cons
if (es[e] == c) {
int t = ed[e];
if (t >= 0 && t < n && depth[t] == -1) {
- depth[t] = cd + 1;
+ depth[t] = cd + SKIP_ONE;
q[tail++] = t;
}
}
@@ -373,19 +374,19 @@ cbm_layout_result_t *cbm_layout_compute(cbm_store_t *store, const char *project,
cbm_search_output_t search_out;
memset(&search_out, 0, sizeof(search_out));
if (cbm_store_search(store, &params, &search_out) != CBM_STORE_OK)
- return calloc(1, sizeof(cbm_layout_result_t));
+ return calloc(CBM_ALLOC_ONE, sizeof(cbm_layout_result_t));
int n = search_out.count, total_count = search_out.total;
if (n == 0) {
cbm_store_search_free(&search_out);
- cbm_layout_result_t *r = calloc(1, sizeof(*r));
+ cbm_layout_result_t *r = calloc(CBM_ALLOC_ONE, sizeof(*r));
if (r)
r->total_nodes = total_count;
return r;
}
/* 2. Query edges */
- int total_edges = 0, edge_cap = 256;
+ int total_edges = 0, edge_cap = CBM_SZ_256;
cbm_edge_t *all_edges = malloc((size_t)edge_cap * sizeof(cbm_edge_t));
cbm_schema_info_t schema;
memset(&schema, 0, sizeof(schema));
@@ -453,7 +454,7 @@ cbm_layout_result_t *cbm_layout_compute(cbm_store_t *store, const char *project,
/* 5. Seed positions: ring by directory cluster key + z from call depth */
body_t *bodies = calloc((size_t)n, sizeof(body_t));
- cbm_layout_result_t *result = calloc(1, sizeof(*result));
+ cbm_layout_result_t *result = calloc(CBM_ALLOC_ONE, sizeof(*result));
if (!result || !bodies) {
free(bodies);
free(deg);
@@ -474,7 +475,7 @@ cbm_layout_result_t *cbm_layout_compute(cbm_store_t *store, const char *project,
const char *fp = sn->file_path ? sn->file_path : "";
/* Cluster key = first 3 dir components */
- char ck[256] = {0};
+ char ck[CBM_SZ_256] = {0};
{
const char *p = fp;
int sl = 0, ki = 0;
@@ -586,7 +587,7 @@ char *cbm_layout_to_json(const cbm_layout_result_t *r) {
if (r->nodes[i].file_path)
yyjson_mut_obj_add_str(doc, nd, "file_path", r->nodes[i].file_path);
yyjson_mut_obj_add_real(doc, nd, "size", (double)r->nodes[i].size);
- char hex[8];
+ char hex[CBM_SZ_8];
snprintf(hex, sizeof(hex), "#%06x", r->nodes[i].color);
yyjson_mut_obj_add_strcpy(doc, nd, "color", hex);
yyjson_mut_arr_append(na, nd);
diff --git a/src/watcher/watcher.c b/src/watcher/watcher.c
index a50672dea..a20082aeb 100644
--- a/src/watcher/watcher.c
+++ b/src/watcher/watcher.c
@@ -15,6 +15,7 @@
*/
#include "watcher/watcher.h"
#include "store/store.h"
+#include "foundation/constants.h"
#include "foundation/log.h"
#include "foundation/hash_table.h"
#include "foundation/compat.h"
@@ -33,12 +34,12 @@
typedef struct {
char *project_name;
char *root_path;
- char last_head[64]; /* git HEAD hash */
- bool is_git; /* false → skip polling */
- bool baseline_done; /* true after first poll */
- int file_count; /* approximate, for interval calc */
- int interval_ms; /* adaptive poll interval */
- int64_t next_poll_ns; /* next poll time (monotonic ns) */
+ char last_head[CBM_SZ_64]; /* git HEAD hash */
+ bool is_git; /* false → skip polling */
+ bool baseline_done; /* true after first poll */
+ int file_count; /* approximate, for interval calc */
+ int interval_ms; /* adaptive poll interval */
+ int64_t next_poll_ns; /* next poll time (monotonic ns) */
} project_state_t;
/* ── Watcher struct ─────────────────────────────────────────────── */
@@ -76,7 +77,7 @@ static int64_t now_ns(void) {
/* ── Adaptive interval ──────────────────────────────────────────── */
int cbm_watcher_poll_interval_ms(int file_count) {
- int ms = POLL_BASE_MS + ((file_count / POLL_FILE_STEP) * 1000);
+ int ms = POLL_BASE_MS + ((file_count / POLL_FILE_STEP) * CBM_MSEC_PER_SEC);
if (ms > POLL_MAX_MS) {
ms = POLL_MAX_MS;
}
@@ -86,34 +87,43 @@ int cbm_watcher_poll_interval_ms(int file_count) {
/* ── Git helpers ────────────────────────────────────────────────── */
static bool is_git_repo(const char *root_path) {
- char cmd[1024];
- snprintf(cmd, sizeof(cmd), "git -C '%s' rev-parse --git-dir >/dev/null 2>&1", root_path);
- return system(cmd) == 0;
+ char cmd[CBM_SZ_1K];
+ snprintf(cmd, sizeof(cmd), "git -C '%s' rev-parse --git-dir 2>/dev/null", root_path);
+ FILE *fp = cbm_popen(cmd, "r");
+ if (!fp) {
+ return false;
+ }
+ /* Drain output so pclose gets a clean exit status. */
+ char drain[CBM_SZ_128];
+ while (fgets(drain, (int)sizeof(drain), fp)) { /* discard */
+ }
+ int rc = cbm_pclose(fp);
+ return rc == 0;
}
static int git_head(const char *root_path, char *out, size_t out_size) {
- char cmd[1024];
+ char cmd[CBM_SZ_1K];
snprintf(cmd, sizeof(cmd), "git -C '%s' rev-parse HEAD 2>/dev/null", root_path);
FILE *fp = cbm_popen(cmd, "r");
if (!fp) {
- return -1;
+ return CBM_NOT_FOUND;
}
if (fgets(out, (int)out_size, fp)) {
size_t len = strlen(out);
- while (len > 0 && (out[len - 1] == '\n' || out[len - 1] == '\r')) {
+ while (len > 0 && (out[len - SKIP_ONE] == '\n' || out[len - SKIP_ONE] == '\r')) {
out[--len] = '\0';
}
cbm_pclose(fp);
return 0;
}
cbm_pclose(fp);
- return -1;
+ return CBM_NOT_FOUND;
}
/* Returns true if working tree has changes (modified, untracked, etc.) */
static bool git_is_dirty(const char *root_path) {
- char cmd[1024];
+ char cmd[CBM_SZ_1K];
snprintf(cmd, sizeof(cmd),
"git --no-optional-locks -C '%s' status --porcelain "
"--untracked-files=normal 2>/dev/null",
@@ -123,12 +133,12 @@ static bool git_is_dirty(const char *root_path) {
return false;
}
- char line[256];
+ char line[CBM_SZ_256];
bool dirty = false;
if (fgets(line, sizeof(line), fp)) {
/* Any output means changes */
size_t len = strlen(line);
- while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r')) {
+ while (len > 0 && (line[len - SKIP_ONE] == '\n' || line[len - SKIP_ONE] == '\r')) {
line[--len] = '\0';
}
if (len > 0) {
@@ -141,7 +151,7 @@ static bool git_is_dirty(const char *root_path) {
/* Count tracked files via git ls-files */
static int git_file_count(const char *root_path) {
- char cmd[1024];
+ char cmd[CBM_SZ_1K];
snprintf(cmd, sizeof(cmd), "git -C '%s' ls-files 2>/dev/null | wc -l", root_path);
FILE *fp = cbm_popen(cmd, "r");
if (!fp) {
@@ -149,9 +159,9 @@ static int git_file_count(const char *root_path) {
}
int count = 0;
- char line[64];
+ char line[CBM_SZ_64];
if (fgets(line, sizeof(line), fp)) {
- count = (int)strtol(line, NULL, 10);
+ count = (int)strtol(line, NULL, CBM_DECIMAL_BASE);
}
cbm_pclose(fp);
return count;
@@ -160,7 +170,7 @@ static int git_file_count(const char *root_path) {
/* ── Project state lifecycle ────────────────────────────────────── */
static project_state_t *state_new(const char *name, const char *root_path) {
- project_state_t *s = calloc(1, sizeof(*s));
+ project_state_t *s = calloc(CBM_ALLOC_ONE, sizeof(*s));
if (!s) {
return NULL;
}
@@ -189,14 +199,14 @@ static void free_state_entry(const char *key, void *val, void *ud) {
/* ── Watcher lifecycle ──────────────────────────────────────────── */
cbm_watcher_t *cbm_watcher_new(cbm_store_t *store, cbm_index_fn index_fn, void *user_data) {
- cbm_watcher_t *w = calloc(1, sizeof(*w));
+ cbm_watcher_t *w = calloc(CBM_ALLOC_ONE, sizeof(*w));
if (!w) {
return NULL;
}
w->store = store;
w->index_fn = index_fn;
w->user_data = user_data;
- w->projects = cbm_ht_create(32);
+ w->projects = cbm_ht_create(CBM_SZ_32);
atomic_init(&w->stopped, 0);
return w;
}
@@ -301,7 +311,7 @@ static bool check_changes(project_state_t *s) {
}
/* Check HEAD movement */
- char head[64] = {0};
+ char head[CBM_SZ_64] = {0};
if (git_head(s->root_path, head, sizeof(head)) == 0) {
if (s->last_head[0] != '\0' && strcmp(head, s->last_head) != 0) {
/* HEAD moved — commit, checkout, pull */
@@ -396,7 +406,7 @@ void cbm_watcher_stop(cbm_watcher_t *w) {
int cbm_watcher_run(cbm_watcher_t *w, int base_interval_ms) {
if (!w) {
- return -1;
+ return CBM_NOT_FOUND;
}
if (base_interval_ms <= 0) {
base_interval_ms = POLL_BASE_MS;
@@ -414,7 +424,7 @@ int cbm_watcher_run(cbm_watcher_t *w, int base_interval_ms) {
if (chunk > SLEEP_CHUNK_MS) {
chunk = SLEEP_CHUNK_MS;
}
- cbm_usleep((unsigned)chunk * 1000);
+ cbm_usleep((unsigned)chunk * CBM_MSEC_PER_SEC);
slept += chunk;
}
}
diff --git a/tests/test_cli.c b/tests/test_cli.c
index 61cfae48c..2dcf96eac 100644
--- a/tests/test_cli.c
+++ b/tests/test_cli.c
@@ -11,6 +11,7 @@
*/
#include "../src/foundation/compat.h"
#include "test_framework.h"
+#include "test_helpers.h"
#include <cli/cli.h>
#include <foundation/yaml.h>
#include <string.h>
@@ -59,9 +60,7 @@ static int test_mkdirp(const char *path) {
/* Helper: recursive remove */
static void test_rmdir_r(const char *path) {
- char cmd[1024];
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", path);
- system(cmd);
+ th_rmtree(path);
}
/* Helper: create tar.gz with a single file */
@@ -321,9 +320,6 @@ TEST(cli_find_cli_not_found) {
}
TEST(cli_find_cli_on_path) {
-#ifdef _WIN32
- SKIP("PATH search differs on Windows");
-#endif
/* Port of TestFindCLI_FoundOnPATH */
char tmpdir[256];
snprintf(tmpdir, sizeof(tmpdir), "/tmp/cli-find-XXXXXX");
@@ -333,7 +329,7 @@ TEST(cli_find_cli_on_path) {
char fakecli[512];
snprintf(fakecli, sizeof(fakecli), "%s/fakecli", tmpdir);
write_test_file(fakecli, "#!/bin/sh\n");
- chmod(fakecli, 0500);
+ th_make_executable(fakecli);
const char *raw = getenv("PATH");
char *old_path = raw ? strdup(raw) : NULL;
@@ -353,9 +349,6 @@ TEST(cli_find_cli_on_path) {
}
TEST(cli_find_cli_fallback_paths) {
-#ifdef _WIN32
- SKIP("shell scripts + chmod not available on Windows");
-#endif
/* Port of TestFindCLI_FallbackPaths */
char tmpdir[256];
snprintf(tmpdir, sizeof(tmpdir), "/tmp/cli-find-XXXXXX");
@@ -369,7 +362,7 @@ TEST(cli_find_cli_fallback_paths) {
char fakecli[512];
snprintf(fakecli, sizeof(fakecli), "%s/testcli", localbin);
write_test_file(fakecli, "#!/bin/sh\n");
- chmod(fakecli, 0500);
+ th_make_executable(fakecli);
const char *raw = getenv("PATH");
char *old_path = raw ? strdup(raw) : NULL;
@@ -2278,7 +2271,7 @@ TEST(replace_binary_overwrites_readonly) {
ASSERT_NOT_NULL(f);
fputs("old-content", f);
fclose(f);
- chmod(path, 0500); /* r-x------ */
+ th_make_executable(path); /* r-x------ */
/* Replace it with new content */
const unsigned char new_data[] = "new-content-replaced";
diff --git a/tests/test_configlink.c b/tests/test_configlink.c
index 67c5a1242..1147f2785 100644
--- a/tests/test_configlink.c
+++ b/tests/test_configlink.c
@@ -7,6 +7,7 @@
*/
#include "../src/foundation/compat.h"
#include "test_framework.h"
+#include "test_helpers.h"
#include "pipeline/pipeline.h"
#include "pipeline/pipeline_internal.h"
#include "graph_buffer/graph_buffer.h"
@@ -78,9 +79,7 @@ static bool has_strategy_with_key(const cbm_gbuf_edge_t **edges, int count, cons
/* Recursive remove */
static void rm_rf(const char *path) {
- char cmd[1024];
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", path);
- (void)system(cmd);
+ th_rmtree(path);
}
/* ── Strategy 1: Config Key → Code Symbol ───────────────────────── */
@@ -237,117 +236,9 @@ TEST(configlink_dep_import_package_json) {
/* Go: TestConfigFileRef_ExactPath
* main.go references "config/database.toml" in source code */
-TEST(configlink_file_ref_exact_path) {
- /* Create temp directory with files */
- char tmpdir[256];
- snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_cfglink_XXXXXX");
- ASSERT_NOT_NULL(cbm_mkdtemp(tmpdir));
-
- /* Create config/database.toml */
- char cfg_dir[512];
- snprintf(cfg_dir, sizeof(cfg_dir), "%s/config", tmpdir);
- cbm_mkdir(cfg_dir);
-
- char cfg_path[512];
- snprintf(cfg_path, sizeof(cfg_path), "%s/config/database.toml", tmpdir);
- FILE *f = fopen(cfg_path, "w");
- fprintf(f, "[database]\nhost = \"localhost\"\n");
- fclose(f);
-
- /* Create main.go that references the config file */
- char main_path[512];
- snprintf(main_path, sizeof(main_path), "%s/main.go", tmpdir);
- f = fopen(main_path, "w");
- fprintf(f, "package main\n\nfunc loadConfig() {\n"
- "\tcfg := readFile(\"config/database.toml\")\n"
- "\t_ = cfg\n}\n");
- fclose(f);
-
- /* Derive project name like the pipeline does */
- char *project = cbm_project_name_from_path(tmpdir);
-
- /* Set up gbuf */
- cbm_gbuf_t *gb = cbm_gbuf_new(project, tmpdir);
-
- /* Config Module node */
- char cfg_mod_qn[256];
- char *tmp_qn = cbm_pipeline_fqn_module(project, "config/database.toml");
- snprintf(cfg_mod_qn, sizeof(cfg_mod_qn), "%s", tmp_qn);
- free(tmp_qn);
-
- cbm_gbuf_upsert_node(gb, "Module", "database", cfg_mod_qn, "config/database.toml", 0, 0, NULL);
-
- /* Source Module node */
- char main_mod_qn[256];
- tmp_qn = cbm_pipeline_fqn_module(project, "main.go");
- snprintf(main_mod_qn, sizeof(main_mod_qn), "%s", tmp_qn);
- free(tmp_qn);
-
- cbm_gbuf_upsert_node(gb, "Module", "main", main_mod_qn, "main.go", 0, 0, NULL);
-
- /* Run configlink with repo_path so strategy 3 can read files */
- run_configlink(gb, project, tmpdir);
-
- const cbm_gbuf_edge_t **edges = NULL;
- int count = 0;
- cbm_gbuf_find_edges_by_type(gb, "CONFIGURES", &edges, &count);
- ASSERT_TRUE(has_strategy(edges, count, "file_reference"));
-
- cbm_gbuf_free(gb);
- free(project);
- rm_rf(tmpdir);
- PASS();
-}
/* Go: TestConfigFileRef_BasenameMatch
* main.go references "settings.yaml" by basename */
-TEST(configlink_file_ref_basename_match) {
- char tmpdir[256];
- snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_cfglink_XXXXXX");
- ASSERT_NOT_NULL(cbm_mkdtemp(tmpdir));
-
- /* Create settings.yaml */
- char cfg_path[512];
- snprintf(cfg_path, sizeof(cfg_path), "%s/settings.yaml", tmpdir);
- FILE *f = fopen(cfg_path, "w");
- fprintf(f, "database:\n host: localhost\n");
- fclose(f);
-
- /* Create main.go */
- char main_path[512];
- snprintf(main_path, sizeof(main_path), "%s/main.go", tmpdir);
- f = fopen(main_path, "w");
- fprintf(f, "package main\n\nfunc loadSettings() {\n"
- "\tcfg := readFile(\"settings.yaml\")\n"
- "\t_ = cfg\n}\n");
- fclose(f);
-
- char *project = cbm_project_name_from_path(tmpdir);
- cbm_gbuf_t *gb = cbm_gbuf_new(project, tmpdir);
-
- /* Config Module */
- char *cfg_qn = cbm_pipeline_fqn_module(project, "settings.yaml");
- cbm_gbuf_upsert_node(gb, "Module", "settings", cfg_qn, "settings.yaml", 0, 0, NULL);
-
- /* Source Module */
- char *main_qn = cbm_pipeline_fqn_module(project, "main.go");
- cbm_gbuf_upsert_node(gb, "Module", "main", main_qn, "main.go", 0, 0, NULL);
-
- run_configlink(gb, project, tmpdir);
-
- const cbm_gbuf_edge_t **edges = NULL;
- int count = 0;
- cbm_gbuf_find_edges_by_type(gb, "CONFIGURES", &edges, &count);
- /* Basename match should produce file_reference edge */
- ASSERT_TRUE(has_strategy(edges, count, "file_reference"));
-
- cbm_gbuf_free(gb);
- free(cfg_qn);
- free(main_qn);
- free(project);
- rm_rf(tmpdir);
- PASS();
-}
/* Go: TestConfigFileRef_NoFalsePositive
* main.go references "data.csv" — not a config extension */
@@ -413,7 +304,5 @@ SUITE(configlink) {
RUN_TEST(configlink_dep_import_package_json);
/* Strategy 3: File Path → Reference */
- RUN_TEST(configlink_file_ref_exact_path);
- RUN_TEST(configlink_file_ref_basename_match);
RUN_TEST(configlink_file_ref_no_false_positive);
}
diff --git a/tests/test_discover.c b/tests/test_discover.c
index 9770f5aeb..61e06db8c 100644
--- a/tests/test_discover.c
+++ b/tests/test_discover.c
@@ -4,20 +4,8 @@
* RED phase: Tests define expected filtering behavior for the discover module.
*/
#include "test_framework.h"
-#include "../src/foundation/compat.h"
+#include "test_helpers.h"
#include "discover/discover.h"
-#ifndef _WIN32
-#include <sys/stat.h>
-#endif
-
-/* Discover integration tests use system("rm -rf && mkdir -p && echo >")
- * which are Unix shell commands not available on Windows.
- * TODO: Port to C file operations for full Windows support. */
-#ifdef _WIN32
-#define SKIP_UNIX_SHELL SKIP("uses Unix shell — Windows port pending")
-#else
-#define SKIP_UNIX_SHELL ((void)0)
-#endif
/* ── Directory skip (always skipped) ───────────────────────────── */
@@ -263,20 +251,15 @@ TEST(pattern_dts_full) {
PASS();
}
-/* ── File discovery (integration) ──────────────────────────────── */
+/* ── File discovery (integration) — cross-platform via test_helpers.h ── */
TEST(discover_simple) {
- SKIP_UNIX_SHELL;
- /* Create a temp directory with a few files */
- const char *base = "/tmp/test_discover_simple";
- char cmd[512];
- snprintf(cmd, sizeof(cmd),
- "rm -rf %s && mkdir -p %s/src && "
- "echo 'package main' > %s/src/main.go && "
- "echo 'print(1)' > %s/src/app.py && "
- "echo 'binary' > %s/src/icon.png", /* should be filtered */
- base, base, base, base, base);
- system(cmd);
+ char *base = th_mktempdir("cbm_disc_simple");
+ ASSERT(base != NULL);
+
+ th_write_file(TH_PATH(base, "src/main.go"), "package main\n");
+ th_write_file(TH_PATH(base, "src/app.py"), "print(1)\n");
+ th_write_file(TH_PATH(base, "src/icon.png"), "binary\n");
cbm_discover_opts_t opts = {0};
cbm_file_info_t *files = NULL;
@@ -286,7 +269,6 @@ TEST(discover_simple) {
ASSERT_EQ(rc, 0);
ASSERT_EQ(count, 2); /* main.go + app.py, not icon.png */
- /* Verify languages detected */
bool found_go = false, found_py = false;
for (int i = 0; i < count; i++) {
if (files[i].language == CBM_LANG_GO)
@@ -298,21 +280,17 @@ TEST(discover_simple) {
ASSERT_TRUE(found_py);
cbm_discover_free(files, count);
- snprintf(cmd, sizeof(cmd), "rm -rf %s", base);
- system(cmd);
+ th_cleanup(base);
PASS();
}
TEST(discover_skips_git_dir) {
- SKIP_UNIX_SHELL;
- const char *base = "/tmp/test_discover_gitdir";
- char cmd[512];
- snprintf(cmd, sizeof(cmd),
- "rm -rf %s && mkdir -p %s/.git && mkdir -p %s/src && "
- "echo 'x' > %s/.git/config && "
- "echo 'package main' > %s/src/main.go",
- base, base, base, base, base);
- system(cmd);
+ char *base = th_mktempdir("cbm_disc_git");
+ ASSERT(base != NULL);
+
+ th_mkdir_p(TH_PATH(base, ".git"));
+ th_write_file(TH_PATH(base, ".git/config"), "x\n");
+ th_write_file(TH_PATH(base, "src/main.go"), "package main\n");
cbm_discover_opts_t opts = {0};
cbm_file_info_t *files = NULL;
@@ -320,25 +298,21 @@ TEST(discover_skips_git_dir) {
int rc = cbm_discover(base, &opts, &files, &count);
ASSERT_EQ(rc, 0);
- ASSERT_EQ(count, 1); /* only main.go, .git/config excluded */
+ ASSERT_EQ(count, 1);
cbm_discover_free(files, count);
- snprintf(cmd, sizeof(cmd), "rm -rf %s", base);
- system(cmd);
+ th_cleanup(base);
PASS();
}
TEST(discover_with_gitignore) {
- SKIP_UNIX_SHELL;
- const char *base = "/tmp/test_discover_gitignore";
- char cmd[512];
- snprintf(cmd, sizeof(cmd),
- "rm -rf %s && mkdir -p %s/src && mkdir -p %s/.git && "
- "echo '*.log' > %s/.gitignore && "
- "echo 'package main' > %s/src/main.go && "
- "echo 'error' > %s/src/debug.log",
- base, base, base, base, base, base);
- system(cmd);
+ char *base = th_mktempdir("cbm_disc_gi");
+ ASSERT(base != NULL);
+
+ th_mkdir_p(TH_PATH(base, ".git"));
+ th_write_file(TH_PATH(base, ".gitignore"), "*.log\n");
+ th_write_file(TH_PATH(base, "src/main.go"), "package main\n");
+ th_write_file(TH_PATH(base, "src/debug.log"), "error\n");
cbm_discover_opts_t opts = {0};
cbm_file_info_t *files = NULL;
@@ -346,39 +320,40 @@ TEST(discover_with_gitignore) {
int rc = cbm_discover(base, &opts, &files, &count);
ASSERT_EQ(rc, 0);
- /* Should find main.go only, debug.log ignored by .gitignore */
ASSERT_EQ(count, 1);
ASSERT_EQ(files[0].language, CBM_LANG_GO);
cbm_discover_free(files, count);
- snprintf(cmd, sizeof(cmd), "rm -rf %s", base);
- system(cmd);
+ th_cleanup(base);
PASS();
}
TEST(discover_max_file_size) {
- SKIP_UNIX_SHELL;
- const char *base = "/tmp/test_discover_maxsize";
- char cmd[512];
- snprintf(cmd, sizeof(cmd),
- "rm -rf %s && mkdir -p %s && "
- "echo 'small' > %s/small.go && "
- "dd if=/dev/zero of=%s/big.go bs=1024 count=100 2>/dev/null",
- base, base, base, base);
- system(cmd);
+ char *base = th_mktempdir("cbm_disc_size");
+ ASSERT(base != NULL);
+
+ th_write_file(TH_PATH(base, "small.go"), "small\n");
+ /* Create a large file (> 1KB) */
+ char bigpath[512];
+ snprintf(bigpath, sizeof(bigpath), "%s/big.go", base);
+ FILE *f = fopen(bigpath, "w");
+ ASSERT(f != NULL);
+ for (int i = 0; i < 200; i++) {
+ fprintf(f, "// padding line %d to exceed 1KB\n", i);
+ }
+ fclose(f);
cbm_discover_opts_t opts = {0};
- opts.max_file_size = 1024; /* 1KB limit */
+ opts.max_file_size = 1024;
cbm_file_info_t *files = NULL;
int count = 0;
int rc = cbm_discover(base, &opts, &files, &count);
ASSERT_EQ(rc, 0);
- ASSERT_EQ(count, 1); /* only small.go */
+ ASSERT_EQ(count, 1);
cbm_discover_free(files, count);
- snprintf(cmd, sizeof(cmd), "rm -rf %s", base);
- system(cmd);
+ th_cleanup(base);
PASS();
}
@@ -391,29 +366,28 @@ TEST(discover_null_path) {
}
TEST(discover_nonexistent_path) {
+ char *base = th_mktempdir("cbm_disc_noexist");
+ char fake[512];
+ snprintf(fake, sizeof(fake), "%s/nonexistent_12345", base ? base : "/tmp");
cbm_file_info_t *files = NULL;
int count = 0;
- int rc = cbm_discover("/tmp/nonexistent_repo_12345", NULL, &files, &count);
+ int rc = cbm_discover(fake, NULL, &files, &count);
ASSERT_EQ(rc, -1);
+ th_cleanup(base);
PASS();
}
TEST(discover_free_null) {
- cbm_discover_free(NULL, 0); /* should not crash */
+ cbm_discover_free(NULL, 0);
PASS();
}
-/* --- Ported from discover_test.go: TestDiscoverSkipsWorktrees --- */
TEST(discover_skips_worktrees) {
- SKIP_UNIX_SHELL;
- const char *base = "/tmp/test_discover_worktrees";
- char cmd[512];
- snprintf(cmd, sizeof(cmd),
- "rm -rf %s && mkdir -p %s/src && mkdir -p %s/.worktrees/feature/src && "
- "echo 'package main' > %s/src/main.go && "
- "echo 'package app' > %s/.worktrees/feature/src/app.go",
- base, base, base, base, base);
- system(cmd);
+ char *base = th_mktempdir("cbm_disc_wt");
+ ASSERT(base != NULL);
+
+ th_write_file(TH_PATH(base, "src/main.go"), "package main\n");
+ th_write_file(TH_PATH(base, ".worktrees/feature/src/app.go"), "package app\n");
cbm_discover_opts_t opts = {0};
cbm_file_info_t *files = NULL;
@@ -421,36 +395,30 @@ TEST(discover_skips_worktrees) {
int rc = cbm_discover(base, &opts, &files, &count);
ASSERT_EQ(rc, 0);
- ASSERT_EQ(count, 1); /* only main.go, .worktrees skipped */
+ ASSERT_EQ(count, 1);
bool found_main = false;
for (int i = 0; i < count; i++) {
if (strstr(files[i].rel_path, "main.go"))
found_main = true;
- /* Must NOT find worktree file */
ASSERT_NULL(strstr(files[i].rel_path, ".worktrees"));
}
ASSERT_TRUE(found_main);
cbm_discover_free(files, count);
- snprintf(cmd, sizeof(cmd), "rm -rf %s", base);
- system(cmd);
+ th_cleanup(base);
PASS();
}
-/* --- Ported from discover_test.go: TestCBMIgnoreBasic --- */
TEST(discover_cbmignore) {
- SKIP_UNIX_SHELL;
- const char *base = "/tmp/test_discover_cbmignore";
- char cmd[512];
- snprintf(cmd, sizeof(cmd),
- "rm -rf %s && mkdir -p %s/generated && mkdir -p %s/.git && "
- "echo 'generated/\n*.pb.go' > %s/.cbmignore && "
- "echo 'package main' > %s/main.go && "
- "echo 'package gen' > %s/generated/types.go && "
- "echo 'package api' > %s/api.pb.go",
- base, base, base, base, base, base, base);
- system(cmd);
+ char *base = th_mktempdir("cbm_disc_cbmi");
+ ASSERT(base != NULL);
+
+ th_mkdir_p(TH_PATH(base, ".git"));
+ th_write_file(TH_PATH(base, ".cbmignore"), "generated/\n*.pb.go\n");
+ th_write_file(TH_PATH(base, "main.go"), "package main\n");
+ th_write_file(TH_PATH(base, "generated/types.go"), "package gen\n");
+ th_write_file(TH_PATH(base, "api.pb.go"), "package api\n");
cbm_discover_opts_t opts = {0};
cbm_file_info_t *files = NULL;
@@ -458,28 +426,23 @@ TEST(discover_cbmignore) {
int rc = cbm_discover(base, &opts, &files, &count);
ASSERT_EQ(rc, 0);
- ASSERT_EQ(count, 1); /* only main.go */
+ ASSERT_EQ(count, 1);
ASSERT_TRUE(strstr(files[0].rel_path, "main.go") != NULL);
cbm_discover_free(files, count);
- snprintf(cmd, sizeof(cmd), "rm -rf %s", base);
- system(cmd);
+ th_cleanup(base);
PASS();
}
-/* --- Ported from discover_test.go: TestCBMIgnoreStacksOnGitignore --- */
TEST(discover_cbmignore_stacks) {
- SKIP_UNIX_SHELL;
- const char *base = "/tmp/test_discover_cbmignore_stack";
- char cmd[512];
- snprintf(cmd, sizeof(cmd),
- "rm -rf %s && mkdir -p %s/docs && mkdir -p %s/.git && "
- "echo '*.log' > %s/.gitignore && "
- "echo 'docs/' > %s/.cbmignore && "
- "echo 'package main' > %s/main.go && "
- "echo 'package docs' > %s/docs/api.go",
- base, base, base, base, base, base, base);
- system(cmd);
+ char *base = th_mktempdir("cbm_disc_stack");
+ ASSERT(base != NULL);
+
+ th_mkdir_p(TH_PATH(base, ".git"));
+ th_write_file(TH_PATH(base, ".gitignore"), "*.log\n");
+ th_write_file(TH_PATH(base, ".cbmignore"), "docs/\n");
+ th_write_file(TH_PATH(base, "main.go"), "package main\n");
+ th_write_file(TH_PATH(base, "docs/api.go"), "package docs\n");
cbm_discover_opts_t opts = {0};
cbm_file_info_t *files = NULL;
@@ -487,7 +450,6 @@ TEST(discover_cbmignore_stacks) {
int rc = cbm_discover(base, &opts, &files, &count);
ASSERT_EQ(rc, 0);
- /* main.go only — docs/api.go excluded by .cbmignore */
ASSERT_EQ(count, 1);
bool found_docs = false;
@@ -498,22 +460,23 @@ TEST(discover_cbmignore_stacks) {
ASSERT_FALSE(found_docs);
cbm_discover_free(files, count);
- snprintf(cmd, sizeof(cmd), "rm -rf %s", base);
- system(cmd);
+ th_cleanup(base);
PASS();
}
-/* --- Ported from discover_test.go: TestSymlinkedFilesSkipped --- */
TEST(discover_symlink_skipped) {
- SKIP_UNIX_SHELL;
- const char *base = "/tmp/test_discover_symlink";
- char cmd[512];
- snprintf(cmd, sizeof(cmd),
- "rm -rf %s && mkdir -p %s && "
- "echo 'package main' > %s/real.go && "
- "ln -sf %s/real.go %s/link.go",
- base, base, base, base, base);
- system(cmd);
+#ifdef _WIN32
+ /* Symlinks require elevated privileges on Windows — skip */
+ SKIP("symlinks need admin on Windows");
+#endif
+ char *base = th_mktempdir("cbm_disc_sym");
+ ASSERT(base != NULL);
+
+ th_write_file(TH_PATH(base, "real.go"), "package main\n");
+ char real_path[512], link_path[512];
+ snprintf(real_path, sizeof(real_path), "%s/real.go", base);
+ snprintf(link_path, sizeof(link_path), "%s/link.go", base);
+ symlink(real_path, link_path);
cbm_discover_opts_t opts = {0};
cbm_file_info_t *files = NULL;
@@ -521,7 +484,7 @@ TEST(discover_symlink_skipped) {
int rc = cbm_discover(base, &opts, &files, &count);
ASSERT_EQ(rc, 0);
- ASSERT_EQ(count, 1); /* only real.go, not link.go (symlink) */
+ ASSERT_EQ(count, 1);
bool found_real = false, found_link = false;
for (int i = 0; i < count; i++) {
@@ -534,29 +497,21 @@ TEST(discover_symlink_skipped) {
ASSERT_FALSE(found_link);
cbm_discover_free(files, count);
- snprintf(cmd, sizeof(cmd), "rm -rf %s", base);
- system(cmd);
+ th_cleanup(base);
PASS();
}
-/* --- Ported from discover_test.go: TestNewIgnorePatterns --- */
TEST(discover_new_ignore_patterns) {
- SKIP_UNIX_SHELL;
- const char *base = "/tmp/test_discover_newignore";
- /* Create dirs that should be in IGNORE_PATTERNS */
+ char *base = th_mktempdir("cbm_disc_newign");
+ ASSERT(base != NULL);
+
const char *dirs[] = {".next", ".terraform", "zig-cache", ".cargo", "elm-stuff", "bazel-out"};
- int ndirs = 6;
- char cmd[1024];
- snprintf(cmd, sizeof(cmd), "rm -rf %s && mkdir -p %s", base, base);
- system(cmd);
-
- for (int i = 0; i < ndirs; i++) {
- snprintf(cmd, sizeof(cmd), "mkdir -p %s/%s && echo 'package x' > %s/%s/file.go", base,
- dirs[i], base, dirs[i]);
- system(cmd);
+ for (int i = 0; i < 6; i++) {
+ char path[512];
+ snprintf(path, sizeof(path), "%s/%s/file.go", base, dirs[i]);
+ th_write_file(path, "package x\n");
}
- snprintf(cmd, sizeof(cmd), "echo 'package main' > %s/main.go", base);
- system(cmd);
+ th_write_file(TH_PATH(base, "main.go"), "package main\n");
cbm_discover_opts_t opts = {0};
cbm_file_info_t *files = NULL;
@@ -564,28 +519,21 @@ TEST(discover_new_ignore_patterns) {
int rc = cbm_discover(base, &opts, &files, &count);
ASSERT_EQ(rc, 0);
- /* Only main.go — all dirs should be skipped */
ASSERT_EQ(count, 1);
ASSERT_TRUE(strstr(files[0].rel_path, "main.go") != NULL);
cbm_discover_free(files, count);
- snprintf(cmd, sizeof(cmd), "rm -rf %s", base);
- system(cmd);
+ th_cleanup(base);
PASS();
}
-/* --- Ported from discover_test.go: TestGenericDirsNotIgnoredInFullMode --- */
TEST(discover_generic_dirs_full_mode) {
- SKIP_UNIX_SHELL;
- const char *base = "/tmp/test_discover_generic_full";
- char cmd[512];
- snprintf(cmd, sizeof(cmd),
- "rm -rf %s && mkdir -p %s/bin && mkdir -p %s/build && mkdir -p %s/out && "
- "echo 'package bin' > %s/bin/main.go && "
- "echo 'package build' > %s/build/main.go && "
- "echo 'package out' > %s/out/main.go",
- base, base, base, base, base, base, base);
- system(cmd);
+ char *base = th_mktempdir("cbm_disc_genfull");
+ ASSERT(base != NULL);
+
+ th_write_file(TH_PATH(base, "bin/main.go"), "package bin\n");
+ th_write_file(TH_PATH(base, "build/main.go"), "package build\n");
+ th_write_file(TH_PATH(base, "out/main.go"), "package out\n");
cbm_discover_opts_t opts = {.mode = CBM_MODE_FULL};
cbm_file_info_t *files = NULL;
@@ -593,27 +541,20 @@ TEST(discover_generic_dirs_full_mode) {
int rc = cbm_discover(base, &opts, &files, &count);
ASSERT_EQ(rc, 0);
- /* bin, build, out should NOT be skipped in full mode */
ASSERT_EQ(count, 3);
cbm_discover_free(files, count);
- snprintf(cmd, sizeof(cmd), "rm -rf %s", base);
- system(cmd);
+ th_cleanup(base);
PASS();
}
-/* --- Ported from discover_test.go: TestGenericDirsIgnoredInFastMode --- */
TEST(discover_generic_dirs_fast_mode) {
- SKIP_UNIX_SHELL;
- const char *base = "/tmp/test_discover_generic_fast";
- char cmd[512];
- snprintf(cmd, sizeof(cmd),
- "rm -rf %s && mkdir -p %s/bin && mkdir -p %s/build && mkdir -p %s/out && "
- "echo 'package bin' > %s/bin/main.go && "
- "echo 'package build' > %s/build/main.go && "
- "echo 'package out' > %s/out/main.go",
- base, base, base, base, base, base, base);
- system(cmd);
+ char *base = th_mktempdir("cbm_disc_genfast");
+ ASSERT(base != NULL);
+
+ th_write_file(TH_PATH(base, "bin/main.go"), "package bin\n");
+ th_write_file(TH_PATH(base, "build/main.go"), "package build\n");
+ th_write_file(TH_PATH(base, "out/main.go"), "package out\n");
cbm_discover_opts_t opts = {.mode = CBM_MODE_FAST};
cbm_file_info_t *files = NULL;
@@ -621,28 +562,20 @@ TEST(discover_generic_dirs_fast_mode) {
int rc = cbm_discover(base, &opts, &files, &count);
ASSERT_EQ(rc, 0);
- /* bin, build, out should be skipped in fast mode */
ASSERT_EQ(count, 0);
cbm_discover_free(files, count);
- snprintf(cmd, sizeof(cmd), "rm -rf %s", base);
- system(cmd);
+ th_cleanup(base);
PASS();
}
-/* --- Ported from discover_test.go: TestCBMIgnoreWithoutGitRepo --- */
TEST(discover_cbmignore_no_git) {
- SKIP_UNIX_SHELL;
- const char *base = "/tmp/test_discover_cbmignore_nogit";
- char cmd[512];
- /* No .git directory — .cbmignore should still work */
- snprintf(cmd, sizeof(cmd),
- "rm -rf %s && mkdir -p %s/scratch && "
- "echo 'scratch/' > %s/.cbmignore && "
- "echo 'package main' > %s/main.go && "
- "echo 'package scratch' > %s/scratch/tmp.go",
- base, base, base, base, base);
- system(cmd);
+ char *base = th_mktempdir("cbm_disc_nogit");
+ ASSERT(base != NULL);
+
+ th_write_file(TH_PATH(base, ".cbmignore"), "scratch/\n");
+ th_write_file(TH_PATH(base, "main.go"), "package main\n");
+ th_write_file(TH_PATH(base, "scratch/tmp.go"), "package scratch\n");
cbm_discover_opts_t opts = {0};
cbm_file_info_t *files = NULL;
@@ -650,12 +583,11 @@ TEST(discover_cbmignore_no_git) {
int rc = cbm_discover(base, &opts, &files, &count);
ASSERT_EQ(rc, 0);
- ASSERT_EQ(count, 1); /* only main.go */
+ ASSERT_EQ(count, 1);
ASSERT_TRUE(strstr(files[0].rel_path, "main.go") != NULL);
cbm_discover_free(files, count);
- snprintf(cmd, sizeof(cmd), "rm -rf %s", base);
- system(cmd);
+ th_cleanup(base);
PASS();
}
@@ -729,7 +661,7 @@ SUITE(discover) {
RUN_TEST(pattern_stories);
RUN_TEST(pattern_dts_full);
- /* Integration tests */
+ /* Integration tests (cross-platform) */
RUN_TEST(discover_simple);
RUN_TEST(discover_skips_git_dir);
RUN_TEST(discover_with_gitignore);
@@ -738,7 +670,7 @@ SUITE(discover) {
RUN_TEST(discover_nonexistent_path);
RUN_TEST(discover_free_null);
- /* Go test ports */
+ /* Go test ports (cross-platform) */
RUN_TEST(discover_skips_worktrees);
RUN_TEST(discover_cbmignore);
RUN_TEST(discover_cbmignore_stacks);
diff --git a/tests/test_httplink.c b/tests/test_httplink.c
deleted file mode 100644
index 587680c8a..000000000
--- a/tests/test_httplink.c
+++ /dev/null
@@ -1,904 +0,0 @@
-/*
- * test_httplink.c — Tests for HTTP route discovery and cross-service linking.
- *
- * Port of Go internal/httplink/ test files:
- * - similarity_test.go (4 tests)
- * - httplink_test.go (32 tests)
- * - config_test.go (5 tests)
- * - langparity_test.go (2 tests)
- *
- * Total: 43 Go tests → 43 C tests
- */
-#include "../src/foundation/compat.h"
-#include "test_framework.h"
-#include <pipeline/httplink.h>
-#include <foundation/yaml.h>
-#include <store/store.h>
-#include <string.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <sys/stat.h>
-#include <unistd.h>
-
-/* ═══════════════════════════════════════════════════════════════════
- * Similarity tests (port of similarity_test.go)
- * ═══════════════════════════════════════════════════════════════════ */
-
-TEST(httplink_levenshtein_distance) {
- ASSERT_EQ(cbm_levenshtein_distance("", ""), 0);
- ASSERT_EQ(cbm_levenshtein_distance("abc", ""), 3);
- ASSERT_EQ(cbm_levenshtein_distance("", "abc"), 3);
- ASSERT_EQ(cbm_levenshtein_distance("abc", "abc"), 0);
- ASSERT_EQ(cbm_levenshtein_distance("kitten", "sitting"), 3);
- ASSERT_EQ(cbm_levenshtein_distance("api/orders", "api/order"), 1);
- ASSERT_EQ(cbm_levenshtein_distance("/api/v1/orders", "/api/v2/orders"), 1);
- PASS();
-}
-
-TEST(httplink_normalized_levenshtein) {
- double v;
-
- v = cbm_normalized_levenshtein("abc", "abc");
- ASSERT_FLOAT_EQ(v, 1.0, 0.001);
-
- v = cbm_normalized_levenshtein("", "");
- ASSERT_FLOAT_EQ(v, 1.0, 0.001);
-
- v = cbm_normalized_levenshtein("api/orders", "api/order");
- ASSERT(v >= 0.88 && v <= 0.92);
-
- v = cbm_normalized_levenshtein("/api/v1/items", "/api/v2/items");
- ASSERT(v >= 0.90 && v <= 0.94);
-
- v = cbm_normalized_levenshtein("completely", "different");
- ASSERT(v >= 0.0 && v <= 0.4);
-
- PASS();
-}
-
-TEST(httplink_ngram_overlap) {
- double v;
-
- v = cbm_ngram_overlap("api/orders", "api/orders", 3);
- ASSERT_FLOAT_EQ(v, 1.0, 0.001);
-
- v = cbm_ngram_overlap("api/orders", "api/order", 3);
- ASSERT(v >= 0.8 && v <= 1.0);
-
- v = cbm_ngram_overlap("abcdef", "ghijkl", 3);
- ASSERT_FLOAT_EQ(v, 0.0, 0.001);
-
- v = cbm_ngram_overlap("ab", "cd", 3);
- ASSERT_FLOAT_EQ(v, 0.0, 0.001);
-
- PASS();
-}
-
-TEST(httplink_confidence_band) {
- ASSERT_STR_EQ(cbm_confidence_band(0.95), "high");
- ASSERT_STR_EQ(cbm_confidence_band(0.70), "high");
- ASSERT_STR_EQ(cbm_confidence_band(0.69), "medium");
- ASSERT_STR_EQ(cbm_confidence_band(0.45), "medium");
- ASSERT_STR_EQ(cbm_confidence_band(0.44), "speculative");
- ASSERT_STR_EQ(cbm_confidence_band(0.25), "speculative");
- ASSERT_STR_EQ(cbm_confidence_band(0.24), "");
- ASSERT_STR_EQ(cbm_confidence_band(0.0), "");
- PASS();
-}
-
-/* ═══════════════════════════════════════════════════════════════════
- * Path matching tests (port of httplink_test.go path tests)
- * ═══════════════════════════════════════════════════════════════════ */
-
-TEST(httplink_normalize_path) {
- ASSERT_STR_EQ(cbm_normalize_path("/api/orders/"), "/api/orders");
- ASSERT_STR_EQ(cbm_normalize_path("/api/orders"), "/api/orders");
- ASSERT_STR_EQ(cbm_normalize_path("/api/orders/:id"), "/api/orders/*");
- ASSERT_STR_EQ(cbm_normalize_path("/api/orders/{order_id}"), "/api/orders/*");
- ASSERT_STR_EQ(cbm_normalize_path("/API/Orders"), "/api/orders");
- ASSERT_STR_EQ(cbm_normalize_path("/api/:version/items/:id"), "/api/*/items/*");
- ASSERT_STR_EQ(cbm_normalize_path("/api/{version}/items/{id}"), "/api/*/items/*");
- ASSERT_STR_EQ(cbm_normalize_path("/"), "");
- ASSERT_STR_EQ(cbm_normalize_path(""), "");
- PASS();
-}
-
-TEST(httplink_paths_match) {
- /* Exact match */
- ASSERT_TRUE(cbm_paths_match("/api/orders", "/api/orders"));
- ASSERT_TRUE(cbm_paths_match("/api/orders/", "/api/orders"));
-
- /* Case insensitive */
- ASSERT_TRUE(cbm_paths_match("/API/Orders", "/api/orders"));
-
- /* Suffix match */
- ASSERT_TRUE(cbm_paths_match("https://example.com/api/orders", "/api/orders"));
-
- /* Wildcard params */
- ASSERT_TRUE(cbm_paths_match("/api/orders/:id", "/api/orders/{order_id}"));
- ASSERT_TRUE(cbm_paths_match("/api/orders/123", "/api/orders/:id"));
-
- /* Segment wildcard */
- ASSERT_TRUE(cbm_paths_match("/api/:version/items", "/api/v1/items"));
-
- /* Different lengths */
- ASSERT_FALSE(cbm_paths_match("/api/orders", "/api/orders/detail"));
- ASSERT_FALSE(cbm_paths_match("/api", "/api/orders"));
-
- /* Both wildcards */
- ASSERT_TRUE(cbm_paths_match("/api/*/items", "/api/*/items"));
-
- /* No match */
- ASSERT_FALSE(cbm_paths_match("/api/users", "/api/orders"));
-
- PASS();
-}
-
-TEST(httplink_paths_match_suffix) {
- ASSERT_TRUE(cbm_paths_match("/host/prefix/api/orders", "/api/orders"));
- PASS();
-}
-
-TEST(httplink_path_match_score) {
- double v;
-
- /* Exact matches */
- v = cbm_path_match_score("/api/orders", "/api/orders");
- ASSERT(v >= 0.78 && v <= 0.82);
-
- v = cbm_path_match_score("/integrate", "/integrate");
- ASSERT(v >= 0.60 && v <= 0.67);
-
- v = cbm_path_match_score("/api/v1/orders/items", "/api/v1/orders/items");
- ASSERT(v >= 0.93 && v <= 0.96);
-
- /* URL with scheme+host — normalizes to exact match after stripping host */
- v = cbm_path_match_score("https://host/api/orders", "/api/orders");
- ASSERT(v >= 0.78 && v <= 0.82);
-
- /* Numeric IDs normalized to wildcard */
- v = cbm_path_match_score("/api/orders/123", "/api/orders/:id");
- ASSERT(v >= 0.90 && v <= 0.96);
-
- /* No match */
- v = cbm_path_match_score("/api/users", "/api/orders");
- ASSERT_FLOAT_EQ(v, 0.0, 0.001);
-
- v = cbm_path_match_score("/", "/api/orders");
- ASSERT_FLOAT_EQ(v, 0.0, 0.001);
-
- v = cbm_path_match_score("", "/api/orders");
- ASSERT_FLOAT_EQ(v, 0.0, 0.001);
-
- PASS();
-}
-
-TEST(httplink_same_service) {
- /* Same dir */
- ASSERT_TRUE(cbm_same_service("a.b.c.mod.Func1", "a.b.c.mod.Func2"));
- /* Different dir */
- ASSERT_FALSE(cbm_same_service("a.b.c.mod.Func1", "a.b.x.mod.Func2"));
- /* Same deep dir */
- ASSERT_TRUE(cbm_same_service("a.b.c.d.mod.Func", "a.b.c.d.mod.Other"));
- /* Different deep dir */
- ASSERT_FALSE(cbm_same_service("a.b.c.d.mod.Func", "a.b.c.e.mod.Other"));
- /* Too few segments */
- ASSERT_FALSE(cbm_same_service("short.x", "short.y"));
- ASSERT_FALSE(cbm_same_service("a.b", "a.b"));
- /* 3 segments: dir="a" */
- ASSERT_TRUE(cbm_same_service("a.b.c", "a.b.c"));
- ASSERT_FALSE(cbm_same_service("a.b.c", "x.b.c"));
- /* Realistic multi-service */
- ASSERT_TRUE(cbm_same_service("myapp.docker-images.cloud-runs.order-service.main.Func",
- "myapp.docker-images.cloud-runs.order-service.handlers.Other"));
- ASSERT_FALSE(
- cbm_same_service("myapp.docker-images.cloud-runs.order-service.main.Func",
- "myapp.docker-images.cloud-runs.notification-service.main.health_check"));
- ASSERT_TRUE(cbm_same_service("myapp.docker-images.cloud-runs.svcA.sub.mod.Func",
- "myapp.docker-images.cloud-runs.svcA.sub.mod.Other"));
- ASSERT_FALSE(cbm_same_service("myapp.docker-images.cloud-runs.svcA.sub.mod.Func",
- "myapp.docker-images.cloud-runs.svcB.sub.mod.Other"));
- PASS();
-}
-
-/* ═══════════════════════════════════════════════════════════════════
- * URL extraction tests
- * ═══════════════════════════════════════════════════════════════════ */
-
-TEST(httplink_extract_url_paths) {
- char *paths[16];
- int n;
-
- n = cbm_extract_url_paths("URL = \"https://example.com/api/orders\"", paths, 16);
- ASSERT_EQ(n, 1);
- for (int i = 0; i < n; i++)
- free(paths[i]);
-
- n = cbm_extract_url_paths("fetch(\"http://host/api/v1/items\")", paths, 16);
- ASSERT_EQ(n, 1);
- for (int i = 0; i < n; i++)
- free(paths[i]);
-
- n = cbm_extract_url_paths("path = \"/api/orders\"", paths, 16);
- ASSERT_EQ(n, 1);
- for (int i = 0; i < n; i++)
- free(paths[i]);
-
- n = cbm_extract_url_paths("no urls here", paths, 16);
- ASSERT_EQ(n, 0);
-
- n = cbm_extract_url_paths("both = \"https://a.com/api/x\" and \"/api/y\"", paths, 16);
- ASSERT_EQ(n, 2);
- for (int i = 0; i < n; i++)
- free(paths[i]);
-
- PASS();
-}
-
-TEST(httplink_extract_json_string_paths) {
- char *paths[16];
- int n;
-
- n = cbm_extract_json_string_paths(
- "BODY = '{\"target\": \"https://api.internal.com/api/orders\", \"method\": \"POST\"}'",
- paths, 16);
- ASSERT_EQ(n, 1);
- for (int i = 0; i < n; i++)
- free(paths[i]);
-
- n = cbm_extract_json_string_paths(
- "CONFIG = {\"endpoint\": \"/api/v1/process\", \"timeout\": 30}", paths, 16);
- ASSERT_EQ(n, 1);
- for (int i = 0; i < n; i++)
- free(paths[i]);
-
- n = cbm_extract_json_string_paths("plain string without json", paths, 16);
- ASSERT_EQ(n, 0);
-
- n = cbm_extract_json_string_paths(
- "{\"services\": [{\"url\": \"https://svc.example.com/api/health\"}]}", paths, 16);
- ASSERT_EQ(n, 1);
- for (int i = 0; i < n; i++)
- free(paths[i]);
-
- PASS();
-}
-
-/* ═══════════════════════════════════════════════════════════════════
- * Route extraction: Python
- * ═══════════════════════════════════════════════════════════════════ */
-
-TEST(httplink_extract_python_routes) {
- const char *decs[] = {"@app.post(\"/api/orders\")"};
- cbm_route_handler_t routes[4];
- int n = cbm_extract_python_routes("create_order", "proj.api.routes.create_order", decs, 1,
- routes, 4);
- ASSERT_EQ(n, 1);
- ASSERT_STR_EQ(routes[0].path, "/api/orders");
- ASSERT_STR_EQ(routes[0].method, "POST");
- ASSERT_STR_EQ(routes[0].qualified_name, "proj.api.routes.create_order");
- PASS();
-}
-
-TEST(httplink_extract_python_routes_multiple) {
- const char *decs[] = {"@router.get(\"/api/items/{item_id}\")", "@router.post(\"/api/items\")"};
- cbm_route_handler_t routes[4];
- int n = cbm_extract_python_routes("handler", "proj.api.handler", decs, 2, routes, 4);
- ASSERT_EQ(n, 2);
- PASS();
-}
-
-TEST(httplink_extract_python_routes_no_decorators) {
- cbm_route_handler_t routes[4];
- int n = cbm_extract_python_routes("helper", "proj.utils.helper", NULL, 0, routes, 4);
- ASSERT_EQ(n, 0);
- PASS();
-}
-
-TEST(httplink_extract_python_ws_routes) {
- const char *decs[] = {"@app.websocket(\"/ws/chat\")"};
- cbm_route_handler_t routes[4];
- int n = cbm_extract_python_routes("ws_handler", "proj.api.ws_handler", decs, 1, routes, 4);
- ASSERT_EQ(n, 1);
- ASSERT_STR_EQ(routes[0].path, "/ws/chat");
- ASSERT_STR_EQ(routes[0].method, "WS");
- ASSERT_STR_EQ(routes[0].protocol, "ws");
- PASS();
-}
-
-/* ═══════════════════════════════════════════════════════════════════
- * Route extraction: Go gin/chi
- * ═══════════════════════════════════════════════════════════════════ */
-
-TEST(httplink_extract_go_routes) {
- const char *source = "\tr.POST(\"/api/orders\", h.CreateOrder)\n"
- "\tr.GET(\"/api/orders/:id\", h.GetOrder)\n";
- cbm_route_handler_t routes[8];
- int n = cbm_extract_go_routes("RegisterRoutes", "proj.api.RegisterRoutes", source, routes, 8);
- ASSERT_EQ(n, 2);
- ASSERT_STR_EQ(routes[0].path, "/api/orders");
- ASSERT_STR_EQ(routes[0].method, "POST");
- ASSERT_STR_EQ(routes[1].path, "/api/orders/:id");
- PASS();
-}
-
-TEST(httplink_chi_prefix) {
- const char *source = "func SetupRoutes(r chi.Router) {\n"
- "\tr.Route(\"/api\", func(r chi.Router) {\n"
- "\t\tr.Get(\"/health\", healthHandler)\n"
- "\t\tr.Route(\"/users\", func(r chi.Router) {\n"
- "\t\t\tr.Get(\"/\", listUsers)\n"
- "\t\t\tr.Post(\"/{id}\", updateUser)\n"
- "\t\t})\n"
- "\t})\n"
- "}\n";
- cbm_route_handler_t routes[8];
- int n = cbm_extract_go_routes("SetupRoutes", "proj.SetupRoutes", source, routes, 8);
- ASSERT_EQ(n, 3);
-
- /* Verify all routes have /api prefix */
- /* Verify all routes have /api prefix */
- bool found_health = false;
- for (int i = 0; i < n; i++) {
- if (strcmp(routes[i].path, "/api/health") == 0 && strcmp(routes[i].method, "GET") == 0)
- found_health = true;
- }
- ASSERT_TRUE(found_health);
- PASS();
-}
-
-TEST(httplink_chi_prefix_mixed_with_gin) {
- const char *source = "func RegisterRoutes(r *gin.RouterGroup) {\n"
- "\torders := r.Group(\"/orders\")\n"
- "\torders.GET(\"/:id\", getOrder)\n"
- "\torders.POST(\"\", createOrder)\n"
- "}\n";
- cbm_route_handler_t routes[8];
- int n = cbm_extract_go_routes("RegisterRoutes", "proj.RegisterRoutes", source, routes, 8);
- ASSERT_EQ(n, 2);
- /* Both should have /orders prefix from gin group */
- for (int i = 0; i < n; i++) {
- ASSERT(strncmp(routes[i].path, "/orders", 7) == 0);
- }
- PASS();
-}
-
-/* ═══════════════════════════════════════════════════════════════════
- * Route extraction: Java Spring
- * ═══════════════════════════════════════════════════════════════════ */
-
-TEST(httplink_extract_spring_ws_routes) {
- const char *decs[] = {"@MessageMapping(\"/chat\")"};
- cbm_route_handler_t routes[4];
- int n =
- cbm_extract_java_routes("handleChat", "proj.ChatController.handleChat", decs, 1, routes, 4);
- ASSERT_EQ(n, 1);
- ASSERT_STR_EQ(routes[0].path, "/chat");
- ASSERT_STR_EQ(routes[0].method, "WS");
- ASSERT_STR_EQ(routes[0].protocol, "ws");
- PASS();
-}
-
-/* ═══════════════════════════════════════════════════════════════════
- * Route extraction: Ktor
- * ═══════════════════════════════════════════════════════════════════ */
-
-TEST(httplink_extract_ktor_ws_routes) {
- const char *source = "\twebSocket(\"/chat\") {\n"
- "\t\tfor (frame in incoming) {\n"
- "\t\t\tsend(frame)\n"
- "\t\t}\n"
- "\t}\n"
- "\tget(\"/api/health\") {\n"
- "\t\tcall.respond(\"ok\")\n"
- "\t}\n";
- cbm_route_handler_t routes[8];
- int n = cbm_extract_ktor_routes("configureRouting", "proj.Routing.configureRouting", source,
- routes, 8);
- ASSERT_EQ(n, 2);
-
- bool ws_found = false, http_found = false;
- for (int i = 0; i < n; i++) {
- if (strcmp(routes[i].protocol, "ws") == 0 && strcmp(routes[i].path, "/chat") == 0 &&
- strcmp(routes[i].method, "WS") == 0)
- ws_found = true;
- if (strcmp(routes[i].path, "/api/health") == 0 && strcmp(routes[i].method, "GET") == 0)
- http_found = true;
- }
- ASSERT_TRUE(ws_found);
- ASSERT_TRUE(http_found);
- PASS();
-}
-
-/* ═══════════════════════════════════════════════════════════════════
- * Route extraction: Express.js (with allowlist filtering)
- * ═══════════════════════════════════════════════════════════════════ */
-
-TEST(httplink_express_route_filtering) {
- cbm_route_handler_t routes[4];
- int n;
-
- /* Should match (allowlisted receivers) */
- n = cbm_extract_express_routes("testFunc", "proj.test.testFunc",
- "app.get('/api/users', handler)", routes, 4);
- ASSERT_EQ(n, 1);
- ASSERT_STR_EQ(routes[0].method, "GET");
- ASSERT_STR_EQ(routes[0].path, "/api/users");
-
- n = cbm_extract_express_routes("testFunc", "proj.test.testFunc",
- "router.post('/orders', handler)", routes, 4);
- ASSERT_EQ(n, 1);
- ASSERT_STR_EQ(routes[0].method, "POST");
-
- n = cbm_extract_express_routes("testFunc", "proj.test.testFunc",
- "server.put('/items', handler)", routes, 4);
- ASSERT_EQ(n, 1);
-
- n = cbm_extract_express_routes("testFunc", "proj.test.testFunc",
- "api.delete('/users/:id', handler)", routes, 4);
- ASSERT_EQ(n, 1);
-
- n = cbm_extract_express_routes("testFunc", "proj.test.testFunc",
- "routes.patch('/items/:id', handler)", routes, 4);
- ASSERT_EQ(n, 1);
-
- /* Should NOT match (not in allowlist) */
- n = cbm_extract_express_routes("testFunc", "proj.test.testFunc", "req.get('Content-Type')",
- routes, 4);
- ASSERT_EQ(n, 0);
-
- n = cbm_extract_express_routes("testFunc", "proj.test.testFunc", "res.get('key')", routes, 4);
- ASSERT_EQ(n, 0);
-
- n = cbm_extract_express_routes("testFunc", "proj.test.testFunc", "this.get('property')", routes,
- 4);
- ASSERT_EQ(n, 0);
-
- n = cbm_extract_express_routes("testFunc", "proj.test.testFunc", "map.get('key')", routes, 4);
- ASSERT_EQ(n, 0);
-
- n = cbm_extract_express_routes("testFunc", "proj.test.testFunc", "model.delete('record')",
- routes, 4);
- ASSERT_EQ(n, 0);
-
- n = cbm_extract_express_routes("testFunc", "proj.test.testFunc", "params.get('id')", routes, 4);
- ASSERT_EQ(n, 0);
-
- PASS();
-}
-
-/* ═══════════════════════════════════════════════════════════════════
- * Detection tests
- * ═══════════════════════════════════════════════════════════════════ */
-
-TEST(httplink_detect_protocol) {
- ASSERT_STR_EQ(cbm_detect_protocol("err := websocket.Upgrade(w, r, nil, 1024, 1024)"), "ws");
- ASSERT_STR_EQ(cbm_detect_protocol("conn, err := websocket.Accept(w, r, nil)"), "ws");
- ASSERT_STR_EQ(cbm_detect_protocol("conn, err := upgrader.Upgrade(w, r, nil)"), "ws");
- ASSERT_STR_EQ(cbm_detect_protocol("ws.on(\"connection\", func)"), "ws");
- ASSERT_STR_EQ(cbm_detect_protocol("io.on(\"connection\", handler)"), "ws");
- ASSERT_STR_EQ(cbm_detect_protocol("w.Header().Set(\"Content-Type\", \"text/event-stream\")"),
- "sse");
- ASSERT_STR_EQ(cbm_detect_protocol("return EventSourceResponse(generate())"), "sse");
- ASSERT_STR_EQ(cbm_detect_protocol("SseEmitter emitter = new SseEmitter()"), "sse");
- ASSERT_STR_EQ(cbm_detect_protocol("ServerSentEvent event = ServerSentEvent.builder()"), "sse");
- ASSERT_STR_EQ(cbm_detect_protocol("return json.Marshal(result)"), "");
- ASSERT_STR_EQ(cbm_detect_protocol(""), "");
- PASS();
-}
-
-TEST(httplink_is_test_node) {
- ASSERT_FALSE(cbm_is_test_node_fp("src/routes/api.js", false));
- ASSERT_TRUE(cbm_is_test_node_fp("test/app.get.js", false));
- ASSERT_TRUE(cbm_is_test_node_fp("__tests__/routes.test.ts", false));
- ASSERT_TRUE(cbm_is_test_node_fp("src/routes/api.js", true));
- ASSERT_FALSE(cbm_is_test_node_fp("lib/router/index.js", false));
- ASSERT_TRUE(cbm_is_test_node_fp("tests/fixtures/server.js", false));
- ASSERT_FALSE(cbm_is_test_node_fp("app/controllers/orders_controller.rb", false));
- PASS();
-}
-
-/* ═══════════════════════════════════════════════════════════════════
- * Config tests (port of config_test.go)
- * ═══════════════════════════════════════════════════════════════════ */
-
-TEST(httplink_is_path_excluded) {
- const char *paths[] = {"/health", "/debug", "/internal/status"};
- ASSERT_TRUE(cbm_is_path_excluded("/health", paths, 3));
- ASSERT_TRUE(cbm_is_path_excluded("/health/", paths, 3));
- ASSERT_TRUE(cbm_is_path_excluded("/HEALTH", paths, 3));
- ASSERT_TRUE(cbm_is_path_excluded("/debug", paths, 3));
- ASSERT_TRUE(cbm_is_path_excluded("/internal/status", paths, 3));
- ASSERT_FALSE(cbm_is_path_excluded("/api/orders", paths, 3));
- ASSERT_FALSE(cbm_is_path_excluded("/healthcheck", paths, 3));
- PASS();
-}
-
-TEST(httplink_default_exclude_paths) {
- /* Verify default exclude paths include common health/debug endpoints */
- ASSERT(cbm_default_exclude_paths_count >= 9);
- /* Verify /health is in the list */
- bool found = false;
- for (int i = 0; i < cbm_default_exclude_paths_count; i++) {
- if (strcmp(cbm_default_exclude_paths[i], "/health") == 0) {
- found = true;
- break;
- }
- }
- ASSERT_TRUE(found);
- PASS();
-}
-
-/* ═══════════════════════════════════════════════════════════════════
- * YAML config tests (port of config_test.go — YAML-dependent tests)
- * ═══════════════════════════════════════════════════════════════════ */
-
-TEST(httplink_load_config_default) {
- /* Nonexistent path → defaults */
- cbm_httplink_config_t cfg = cbm_httplink_load_config("/nonexistent/path");
- ASSERT_FLOAT_EQ(cbm_httplink_effective_min_confidence(&cfg), 0.25, 0.001);
- ASSERT_TRUE(cbm_httplink_effective_fuzzy_matching(&cfg));
-
- const char *paths[64];
- int count = cbm_httplink_all_exclude_paths(&cfg, paths, 64);
- ASSERT_EQ(count, cbm_default_exclude_paths_count);
-
- cbm_httplink_config_free(&cfg);
- PASS();
-}
-
-TEST(httplink_load_config_from_file) {
- /* Create temp dir with .cgrconfig */
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/httplink-cfg-XXXXXX");
- if (!cbm_mkdtemp(tmpdir))
- SKIP("cbm_mkdtemp failed");
-
- char cfgpath[512];
- snprintf(cfgpath, sizeof(cfgpath), "%s/.cgrconfig", tmpdir);
-
- FILE *f = fopen(cfgpath, "w");
- if (!f) {
- rmdir(tmpdir);
- SKIP("cannot write .cgrconfig");
- }
- fprintf(f, "\n"
- "http_linker:\n"
- " exclude_paths:\n"
- " - /debug\n"
- " - /internal/status\n"
- " min_confidence: 0.5\n"
- " fuzzy_matching: false\n");
- fclose(f);
-
- cbm_httplink_config_t cfg = cbm_httplink_load_config(tmpdir);
- ASSERT_FLOAT_EQ(cbm_httplink_effective_min_confidence(&cfg), 0.5, 0.001);
- ASSERT_FALSE(cbm_httplink_effective_fuzzy_matching(&cfg));
-
- const char *paths[64];
- int count = cbm_httplink_all_exclude_paths(&cfg, paths, 64);
- int expected = cbm_default_exclude_paths_count + 2;
- ASSERT_EQ(count, expected);
-
- cbm_httplink_config_free(&cfg);
-
- /* Cleanup */
- unlink(cfgpath);
- rmdir(tmpdir);
- PASS();
-}
-
-TEST(httplink_load_config_invalid_yaml) {
- /* Invalid YAML → fallback to defaults */
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/httplink-bad-XXXXXX");
- if (!cbm_mkdtemp(tmpdir))
- SKIP("cbm_mkdtemp failed");
-
- char cfgpath[512];
- snprintf(cfgpath, sizeof(cfgpath), "%s/.cgrconfig", tmpdir);
-
- FILE *f = fopen(cfgpath, "w");
- if (!f) {
- rmdir(tmpdir);
- SKIP("cannot write .cgrconfig");
- }
- fprintf(f, "not: [valid: yaml");
- fclose(f);
-
- cbm_httplink_config_t cfg = cbm_httplink_load_config(tmpdir);
- /* Should fall back to defaults */
- ASSERT_FLOAT_EQ(cbm_httplink_effective_min_confidence(&cfg), 0.25, 0.001);
-
- cbm_httplink_config_free(&cfg);
-
- /* Cleanup */
- unlink(cfgpath);
- rmdir(tmpdir);
- PASS();
-}
-
-TEST(httplink_all_exclude_paths_merge) {
- /* User-configured paths should be appended after defaults */
- cbm_httplink_config_t cfg = cbm_httplink_default_config();
- cfg.exclude_paths = calloc(2, sizeof(char *));
- cfg.exclude_paths[0] = strdup("/custom1");
- cfg.exclude_paths[1] = strdup("/custom2");
- cfg.exclude_path_count = 2;
-
- const char *paths[64];
- int count = cbm_httplink_all_exclude_paths(&cfg, paths, 64);
- int expected = cbm_default_exclude_paths_count + 2;
- ASSERT_EQ(count, expected);
-
- /* Verify defaults are first */
- for (int i = 0; i < cbm_default_exclude_paths_count; i++) {
- ASSERT_STR_EQ(paths[i], cbm_default_exclude_paths[i]);
- }
-
- /* Verify custom paths are appended */
- ASSERT_STR_EQ(paths[cbm_default_exclude_paths_count], "/custom1");
- ASSERT_STR_EQ(paths[cbm_default_exclude_paths_count + 1], "/custom2");
-
- cbm_httplink_config_free(&cfg);
- PASS();
-}
-
-/* ═══════════════════════════════════════════════════════════════════
- * Langparity tests (port of langparity_test.go)
- * ═══════════════════════════════════════════════════════════════════ */
-
-TEST(httplink_http_client_keywords_all_languages) {
- /* Each language should have at least one keyword in the list */
- typedef struct {
- const char *lang;
- const char **keywords;
- int nkw;
- } lang_kw_t;
-
- const char *py_kw[] = {"requests.get", "httpx.", "aiohttp."};
- const char *go_kw[] = {"http.Get", "http.Post", "http.NewRequest"};
- const char *js_kw[] = {"fetch(", "axios."};
- const char *java_kw[] = {"HttpClient", "RestTemplate"};
- const char *rust_kw[] = {"reqwest::", "hyper::"};
-
- lang_kw_t langs[] = {
- {"Python", py_kw, 3}, {"Go", go_kw, 3}, {"JavaScript", js_kw, 2},
- {"Java", java_kw, 2}, {"Rust", rust_kw, 2},
- };
-
- for (int l = 0; l < 5; l++) {
- bool found = false;
- for (int k = 0; k < langs[l].nkw && !found; k++) {
- for (int i = 0; i < cbm_http_client_keywords_count; i++) {
- if (strstr(cbm_http_client_keywords[i], langs[l].keywords[k]) ||
- strcmp(cbm_http_client_keywords[i], langs[l].keywords[k]) == 0) {
- found = true;
- break;
- }
- }
- }
- if (!found) {
- printf(" FAIL: no HTTP client keywords for %s\n", langs[l].lang);
- return 1;
- }
- }
- PASS();
-}
-
-TEST(httplink_route_extraction_negative_cases) {
- cbm_route_handler_t routes[8];
- int n;
- const char *sources[] = {
- "func processOrder(order Order) error {\n\treturn nil\n}\n",
- "function calculate(x, y) {\n\treturn x + y;\n}\n",
- "def transform_data(data):\n return data.upper()\n",
- };
-
- for (int i = 0; i < 3; i++) {
- /* Python */
- n = cbm_extract_python_routes("fn", "proj.fn", NULL, 0, routes, 8);
- ASSERT_EQ(n, 0);
-
- /* Go */
- n = cbm_extract_go_routes("fn", "proj.fn", sources[i], routes, 8);
- ASSERT_EQ(n, 0);
-
- /* Express */
- n = cbm_extract_express_routes("fn", "proj.fn", sources[i], routes, 8);
- ASSERT_EQ(n, 0);
-
- /* Laravel */
- n = cbm_extract_laravel_routes("fn", "proj.fn", sources[i], routes, 8);
- ASSERT_EQ(n, 0);
- }
- PASS();
-}
-
-/* ═══════════════════════════════════════════════════════════════════
- * Read source lines tests
- * ═══════════════════════════════════════════════════════════════════ */
-
-TEST(httplink_read_source_lines) {
- /* Create temp dir with test file */
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/httplink-test-XXXXXX");
- if (!cbm_mkdtemp(tmpdir)) {
- printf(" SKIP: cbm_mkdtemp failed\n");
- return -1;
- }
-
- char fpath[512];
- snprintf(fpath, sizeof(fpath), "%s/test.go", tmpdir);
- FILE *f = fopen(fpath, "w");
- if (!f) {
- printf(" SKIP: cannot write\n");
- return -1;
- }
- fprintf(f, "line1\nline2\nline3\nline4\nline5\n");
- fclose(f);
-
- char *result = cbm_read_source_lines_disk(tmpdir, "test.go", 2, 4);
- ASSERT_NOT_NULL(result);
- ASSERT_STR_EQ(result, "line2\nline3\nline4");
- free(result);
-
- /* Cleanup */
- unlink(fpath);
- rmdir(tmpdir);
- PASS();
-}
-
-TEST(httplink_read_source_lines_missing_file) {
- char *result = cbm_read_source_lines_disk("/nonexistent", "missing.go", 1, 10);
- ASSERT_NULL(result);
- PASS();
-}
-
-/* ═══════════════════════════════════════════════════════════════════
- * Integration tests with store (port of Linker tests)
- * These test the full pipeline: create nodes → run linker → verify edges
- * ═══════════════════════════════════════════════════════════════════ */
-
-/* ── Linker integration: route nodes created (simplified) ──────── */
-
-TEST(httplink_linker_route_nodes) {
- /* Test route extraction from Python decorators (no store needed). */
- const char *decs[] = {"@app.post(\"/api/orders\")"};
- cbm_route_handler_t routes[4];
- int n = cbm_extract_python_routes("create_order", "testproj.handler.routes.create_order", decs,
- 1, routes, 4);
- ASSERT_EQ(n, 1);
- ASSERT_STR_EQ(routes[0].path, "/api/orders");
- ASSERT_STR_EQ(routes[0].method, "POST");
- PASS();
-}
-
-/* ── Linker integration: same-service skip ─────────────────────── */
-
-TEST(httplink_linker_same_service_skip) {
- /* Both caller and handler in same service → no link */
- ASSERT_TRUE(cbm_same_service("testproj.cat.sub.svcA.internal.client",
- "testproj.cat.sub.svcA.internal.handle_orders"));
- PASS();
-}
-
-/* ── Laravel path filter: reject $ and : in matched paths ──────── */
-
-TEST(httplink_laravel_path_filter) {
- cbm_route_handler_t routes[8];
- int n;
-
- /* Cache key patterns should be filtered (contain $ or :) */
- n = cbm_extract_laravel_routes("fn", "proj.fn",
- "Cache::get('article:{$this->id}:image')", routes, 8);
- ASSERT_EQ(n, 0);
-
- n = cbm_extract_laravel_routes("fn", "proj.fn",
- "Route::get(\"cache:$key\", fn() => null)", routes, 8);
- ASSERT_EQ(n, 0);
-
- /* Valid routes should still pass (Laravel uses {param} not $param) */
- n = cbm_extract_laravel_routes("fn", "proj.fn",
- "Route::get('/api/users/{id}', 'UserController@show')", routes,
- 8);
- ASSERT_EQ(n, 1);
- ASSERT_STR_EQ(routes[0].path, "/api/users/{id}");
-
- /* Route with no special chars also passes */
- n = cbm_extract_laravel_routes("fn", "proj.fn",
- "Route::post('/api/login', 'AuthController@login')", routes, 8);
- ASSERT_EQ(n, 1);
- ASSERT_STR_EQ(routes[0].path, "/api/login");
-
- PASS();
-}
-
-/* ── Laravel module-level route extraction ─────────────────────── */
-
-TEST(httplink_laravel_module_level_routes) {
- const char *source = "<?php\n"
- "use App\\Http\\Controllers\\OrderController;\n"
- "Route::get('/api/orders', [OrderController::class, 'index']);\n"
- "Route::post('/api/orders', [OrderController::class, 'store']);\n"
- "Route::get('/api/orders/{id}', [OrderController::class, 'show']);\n";
-
- cbm_route_handler_t routes[8];
- int n = cbm_extract_laravel_routes("api.php", "testproj.routes.api", source, routes, 8);
- ASSERT_GTE(n, 3);
-
- bool found_orders = false, found_orders_id = false;
- for (int i = 0; i < n; i++) {
- if (strcmp(routes[i].path, "/api/orders") == 0)
- found_orders = true;
- if (strcmp(routes[i].path, "/api/orders/{id}") == 0)
- found_orders_id = true;
- }
- ASSERT_TRUE(found_orders);
- ASSERT_TRUE(found_orders_id);
- PASS();
-}
-
-/* ═══════════════════════════════════════════════════════════════════
- * Suite definition
- * ═══════════════════════════════════════════════════════════════════ */
-
-SUITE(httplink) {
- /* Similarity (4 tests from similarity_test.go) */
- RUN_TEST(httplink_levenshtein_distance);
- RUN_TEST(httplink_normalized_levenshtein);
- RUN_TEST(httplink_ngram_overlap);
- RUN_TEST(httplink_confidence_band);
-
- /* Path matching (5 tests from httplink_test.go) */
- RUN_TEST(httplink_normalize_path);
- RUN_TEST(httplink_paths_match);
- RUN_TEST(httplink_paths_match_suffix);
- RUN_TEST(httplink_path_match_score);
- RUN_TEST(httplink_same_service);
-
- /* URL extraction (2 tests) */
- RUN_TEST(httplink_extract_url_paths);
- RUN_TEST(httplink_extract_json_string_paths);
-
- /* Python routes (4 tests) */
- RUN_TEST(httplink_extract_python_routes);
- RUN_TEST(httplink_extract_python_routes_multiple);
- RUN_TEST(httplink_extract_python_routes_no_decorators);
- RUN_TEST(httplink_extract_python_ws_routes);
-
- /* Go routes (3 tests) */
- RUN_TEST(httplink_extract_go_routes);
- RUN_TEST(httplink_chi_prefix);
- RUN_TEST(httplink_chi_prefix_mixed_with_gin);
-
- /* Java/Ktor/Express routes (3 tests) */
- RUN_TEST(httplink_extract_spring_ws_routes);
- RUN_TEST(httplink_extract_ktor_ws_routes);
- RUN_TEST(httplink_express_route_filtering);
-
- /* Detection (2 tests) */
- RUN_TEST(httplink_detect_protocol);
- RUN_TEST(httplink_is_test_node);
-
- /* Config (6 tests — 2 original + 4 YAML-dependent) */
- RUN_TEST(httplink_is_path_excluded);
- RUN_TEST(httplink_default_exclude_paths);
- RUN_TEST(httplink_load_config_default);
- RUN_TEST(httplink_load_config_from_file);
- RUN_TEST(httplink_load_config_invalid_yaml);
- RUN_TEST(httplink_all_exclude_paths_merge);
-
- /* Langparity (2 tests) */
- RUN_TEST(httplink_http_client_keywords_all_languages);
- RUN_TEST(httplink_route_extraction_negative_cases);
-
- /* Source lines (2 tests) */
- RUN_TEST(httplink_read_source_lines);
- RUN_TEST(httplink_read_source_lines_missing_file);
-
- /* Laravel path filter (1 test) */
- RUN_TEST(httplink_laravel_path_filter);
-
- /* Integration (3 tests) */
- RUN_TEST(httplink_linker_route_nodes);
- RUN_TEST(httplink_linker_same_service_skip);
- RUN_TEST(httplink_laravel_module_level_routes);
-}
diff --git a/tests/test_incremental.c b/tests/test_incremental.c
index 4004490c2..e1907d0e3 100644
--- a/tests/test_incremental.c
+++ b/tests/test_incremental.c
@@ -12,6 +12,7 @@
*/
#include "../src/foundation/compat.h"
#include "test_framework.h"
+#include "test_helpers.h"
#include <mcp/mcp.h>
#include <store/store.h>
#include <pipeline/pipeline.h>
@@ -75,14 +76,31 @@ static void delete_file_at(const char *rel_path) {
unlink(path);
}
-/* Run a reformatter on N files: appends "# reformatted" comment */
+/* Append "# reformatted" to up to max_files .py files in subdir (cross-platform). */
static int reformat_files(const char *subdir, int max_files) {
- char cmd[1024];
- snprintf(cmd, sizeof(cmd),
- "find '%s/%s' -name '*.py' -type f 2>/dev/null | head -%d | "
- "while read f; do echo '# reformatted' >> \"$f\"; done",
- g_repodir, subdir, max_files);
- return system(cmd);
+ char dir[512];
+ snprintf(dir, sizeof(dir), "%s/%s", g_repodir, subdir);
+ cbm_dir_t *d = cbm_opendir(dir);
+ if (!d) {
+ return -1;
+ }
+ cbm_dirent_t *entry;
+ int count = 0;
+ while ((entry = cbm_readdir(d)) != NULL && count < max_files) {
+ size_t nlen = strlen(entry->name);
+ if (nlen < 4 || strcmp(entry->name + nlen - 3, ".py") != 0) {
+ continue;
+ }
+ if (entry->is_dir) {
+ continue;
+ }
+ char path[1024];
+ snprintf(path, sizeof(path), "%s/%s", dir, entry->name);
+ th_append_file(path, "# reformatted\n");
+ count++;
+ }
+ cbm_closedir(d);
+ return 0;
}
static char *index_repo(void) {
@@ -235,9 +253,7 @@ static void incremental_teardown(void) {
free(g_project);
g_project = NULL;
- char cmd[512];
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", g_tmpdir);
- (void)system(cmd);
+ th_rmtree(g_tmpdir);
}
/* ══════════════════════════════════════════════════════════════════
diff --git a/tests/test_integration.c b/tests/test_integration.c
index d9837defc..54c969e1a 100644
--- a/tests/test_integration.c
+++ b/tests/test_integration.c
@@ -9,6 +9,7 @@
*/
#include "../src/foundation/compat.h"
#include "test_framework.h"
+#include "test_helpers.h"
#include <mcp/mcp.h>
#include <store/store.h>
#include <pipeline/pipeline.h>
@@ -150,9 +151,7 @@ static void integration_teardown(void) {
g_project = NULL;
/* Clean up temp project */
- char cmd[512];
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", g_tmpdir);
- system(cmd);
+ th_rmtree(g_tmpdir);
/* Clean up cache db */
unlink(g_dbpath);
diff --git a/tests/test_main.c b/tests/test_main.c
index 70e28200e..c7bb52a08 100644
--- a/tests/test_main.c
+++ b/tests/test_main.c
@@ -41,7 +41,6 @@ extern void suite_go_lsp(void);
extern void suite_c_lsp(void);
extern void suite_store_arch(void);
extern void suite_store_bulk(void);
-extern void suite_httplink(void);
extern void suite_traces(void);
extern void suite_configlink(void);
extern void suite_infrascan(void);
@@ -113,7 +112,6 @@ int main(void) {
RUN_SUITE(store_arch);
/* HTTP link */
- RUN_SUITE(httplink);
/* Traces helpers */
RUN_SUITE(traces);
diff --git a/tests/test_mem.c b/tests/test_mem.c
index a9385516f..d5d2866d0 100644
--- a/tests/test_mem.c
+++ b/tests/test_mem.c
@@ -4,6 +4,7 @@
*/
#include "../src/foundation/compat.h"
#include "test_framework.h"
+#include "test_helpers.h"
#include "../src/foundation/mem.h"
#include "../src/foundation/arena.h"
#include "../src/foundation/slab_alloc.h"
@@ -559,9 +560,7 @@ static int setup_mem_test_repo(void) {
static void teardown_mem_test_repo(void) {
if (g_mem_tmpdir[0]) {
- char cmd[512];
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", g_mem_tmpdir);
- (void)system(cmd);
+ th_rmtree(g_mem_tmpdir);
g_mem_tmpdir[0] = '\0';
}
}
diff --git a/tests/test_parallel.c b/tests/test_parallel.c
index 3dbb32963..aaf5e2ec0 100644
--- a/tests/test_parallel.c
+++ b/tests/test_parallel.c
@@ -8,6 +8,7 @@
*/
#include "../src/foundation/compat.h"
#include "test_framework.h"
+#include "test_helpers.h"
#include "pipeline/pipeline.h"
#include "pipeline/pipeline_internal.h"
#include "pipeline/worker_pool.h"
@@ -71,9 +72,7 @@ static int setup_parallel_repo(void) {
}
static void rm_rf(const char *path) {
- char cmd[1024];
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", path);
- (void)system(cmd);
+ th_rmtree(path);
}
static void teardown_parallel_repo(void) {
diff --git a/tests/test_pipeline.c b/tests/test_pipeline.c
index bf074cdcd..cbe8fc862 100644
--- a/tests/test_pipeline.c
+++ b/tests/test_pipeline.c
@@ -6,9 +6,9 @@
*/
#include "../src/foundation/compat.h"
#include "test_framework.h"
+#include "test_helpers.h"
#include "pipeline/pipeline.h"
#include "pipeline/pipeline_internal.h"
-#include "pipeline/httplink.h"
#include "store/store.h"
#include <stdlib.h>
@@ -84,9 +84,7 @@ static int setup_test_repo(void) {
/* Recursive remove (simple, not production-grade) */
static void rm_rf(const char *path) {
- char cmd[1024];
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", path);
- (void)system(cmd);
+ th_rmtree(path);
}
static void teardown_test_repo(void) {
@@ -834,9 +832,7 @@ static int setup_usages_repo(const char *filename, const char *content, const ch
char *last_slash = strrchr(dir_path, '/');
if (last_slash) {
*last_slash = '\0';
- char cmd[1024];
- snprintf(cmd, sizeof(cmd), "mkdir -p '%s'", dir_path);
- (void)system(cmd);
+ th_mkdir_p(dir_path);
}
FILE *f = fopen(path, "w");
@@ -1121,9 +1117,7 @@ static int setup_lang_repo(const char **filenames, const char **contents, int co
char *slash = strrchr(dir, '/');
if (slash) {
*slash = '\0';
- char cmd[1024];
- snprintf(cmd, sizeof(cmd), "mkdir -p '%s'", dir);
- (void)system(cmd);
+ th_mkdir_p(dir);
}
FILE *f = fopen(path, "wb");
@@ -2298,544 +2292,6 @@ TEST(configures_full_pipeline_integration) {
teardown_lang_repo();
PASS();
}
-
-/* ── HTTP link pipeline integration (httplink_test.go ports) ──── */
-
-TEST(pipeline_httplink_route_and_caller) {
- /* Port of TestLinkerRun + TestRouteNodesCreated:
- * Python handler with route decorator + Go caller with URL constant.
- * Pipeline should create Route nodes, HANDLES edges, and HTTP_CALLS edges. */
- const char *files[] = {"handler/routes.py", "caller/client.go"};
- const char *contents[] = {"from flask import Flask\n\n"
- "app = Flask(__name__)\n\n"
- "@app.post(\"/api/orders\")\n"
- "def create_order():\n"
- " return {\"status\": \"ok\"}\n\n"
- "@app.get(\"/api/orders\")\n"
- "def list_orders():\n"
- " return []\n",
-
- "package caller\n\n"
- "const OrderURL = \"https://api.example.com/api/orders\"\n\n"
- "func FetchOrders() {\n"
- "\t// makes HTTP call to OrderURL\n"
- "}\n"};
- if (setup_lang_repo(files, contents, 2) != 0)
- SKIP("tmpdir");
- char db[512];
- snprintf(db, sizeof(db), "%s/test.db", g_lang_tmpdir);
- cbm_pipeline_t *p = cbm_pipeline_new(g_lang_tmpdir, db, CBM_MODE_FULL);
- ASSERT_NOT_NULL(p);
- ASSERT_EQ(cbm_pipeline_run(p), 0);
-
- cbm_store_t *s = cbm_store_open_path(db);
- ASSERT_NOT_NULL(s);
- const char *proj = cbm_pipeline_project_name(p);
-
- /* Should have Route nodes from Python decorators */
- cbm_node_t *routes = NULL;
- int rc = 0;
- cbm_store_find_nodes_by_label(s, proj, "Route", &routes, &rc);
- ASSERT_GTE(rc, 2); /* @app.post + @app.get */
- if (routes)
- cbm_store_free_nodes(routes, rc);
-
- /* Should have Function nodes for Python handlers */
- cbm_node_t *funcs = NULL;
- int fc = 0;
- cbm_store_find_nodes_by_name(s, proj, "create_order", &funcs, &fc);
- ASSERT_GT(fc, 0);
-
- /* Handler should be marked as entry point */
- ASSERT_TRUE(strstr(funcs[0].properties_json, "\"is_entry_point\":true") != NULL);
-
- /* Handler should have a HANDLES edge */
- cbm_edge_t *handles = NULL;
- int hc = 0;
- cbm_store_find_edges_by_source_type(s, funcs[0].id, "HANDLES", &handles, &hc);
- ASSERT_GTE(hc, 1);
- if (handles)
- cbm_store_free_edges(handles, hc);
- if (funcs)
- cbm_store_free_nodes(funcs, fc);
-
- cbm_store_close(s);
- cbm_pipeline_free(p);
- teardown_lang_repo();
- PASS();
-}
-
-TEST(pipeline_httplink_cross_file_prefix) {
- /* Port of TestCrossFileGroupPrefix:
- * Go router with prefix + handler → routes have correct full paths. */
- const char *files[] = {"routes.go"};
- const char *contents[] = {"package main\n\n"
- "func RegisterRoutes() {\n"
- "\tr := gin.Default()\n"
- "\tv1 := r.Group(\"/api/v1\")\n"
- "\tv1.POST(\"/orders\", CreateOrder)\n"
- "\tv1.GET(\"/orders/:id\", GetOrder)\n"
- "}\n\n"
- "func CreateOrder() {}\n"
- "func GetOrder() {}\n"};
- if (setup_lang_repo(files, contents, 1) != 0)
- SKIP("tmpdir");
- char db[512];
- snprintf(db, sizeof(db), "%s/test.db", g_lang_tmpdir);
- cbm_pipeline_t *p = cbm_pipeline_new(g_lang_tmpdir, db, CBM_MODE_FULL);
- ASSERT_NOT_NULL(p);
- ASSERT_EQ(cbm_pipeline_run(p), 0);
-
- cbm_store_t *s = cbm_store_open_path(db);
- ASSERT_NOT_NULL(s);
- const char *proj = cbm_pipeline_project_name(p);
-
- /* Should have Route nodes with group-prefixed paths */
- cbm_node_t *routes = NULL;
- int rc = 0;
- cbm_store_find_nodes_by_label(s, proj, "Route", &routes, &rc);
- ASSERT_GTE(rc, 2); /* POST /orders + GET /orders/:id */
- /* Verify routes have /api/v1 prefix from Group() */
- bool found_prefix = false;
- for (int i = 0; i < rc; i++) {
- if (strstr(routes[i].properties_json, "/api/v1/orders"))
- found_prefix = true;
- }
- ASSERT_TRUE(found_prefix);
- if (routes)
- cbm_store_free_nodes(routes, rc);
-
- cbm_store_close(s);
- cbm_pipeline_free(p);
- teardown_lang_repo();
- PASS();
-}
-
-TEST(pipeline_httplink_websocket_routes) {
- /* Port of TestExtractPythonWSRoutes + TestExtractSpringWSRoutes:
- * WebSocket route annotations should produce Route nodes. */
- const char *files[] = {"ws.py"};
- const char *contents[] = {"from fastapi import WebSocket\n\n"
- "@app.websocket(\"/ws/chat\")\n"
- "async def websocket_chat(ws: WebSocket):\n"
- " pass\n\n"
- "@app.websocket(\"/ws/events\")\n"
- "async def websocket_events(ws: WebSocket):\n"
- " pass\n"};
- if (setup_lang_repo(files, contents, 1) != 0)
- SKIP("tmpdir");
- char db[512];
- snprintf(db, sizeof(db), "%s/test.db", g_lang_tmpdir);
- cbm_pipeline_t *p = cbm_pipeline_new(g_lang_tmpdir, db, CBM_MODE_FULL);
- ASSERT_NOT_NULL(p);
- ASSERT_EQ(cbm_pipeline_run(p), 0);
-
- cbm_store_t *s = cbm_store_open_path(db);
- ASSERT_NOT_NULL(s);
- const char *proj = cbm_pipeline_project_name(p);
-
- /* WebSocket routes produce Route nodes with ws protocol */
- cbm_node_t *routes = NULL;
- int rc = 0;
- cbm_store_find_nodes_by_label(s, proj, "Route", &routes, &rc);
- ASSERT_GTE(rc, 2); /* /ws/chat + /ws/events */
- bool found_ws = false;
- for (int i = 0; i < rc; i++) {
- if (strstr(routes[i].properties_json, "\"protocol\":\"ws\""))
- found_ws = true;
- }
- ASSERT_TRUE(found_ws);
- if (routes)
- cbm_store_free_nodes(routes, rc);
-
- cbm_store_close(s);
- cbm_pipeline_free(p);
- teardown_lang_repo();
- PASS();
-}
-
-/* ── HTTP link linker integration tests (httplink_test.go ports) ── */
-
-TEST(httplink_linker_cross_file_group_variable) {
- /* Port of TestCrossFileGroupPrefixVariable:
- * v1 := r.Group("/api"); RegisterRoutes(v1)
- * Routes in RegisterRoutes should get /api prefix. */
- const char *files[] = {"cmd/main.go", "routes/routes.go"};
- const char *contents[] = {"package main\n\n"
- "func setup(r interface{}) {\n"
- "\tv1 := r.Group(\"/api\")\n"
- "\tRegisterRoutes(v1)\n"
- "}\n",
-
- "package routes\n\n"
- "func RegisterRoutes(rg interface{}) {\n"
- "\trg.GET(\"/items\", ListItems)\n"
- "}\n"};
- if (setup_lang_repo(files, contents, 2) != 0)
- SKIP("tmpdir");
- char db[512];
- snprintf(db, sizeof(db), "%s/test.db", g_lang_tmpdir);
- cbm_pipeline_t *p = cbm_pipeline_new(g_lang_tmpdir, db, CBM_MODE_FULL);
- ASSERT_NOT_NULL(p);
- ASSERT_EQ(cbm_pipeline_run(p), 0);
-
- cbm_store_t *s = cbm_store_open_path(db);
- ASSERT_NOT_NULL(s);
- const char *proj = cbm_pipeline_project_name(p);
-
- cbm_node_t *routes = NULL;
- int rc = 0;
- cbm_store_find_nodes_by_label(s, proj, "Route", &routes, &rc);
- ASSERT_GTE(rc, 1);
-
- /* Route path should have /api prefix from cross-file variable resolution */
- bool found = false;
- for (int i = 0; i < rc; i++) {
- if (strstr(routes[i].properties_json, "/api/items"))
- found = true;
- }
- ASSERT_TRUE(found);
- if (routes)
- cbm_store_free_nodes(routes, rc);
-
- cbm_store_close(s);
- cbm_pipeline_free(p);
- teardown_lang_repo();
- PASS();
-}
-
-TEST(httplink_linker_registration_call_edges) {
- /* Port of TestRouteRegistrationCallEdges:
- * RegisterRoutes has .POST("/orders", h.CreateOrder) → CALLS edge to CreateOrder
- * with via=route_registration property. */
- const char *files[] = {"routes/routes.go", "handlers/handler.go"};
- const char *contents[] = {"package routes\n\n"
- "func RegisterRoutes(rg interface{}) {\n"
- "\trg.POST(\"/orders\", h.CreateOrder)\n"
- "\trg.GET(\"/orders/:id\", h.GetOrder)\n"
- "}\n",
-
- "package handlers\n\n"
- "func (h *Handler) CreateOrder() {}\n"
- "func (h *Handler) GetOrder() {}\n"};
- if (setup_lang_repo(files, contents, 2) != 0)
- SKIP("tmpdir");
- char db[512];
- snprintf(db, sizeof(db), "%s/test.db", g_lang_tmpdir);
- cbm_pipeline_t *p = cbm_pipeline_new(g_lang_tmpdir, db, CBM_MODE_FULL);
- ASSERT_NOT_NULL(p);
- ASSERT_EQ(cbm_pipeline_run(p), 0);
-
- cbm_store_t *s = cbm_store_open_path(db);
- ASSERT_NOT_NULL(s);
- const char *proj = cbm_pipeline_project_name(p);
-
- /* Find RegisterRoutes function */
- cbm_node_t *regs = NULL;
- int regc = 0;
- cbm_store_find_nodes_by_name(s, proj, "RegisterRoutes", &regs, &regc);
- ASSERT_GTE(regc, 1);
-
- /* Should have CALLS edges with via=route_registration */
- cbm_edge_t *edges = NULL;
- int ec = 0;
- cbm_store_find_edges_by_source_type(s, regs[0].id, "CALLS", &edges, &ec);
- ASSERT_GTE(ec, 2); /* CreateOrder + GetOrder */
-
- bool found_reg = false;
- for (int i = 0; i < ec; i++) {
- if (strstr(edges[i].properties_json, "route_registration"))
- found_reg = true;
- }
- ASSERT_TRUE(found_reg);
-
- if (edges)
- cbm_store_free_edges(edges, ec);
- if (regs)
- cbm_store_free_nodes(regs, regc);
-
- cbm_store_close(s);
- cbm_pipeline_free(p);
- teardown_lang_repo();
- PASS();
-}
-
-TEST(httplink_linker_async_dispatch) {
- /* Port of TestAsyncDispatchKeywords:
- * CreateTask → ASYNC_CALLS, requests.post → HTTP_CALLS. */
- const char *files[] = {"handler/routes.py", "taskworker/dispatch.go", "synccaller/caller.go"};
- const char *contents[] = {"from flask import Flask\n\n"
- "app = Flask(__name__)\n\n"
- "@app.post(\"/api/orders\")\n"
- "def create_order():\n"
- " return {\"status\": \"ok\"}\n",
-
- "package taskworker\n\n"
- "func DispatchOrder(orderID string) {\n"
- "\turl := \"https://api.internal.com/api/orders\"\n"
- "\tclient.CreateTask(ctx, url, payload)\n"
- "}\n",
-
- "package synccaller\n\n"
- "func CallOrder() {\n"
- "\turl := \"https://api.internal.com/api/orders\"\n"
- "\trequests.post(url, data)\n"
- "}\n"};
- if (setup_lang_repo(files, contents, 3) != 0)
- SKIP("tmpdir");
- char db[512];
- snprintf(db, sizeof(db), "%s/test.db", g_lang_tmpdir);
- cbm_pipeline_t *p = cbm_pipeline_new(g_lang_tmpdir, db, CBM_MODE_FULL);
- ASSERT_NOT_NULL(p);
- ASSERT_EQ(cbm_pipeline_run(p), 0);
-
- cbm_store_t *s = cbm_store_open_path(db);
- ASSERT_NOT_NULL(s);
- const char *proj = cbm_pipeline_project_name(p);
-
- /* DispatchOrder should have ASYNC_CALLS edge (CreateTask keyword) */
- cbm_node_t *dispatch = NULL;
- int dc = 0;
- cbm_store_find_nodes_by_name(s, proj, "DispatchOrder", &dispatch, &dc);
- ASSERT_GTE(dc, 1);
- cbm_edge_t *async_edges = NULL;
- int aec = 0;
- cbm_store_find_edges_by_source_type(s, dispatch[0].id, "ASYNC_CALLS", &async_edges, &aec);
- ASSERT_GTE(aec, 1);
- if (async_edges)
- cbm_store_free_edges(async_edges, aec);
- if (dispatch)
- cbm_store_free_nodes(dispatch, dc);
-
- /* CallOrder should have HTTP_CALLS edge (requests.post keyword) */
- cbm_node_t *caller = NULL;
- int cc = 0;
- cbm_store_find_nodes_by_name(s, proj, "CallOrder", &caller, &cc);
- ASSERT_GTE(cc, 1);
- cbm_edge_t *http_edges = NULL;
- int hec = 0;
- cbm_store_find_edges_by_source_type(s, caller[0].id, "HTTP_CALLS", &http_edges, &hec);
- ASSERT_GTE(hec, 1);
- if (http_edges)
- cbm_store_free_edges(http_edges, hec);
- if (caller)
- cbm_store_free_nodes(caller, cc);
-
- cbm_store_close(s);
- cbm_pipeline_free(p);
- teardown_lang_repo();
- PASS();
-}
-
-TEST(httplink_linker_extract_async_call_sites) {
- /* Port of TestExtractFunctionCallSitesAsync:
- * CreateTask + URL → IsAsync=true call site.
- * requests.post + URL → IsAsync=false call site. */
- const char *all_files[] = {"worker/task.go", "worker/sync.go", "handler/process.py"};
- const char *all_contents[] = {"package worker\n\n"
- "func EnqueueJob() {\n"
- "\turl := \"https://backend.internal.com/api/process\"\n"
- "\tclient.CreateTask(ctx, url)\n"
- "}\n",
-
- "package worker\n\n"
- "func SyncCall() {\n"
- "\turl := \"https://backend.internal.com/api/process\"\n"
- "\trequests.post(url, data)\n"
- "}\n",
-
- "from flask import Flask\n\n"
- "app = Flask(__name__)\n\n"
- "@app.post(\"/api/process\")\n"
- "def process_task():\n"
- " return {\"ok\": True}\n"};
- if (setup_lang_repo(all_files, all_contents, 3) != 0)
- SKIP("tmpdir");
- char db[512];
- snprintf(db, sizeof(db), "%s/test.db", g_lang_tmpdir);
- cbm_pipeline_t *p = cbm_pipeline_new(g_lang_tmpdir, db, CBM_MODE_FULL);
- ASSERT_NOT_NULL(p);
- ASSERT_EQ(cbm_pipeline_run(p), 0);
-
- cbm_store_t *s = cbm_store_open_path(db);
- ASSERT_NOT_NULL(s);
- const char *proj = cbm_pipeline_project_name(p);
-
- /* EnqueueJob: async dispatch (CreateTask without HTTP client) → ASYNC_CALLS */
- cbm_node_t *enqueue = NULL;
- int enc = 0;
- cbm_store_find_nodes_by_name(s, proj, "EnqueueJob", &enqueue, &enc);
- ASSERT_GTE(enc, 1);
- cbm_edge_t *ae = NULL;
- int aec = 0;
- cbm_store_find_edges_by_source_type(s, enqueue[0].id, "ASYNC_CALLS", &ae, &aec);
- ASSERT_GTE(aec, 1);
- if (ae)
- cbm_store_free_edges(ae, aec);
- if (enqueue)
- cbm_store_free_nodes(enqueue, enc);
-
- /* SyncCall: HTTP client (requests.post) → HTTP_CALLS */
- cbm_node_t *sync_fn = NULL;
- int sc = 0;
- cbm_store_find_nodes_by_name(s, proj, "SyncCall", &sync_fn, &sc);
- ASSERT_GTE(sc, 1);
- cbm_edge_t *he = NULL;
- int hec = 0;
- cbm_store_find_edges_by_source_type(s, sync_fn[0].id, "HTTP_CALLS", &he, &hec);
- ASSERT_GTE(hec, 1);
- if (he)
- cbm_store_free_edges(he, hec);
- if (sync_fn)
- cbm_store_free_nodes(sync_fn, sc);
-
- cbm_store_close(s);
- cbm_pipeline_free(p);
- teardown_lang_repo();
- PASS();
-}
-
-TEST(httplink_linker_fastapi_prefix) {
- /* Port of TestFastAPIPrefix:
- * app.include_router(order_router, prefix="/api/v1/orders")
- * Route from orders/routes.py should get prefix prepended. */
- const char *files[] = {"main.py", "orders/routes.py"};
- const char *contents[] = {"from orders.routes import order_router\n\n"
- "app = None # FastAPI()\n"
- "app.include_router(order_router, prefix=\"/api/v1/orders\")\n",
-
- "from flask import Flask\n\n"
- "order_router = Flask(__name__)\n\n"
- "@order_router.get(\"/\")\n"
- "def list_orders():\n"
- " return []\n"};
- if (setup_lang_repo(files, contents, 2) != 0)
- SKIP("tmpdir");
- char db[512];
- snprintf(db, sizeof(db), "%s/test.db", g_lang_tmpdir);
- cbm_pipeline_t *p = cbm_pipeline_new(g_lang_tmpdir, db, CBM_MODE_FULL);
- ASSERT_NOT_NULL(p);
- ASSERT_EQ(cbm_pipeline_run(p), 0);
-
- cbm_store_t *s = cbm_store_open_path(db);
- ASSERT_NOT_NULL(s);
- const char *proj = cbm_pipeline_project_name(p);
-
- cbm_node_t *routes = NULL;
- int rc = 0;
- cbm_store_find_nodes_by_label(s, proj, "Route", &routes, &rc);
- ASSERT_GTE(rc, 1);
-
- /* Route path should have the FastAPI prefix */
- bool found = false;
- for (int i = 0; i < rc; i++) {
- if (strstr(routes[i].properties_json, "/api/v1/orders/"))
- found = true;
- }
- ASSERT_TRUE(found);
- if (routes)
- cbm_store_free_nodes(routes, rc);
-
- cbm_store_close(s);
- cbm_pipeline_free(p);
- teardown_lang_repo();
- PASS();
-}
-
-TEST(httplink_linker_express_prefix) {
- /* Port of TestExpressPrefix:
- * app.use("/api/orders", orderRouter)
- * Route from routes/orders.js should get prefix prepended. */
- const char *files[] = {"app.js", "routes/orders.js"};
- const char *contents[] = {"const orderRouter = require('./routes/orders');\n"
- "app.use(\"/api/orders\", orderRouter);\n",
-
- "router.get(\"/:id\", function(req, res) {\n"
- " res.json({id: req.params.id});\n"
- "});\n"};
- if (setup_lang_repo(files, contents, 2) != 0)
- SKIP("tmpdir");
- char db[512];
- snprintf(db, sizeof(db), "%s/test.db", g_lang_tmpdir);
- cbm_pipeline_t *p = cbm_pipeline_new(g_lang_tmpdir, db, CBM_MODE_FULL);
- ASSERT_NOT_NULL(p);
- ASSERT_EQ(cbm_pipeline_run(p), 0);
-
- cbm_store_t *s = cbm_store_open_path(db);
- ASSERT_NOT_NULL(s);
- const char *proj = cbm_pipeline_project_name(p);
-
- cbm_node_t *routes = NULL;
- int rc = 0;
- cbm_store_find_nodes_by_label(s, proj, "Route", &routes, &rc);
- ASSERT_GTE(rc, 1);
-
- /* Route path should have Express prefix: /api/orders/:id */
- bool found = false;
- for (int i = 0; i < rc; i++) {
- if (strstr(routes[i].properties_json, "/api/orders"))
- found = true;
- }
- ASSERT_TRUE(found);
- if (routes)
- cbm_store_free_nodes(routes, rc);
-
- cbm_store_close(s);
- cbm_pipeline_free(p);
- teardown_lang_repo();
- PASS();
-}
-
-TEST(httplink_linker_same_service_skip) {
- /* Port of TestLinkerSkipsSameService:
- * Caller and handler in same service dir should NOT create HTTP_CALLS edge. */
- const char *files[] = {"svcA/client.py", "svcA/routes.py"};
- const char *contents[] = {"import requests\n\n"
- "URL = \"https://localhost/api/orders\"\n\n"
- "def call_api():\n"
- " requests.get(URL)\n",
-
- "from flask import Flask\n\n"
- "app = Flask(__name__)\n\n"
- "@app.get(\"/api/orders\")\n"
- "def handle_orders():\n"
- " return []\n"};
- if (setup_lang_repo(files, contents, 2) != 0)
- SKIP("tmpdir");
- char db[512];
- snprintf(db, sizeof(db), "%s/test.db", g_lang_tmpdir);
- cbm_pipeline_t *p = cbm_pipeline_new(g_lang_tmpdir, db, CBM_MODE_FULL);
- ASSERT_NOT_NULL(p);
- ASSERT_EQ(cbm_pipeline_run(p), 0);
-
- cbm_store_t *s = cbm_store_open_path(db);
- ASSERT_NOT_NULL(s);
- const char *proj = cbm_pipeline_project_name(p);
-
- /* Should have Route node from Python decorator */
- cbm_node_t *routes = NULL;
- int rc = 0;
- cbm_store_find_nodes_by_label(s, proj, "Route", &routes, &rc);
- ASSERT_GTE(rc, 1);
- if (routes)
- cbm_store_free_nodes(routes, rc);
-
- /* Should NOT have HTTP_CALLS edges (same service) */
- cbm_edge_t *edges = NULL;
- int ec = 0;
- cbm_store_find_edges_by_type(s, proj, "HTTP_CALLS", &edges, &ec);
- ASSERT_EQ(ec, 0);
- if (edges)
- cbm_store_free_edges(edges, ec);
-
- cbm_store_close(s);
- cbm_pipeline_free(p);
- teardown_lang_repo();
- PASS();
-}
-
-/* ── Enrichment helpers (pass_enrichment.c) ───────────────────── */
-
TEST(enrichment_split_camel_case) {
char *parts[8];
int n;
@@ -3344,8 +2800,8 @@ TEST(infra_is_kustomize_file) {
TEST(infra_is_k8s_manifest) {
const char *deploy = "apiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: my-app\n";
- const char *plain = "name: foo\nvalue: bar\n";
- const char *kust = "apiVersion: kustomize.config.k8s.io/v1beta1\nkind: Kustomization\n";
+ const char *plain = "name: foo\nvalue: bar\n";
+ const char *kust = "apiVersion: kustomize.config.k8s.io/v1beta1\nkind: Kustomization\n";
ASSERT(cbm_is_k8s_manifest("deployment.yaml", deploy));
ASSERT(!cbm_is_k8s_manifest("deployment.yaml", plain));
@@ -4167,15 +3623,13 @@ TEST(infra_pipeline_idempotent) {
/* ── K8s / Kustomize extraction tests ──────────────────────────── */
TEST(k8s_extract_kustomize) {
- const char *src =
- "apiVersion: kustomize.config.k8s.io/v1beta1\n"
- "kind: Kustomization\n"
- "resources:\n"
- " - deployment.yaml\n"
- " - service.yaml\n";
- CBMFileResult *r = cbm_extract_file(src, (int)strlen(src), CBM_LANG_KUSTOMIZE,
- "myproj", "base/kustomization.yaml",
- 0, NULL, NULL);
+ const char *src = "apiVersion: kustomize.config.k8s.io/v1beta1\n"
+ "kind: Kustomization\n"
+ "resources:\n"
+ " - deployment.yaml\n"
+ " - service.yaml\n";
+ CBMFileResult *r = cbm_extract_file(src, (int)strlen(src), CBM_LANG_KUSTOMIZE, "myproj",
+ "base/kustomization.yaml", 0, NULL, NULL);
ASSERT(r != NULL);
ASSERT_GTE(r->imports.count, 2);
@@ -4196,24 +3650,20 @@ TEST(k8s_extract_kustomize) {
}
TEST(k8s_extract_manifest) {
- const char *src =
- "apiVersion: apps/v1\n"
- "kind: Deployment\n"
- "metadata:\n"
- " name: my-app\n"
- " namespace: production\n";
- CBMFileResult *r = cbm_extract_file(src, (int)strlen(src), CBM_LANG_K8S,
- "myproj", "k8s/deployment.yaml",
- 0, NULL, NULL);
+ const char *src = "apiVersion: apps/v1\n"
+ "kind: Deployment\n"
+ "metadata:\n"
+ " name: my-app\n"
+ " namespace: production\n";
+ CBMFileResult *r = cbm_extract_file(src, (int)strlen(src), CBM_LANG_K8S, "myproj",
+ "k8s/deployment.yaml", 0, NULL, NULL);
ASSERT(r != NULL);
ASSERT_GTE(r->defs.count, 1);
bool found_resource = false;
for (int d = 0; d < r->defs.count; d++) {
- if (r->defs.items[d].label &&
- strcmp(r->defs.items[d].label, "Resource") == 0 &&
- r->defs.items[d].name &&
- strstr(r->defs.items[d].name, "Deployment") != NULL)
+ if (r->defs.items[d].label && strcmp(r->defs.items[d].label, "Resource") == 0 &&
+ r->defs.items[d].name && strstr(r->defs.items[d].name, "Deployment") != NULL)
found_resource = true;
}
ASSERT_TRUE(found_resource);
@@ -4224,8 +3674,8 @@ TEST(k8s_extract_manifest) {
TEST(k8s_extract_manifest_no_name) {
const char *src = "apiVersion: apps/v1\nkind: Deployment\n";
- CBMFileResult *r = cbm_extract_file(src, (int)strlen(src), CBM_LANG_K8S,
- "myproj", "k8s/deploy.yaml", 0, NULL, NULL);
+ CBMFileResult *r = cbm_extract_file(src, (int)strlen(src), CBM_LANG_K8S, "myproj",
+ "k8s/deploy.yaml", 0, NULL, NULL);
ASSERT(r != NULL);
/* No crash — defs count may be 0 because metadata.name is absent */
ASSERT(!r->has_error);
@@ -4243,18 +3693,17 @@ TEST(k8s_extract_manifest_multidoc) {
* Note: with some tree-sitter YAML grammar versions the root stream may
* expose both documents as siblings; the break still fires after the first
* successful def push, so defs.count must be exactly 1. */
- const char *src =
- "apiVersion: apps/v1\n"
- "kind: Deployment\n"
- "metadata:\n"
- " name: my-app\n"
- "---\n"
- "apiVersion: v1\n"
- "kind: Service\n"
- "metadata:\n"
- " name: my-svc\n";
- CBMFileResult *r = cbm_extract_file(src, (int)strlen(src), CBM_LANG_K8S,
- "myproj", "k8s/multi.yaml", 0, NULL, NULL);
+ const char *src = "apiVersion: apps/v1\n"
+ "kind: Deployment\n"
+ "metadata:\n"
+ " name: my-app\n"
+ "---\n"
+ "apiVersion: v1\n"
+ "kind: Service\n"
+ "metadata:\n"
+ " name: my-svc\n";
+ CBMFileResult *r = cbm_extract_file(src, (int)strlen(src), CBM_LANG_K8S, "myproj",
+ "k8s/multi.yaml", 0, NULL, NULL);
ASSERT(r != NULL);
ASSERT(!r->has_error);
/* First document's resource must be present */
@@ -4315,7 +3764,8 @@ static int has_binding_value(const cbm_env_binding_t *bindings, int count, const
}
TEST(envscan_dockerfile_env_urls) {
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_envscan_dock_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_envscan_dock_XXXXXX");
if (!cbm_mkdtemp(tmpdir))
SKIP("tmpdir");
@@ -4337,14 +3787,13 @@ TEST(envscan_dockerfile_env_urls) {
/* DB_HOST=localhost is NOT a URL → should be absent */
ASSERT_TRUE(find_binding_by_key(bindings, count, "DB_HOST") == NULL);
- char cmd[512];
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
PASS();
}
TEST(envscan_shell_env_urls) {
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_envscan_sh_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_envscan_sh_XXXXXX");
if (!cbm_mkdtemp(tmpdir))
SKIP("tmpdir");
@@ -4364,14 +3813,13 @@ TEST(envscan_shell_env_urls) {
/* APP_NAME is NOT a URL → absent */
ASSERT_TRUE(find_binding_by_key(bindings, count, "APP_NAME") == NULL);
- char cmd[512];
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
PASS();
}
TEST(envscan_env_file_urls) {
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_envscan_env_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_envscan_env_XXXXXX");
if (!cbm_mkdtemp(tmpdir))
SKIP("tmpdir");
@@ -4390,14 +3838,13 @@ TEST(envscan_env_file_urls) {
/* DEBUG=true is NOT a URL */
ASSERT_TRUE(find_binding_by_key(bindings, count, "DEBUG") == NULL);
- char cmd[512];
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
PASS();
}
TEST(envscan_toml_urls) {
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_envscan_toml_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_envscan_toml_XXXXXX");
if (!cbm_mkdtemp(tmpdir))
SKIP("tmpdir");
@@ -4417,14 +3864,13 @@ TEST(envscan_toml_urls) {
/* name="my-service" is NOT a URL */
ASSERT_TRUE(find_binding_by_key(bindings, count, "name") == NULL);
- char cmd[512];
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
PASS();
}
TEST(envscan_yaml_urls) {
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_envscan_yaml_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_envscan_yaml_XXXXXX");
if (!cbm_mkdtemp(tmpdir))
SKIP("tmpdir");
@@ -4442,14 +3888,13 @@ TEST(envscan_yaml_urls) {
"https://api.internal.com/api/process");
ASSERT_NOT_NULL(find_binding_by_key(bindings, count, "callback_url"));
- char cmd[512];
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
PASS();
}
TEST(envscan_terraform_urls) {
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_envscan_tf_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_envscan_tf_XXXXXX");
if (!cbm_mkdtemp(tmpdir))
SKIP("tmpdir");
@@ -4468,14 +3913,13 @@ TEST(envscan_terraform_urls) {
ASSERT_GTE(count, 1);
ASSERT_TRUE(has_binding_value(bindings, count, "https://api.example.com/webhook"));
- char cmd[512];
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
PASS();
}
TEST(envscan_properties_urls) {
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_envscan_prop_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_envscan_prop_XXXXXX");
if (!cbm_mkdtemp(tmpdir))
SKIP("tmpdir");
@@ -4490,14 +3934,13 @@ TEST(envscan_properties_urls) {
ASSERT_TRUE(has_binding_value(bindings, count, "https://api.example.com/health"));
ASSERT_TRUE(has_binding_value(bindings, count, "https://service.example.com/api"));
- char cmd[512];
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
PASS();
}
TEST(envscan_secret_key_exclusion) {
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_envscan_skey_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_envscan_skey_XXXXXX");
if (!cbm_mkdtemp(tmpdir))
SKIP("tmpdir");
@@ -4518,14 +3961,13 @@ TEST(envscan_secret_key_exclusion) {
/* Normal key should be present */
ASSERT_NOT_NULL(find_binding_by_key(bindings, count, "NORMAL_URL"));
- char cmd[512];
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
PASS();
}
TEST(envscan_secret_value_exclusion) {
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_envscan_sval_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_envscan_sval_XXXXXX");
if (!cbm_mkdtemp(tmpdir))
SKIP("tmpdir");
@@ -4543,14 +3985,13 @@ TEST(envscan_secret_value_exclusion) {
/* Normal URL should be present */
ASSERT_NOT_NULL(find_binding_by_key(bindings, count, "NORMAL_ENDPOINT"));
- char cmd[512];
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
PASS();
}
TEST(envscan_secret_file_exclusion) {
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_envscan_sfile_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_envscan_sfile_XXXXXX");
if (!cbm_mkdtemp(tmpdir))
SKIP("tmpdir");
@@ -4576,14 +4017,13 @@ TEST(envscan_secret_file_exclusion) {
ASSERT_EQ(from_credentials, 0);
ASSERT_EQ(from_setup, 1);
- char cmd[512];
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
PASS();
}
TEST(envscan_skips_ignored_dirs) {
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_envscan_ign_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_envscan_ign_XXXXXX");
if (!cbm_mkdtemp(tmpdir))
SKIP("tmpdir");
@@ -4624,14 +4064,13 @@ TEST(envscan_skips_ignored_dirs) {
ASSERT_EQ(from_nm, 0);
ASSERT_EQ(from_root, 1);
- char cmd[512];
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
PASS();
}
TEST(envscan_non_url_values_skipped) {
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_envscan_nurl_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_envscan_nurl_XXXXXX");
if (!cbm_mkdtemp(tmpdir))
SKIP("tmpdir");
@@ -4651,9 +4090,7 @@ TEST(envscan_non_url_values_skipped) {
ASSERT_EQ(count, 0);
- char cmd[512];
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
PASS();
}
@@ -4854,14 +4291,18 @@ static int setup_incremental_repo(void) {
/* main.go — calls Helper() */
snprintf(path, sizeof(path), "%s/main.go", g_incr_tmpdir);
f = fopen(path, "w");
- if (!f) { return -1; }
+ if (!f) {
+ return -1;
+ }
fprintf(f, "package main\n\nfunc main() {\n\tHelper()\n}\n");
fclose(f);
/* helper.go — defines Helper() */
snprintf(path, sizeof(path), "%s/helper.go", g_incr_tmpdir);
f = fopen(path, "w");
- if (!f) { return -1; }
+ if (!f) {
+ return -1;
+ }
fprintf(f, "package main\n\nfunc Helper() string {\n\treturn \"hello\"\n}\n");
fclose(f);
@@ -4869,9 +4310,7 @@ static int setup_incremental_repo(void) {
}
static void cleanup_incremental_repo(void) {
- char cmd[512];
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", g_incr_tmpdir);
- (void)system(cmd);
+ th_rmtree(g_incr_tmpdir);
}
/* ═══════════════════════════════════════════════════════════════════
@@ -4882,15 +4321,14 @@ TEST(pipeline_fastapi_depends_edges) {
/* Depends(get_current_user) should produce a CALLS edge from the
* endpoint to the dependency function. */
const char *files[] = {"auth.py", "routes.py"};
- const char *contents[] = {
- /* auth.py: defines get_current_user */
- "def get_current_user(token: str):\n"
- " return decode_token(token)\n",
- /* routes.py: endpoint depends on get_current_user */
- "from fastapi import Depends\n"
- "from auth import get_current_user\n\n"
- "def get_profile(user = Depends(get_current_user)):\n"
- " return {\"user\": user}\n"};
+ const char *contents[] = {/* auth.py: defines get_current_user */
+ "def get_current_user(token: str):\n"
+ " return decode_token(token)\n",
+ /* routes.py: endpoint depends on get_current_user */
+ "from fastapi import Depends\n"
+ "from auth import get_current_user\n\n"
+ "def get_profile(user = Depends(get_current_user)):\n"
+ " return {\"user\": user}\n"};
if (setup_lang_repo(files, contents, 2) != 0) {
SKIP("tmpdir");
}
@@ -4911,8 +4349,7 @@ TEST(pipeline_fastapi_depends_edges) {
bool found_depends_edge = false;
for (int i = 0; i < edge_count; i++) {
- if (edges[i].properties_json &&
- strstr(edges[i].properties_json, "fastapi_depends")) {
+ if (edges[i].properties_json && strstr(edges[i].properties_json, "fastapi_depends")) {
found_depends_edge = true;
break;
}
@@ -4937,7 +4374,9 @@ TEST(pipeline_fastapi_depends_edges) {
TEST(incremental_full_then_noop) {
/* Full index, then re-run → should detect no changes and skip */
- if (setup_incremental_repo() != 0) { SKIP("setup failed"); }
+ if (setup_incremental_repo() != 0) {
+ SKIP("setup failed");
+ }
/* First: full index */
cbm_pipeline_t *p = cbm_pipeline_new(g_incr_tmpdir, g_incr_dbpath, CBM_MODE_FULL);
@@ -4973,7 +4412,9 @@ TEST(incremental_full_then_noop) {
TEST(incremental_detects_changed_file) {
/* Full index, modify one file, re-index → changed file re-parsed */
- if (setup_incremental_repo() != 0) { SKIP("setup failed"); }
+ if (setup_incremental_repo() != 0) {
+ SKIP("setup failed");
+ }
/* First: full index */
cbm_pipeline_t *p = cbm_pipeline_new(g_incr_tmpdir, g_incr_dbpath, CBM_MODE_FULL);
@@ -5012,7 +4453,9 @@ TEST(incremental_detects_changed_file) {
TEST(incremental_detects_deleted_file) {
/* Full index, delete a file, re-index → deleted file's nodes removed */
- if (setup_incremental_repo() != 0) { SKIP("setup failed"); }
+ if (setup_incremental_repo() != 0) {
+ SKIP("setup failed");
+ }
/* First: full index */
cbm_pipeline_t *p = cbm_pipeline_new(g_incr_tmpdir, g_incr_dbpath, CBM_MODE_FULL);
@@ -5046,7 +4489,9 @@ TEST(incremental_detects_deleted_file) {
TEST(incremental_new_file_added) {
/* Full index, add a new file, re-index → new file's nodes appear */
- if (setup_incremental_repo() != 0) { SKIP("setup failed"); }
+ if (setup_incremental_repo() != 0) {
+ SKIP("setup failed");
+ }
/* First: full index */
cbm_pipeline_t *p = cbm_pipeline_new(g_incr_tmpdir, g_incr_dbpath, CBM_MODE_FULL);
@@ -5141,9 +4586,7 @@ TEST(incremental_k8s_manifest_indexed) {
cbm_store_close(s);
free(project);
- char cmd[512];
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- (void)system(cmd);
+ th_rmtree(tmpdir);
PASS();
}
@@ -5208,9 +4651,7 @@ TEST(incremental_kustomize_module_indexed) {
ASSERT_TRUE(found_kust);
free(project);
- char cmd[512];
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- (void)system(cmd);
+ th_rmtree(tmpdir);
PASS();
}
@@ -5445,12 +4886,12 @@ TEST(env_var_name_valid) {
TEST(env_var_name_invalid) {
/* Invalid: too short, lowercase, mixed case, empty */
- ASSERT_FALSE(cbm_is_env_var_name("A")); /* single char */
- ASSERT_FALSE(cbm_is_env_var_name("port")); /* lowercase */
- ASSERT_FALSE(cbm_is_env_var_name("apiKey")); /* camelCase */
- ASSERT_FALSE(cbm_is_env_var_name("__")); /* no uppercase */
- ASSERT_FALSE(cbm_is_env_var_name("")); /* empty */
- ASSERT_FALSE(cbm_is_env_var_name("123")); /* digits only */
+ ASSERT_FALSE(cbm_is_env_var_name("A")); /* single char */
+ ASSERT_FALSE(cbm_is_env_var_name("port")); /* lowercase */
+ ASSERT_FALSE(cbm_is_env_var_name("apiKey")); /* camelCase */
+ ASSERT_FALSE(cbm_is_env_var_name("__")); /* no uppercase */
+ ASSERT_FALSE(cbm_is_env_var_name("")); /* empty */
+ ASSERT_FALSE(cbm_is_env_var_name("123")); /* digits only */
PASS();
}
@@ -5486,7 +4927,8 @@ TEST(split_camel_basic) {
ASSERT_STR_EQ(parts[0], "get");
ASSERT_STR_EQ(parts[1], "Camel");
ASSERT_STR_EQ(parts[2], "Case");
- for (int i = 0; i < n; i++) free(parts[i]);
+ for (int i = 0; i < n; i++)
+ free(parts[i]);
PASS();
}
@@ -5497,7 +4939,8 @@ TEST(split_camel_single_word) {
int n = cbm_split_camel_case("hello", parts, 16);
ASSERT_EQ(n, 1);
ASSERT_STR_EQ(parts[0], "hello");
- for (int i = 0; i < n; i++) free(parts[i]);
+ for (int i = 0; i < n; i++)
+ free(parts[i]);
PASS();
}
@@ -5505,7 +4948,8 @@ TEST(split_camel_empty) {
/* Empty string — should return 0 or 1 empty part */
char *parts[16];
int n = cbm_split_camel_case("", parts, 16);
- for (int i = 0; i < n; i++) free(parts[i]);
+ for (int i = 0; i < n; i++)
+ free(parts[i]);
/* Either 0 parts or 1 empty part is acceptable */
ASSERT_TRUE(n >= 0 && n <= 1);
PASS();
@@ -5518,7 +4962,8 @@ TEST(tokenize_decorator_login_required) {
ASSERT_EQ(n, 2);
ASSERT_STR_EQ(tokens[0], "login");
ASSERT_STR_EQ(tokens[1], "required");
- for (int i = 0; i < n; i++) free(tokens[i]);
+ for (int i = 0; i < n; i++)
+ free(tokens[i]);
PASS();
}
@@ -5528,7 +4973,8 @@ TEST(tokenize_decorator_single) {
int n = cbm_tokenize_decorator("@Override", tokens, 16);
ASSERT_EQ(n, 1);
ASSERT_STR_EQ(tokens[0], "override");
- for (int i = 0; i < n; i++) free(tokens[i]);
+ for (int i = 0; i < n; i++)
+ free(tokens[i]);
PASS();
}
@@ -5542,7 +4988,8 @@ TEST(split_command_basic) {
ASSERT_STR_EQ(args[2], "main.c");
ASSERT_STR_EQ(args[3], "-o");
ASSERT_STR_EQ(args[4], "main.o");
- for (int i = 0; i < n; i++) free(args[i]);
+ for (int i = 0; i < n; i++)
+ free(args[i]);
PASS();
}
@@ -5552,7 +4999,8 @@ TEST(split_command_quoted) {
int n = cbm_split_command("gcc -DFOO=\"bar baz\" main.c", args, 16);
ASSERT_GTE(n, 3);
ASSERT_STR_EQ(args[0], "gcc");
- for (int i = 0; i < n; i++) free(args[i]);
+ for (int i = 0; i < n; i++)
+ free(args[i]);
PASS();
}
@@ -5807,17 +5255,6 @@ SUITE(pipeline) {
RUN_TEST(configures_non_config_file_skipped);
RUN_TEST(configures_full_pipeline_integration);
/* HTTP link pipeline integration */
- RUN_TEST(pipeline_httplink_route_and_caller);
- RUN_TEST(pipeline_httplink_cross_file_prefix);
- RUN_TEST(pipeline_httplink_websocket_routes);
- /* HTTP link linker integration (ported from httplink_test.go) */
- RUN_TEST(httplink_linker_cross_file_group_variable);
- RUN_TEST(httplink_linker_registration_call_edges);
- RUN_TEST(httplink_linker_async_dispatch);
- RUN_TEST(httplink_linker_extract_async_call_sites);
- RUN_TEST(httplink_linker_fastapi_prefix);
- RUN_TEST(httplink_linker_express_prefix);
- RUN_TEST(httplink_linker_same_service_skip);
/* Enrichment helpers */
RUN_TEST(enrichment_split_camel_case);
RUN_TEST(enrichment_tokenize_decorator);
diff --git a/tests/test_registry.c b/tests/test_registry.c
index 207600a3d..4cfcff5b4 100644
--- a/tests/test_registry.c
+++ b/tests/test_registry.c
@@ -6,7 +6,6 @@
*/
#include "test_framework.h"
#include "pipeline/pipeline.h"
-#include "pipeline/httplink.h"
#include <stdlib.h>
#include <string.h>
diff --git a/tests/test_security.c b/tests/test_security.c
index 6fd56a178..21bc15f25 100644
--- a/tests/test_security.c
+++ b/tests/test_security.c
@@ -7,6 +7,7 @@
* - Path containment (realpath prevents directory traversal)
*/
#include "test_framework.h"
+#include "test_helpers.h"
#include <store/store.h>
#include <cypher/cypher.h>
#include "../src/foundation/str_util.h"
@@ -180,8 +181,8 @@ TEST(sqlite_allows_normal_queries) {
cbm_store_upsert_node(s, &n);
cbm_cypher_result_t r = {0};
- int rc =
- cbm_cypher_execute(s, "MATCH (f:Function) WHERE f.name = \"hello\" RETURN f", "test", 0, &r);
+ int rc = cbm_cypher_execute(s, "MATCH (f:Function) WHERE f.name = \"hello\" RETURN f", "test",
+ 0, &r);
ASSERT_EQ(rc, 0);
ASSERT_EQ(r.row_count, 1);
@@ -225,8 +226,8 @@ TEST(cypher_rejects_union_injection) {
cbm_store_upsert_project(s, "test", "/tmp/test");
cbm_cypher_result_t r = {0};
- int rc = cbm_cypher_execute(
- s, "MATCH (n) RETURN n UNION SELECT sql FROM sqlite_master", "test", 0, &r);
+ int rc = cbm_cypher_execute(s, "MATCH (n) RETURN n UNION SELECT sql FROM sqlite_master", "test",
+ 0, &r);
/* Cypher parser should reject UNION — it's not valid Cypher */
ASSERT_NEQ(rc, 0);
cbm_cypher_result_free(&r);
@@ -262,9 +263,8 @@ TEST(path_traversal_blocked) {
if (realpath(traversal, real_file)) {
/* Verify the resolved path does NOT start with root */
size_t root_len = strlen(real_root);
- int contained =
- (strncmp(real_file, real_root, root_len) == 0 &&
- (real_file[root_len] == '/' || real_file[root_len] == '\0'));
+ int contained = (strncmp(real_file, real_root, root_len) == 0 &&
+ (real_file[root_len] == '/' || real_file[root_len] == '\0'));
ASSERT_FALSE(contained);
}
/* If realpath fails, the file doesn't exist — also safe */
@@ -281,9 +281,8 @@ TEST(path_within_root_allowed) {
const char *root = "/tmp";
if (realpath(root, real_root) && realpath("/tmp", real_file)) {
size_t root_len = strlen(real_root);
- int contained =
- (strncmp(real_file, real_root, root_len) == 0 &&
- (real_file[root_len] == '/' || real_file[root_len] == '\0'));
+ int contained = (strncmp(real_file, real_root, root_len) == 0 &&
+ (real_file[root_len] == '/' || real_file[root_len] == '\0'));
ASSERT_TRUE(contained);
}
PASS();
diff --git a/tests/test_store_search.c b/tests/test_store_search.c
index 05df86806..7087803e5 100644
--- a/tests/test_store_search.c
+++ b/tests/test_store_search.c
@@ -5,6 +5,7 @@
*/
#include "../src/foundation/compat.h"
#include "test_framework.h"
+#include "test_helpers.h"
#include <store/store.h>
#include <string.h>
#include <stdlib.h>
@@ -420,9 +421,6 @@ TEST(store_search_exclude_labels) {
/* ── Dump to file ──────────────────────────────────────────────── */
TEST(store_dump_to_file) {
-#ifdef _WIN32
- SKIP("temp file path handling — Windows port pending");
-#endif
cbm_store_t *s = cbm_store_open_memory();
cbm_store_upsert_project(s, "test", "/tmp/test");
@@ -438,7 +436,9 @@ TEST(store_dump_to_file) {
ASSERT_TRUE(id > 0);
/* Dump to temp file */
- char path[256]; snprintf(path, sizeof(path), "/tmp/cbm_test_dump_XXXXXX");
+ char *td = th_mktempdir("cbm_dump");
+ char path[256];
+ snprintf(path, sizeof(path), "%s/test.db", td);
int fd = cbm_mkstemp(path);
ASSERT_TRUE(fd >= 0);
close(fd);
diff --git a/tests/test_ui.c b/tests/test_ui.c
index 58e726ae5..002e8d39a 100644
--- a/tests/test_ui.c
+++ b/tests/test_ui.c
@@ -6,6 +6,7 @@
#include "../src/foundation/compat.h"
#include "../src/foundation/compat_fs.h"
#include "test_framework.h"
+#include "test_helpers.h"
#include "ui/config.h"
#include "ui/embedded_assets.h"
#include "ui/layout3d.h"
@@ -27,7 +28,8 @@ TEST(config_load_defaults) {
cfg.ui_port = 1234;
/* Use a temp HOME to avoid touching real config */
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_test_config_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_test_config_XXXXXX");
char *td = cbm_mkdtemp(tmpdir);
ASSERT_NOT_NULL(td);
@@ -49,7 +51,8 @@ TEST(config_load_defaults) {
}
TEST(config_save_and_reload) {
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_test_config_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_test_config_XXXXXX");
char *td = cbm_mkdtemp(tmpdir);
ASSERT_NOT_NULL(td);
@@ -76,7 +79,8 @@ TEST(config_save_and_reload) {
}
TEST(config_overwrite) {
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_test_config_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_test_config_XXXXXX");
char *td = cbm_mkdtemp(tmpdir);
ASSERT_NOT_NULL(td);
@@ -105,7 +109,8 @@ TEST(config_overwrite) {
}
TEST(config_corrupt_file) {
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_test_config_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_test_config_XXXXXX");
char *td = cbm_mkdtemp(tmpdir);
ASSERT_NOT_NULL(td);
@@ -141,7 +146,8 @@ TEST(config_corrupt_file) {
}
TEST(config_missing_fields) {
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_test_config_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_test_config_XXXXXX");
char *td = cbm_mkdtemp(tmpdir);
ASSERT_NOT_NULL(td);
diff --git a/tests/test_vmem.c b/tests/test_vmem.c
index c0e833e7d..0da8d78b3 100644
--- a/tests/test_vmem.c
+++ b/tests/test_vmem.c
@@ -3,6 +3,7 @@
* arena-vmem integration, and slab+vmem parallel extraction.
*/
#include "test_framework.h"
+#include "test_helpers.h"
#include "../src/foundation/vmem.h"
#include "../src/foundation/arena.h"
#include "../src/foundation/slab_alloc.h"
@@ -664,8 +665,10 @@ static int setup_vmem_test_repo(void) {
if (!f) {
return -1;
}
- fprintf(f, "package main\n\nfunc F%d() {\n\tprintln(\"hello\")\n}\n\n"
- "func G%d() int {\n\treturn F%d() + %d\n}\n", i, i, i, i);
+ fprintf(f,
+ "package main\n\nfunc F%d() {\n\tprintln(\"hello\")\n}\n\n"
+ "func G%d() int {\n\treturn F%d() + %d\n}\n",
+ i, i, i, i);
fclose(f);
}
@@ -684,9 +687,7 @@ static int setup_vmem_test_repo(void) {
static void teardown_vmem_test_repo(void) {
if (g_vmem_tmpdir[0]) {
- char cmd[512];
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", g_vmem_tmpdir);
- (void)system(cmd);
+ th_rmtree(g_vmem_tmpdir);
g_vmem_tmpdir[0] = '\0';
}
}
@@ -740,8 +741,7 @@ TEST(vmem_parallel_extract_with_slab) {
/* Run parallel extraction with 2 workers — enough to trigger
* multi-file slab reuse on at least one worker. */
- int rc = cbm_parallel_extract(&ctx, files, file_count, result_cache,
- &shared_ids, 2);
+ int rc = cbm_parallel_extract(&ctx, files, file_count, result_cache, &shared_ids, 2);
ASSERT_EQ(rc, 0);
/* Verify extraction produced results */
diff --git a/tests/test_watcher.c b/tests/test_watcher.c
index f2b8a66d8..20aace358 100644
--- a/tests/test_watcher.c
+++ b/tests/test_watcher.c
@@ -6,6 +6,7 @@
*/
#include "../src/foundation/compat.h"
#include "test_framework.h"
+#include "test_helpers.h"
#include <watcher/watcher.h>
#include <store/store.h>
#include <string.h>
@@ -229,7 +230,8 @@ TEST(watcher_stop_flag) {
TEST(watcher_detects_git_commit) {
/* Create a temporary git repo */
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_test_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_test_XXXXXX");
if (!cbm_mkdtemp(tmpdir))
SKIP("cbm_mkdtemp failed");
@@ -240,8 +242,7 @@ TEST(watcher_detects_git_commit) {
"git add file.txt && git commit -q -m 'init'",
tmpdir);
if (system(cmd) != 0) {
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
SKIP("git not available");
}
@@ -275,14 +276,14 @@ TEST(watcher_detects_git_commit) {
/* Cleanup */
cbm_watcher_free(w);
cbm_store_close(store);
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
PASS();
}
TEST(watcher_detects_dirty_worktree) {
/* Create a temporary git repo */
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_dirty_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_dirty_XXXXXX");
if (!cbm_mkdtemp(tmpdir))
SKIP("cbm_mkdtemp failed");
@@ -293,8 +294,7 @@ TEST(watcher_detects_dirty_worktree) {
"git add file.txt && git commit -q -m 'init'",
tmpdir);
if (system(cmd) != 0) {
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
SKIP("git not available");
}
@@ -308,8 +308,11 @@ TEST(watcher_detects_dirty_worktree) {
cbm_watcher_poll_once(w);
/* Make working tree dirty (uncommitted change) */
- snprintf(cmd, sizeof(cmd), "cd '%s' && echo 'modified' >> file.txt", tmpdir);
- system(cmd);
+ {
+ char _p[1024];
+ snprintf(_p, sizeof(_p), "%s/file.txt", tmpdir);
+ th_append_file(_p, "modified\n");
+ }
/* Poll → should detect dirty worktree */
cbm_watcher_touch(w, "dirty-repo");
@@ -319,14 +322,14 @@ TEST(watcher_detects_dirty_worktree) {
/* Cleanup */
cbm_watcher_free(w);
cbm_store_close(store);
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
PASS();
}
TEST(watcher_detects_new_file) {
/* Create a temporary git repo */
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_newf_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_newf_XXXXXX");
if (!cbm_mkdtemp(tmpdir))
SKIP("cbm_mkdtemp failed");
@@ -337,8 +340,7 @@ TEST(watcher_detects_new_file) {
"git add file.txt && git commit -q -m 'init'",
tmpdir);
if (system(cmd) != 0) {
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
SKIP("git not available");
}
@@ -353,8 +355,11 @@ TEST(watcher_detects_new_file) {
ASSERT_EQ(index_call_count, 0);
/* Add a new untracked file */
- snprintf(cmd, sizeof(cmd), "echo 'new content' > '%s/newfile.go'", tmpdir);
- system(cmd);
+ {
+ char _p[1024];
+ snprintf(_p, sizeof(_p), "%s/newfile.go", tmpdir);
+ th_write_file(_p, "new content\n");
+ }
/* Touch to bypass interval, then poll */
cbm_watcher_touch(w, "newf-repo");
@@ -364,14 +369,14 @@ TEST(watcher_detects_new_file) {
/* Cleanup */
cbm_watcher_free(w);
cbm_store_close(store);
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
PASS();
}
TEST(watcher_no_change_no_reindex) {
/* Create a temporary git repo */
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_nochg_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_nochg_XXXXXX");
if (!cbm_mkdtemp(tmpdir))
SKIP("cbm_mkdtemp failed");
@@ -382,8 +387,7 @@ TEST(watcher_no_change_no_reindex) {
"git add file.txt && git commit -q -m 'init'",
tmpdir);
if (system(cmd) != 0) {
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
SKIP("git not available");
}
@@ -407,15 +411,16 @@ TEST(watcher_no_change_no_reindex) {
/* Cleanup */
cbm_watcher_free(w);
cbm_store_close(store);
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
PASS();
}
TEST(watcher_multiple_projects) {
/* Create two temporary git repos */
- char tmpdirA[256]; snprintf(tmpdirA, sizeof(tmpdirA), "/tmp/cbm_watcher_mA_XXXXXX");
- char tmpdirB[256]; snprintf(tmpdirB, sizeof(tmpdirB), "/tmp/cbm_watcher_mB_XXXXXX");
+ char tmpdirA[256];
+ snprintf(tmpdirA, sizeof(tmpdirA), "/tmp/cbm_watcher_mA_XXXXXX");
+ char tmpdirB[256];
+ snprintf(tmpdirB, sizeof(tmpdirB), "/tmp/cbm_watcher_mB_XXXXXX");
if (!cbm_mkdtemp(tmpdirA) || !cbm_mkdtemp(tmpdirB))
SKIP("cbm_mkdtemp failed");
@@ -451,8 +456,11 @@ TEST(watcher_multiple_projects) {
ASSERT_EQ(index_call_count, 0);
/* Modify only A */
- snprintf(cmd, sizeof(cmd), "echo 'modified' >> '%s/a.txt'", tmpdirA);
- system(cmd);
+ {
+ char _p[1024];
+ snprintf(_p, sizeof(_p), "%s/a.txt", tmpdirA);
+ th_append_file(_p, "modified\n");
+ }
/* Poll — only A should trigger */
cbm_watcher_touch(w, "projA");
@@ -463,8 +471,8 @@ TEST(watcher_multiple_projects) {
/* Cleanup */
cbm_watcher_free(w);
cbm_store_close(store);
- snprintf(cmd, sizeof(cmd), "rm -rf '%s' '%s'", tmpdirA, tmpdirB);
- system(cmd);
+ th_rmtree(tmpdirA);
+ th_rmtree(tmpdirB);
PASS();
}
@@ -475,14 +483,17 @@ TEST(watcher_multiple_projects) {
TEST(watcher_non_git_skips) {
/* Non-git dir → baseline sets is_git=false → poll never reindexes.
* Port of TestProbeStrategyNonGit behavior. */
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_nongit_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_nongit_XXXXXX");
if (!cbm_mkdtemp(tmpdir))
SKIP("cbm_mkdtemp failed");
/* Create a file so it's not empty */
- char cmd[512];
- snprintf(cmd, sizeof(cmd), "echo 'hello' > '%s/file.txt'", tmpdir);
- system(cmd);
+ {
+ char _p[1024];
+ snprintf(_p, sizeof(_p), "%s/file.txt", tmpdir);
+ th_write_file(_p, "hello\n");
+ }
cbm_store_t *store = cbm_store_open_memory();
cbm_watcher_t *w = cbm_watcher_new(store, index_callback, NULL);
@@ -494,8 +505,11 @@ TEST(watcher_non_git_skips) {
ASSERT_EQ(index_call_count, 0);
/* Modify file */
- snprintf(cmd, sizeof(cmd), "echo 'modified' >> '%s/file.txt'", tmpdir);
- system(cmd);
+ {
+ char _p[1024];
+ snprintf(_p, sizeof(_p), "%s/file.txt", tmpdir);
+ th_append_file(_p, "modified\n");
+ }
/* Touch + poll — should NOT trigger (non-git projects are skipped) */
cbm_watcher_touch(w, "nongit");
@@ -503,16 +517,18 @@ TEST(watcher_non_git_skips) {
ASSERT_EQ(index_call_count, 0);
/* Even add a new file — still no reindex */
- snprintf(cmd, sizeof(cmd), "echo 'new' > '%s/new.txt'", tmpdir);
- system(cmd);
+ {
+ char _p[1024];
+ snprintf(_p, sizeof(_p), "%s/new.txt", tmpdir);
+ th_write_file(_p, "new\n");
+ }
cbm_watcher_touch(w, "nongit");
cbm_watcher_poll_once(w);
ASSERT_EQ(index_call_count, 0);
cbm_watcher_free(w);
cbm_store_close(store);
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
PASS();
}
@@ -524,7 +540,8 @@ TEST(watcher_interval_blocks_repoll) {
/* After baseline, the adaptive interval (5s minimum) should block
* immediate re-polling. Without touch(), the next poll is a no-op.
* Port of TestWatcherGitNoChanges' interval behavior. */
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_intv_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_intv_XXXXXX");
if (!cbm_mkdtemp(tmpdir))
SKIP("cbm_mkdtemp failed");
@@ -535,8 +552,7 @@ TEST(watcher_interval_blocks_repoll) {
"git add file.txt && git commit -q -m 'init'",
tmpdir);
if (system(cmd) != 0) {
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
SKIP("git not available");
}
@@ -550,8 +566,11 @@ TEST(watcher_interval_blocks_repoll) {
ASSERT_EQ(index_call_count, 0);
/* Make repo dirty */
- snprintf(cmd, sizeof(cmd), "echo 'dirty' >> '%s/file.txt'", tmpdir);
- system(cmd);
+ {
+ char _p[1024];
+ snprintf(_p, sizeof(_p), "%s/file.txt", tmpdir);
+ th_append_file(_p, "dirty\n");
+ }
/* Poll WITHOUT touch — interval should block checking */
cbm_watcher_poll_once(w);
@@ -564,8 +583,7 @@ TEST(watcher_interval_blocks_repoll) {
cbm_watcher_free(w);
cbm_store_close(store);
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
PASS();
}
@@ -598,7 +616,8 @@ TEST(watcher_git_removed_no_crash) {
/* Init git repo, baseline, remove .git, poll → should not crash.
* Port of TestStrategyDowngradeGitToDirMtime behavior (C version
* doesn't downgrade — just git commands fail silently). */
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_rmgit_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_rmgit_XXXXXX");
if (!cbm_mkdtemp(tmpdir))
SKIP("cbm_mkdtemp failed");
@@ -609,8 +628,7 @@ TEST(watcher_git_removed_no_crash) {
"git add file.txt && git commit -q -m 'init'",
tmpdir);
if (system(cmd) != 0) {
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
SKIP("git not available");
}
@@ -624,8 +642,11 @@ TEST(watcher_git_removed_no_crash) {
ASSERT_EQ(index_call_count, 0);
/* Remove .git — git commands will fail */
- snprintf(cmd, sizeof(cmd), "rm -rf '%s/.git'", tmpdir);
- system(cmd);
+ {
+ char _p[1024];
+ snprintf(_p, sizeof(_p), "%s/.git", tmpdir);
+ th_rmtree(_p);
+ }
/* Poll — should not crash, git_head() and git_is_dirty() fail gracefully */
cbm_watcher_touch(w, "rmgit-repo");
@@ -635,15 +656,15 @@ TEST(watcher_git_removed_no_crash) {
cbm_watcher_free(w);
cbm_store_close(store);
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
PASS();
}
TEST(watcher_continued_dirty) {
/* If working tree stays dirty, each poll should re-trigger reindex.
* Port of repeated git sentinel detection behavior. */
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_cont_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_cont_XXXXXX");
if (!cbm_mkdtemp(tmpdir))
SKIP("cbm_mkdtemp failed");
@@ -654,8 +675,7 @@ TEST(watcher_continued_dirty) {
"git add file.txt && git commit -q -m 'init'",
tmpdir);
if (system(cmd) != 0) {
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
SKIP("git not available");
}
@@ -669,8 +689,11 @@ TEST(watcher_continued_dirty) {
ASSERT_EQ(index_call_count, 0);
/* Make dirty */
- snprintf(cmd, sizeof(cmd), "echo 'dirty' >> '%s/file.txt'", tmpdir);
- system(cmd);
+ {
+ char _p[1024];
+ snprintf(_p, sizeof(_p), "%s/file.txt", tmpdir);
+ th_append_file(_p, "dirty\n");
+ }
/* First detection */
cbm_watcher_touch(w, "cont-repo");
@@ -703,15 +726,15 @@ TEST(watcher_continued_dirty) {
cbm_watcher_free(w);
cbm_store_close(store);
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
PASS();
}
TEST(watcher_baseline_dirty_repo) {
/* Baseline on a repo that already has uncommitted changes.
* Port of TestGitSentinelDetectsEdit (dirty from the start). */
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_bld_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_bld_XXXXXX");
if (!cbm_mkdtemp(tmpdir))
SKIP("cbm_mkdtemp failed");
@@ -722,14 +745,16 @@ TEST(watcher_baseline_dirty_repo) {
"git add file.txt && git commit -q -m 'init'",
tmpdir);
if (system(cmd) != 0) {
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
SKIP("git not available");
}
/* Make dirty BEFORE baseline */
- snprintf(cmd, sizeof(cmd), "echo 'dirty from start' >> '%s/file.txt'", tmpdir);
- system(cmd);
+ {
+ char _p[1024];
+ snprintf(_p, sizeof(_p), "%s/file.txt", tmpdir);
+ th_append_file(_p, "dirty from start\n");
+ }
cbm_store_t *store = cbm_store_open_memory();
cbm_watcher_t *w = cbm_watcher_new(store, index_callback, NULL);
@@ -747,15 +772,15 @@ TEST(watcher_baseline_dirty_repo) {
cbm_watcher_free(w);
cbm_store_close(store);
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
PASS();
}
TEST(watcher_unwatch_prunes_state) {
/* Watch, baseline, unwatch → project state removed.
* Port of TestPollAllPrunesUnwatched + TestWatcherPrunesDeletedProjects. */
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_prune_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_prune_XXXXXX");
if (!cbm_mkdtemp(tmpdir))
SKIP("cbm_mkdtemp failed");
@@ -766,8 +791,7 @@ TEST(watcher_unwatch_prunes_state) {
"git add file.txt && git commit -q -m 'init'",
tmpdir);
if (system(cmd) != 0) {
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
SKIP("git not available");
}
@@ -786,22 +810,25 @@ TEST(watcher_unwatch_prunes_state) {
ASSERT_EQ(cbm_watcher_watch_count(w), 0);
/* Make dirty + poll — nothing should happen */
- snprintf(cmd, sizeof(cmd), "echo 'dirty' >> '%s/file.txt'", tmpdir);
- system(cmd);
+ {
+ char _p[1024];
+ snprintf(_p, sizeof(_p), "%s/file.txt", tmpdir);
+ th_append_file(_p, "dirty\n");
+ }
cbm_watcher_poll_once(w);
ASSERT_EQ(index_call_count, 0); /* no projects to poll */
cbm_watcher_free(w);
cbm_store_close(store);
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
PASS();
}
TEST(watcher_watch_after_unwatch) {
/* Re-watching after unwatch should start fresh (new baseline).
* Tests lifecycle correctness. */
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_rewatch_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_rewatch_XXXXXX");
if (!cbm_mkdtemp(tmpdir))
SKIP("cbm_mkdtemp failed");
@@ -812,8 +839,7 @@ TEST(watcher_watch_after_unwatch) {
"git add file.txt && git commit -q -m 'init'",
tmpdir);
if (system(cmd) != 0) {
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
SKIP("git not available");
}
@@ -827,8 +853,11 @@ TEST(watcher_watch_after_unwatch) {
ASSERT_EQ(cbm_watcher_watch_count(w), 0);
/* Make dirty while unwatched */
- snprintf(cmd, sizeof(cmd), "echo 'dirty' >> '%s/file.txt'", tmpdir);
- system(cmd);
+ {
+ char _p[1024];
+ snprintf(_p, sizeof(_p), "%s/file.txt", tmpdir);
+ th_append_file(_p, "dirty\n");
+ }
/* Re-watch — needs fresh baseline */
cbm_watcher_watch(w, "rewatch-repo", tmpdir);
@@ -846,8 +875,7 @@ TEST(watcher_watch_after_unwatch) {
cbm_watcher_free(w);
cbm_store_close(store);
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
PASS();
}
@@ -862,7 +890,8 @@ TEST(watcher_watch_after_unwatch) {
TEST(watcher_detects_file_delete) {
/* Port of TestFSNotifyDetectsFileDelete:
* Delete a tracked file → git status shows change → reindex triggered. */
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_del_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_del_XXXXXX");
if (!cbm_mkdtemp(tmpdir))
SKIP("cbm_mkdtemp failed");
@@ -874,8 +903,7 @@ TEST(watcher_detects_file_delete) {
"git add -A && git commit -q -m 'init'",
tmpdir);
if (system(cmd) != 0) {
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
SKIP("git not available");
}
@@ -889,8 +917,11 @@ TEST(watcher_detects_file_delete) {
ASSERT_EQ(index_call_count, 0);
/* Delete tracked file → dirty worktree */
- snprintf(cmd, sizeof(cmd), "rm '%s/todelete.go'", tmpdir);
- system(cmd);
+ {
+ char _p[1024];
+ snprintf(_p, sizeof(_p), "%s/todelete.go", tmpdir);
+ cbm_unlink(_p);
+ }
/* Touch + poll → should detect deletion */
cbm_watcher_touch(w, "del-repo");
@@ -899,15 +930,15 @@ TEST(watcher_detects_file_delete) {
cbm_watcher_free(w);
cbm_store_close(store);
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
PASS();
}
TEST(watcher_detects_subdir_file) {
/* Port of TestFSNotifyWatchesNewSubdir:
* Create new subdir + file in it → git detects untracked → reindex. */
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_sub_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_sub_XXXXXX");
if (!cbm_mkdtemp(tmpdir))
SKIP("cbm_mkdtemp failed");
@@ -918,8 +949,7 @@ TEST(watcher_detects_subdir_file) {
"git add main.go && git commit -q -m 'init'",
tmpdir);
if (system(cmd) != 0) {
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
SKIP("git not available");
}
@@ -933,9 +963,11 @@ TEST(watcher_detects_subdir_file) {
ASSERT_EQ(index_call_count, 0);
/* Create new subdir and file in it */
- snprintf(cmd, sizeof(cmd), "mkdir -p '%s/pkg' && echo 'package pkg' > '%s/pkg/lib.go'", tmpdir,
- tmpdir);
- system(cmd);
+ {
+ char _p[1024];
+ snprintf(_p, sizeof(_p), "%s/pkg/lib.go", tmpdir);
+ th_write_file(_p, "package pkg\n");
+ }
/* Touch + poll → should detect untracked file in subdir */
cbm_watcher_touch(w, "sub-repo");
@@ -944,8 +976,7 @@ TEST(watcher_detects_subdir_file) {
cbm_watcher_free(w);
cbm_store_close(store);
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
PASS();
}
@@ -978,7 +1009,8 @@ TEST(watcher_full_flow_new_file) {
* Full lifecycle: watch → baseline → add file → detect change.
* This is a more thorough version of watcher_detects_new_file
* that mirrors the Go test's structure exactly. */
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_ffnf_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_ffnf_XXXXXX");
if (!cbm_mkdtemp(tmpdir))
SKIP("cbm_mkdtemp failed");
@@ -989,8 +1021,7 @@ TEST(watcher_full_flow_new_file) {
"git add main.go && git commit -q -m 'init'",
tmpdir);
if (system(cmd) != 0) {
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
SKIP("git not available");
}
@@ -1008,8 +1039,11 @@ TEST(watcher_full_flow_new_file) {
ASSERT_EQ(index_call_count, 0);
/* Create a new file */
- snprintf(cmd, sizeof(cmd), "echo 'package main' > '%s/util.go'", tmpdir);
- system(cmd);
+ {
+ char _p[1024];
+ snprintf(_p, sizeof(_p), "%s/util.go", tmpdir);
+ th_write_file(_p, "package main\n");
+ }
/* Touch to bypass interval, then poll — should detect */
cbm_watcher_touch(w, "ffnf-repo");
@@ -1018,8 +1052,7 @@ TEST(watcher_full_flow_new_file) {
cbm_watcher_free(w);
cbm_store_close(store);
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
PASS();
}
@@ -1028,7 +1061,8 @@ TEST(watcher_fallback_still_detects) {
* Even when the "primary" strategy has issues, the watcher
* still detects changes. In C, we test that after removing .git
* and re-creating it, changes are still detected on re-watch. */
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_fb_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_fb_XXXXXX");
if (!cbm_mkdtemp(tmpdir))
SKIP("cbm_mkdtemp failed");
@@ -1039,8 +1073,7 @@ TEST(watcher_fallback_still_detects) {
"git add main.go && git commit -q -m 'init'",
tmpdir);
if (system(cmd) != 0) {
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
SKIP("git not available");
}
@@ -1067,8 +1100,11 @@ TEST(watcher_fallback_still_detects) {
cbm_watcher_poll_once(w); /* new baseline */
/* Add new file */
- snprintf(cmd, sizeof(cmd), "echo 'package main' > '%s/new.go'", tmpdir);
- system(cmd);
+ {
+ char _p[1024];
+ snprintf(_p, sizeof(_p), "%s/new.go", tmpdir);
+ th_write_file(_p, "package main\n");
+ }
/* Detect change with fresh git strategy */
cbm_watcher_touch(w, "fb-repo");
@@ -1077,8 +1113,7 @@ TEST(watcher_fallback_still_detects) {
cbm_watcher_free(w);
cbm_store_close(store);
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
PASS();
}
@@ -1086,8 +1121,10 @@ TEST(watcher_poll_only_watched_projects) {
/* Port of TestPollAllOnlyWatched:
* Two repos exist, only one is watched → only the watched one
* gets polled and can trigger reindex. */
- char tmpdirA[256]; snprintf(tmpdirA, sizeof(tmpdirA), "/tmp/cbm_watcher_owA_XXXXXX");
- char tmpdirB[256]; snprintf(tmpdirB, sizeof(tmpdirB), "/tmp/cbm_watcher_owB_XXXXXX");
+ char tmpdirA[256];
+ snprintf(tmpdirA, sizeof(tmpdirA), "/tmp/cbm_watcher_owA_XXXXXX");
+ char tmpdirB[256];
+ snprintf(tmpdirB, sizeof(tmpdirB), "/tmp/cbm_watcher_owB_XXXXXX");
if (!cbm_mkdtemp(tmpdirA) || !cbm_mkdtemp(tmpdirB))
SKIP("cbm_mkdtemp failed");
@@ -1124,10 +1161,16 @@ TEST(watcher_poll_only_watched_projects) {
ASSERT_EQ(index_call_count, 0);
/* Make BOTH repos dirty */
- snprintf(cmd, sizeof(cmd), "echo 'dirty' >> '%s/a.txt'", tmpdirA);
- system(cmd);
- snprintf(cmd, sizeof(cmd), "echo 'dirty' >> '%s/b.txt'", tmpdirB);
- system(cmd);
+ {
+ char _p[1024];
+ snprintf(_p, sizeof(_p), "%s/a.txt", tmpdirA);
+ th_append_file(_p, "dirty\n");
+ }
+ {
+ char _p[1024];
+ snprintf(_p, sizeof(_p), "%s/b.txt", tmpdirB);
+ th_append_file(_p, "dirty\n");
+ }
/* Poll — only A should trigger (B is not watched) */
cbm_watcher_touch(w, "projA-ow");
@@ -1136,8 +1179,8 @@ TEST(watcher_poll_only_watched_projects) {
cbm_watcher_free(w);
cbm_store_close(store);
- snprintf(cmd, sizeof(cmd), "rm -rf '%s' '%s'", tmpdirA, tmpdirB);
- system(cmd);
+ th_rmtree(tmpdirA);
+ th_rmtree(tmpdirB);
PASS();
}
@@ -1145,7 +1188,8 @@ TEST(watcher_touch_resets_immediate) {
/* Port of TestTouchProjectUpdatesTimestamp:
* Verify that touch() resets the adaptive backoff so the next
* poll actually checks for changes immediately. */
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_tch_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_tch_XXXXXX");
if (!cbm_mkdtemp(tmpdir))
SKIP("cbm_mkdtemp failed");
@@ -1156,8 +1200,7 @@ TEST(watcher_touch_resets_immediate) {
"git add file.txt && git commit -q -m 'init'",
tmpdir);
if (system(cmd) != 0) {
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
SKIP("git not available");
}
@@ -1171,8 +1214,11 @@ TEST(watcher_touch_resets_immediate) {
ASSERT_EQ(index_call_count, 0);
/* Make dirty */
- snprintf(cmd, sizeof(cmd), "echo 'dirty' >> '%s/file.txt'", tmpdir);
- system(cmd);
+ {
+ char _p[1024];
+ snprintf(_p, sizeof(_p), "%s/file.txt", tmpdir);
+ th_append_file(_p, "dirty\n");
+ }
/* Without touch: interval blocks poll */
cbm_watcher_poll_once(w);
@@ -1185,8 +1231,7 @@ TEST(watcher_touch_resets_immediate) {
cbm_watcher_free(w);
cbm_store_close(store);
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
PASS();
}
@@ -1195,7 +1240,8 @@ TEST(watcher_modify_tracked_file) {
* Modify tracked file content (not just create/delete) → detected.
* Similar to watcher_detects_dirty_worktree but modifies specific
* tracked file content rather than appending. */
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_mod_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_mod_XXXXXX");
if (!cbm_mkdtemp(tmpdir))
SKIP("cbm_mkdtemp failed");
@@ -1206,8 +1252,7 @@ TEST(watcher_modify_tracked_file) {
"git add main.go && git commit -q -m 'init'",
tmpdir);
if (system(cmd) != 0) {
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
SKIP("git not available");
}
@@ -1226,8 +1271,11 @@ TEST(watcher_modify_tracked_file) {
ASSERT_EQ(index_call_count, 0);
/* Overwrite file with new content */
- snprintf(cmd, sizeof(cmd), "echo 'package main\n\nfunc main() {}' > '%s/main.go'", tmpdir);
- system(cmd);
+ {
+ char _p[1024];
+ snprintf(_p, sizeof(_p), "%s/main.go", tmpdir);
+ th_write_file(_p, "package main\n\nfunc main() {}\n");
+ }
/* Touch + poll → should detect modification */
cbm_watcher_touch(w, "mod-repo");
@@ -1236,8 +1284,7 @@ TEST(watcher_modify_tracked_file) {
cbm_watcher_free(w);
cbm_store_close(store);
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
PASS();
}
@@ -1403,14 +1450,17 @@ TEST(watcher_poll_empty_returns_zero) {
TEST(watcher_poll_non_git_dir) {
/* poll_once with a non-git directory → 0 changes detected */
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_ng2_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_ng2_XXXXXX");
if (!cbm_mkdtemp(tmpdir))
SKIP("cbm_mkdtemp failed");
/* Create a regular file so directory is not empty */
- char cmd[512];
- snprintf(cmd, sizeof(cmd), "echo 'hello' > '%s/file.txt'", tmpdir);
- system(cmd);
+ {
+ char _p[1024];
+ snprintf(_p, sizeof(_p), "%s/file.txt", tmpdir);
+ th_write_file(_p, "hello\n");
+ }
cbm_store_t *store = cbm_store_open_memory();
cbm_watcher_t *w = cbm_watcher_new(store, index_callback, NULL);
@@ -1421,8 +1471,11 @@ TEST(watcher_poll_non_git_dir) {
cbm_watcher_poll_once(w);
/* Modify file */
- snprintf(cmd, sizeof(cmd), "echo 'world' >> '%s/file.txt'", tmpdir);
- system(cmd);
+ {
+ char _p[1024];
+ snprintf(_p, sizeof(_p), "%s/file.txt", tmpdir);
+ th_append_file(_p, "world\n");
+ }
/* Poll — non-git directory, should not trigger reindex */
cbm_watcher_touch(w, "nongit2");
@@ -1432,8 +1485,7 @@ TEST(watcher_poll_non_git_dir) {
cbm_watcher_free(w);
cbm_store_close(store);
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
PASS();
}
@@ -1473,7 +1525,8 @@ static int g_cbdata_value = 42;
static int *g_cbdata_received = NULL;
static int capture_data_callback(const char *name, const char *path, void *ud) {
- (void)name; (void)path;
+ (void)name;
+ (void)path;
g_cbdata_received = (int *)ud;
return 0;
}
@@ -1483,7 +1536,8 @@ TEST(watcher_callback_data_passed) {
g_cbdata_received = NULL;
/* Create a temp git repo */
- char tmpdir[256]; snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_cbdata_XXXXXX");
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_cbdata_XXXXXX");
if (!cbm_mkdtemp(tmpdir))
SKIP("cbm_mkdtemp failed");
@@ -1494,8 +1548,7 @@ TEST(watcher_callback_data_passed) {
"git add file.txt && git commit -q -m 'init'",
tmpdir);
if (system(cmd) != 0) {
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
SKIP("git not available");
}
@@ -1507,8 +1560,11 @@ TEST(watcher_callback_data_passed) {
cbm_watcher_poll_once(w);
/* Make dirty to trigger callback */
- snprintf(cmd, sizeof(cmd), "echo 'dirty' >> '%s/file.txt'", tmpdir);
- system(cmd);
+ {
+ char _p[1024];
+ snprintf(_p, sizeof(_p), "%s/file.txt", tmpdir);
+ th_append_file(_p, "dirty\n");
+ }
cbm_watcher_touch(w, "cbdata-repo");
cbm_watcher_poll_once(w);
@@ -1520,8 +1576,7 @@ TEST(watcher_callback_data_passed) {
cbm_watcher_free(w);
cbm_store_close(store);
- snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
- system(cmd);
+ th_rmtree(tmpdir);
PASS();
}