diff --git a/.github/actions/upload-test-artifact/action.yml b/.github/actions/upload-test-artifact/action.yml new file mode 100644 index 0000000000..cf1b2df7ea --- /dev/null +++ b/.github/actions/upload-test-artifact/action.yml @@ -0,0 +1,66 @@ +name: Upload test artifact +description: Upload required CI evidence with bounded transport retries + +inputs: + name: + description: Unique artifact name for this job + required: true + path: + description: Files to upload + required: true + retention-days: + description: Artifact retention in days + default: '5' + include-hidden-files: + description: Include explicitly selected hidden report directories + default: 'false' + +runs: + using: composite + steps: + - name: Upload + id: first + if: ${{ always() }} + continue-on-error: true + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: ${{ inputs.name }} + path: ${{ inputs.path }} + retention-days: ${{ inputs.retention-days }} + include-hidden-files: ${{ inputs.include-hidden-files }} + if-no-files-found: error + + - name: Wait before retry + if: ${{ !cancelled() && steps.first.outcome == 'failure' }} + shell: bash + run: sleep 10 + + - name: Retry upload + id: second + if: ${{ !cancelled() && steps.first.outcome == 'failure' }} + continue-on-error: true + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: ${{ inputs.name }} + path: ${{ inputs.path }} + retention-days: ${{ inputs.retention-days }} + include-hidden-files: ${{ inputs.include-hidden-files }} + if-no-files-found: error + # A failed request may already have created an incomplete artifact. + overwrite: true + + - name: Wait before final attempt + if: ${{ !cancelled() && steps.second.outcome == 'failure' }} + shell: bash + run: sleep 30 + + - name: Final upload attempt + if: ${{ !cancelled() && steps.second.outcome == 'failure' }} + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: ${{ inputs.name }} + path: ${{ inputs.path }} + retention-days: ${{ inputs.retention-days }} + include-hidden-files: ${{ inputs.include-hidden-files }} + if-no-files-found: error + overwrite: true diff --git a/.github/workflows/ci-tests.yml b/.github/workflows/ci-tests.yml index 7726ed6342..ea3703b6c7 100644 --- a/.github/workflows/ci-tests.yml +++ b/.github/workflows/ci-tests.yml @@ -29,13 +29,12 @@ jobs: fi - name: Upload release accuracy evidence if: always() - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + uses: ./.github/actions/upload-test-artifact with: name: release-tool-accuracy path: | ${{ runner.temp }}/tool-accuracy/accuracy.json ${{ runner.temp }}/tool-accuracy/accuracy.md - if-no-files-found: error retention-days: 30 # Ubuntu full-suite coverage, sharded. Each shard writes a vitest blob report @@ -108,7 +107,7 @@ jobs: working-directory: gitnexus - name: Upload coverage blob if: always() - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + uses: ./.github/actions/upload-test-artifact with: name: coverage-blob-${{ matrix.shard }} path: gitnexus/.vitest/blob/ @@ -171,7 +170,7 @@ jobs: run: node --test docker-server.test.mjs - name: Upload test reports if: always() - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + uses: ./.github/actions/upload-test-artifact with: name: coverage-reports path: | @@ -195,9 +194,10 @@ jobs: steps: - id: gen run: | - # Refreshed Windows timings leave eight shards too close to the - # 20-minute watchdog. Eleven preserve headroom for runner variation. - TOTAL=11 # cross-platform (windows/macOS) shards per OS + # Keep the recorded native workload below 17 minutes, leaving + # headroom for runner variation under the 20-minute watchdog. The two + # R rename suites (695 s each) need a twelfth shard to stay below it. + TOTAL=12 # cross-platform (windows/macOS) shards per OS # Four coverage shards exceeded the 25-minute job limit while tests # were still passing. Split the full suite further; keep the timeout # and merged coverage thresholds unchanged. @@ -297,20 +297,19 @@ jobs: working-directory: gitnexus - name: Upload platform execution report if: always() - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + uses: ./.github/actions/upload-test-artifact with: name: execution-${{ matrix.os }}-${{ matrix.shard }} path: gitnexus/${{ matrix.os }}-${{ matrix.shard }}.json - if-no-files-found: error retention-days: 5 # Branch protection still requires these six names from the three-shard # matrix. Keep them as aggregate gates as the real matrix grows: every native - # shard and the complete execution audit must pass before any gate succeeds. + # shard, the complete execution audit, and the scope measurements must pass. # These jobs only verify dependency results; tests run in cross-platform above. protected-platform-checks: name: ${{ matrix.os }} (platform-sensitive) ${{ matrix.check }}/3 - needs: [cross-platform, test-completeness] + needs: [cross-platform, test-completeness, scope-resolution-benchmark] if: always() permissions: {} strategy: @@ -321,17 +320,19 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 2 steps: - - name: Require all native shards and the execution audit + - name: Require native shards, execution audit, and scope measurements shell: bash env: NATIVE_RESULT: ${{ needs.cross-platform.result }} EXECUTION_RESULT: ${{ needs.test-completeness.result }} + SCOPE_BENCH_RESULT: ${{ needs.scope-resolution-benchmark.result }} run: | echo "Compatibility gate for the former three-shard check name." echo "All native shards: $NATIVE_RESULT" echo "Complete execution audit: $EXECUTION_RESULT" - if [[ "$NATIVE_RESULT" != "success" || "$EXECUTION_RESULT" != "success" ]]; then - echo "::error::Every native shard and the execution audit must succeed." + echo "Scope-resolution measurements: $SCOPE_BENCH_RESULT" + if [[ "$NATIVE_RESULT" != "success" || "$EXECUTION_RESULT" != "success" || "$SCOPE_BENCH_RESULT" != "success" ]]; then + echo "::error::Every native shard, the execution audit, and scope-resolution measurements must succeed." exit 1 fi @@ -1101,11 +1102,36 @@ jobs: working-directory: gitnexus - name: Upload benchmark execution report if: always() - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + uses: ./.github/actions/upload-test-artifact with: name: execution-benchmarks path: gitnexus/benchmarks.json - if-no-files-found: error + retention-days: 5 + + # Fresh-process measurements have their own runner and time budget so they + # neither contend with nor consume the existing benchmark gate's allowance. + scope-resolution-benchmark: + name: scope resolution time / memory (all languages) + runs-on: ubuntu-latest + timeout-minutes: 45 + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: ./.github/actions/setup-gitnexus + with: + build: 'true' + - name: Measure all languages and check graph and binding baselines + run: node --import tsx bench/scope-resolution/measure.mts --check --output scope-resolution-benchmark.json + working-directory: gitnexus + - name: Upload scope-resolution measurements + if: always() + uses: ./.github/actions/upload-test-artifact + with: + name: scope-resolution-benchmark + path: gitnexus/scope-resolution-benchmark.json retention-days: 5 # Locked eval suite. setup-uv and uv itself are immutable so CI exercises @@ -1129,11 +1155,10 @@ jobs: working-directory: eval - name: Upload pytest execution report if: always() - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + uses: ./.github/actions/upload-test-artifact with: name: execution-pytest-locked path: eval/pytest-locked.xml - if-no-files-found: error retention-days: 5 - uses: ./.github/actions/setup-gitnexus with: @@ -1146,11 +1171,10 @@ jobs: working-directory: gitnexus - name: Upload preflight execution report if: always() - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + uses: ./.github/actions/upload-test-artifact with: name: execution-preflight path: gitnexus/preflight.json - if-no-files-found: error retention-days: 5 test-completeness: @@ -1196,7 +1220,7 @@ jobs: run: python3 eval/check_test_execution.py execution-reports eval/pytest-results.json - name: Upload complete test reports if: always() - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + uses: ./.github/actions/upload-test-artifact with: name: test-reports path: | @@ -1205,7 +1229,6 @@ jobs: gitnexus/test-results.json gitnexus-web/web-test-results.json eval/pytest-results.json - if-no-files-found: error retention-days: 5 # Native Linux ownership and Bubblewrap boundary. The environment flag makes @@ -1307,11 +1330,10 @@ jobs: working-directory: eval - name: Upload pytest execution report if: always() - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + uses: ./.github/actions/upload-test-artifact with: name: execution-pytest-ubuntu path: eval/pytest-ubuntu.xml - if-no-files-found: error retention-days: 5 # Native Windows Job Object canary. POSIX-only tests skip by platform, while @@ -1338,9 +1360,8 @@ jobs: working-directory: eval - name: Upload pytest execution report if: always() - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + uses: ./.github/actions/upload-test-artifact with: name: execution-pytest-windows path: eval/pytest-windows.xml - if-no-files-found: error retention-days: 5 diff --git a/docs/optimize/guard-taint-overhead-report.md b/docs/optimize/guard-taint-overhead-report.md new file mode 100644 index 0000000000..ec24b0c94c --- /dev/null +++ b/docs/optimize/guard-taint-overhead-report.md @@ -0,0 +1,123 @@ +# Guard-aware taint collection optimization + +Measured 2026-10-24 for PR #3703. The corrected final implementation meets the planned **<=5% guard-free CFG collection-time overhead** target on all three measured workloads. Against the original PR implementation, the selection workload is **12.55% faster** and the transitive-alias holdout is **18.38% faster**. No proof rule or budget was weakened. + +## Confirmed results + +Each row compares two revisions in one process with 15 alternating paired samples. Negative overhead means faster collection. Compare timings within a row: this shared host also ran tests, and load changed between comparisons. These are ratios of sample medians, not averages of per-pair ratios. [Raw samples and source hashes](guard-taint-overhead-results.json) accompany this report. + +| Reference | Workload | Reference median (ms) | Optimized median (ms) | Change | +| ------------------- | ---------- | --------------------: | --------------------: | ------: | +| Pre-feature f3fa67b | arguments | 926.98 | 916.33 | -1.15% | +| Pre-feature f3fa67b | transitive | 1319.92 | 1370.44 | 3.83% | +| Pre-feature f3fa67b | direct | 548.73 | 540.19 | -1.56% | +| Original PR 6ee7ce1 | arguments | 801.44 | 700.84 | -12.55% | +| Original PR 6ee7ce1 | transitive | 1167.84 | 953.23 | -18.38% | + +Every consecutive five-pair block also meets the target against the pre-feature reference: + +| Workload | Pairs 1–5 | Pairs 6–10 | Pairs 11–15 | +| ---------- | --------: | ---------: | ----------: | +| arguments | 1.39% | -0.07% | -0.34% | +| transitive | 0.62% | -2.35% | -0.95% | +| direct | 0.17% | 0.74% | -2.62% | + +The integrated savings against the original PR are 100.59 ms on argument forwarding and 214.61 ms on transitive aliases. The final confirmation includes the malformed-AST correction discovered during review. Earlier five-pair selection batches varied enough to cross the target; 15 pairs were specified before final confirmation. All inputs, timing boundaries, correctness gates and thresholds stayed fixed. This establishes the target for the measured workloads and run, not a statistical guarantee for every host or source program. + +## What changed + +Only the TypeScript/JavaScript fact harvester changes at runtime. It now: + +- Reuses known parent and parameter scopes during declaration scanning. +- Records nearest scopes for identifiers, avoiding native ID reads and map entries for structural nodes. +- Reuses adjacent resolution results and captured call-argument bindings while still recording ordinary call-frame occurrences. +- Reads native child counts and source positions once where the AST is immutable. +- Skips well-formed string/regex internals. Malformed literals retain full traversal; template substitutions, qualified identifiers and unsafe-name checks remain covered. +- Constructs each statement fact record once and allocates predicate-site maps only when predicates can be recognized. + +There is no new dependency, solver, persistent cache or wire format. Declaration order, shadowing, synthetic binding identity, call frames, shape/proof limits and conservative fallback behavior remain unchanged. + +## Reproduce the measurements + +The portable harness is [compare-guard-overhead.mjs](../../gitnexus/bench/cfg/compare-guard-overhead.mjs). Both source checkouts need dependencies installed. From the optimized checkout's gitnexus package: + +```bash +node --expose-gc --import tsx bench/cfg/compare-guard-overhead.mjs \ + --baseline /path/to/reference/gitnexus \ + --workload arguments --pairs 15 --check --out result.json +``` + +Repeat with transitive and direct. Use CPU affinity on a suitable quiet core when available. The measured run pinned both versions to CPU 23. Reference revisions: + +- Pre-feature target: f3fa67b1445b8e8eeb23ae253fd3110044dc3624. +- Original PR implementation: 6ee7ce1cc463a8ad55cbdf2aea8325e0eb0396e0. +- Integration head: 09d2ebdb1f6d1571fded04ea917fb1935c4787e1. The main merge introduced no CFG/taint changes. +- Final harvester SHA-256: 19b0ca87758a18009b1f740ed4a22c81ccbc12ee756ba53f2d7fc823090e78ff. + +Each workload contains 4,000 functions. Parsing occurs once, outside collection timing. Three warmup repetitions precede alternating reference/candidate samples, with explicit GC before each sample. Timed work is collectFunctionCfgs through the production visitor. Serialization and correctness checks occur outside timing; prior CFG outputs are not deliberately retained while timing the next sample. Every final sample exceeded 100 ms. + +The harness always requires exact legacy CFG equality, all 4,000 functions, and all 4,000 helper argument effects with the exact prefix/input/suffix composition and ordinary-shell contract. Its --check additionally requires at least five pairs, >=100 ms samples and <=5% median overhead. An empty-output probe of the original harness failed all correctness gates. No CI wiring or existing benchmark allowance changes are part of this optimization. + +Function bodies use unique function and consumer names: + +```ts +// arguments: selection workload +function f(x: string) { + const y = 'prefix ' + x; + return consume(y); +} +// transitive: separate confirmation workload +function f(x: string) { + const a = 'prefix ' + x; + const b = a + ' suffix'; + return consume(b); +} +// direct: additional guard-free check +function f(x: string) { + return consume('prefix ' + x); +} +``` + +## Correctness and validation + +- Ad hoc full-output comparison against the original PR: 633 fixture files plus 30 explicit edge cases, **1,140 CFGs with zero differences**, including refinement data and skip counts. Corpus output SHA-256: 0d663493b85105b8cd3f4eeb15dad0061473aef785a342344c6db1f511385cd0. +- A separate **2,520 malformed-input mutation corpus** produced 1,651 CFGs with zero differences. Forty malformed literal nodes exercised parser recovery. +- Independent adversarial review identified a possible literal-recovery omission. Real parser reproductions made two new tests fail; requiring !node.hasError fixed both. Seven new cases cover recovery, repeated arguments, capture caps and nested declaration scope fallback. All **177 CFG/refinement tests** pass. +- Corrected-source default unit project: **900 files, 20,696 passed, 47 skipped, zero failures**. Corrected-source CFG integration: **13 files, 141 passed**. +- Corrected-source CLI build, source and test typechecks pass. Changed-file ESLint reports zero errors; warning-level diagnostics remain. +- Corrected-source persisted tool accuracy: **32/32 fixed answers pass** with the existing oracle. +- Corrected-source CFG benchmark: **15/15 scenarios pass**, including existing time, serialized-size, retained-heap, fingerprint, reaching-definition and taint budgets. +- Graph analysis: the optimization changes six files and 77 symbols across three observed processes (**MEDIUM** risk). The entire PR against merge base 11a49a15c6befbe4d5de1cebe74b5456aeb44b99 changes 42 files and 399 symbols across 16 observed processes (**CRITICAL**, covered by the prior shared-taint approval). Neither result carries a partial/truncated flag. Process counts are bounded graph observations; this refreshed index does not include the PDG layer. +- Four-shard full suite: **1,338 files, 28,267 passed, 88 skipped, zero failures**. + +The full-suite snapshot was frozen before the final malformed-literal correction. It covers all other optimized code at the integration head. The corrected source was separately rebuilt and checked by the unit, CFG integration, differential, scaling and accuracy runs above. + +The focused review combined a local correctness read with an independent Claude CLI adversarial read. The peer receipt verifies claude-opus-5-5; requested effort was high and actual effort is unverified. The peer reviewed the runtime optimization before the correction; local follow-up verified the fix, added tests and portable harness. The public harness reproduces timing and synthetic correctness checks; the broader ad hoc corpus comparisons are local validation evidence, not a new CI gate. + +## Limits and remaining costs + +The <=5% target concerns collection time on these guard-free workloads. It is not an end-to-end latency or peak-memory guarantee. Existing guarded, capped, time, payload and retained-heap scaling budgets remain unchanged. This run makes no peak-heap improvement claim. + +Serialized size is identical to the original PR's normalized proof facts. Argument forwarding remains 5,118,249 bytes versus 4,030,249 before the feature (**+27.00%**); transitive aliases remain +37.40%, direct arguments +23.69%. Removing the value facts loses forwarding precision. A compact wire format is a separate tradeoff and was not introduced here. + +The initial profile attributed substantial cost to declaration scanning, name resolution and duplicate value traversal. The retained changes target that work. No fresh profile establishes the remaining bottleneck; broader parser rewrites or a new cache framework are not justified by these results. + +## Experiment accounting + +Twelve bounded experiments ran serially: seven component experiments remain in the final implementation and five were rejected. There were no deferred dependency requests, unselected parallel candidates, censored experiments, runner errors or timeouts. A malformed-input correctness fix followed selection; it was not a new optimization experiment. + +The table preserves the original component forecasts and contemporaneous five-pair results. Forecasts estimated savings against the original or preceding candidate; measurements compared the accumulated candidate against the pre-feature revision. **Those references differ, so the results do not validate individual forecasts.** They also show the timing variance that motivated final 15-pair confirmation. Do not add component percentages; only the original-to-final paired comparisons establish the integrated gain. + +| Retained component | Forecast savings | Accumulated candidate vs pre-feature during selection | +| ------------------------------------ | ---------------: | ----------------------------------------------------: | +| Parameter scope reuse | 4–8 pp | 575.61 → 551.19 ms (-4.24%) | +| Identifier-only scope cache | 5–12 pp | 487.28 → 520.21 ms (6.76%) | +| Reuse call argument reads | 3–6 pp | 544.05 → 569.75 ms (4.72%) | +| Reuse native loop bounds/positions | 2–6 pp | 479.96 → 507.24 ms (5.68%) | +| Reuse last resolved name | 2–5 pp | 574.21 → 581.69 ms (1.30%) | +| Skip well-formed literal internals | 2–6 pp | 516.22 → 533.60 ms (3.37%) | +| Reuse scope parent; build facts once | 3–7 pp | 554.10 → 496.07 ms (-10.47%) | + +Early leaf shortcuts, bulk child enumeration, a per-node resolution map and standalone allocation changes did not show a reliable win. A generic identifier-leaf shortcut was also rejected because qualified identifier nodes have children. The final literal shortcut explicitly preserves parser recovery. + +Stopping reason: the corrected final candidate meets the target and all synthetic correctness gates, including the original-to-final holdout. Optimization began at 10:35 UTC and corrected performance confirmation finished at 11:46 UTC (about 71 minutes); validation and publication continued afterward. No paid judge was used for timing. Compute and review spend were not metered, so whole-run cost is unrecorded. The local audit ledger and specification remain under .context/compound-engineering/ce-optimize/guard-taint-overhead/; this tracked report, raw results and portable harness are the shared evidence. diff --git a/docs/optimize/guard-taint-overhead-results.json b/docs/optimize/guard-taint-overhead-results.json new file mode 100644 index 0000000000..19c66eeb1e --- /dev/null +++ b/docs/optimize/guard-taint-overhead-results.json @@ -0,0 +1,380 @@ +{ + "measured_at": "2026-10-24T11:46:01.733Z", + "references": { + "target": "f3fa67b1445b8e8eeb23ae253fd3110044dc3624", + "original": "6ee7ce1cc463a8ad55cbdf2aea8325e0eb0396e0", + "integration": "09d2ebdb1f6d1571fded04ea917fb1935c4787e1" + }, + "candidate_source_sha256": "19b0ca87758a18009b1f740ed4a22c81ccbc12ee756ba53f2d7fc823090e78ff", + "environment": { + "node": "v22.23.3", + "v8": "12.4.254.21-node.57", + "platform": "linux", + "arch": "x64", + "cpu": "12th Gen Intel(R) Core(TM) i9-12900K", + "affinity_cpu": 23, + "shared_host": true + }, + "protocol": { + "functions": 4000, + "warmup_repetitions": 3, + "pairs": 15, + "sample_order": "baseline/candidate, then candidate/baseline, alternating", + "parse": "once outside timing", + "gc": "before each timed sample", + "metric": "ratio of candidate and baseline sample medians minus one", + "serialization": "outside timing", + "target_percent": 5, + "correctness_gates": ["legacy_equal", "functions_complete", "forwarding_complete"], + "heap_diagnostic": "after-collection heap growth; not peak heap" + }, + "comparisons": [ + { + "baseline": "target", + "kind": "selection", + "iteration": 12, + "final": true, + "post_review_fix": true, + "exit_code": 0, + "blocks": [ + { + "medians_ms": [926.980541, 939.893447], + "time_overhead_pct": 1.393007234657806 + }, + { + "medians_ms": [874.998572, 874.380178], + "time_overhead_pct": -0.07067371533949762 + }, + { + "medians_ms": [936.643365, 933.451269], + "time_overhead_pct": -0.3408016454587326 + } + ], + "workload": "arguments", + "pairs": 15, + "time_overhead_pct": -1.1486265923677075, + "serialized_overhead_pct": 26.995850628583984, + "legacy_equal": 1, + "functions_complete": 1, + "forwarding_complete": 1, + "samples_ms": [ + [ + 991.636407, 926.980541, 1052.223997, 874.353997, 814.005086, 846.39417, 939.310542, + 968.675534, 850.55565, 874.998572, 924.263215, 816.897822, 936.643365, 960.946203, + 952.875645 + ], + [ + 939.893447, 835.342256, 1062.366743, 980.586552, 785.881103, 819.862887, 1108.397972, + 916.332996, 874.380178, 863.18481, 874.130014, 873.202115, 1027.155567, 1014.473391, + 933.451269 + ] + ], + "medians_ms": [926.980541, 916.332996], + "bytes": [4030249, 5118249], + "heap_growth_medians": [22076336, 21050152], + "base_hash": "0ceb296402cd3a89e3d9141152bd56d9584a50634fe2b718cabb5ee0e9aeab15", + "source_hashes": [ + "eb5449241b235c26ed92d6f629a89868d5b3612c47095f96d3eb20b474cb85aa", + "19b0ca87758a18009b1f740ed4a22c81ccbc12ee756ba53f2d7fc823090e78ff" + ] + }, + { + "baseline": "target", + "kind": "holdout", + "iteration": 12, + "final": true, + "post_review_fix": true, + "exit_code": 0, + "blocks": [ + { + "medians_ms": [1282.768951, 1290.729238], + "time_overhead_pct": 0.6205550106115565 + }, + { + "medians_ms": [1417.752374, 1384.478543], + "time_overhead_pct": -2.3469423582146653 + }, + { + "medians_ms": [1383.63807, 1370.441898], + "time_overhead_pct": -0.9537300458927089 + } + ], + "workload": "transitive", + "pairs": 15, + "time_overhead_pct": 3.8279811568370237, + "serialized_overhead_pct": 37.40160977949929, + "legacy_equal": 1, + "functions_complete": 1, + "forwarding_complete": 1, + "samples_ms": [ + [ + 1319.915771, 1288.475793, 1236.561698, 1282.768951, 1255.029194, 1430.325594, 1478.997302, + 1351.424832, 1317.151013, 1417.752374, 1394.826591, 1299.54403, 1287.726552, 1383.63807, + 1483.755553 + ], + [ + 1290.729238, 1222.891716, 1303.250259, 1270.870905, 1489.054094, 1433.201519, 1567.401177, + 1384.478543, 1383.860575, 1334.753843, 1386.789066, 1346.508798, 1370.441898, 1413.529929, + 1272.542746 + ] + ], + "medians_ms": [1319.915771, 1370.441898], + "bytes": [4502480, 6186480], + "heap_growth_medians": [30367416, 33670488], + "base_hash": "e9e120d2c163949405ae52dc5cd4d08a8d0c8647302f3fb1fafd3b431ab76930", + "source_hashes": [ + "eb5449241b235c26ed92d6f629a89868d5b3612c47095f96d3eb20b474cb85aa", + "19b0ca87758a18009b1f740ed4a22c81ccbc12ee756ba53f2d7fc823090e78ff" + ] + }, + { + "baseline": "target", + "kind": "selection", + "iteration": 12, + "final": true, + "post_review_fix": true, + "exit_code": 0, + "blocks": [ + { + "medians_ms": [546.287538, 547.190939], + "time_overhead_pct": 0.16537096989386324 + }, + { + "medians_ms": [548.729001, 552.784326], + "time_overhead_pct": 0.7390396703307989 + }, + { + "medians_ms": [554.717647, 540.177424], + "time_overhead_pct": -2.6211935168523826 + } + ], + "workload": "direct", + "pairs": 15, + "time_overhead_pct": -1.5555201172974042, + "serialized_overhead_pct": 23.685278087842153, + "legacy_equal": 1, + "functions_complete": 1, + "forwarding_complete": 1, + "samples_ms": [ + [ + 585.832439, 604.653849, 508.324025, 528.45936, 546.287538, 590.143343, 542.103699, + 506.672531, 548.729001, 653.093038, 566.802297, 554.717647, 556.273056, 510.102922, + 519.793483 + ], + [ + 576.02371, 637.452543, 547.190939, 530.045111, 524.659083, 539.414348, 572.697724, + 511.161353, 552.784326, 558.685312, 532.658077, 501.323318, 540.193411, 560.527328, + 540.177424 + ] + ], + "medians_ms": [548.729001, 540.193411], + "bytes": [3174968, 3926968], + "heap_growth_medians": [11372208, 18987256], + "base_hash": "e32fa1876c674740fa2d85a0e1b9bc263799c704f4d537694427da2dd197f264", + "source_hashes": [ + "eb5449241b235c26ed92d6f629a89868d5b3612c47095f96d3eb20b474cb85aa", + "19b0ca87758a18009b1f740ed4a22c81ccbc12ee756ba53f2d7fc823090e78ff" + ] + }, + { + "baseline": "original", + "kind": "selection", + "iteration": 12, + "final": true, + "post_review_fix": true, + "exit_code": 0, + "blocks": [ + { + "medians_ms": [839.997564, 715.49347], + "time_overhead_pct": -14.821958936061863 + }, + { + "medians_ms": [800.101563, 720.123923], + "time_overhead_pct": -9.995935978442782 + }, + { + "medians_ms": [801.435984, 675.281283], + "time_overhead_pct": -15.741082696381635 + } + ], + "workload": "arguments", + "pairs": 15, + "time_overhead_pct": -12.551510290059543, + "serialized_overhead_pct": 0, + "legacy_equal": 1, + "functions_complete": 1, + "forwarding_complete": 1, + "samples_ms": [ + [ + 839.997564, 738.463058, 857.906524, 842.421851, 799.280266, 960.616255, 902.391745, + 782.451825, 800.101563, 792.380063, 801.435984, 770.546193, 862.753015, 757.292758, + 802.344464 + ], + [ + 659.721701, 715.49347, 700.843664, 742.920449, 842.665567, 751.378898, 864.312785, + 694.810253, 682.495461, 720.123923, 635.26501, 668.832835, 705.642196, 687.253768, + 675.281283 + ] + ], + "medians_ms": [801.435984, 700.843664], + "bytes": [5118249, 5118249], + "heap_growth_medians": [30844760, 20766944], + "base_hash": "0ceb296402cd3a89e3d9141152bd56d9584a50634fe2b718cabb5ee0e9aeab15", + "source_hashes": [ + "3b2a2bccf8254b61fd0ab1b8ab9423f89b29073afc402ad078189a31d67e0748", + "19b0ca87758a18009b1f740ed4a22c81ccbc12ee756ba53f2d7fc823090e78ff" + ] + }, + { + "baseline": "original", + "kind": "holdout", + "iteration": 12, + "final": true, + "post_review_fix": true, + "exit_code": 0, + "blocks": [ + { + "medians_ms": [1022.240662, 943.977474], + "time_overhead_pct": -7.656043328082762 + }, + { + "medians_ms": [1074.679531, 1071.170551], + "time_overhead_pct": -0.3265140815266965 + }, + { + "medians_ms": [1214.845854, 953.230029], + "time_overhead_pct": -21.53489878066456 + } + ], + "workload": "transitive", + "pairs": 15, + "time_overhead_pct": -18.376410863434145, + "serialized_overhead_pct": 0, + "legacy_equal": 1, + "functions_complete": 1, + "forwarding_complete": 1, + "samples_ms": [ + [ + 991.262411, 1022.240662, 954.091735, 1211.352262, 1328.408798, 994.117618, 1074.679531, + 1113.739816, 1417.601299, 1056.288179, 1204.450932, 1214.845854, 1325.823707, 1225.401996, + 1167.836454 + ], + [ + 855.369854, 899.467318, 944.243232, 1123.037271, 943.977474, 944.358269, 1071.170551, + 1109.569003, 1180.041345, 1034.802502, 904.834811, 910.174455, 1218.088988, 1315.290326, + 953.230029 + ] + ], + "medians_ms": [1167.836454, 953.230029], + "bytes": [6186480, 6186480], + "heap_growth_medians": [22416784, 33734328], + "base_hash": "e9e120d2c163949405ae52dc5cd4d08a8d0c8647302f3fb1fafd3b431ab76930", + "source_hashes": [ + "3b2a2bccf8254b61fd0ab1b8ab9423f89b29073afc402ad078189a31d67e0748", + "19b0ca87758a18009b1f740ed4a22c81ccbc12ee756ba53f2d7fc823090e78ff" + ] + } + ], + "validation": { + "corrected_source_sha256": "19b0ca87758a18009b1f740ed4a22c81ccbc12ee756ba53f2d7fc823090e78ff", + "default_units": { + "files": 900, + "passed": 20696, + "skipped": 47, + "failed": 0 + }, + "cfg_integration": { + "files": 13, + "passed": 141, + "failed": 0 + }, + "cfg_scaling": { + "scenarios": 15, + "passed": 15 + }, + "tool_accuracy": { + "checks": 32, + "passed": 32 + }, + "build": true, + "source_typecheck": true, + "test_typecheck": true, + "changed_file_lint_errors": 0, + "fixture_equivalence": { + "files": 633, + "custom_cases": 30, + "cfgs": 1140, + "mismatches": 0, + "sha256": "0d663493b85105b8cd3f4eeb15dad0061473aef785a342344c6db1f511385cd0" + }, + "malformed_equivalence": { + "cases": 2520, + "cfgs": 1651, + "malformed_literal_nodes": 40, + "mismatches": 0 + }, + "graph": { + "base": "11a49a15c6befbe4d5de1cebe74b5456aeb44b99", + "optimization": { + "changed_count": 77, + "affected_count": 3, + "changed_files": 6, + "risk_level": "medium" + }, + "whole_pr": { + "changed_count": 399, + "affected_count": 16, + "changed_files": 42, + "risk_level": "critical" + }, + "partial_flag": false, + "truncated_flag": false, + "pdg_layer": false + }, + "full_suite": { + "source_sha256": "37624680cb858fddfab7f7dcd167606b62f91b89cca7694091e5ac827bf7279c", + "revision_note": "Frozen candidate before !node.hasError correction. Corrected source separately validated as detailed above.", + "shards": [ + { + "shard": 1, + "files": 334, + "passed": 7835, + "skipped": 10, + "failed": 0, + "total": 7845 + }, + { + "shard": 2, + "files": 335, + "passed": 7030, + "skipped": 8, + "failed": 0, + "total": 7038 + }, + { + "shard": 3, + "files": 335, + "passed": 6410, + "skipped": 14, + "failed": 0, + "total": 6424 + }, + { + "shard": 4, + "files": 334, + "passed": 6992, + "skipped": 56, + "failed": 0, + "total": 7048 + } + ], + "totals": { + "files": 1338, + "passed": 28267, + "skipped": 88, + "failed": 0, + "total": 28355 + } + } + } +} diff --git a/eval/tests/test_pr_evaluation.py b/eval/tests/test_pr_evaluation.py index 9b5ccedce0..0a7f4589cc 100644 --- a/eval/tests/test_pr_evaluation.py +++ b/eval/tests/test_pr_evaluation.py @@ -38,6 +38,7 @@ def evidence(): "task_base_sha": "e" * 40, "oracle_digest": "f" * 64, "sandbox_backend": "bwrap", + "runtime_exposure": "none" if arm == "baseline_nomcp" else "stdio-only", "sandbox_dependency_content_digest": "9" * 64, "ok": True, "resolved": True, @@ -66,6 +67,12 @@ def compare(evidence): ) +def test_pr_comparison_rejects_readable_runtime_cells(evidence): + evidence[1][0]["runtime_exposure"] = "readable" + report = compare(evidence) + assert not report["complete"] and not report["improved"] + + def test_comparison_measures_only_new_mcp_cells_and_preserves_historical_cost(evidence): before = deepcopy(evidence) report = compare(evidence) diff --git a/eval/tests/test_proposer_sandbox.py b/eval/tests/test_proposer_sandbox.py index a91166b27d..a439b30b96 100644 --- a/eval/tests/test_proposer_sandbox.py +++ b/eval/tests/test_proposer_sandbox.py @@ -5,10 +5,14 @@ from __future__ import annotations import json import os import shutil +import socket import stat import subprocess import sys import threading +import time +import uuid +from contextlib import ExitStack from dataclasses import replace from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path @@ -58,6 +62,222 @@ from workflow_bench.review_scoring import REVIEW_OUTPUT, parse_review_output from workflow_bench.task_assets import TaskAssetCache, stage_task_assets as stage_immutable_task_assets +@pytest.fixture +def mcp_socket_client(monkeypatch): + """Exercise a real connection attempt between bind() and listen().""" + bound, attempted = threading.Event(), threading.Event() + original_listen = socket.socket.listen + + def delayed_listen(listener, backlog): + bound.set() + assert attempted.wait(5), "client never attempted to connect" + return original_listen(listener, backlog) + + monkeypatch.setattr(socket.socket, "listen", delayed_listen) + + def connect(endpoint): + assert bound.wait(5), "server never bound its socket" + deadline = time.monotonic() + 5 + while True: + client = socket.socket(socket.AF_UNIX) + client.settimeout(5) + try: + client.connect(str(endpoint)) + return client + except ConnectionRefusedError: + client.close() + if time.monotonic() >= deadline: + raise + except Exception: + client.close() + raise + finally: + attempted.set() + time.sleep(0.01) + + return connect + + +@pytest.mark.skipif(os.name == "nt", reason="Unix socket transport requires POSIX socket flags") +def test_mcp_socket_transport_reconnects_and_reports_server_failure(tmp_path: Path, mcp_socket_client) -> None: + from workflow_bench.mcp_transport import serve_stdio + + endpoint = tmp_path / "mcp.sock" + failure = tmp_path / "failure" + command = [sys.executable, "-c", "import sys; line=sys.stdin.readline(); print(line.strip(), flush=True); sys.exit(3 if line.strip() == 'fail' else 0)"] + errors: list[Exception] = [] + + def serve() -> None: + try: + serve_stdio(endpoint, failure, command) + except Exception as exc: + errors.append(exc) + + worker = threading.Thread(target=serve, daemon=True) + worker.start() + try: + for message in (b"first\n", b"second\n", b"fail\n"): + with mcp_socket_client(endpoint) as client: + client.sendall(message) + client.shutdown(socket.SHUT_WR) + assert client.recv(100) == message + worker.join(timeout=5) + assert not worker.is_alive() + assert errors and "3" in failure.read_text() + finally: + worker.join(timeout=1) + + +@pytest.mark.skipif(os.name == "nt", reason="Unix socket transport requires POSIX socket flags") +def test_mcp_socket_transport_rejects_premature_clean_server_exit(tmp_path, mcp_socket_client): + from workflow_bench.mcp_transport import serve_stdio + + endpoint, failure = tmp_path / "mcp.sock", tmp_path / "failure" + errors = [] + + def serve(): + try: + serve_stdio(endpoint, failure, [sys.executable, "-c", "pass"]) + except Exception as exc: + errors.append(exc) + + worker = threading.Thread(target=serve, daemon=True) + worker.start() + with mcp_socket_client(endpoint): + worker.join(timeout=2) + assert errors and "before client EOF" in failure.read_text() + + +def test_mcp_only_sandbox_does_not_supply_a_cli_wrapper(tmp_path): + clone = tmp_path / "clone" + clone.mkdir() + with prepare_sandbox( + clone=clone, claude_bin=sys.executable, bwrap_bin=sys.executable, + preflight=False, gitnexus_cli_available=False, + ) as sandbox: + assert not (sandbox.private_root / "gitnexus").exists() + assert SANDBOX_GITNEXUS_CLI not in {mount.target for mount in sandbox.read_only_mounts} + + +@pytest.mark.skipif( + os.environ.get("GITNEXUS_REQUIRE_BWRAP_CANARY") != "1", + reason="real Bubblewrap canary is mandatory in the named Ubuntu CI job", +) +def test_real_sibling_mcp_failure_invalidates_cell_after_client_eof(tmp_path): + from workflow_bench.mcp_transport import isolated_mcp + + clone = tmp_path / "clone" + clone.mkdir() + runtime = tmp_path / "runtime" + entrypoint = runtime / "dist/cli/index.js" + entrypoint.parent.mkdir(parents=True) + entrypoint.write_text("process.exit(7)") + bwrap = preflight_bubblewrap() + with pytest.raises(SandboxError, match="MCP transport failed"): + with isolated_mcp(clone=clone, mounts=[ReadOnlyMount(runtime, proposer_sandbox.SANDBOX_GITNEXUS)], + bwrap_bin=bwrap) as endpoint: + with socket.socket(socket.AF_UNIX) as client: + client.settimeout(10) + client.connect(str(endpoint.source)) + assert client.recv(1) == b"" + assert not endpoint.source.exists() + + +@pytest.mark.skipif( + os.environ.get("GITNEXUS_REQUIRE_BWRAP_CANARY") != "1", + reason="real Bubblewrap canary is mandatory in the named Ubuntu CI job", +) +def test_real_sibling_mcp_hides_runtime_and_reaps_detached_children(tmp_path): + from workflow_bench.mcp_transport import isolated_mcp, connector_config + + marker = "mcp-child-" + uuid.uuid4().hex + clone = tmp_path / "clone" + clone.mkdir() + (clone / "source.txt").write_text("unsolved") + runtime = tmp_path / "runtime with spaces" + entrypoint = runtime / "dist/cli/index.js" + entrypoint.parent.mkdir(parents=True) + host_listener = socket.socket() + host_listener.bind(("127.0.0.1", 0)) + host_listener.listen() + entrypoint.write_text(""" +const fs = require('fs'); +const cp = require('child_process'); +const net = require('net'); +const readline = require('readline'); +cp.spawn('/usr/bin/python3', ['-c', 'import time; time.sleep(60)', MARKER], + {detached:true, stdio:'ignore'}).unref(); +const input = readline.createInterface({input:process.stdin}); +input.on('line', async line => { + const request = JSON.parse(line); + let writeBlocked = false; + try { fs.writeFileSync('/workspace/source.txt', 'solution'); } catch { writeBlocked = true; } + const privateState = !fs.existsSync('/home/agent/secret'); + const runtimeReadable = fs.readFileSync(__filename, 'utf8').length > 0; + const credentialAbsent = !process.env.ANTHROPIC_API_KEY; + const networkBlocked = await new Promise(resolve => { + const client = net.connect({host:'127.0.0.1', port:HOST_PORT}); + client.once('connect', () => { client.destroy(); resolve(false); }); + client.once('error', () => resolve(true)); + client.setTimeout(1000, () => { client.destroy(); resolve(true); }); + }); + process.stdout.write(JSON.stringify({id:request.id, writeBlocked, privateState, + runtimeReadable, credentialAbsent, networkBlocked}) + '\\n'); +}); +""".replace("MARKER", json.dumps(marker)).replace("HOST_PORT", str(host_listener.getsockname()[1]))) + bwrap = preflight_bubblewrap() + mounts = [ReadOnlyMount(runtime, proposer_sandbox.SANDBOX_GITNEXUS)] + with host_listener, ExitStack() as clients, ExitStack() as stack: + endpoints = [stack.enter_context(isolated_mcp(clone=clone, mounts=mounts, bwrap_bin=bwrap)) for _ in range(2)] + assert endpoints[0].source != endpoints[1].source + server = json.loads(connector_config())["mcpServers"]["gitnexus"] + connector = [server["command"], *server["args"]] + for index, endpoint in enumerate(endpoints): + with prepare_sandbox( + clone=clone, claude_bin=sys.executable, bwrap_bin=bwrap, + read_only_mounts=[endpoint], preflight=False, gitnexus_cli_available=False, + ) as sandbox: + (sandbox.home / "secret").write_text("agent-secret") + probe = f""" +import json, subprocess +from pathlib import Path +for path in ['/opt/gitnexus', '/opt/gitnexus-shared', '/opt/gitnexus-registry', + '/opt/claude/gitnexus', {str(endpoint.source.parent)!r}]: + assert not Path(path).exists(), path +for proc in Path('/proc').glob('[0-9]*'): + assert not (proc / 'root/opt/gitnexus').exists() +for request_id in [{index}, {index + 10}]: + result = subprocess.run({connector!r}, input=json.dumps({{'id':request_id}})+'\\n', + text=True, capture_output=True, timeout=10) + assert result.returncode == 0, result.stderr + reply = json.loads(result.stdout) + assert reply.pop('id') == request_id + assert all(reply.values()), reply +""" + result = sandbox.run(["/usr/bin/python3", "-c", probe], timeout=30, + env=build_sandbox_environment(auth_token="agent-secret")) + assert result.ok, result.stderr_tail + # Keep requests open while the cell owner cancels its server namespaces. + for endpoint in endpoints: + client = clients.enter_context(socket.socket(socket.AF_UNIX)) + client.settimeout(10) + client.connect(str(endpoint.source)) + client.sendall(b'{"id":99}\n') + assert json.loads(client.recv(4096))["id"] == 99 + children = [] + for cmdline in Path("/proc").glob("[0-9]*/cmdline"): + try: + if marker.encode() in cmdline.read_bytes(): + children.append(cmdline.parent) + except (FileNotFoundError, PermissionError): + # Processes may exit during the scan or belong to another user. + pass + assert children, "canary must create detached descendants" + assert all(not process.exists() for process in children) + assert all(not endpoint.source.exists() for endpoint in endpoints) + assert (clone / "source.txt").read_text() == "unsolved" + + def test_nomcp_sandbox_hides_graph_and_guidance_without_exposing_the_cli(tmp_path): clone = tmp_path / "clone" (clone / ".gitnexus").mkdir(parents=True) diff --git a/eval/tests/test_release_evidence.py b/eval/tests/test_release_evidence.py index 3dbdaced45..97adc12560 100644 --- a/eval/tests/test_release_evidence.py +++ b/eval/tests/test_release_evidence.py @@ -64,6 +64,7 @@ def make_report(*, harness_sha: str = HARNESS, runtime_sha: str = RUNTIME) -> di task_base_sha=PINS["one"]["sha"], oracle_digest=PINS["one"]["oracle_digest"], sandbox_backend="bwrap", + runtime_exposure="none" if arm == "baseline_nomcp" else "stdio-only", ok=True, resolved=True, authored_tests_passed=True, diff --git a/eval/tests/test_release_gate.py b/eval/tests/test_release_gate.py index 53812a37d8..cadedda41a 100644 --- a/eval/tests/test_release_gate.py +++ b/eval/tests/test_release_gate.py @@ -38,6 +38,7 @@ def reports(): task_base_sha=pin["sha"], oracle_digest=pin["oracle_digest"], sandbox_backend="bwrap", + runtime_exposure="none" if arm == "baseline_nomcp" else "stdio-only", sandbox_dependency_content_digest=DEPENDENCIES, ok=True, resolved=run != 0, diff --git a/eval/tests/test_release_report.py b/eval/tests/test_release_report.py index 6abac8226b..dd483fbc0f 100644 --- a/eval/tests/test_release_report.py +++ b/eval/tests/test_release_report.py @@ -39,6 +39,7 @@ def rows(): "task_base_sha": "d" * 40, "oracle_digest": "e" * 64, "sandbox_backend": "bwrap", + "runtime_exposure": "none" if arm == "baseline_nomcp" else "stdio-only", "sandbox_dependency_content_digest": "9" * 64, "ok": True, "resolved": arm == "baseline_nomcp" or run != 1, @@ -125,6 +126,24 @@ def test_gate_recomputes_measurements_instead_of_trusting_totals(): validate_report(report, runtime_sha=SHA, task_set_digest=DIGEST, now=NOW) +@pytest.mark.parametrize("exposure", [None, "readable", "none"]) +def test_mcp_measurements_require_host_recorded_socket_isolation(exposure): + measured = rows() + for row in measured: + row["runtime_exposure"] = "none" if row["arm"] == "baseline_nomcp" else "stdio-only" + measured[1]["runtime_exposure"] = exposure + assert build_report(measured, metadata(), now=NOW)["complete"] is False + + +def test_historical_renderer_does_not_claim_socket_isolation(): + report = build_report(rows(), metadata(), now=NOW) + for row in report["per_run"]: + row.pop("runtime_exposure", None) + assert "readable compiled runtime" in render_markdown(report) + with pytest.raises(ValueError, match="summary"): + validate_report(report, runtime_sha=SHA, task_set_digest=DIGEST, now=NOW) + + def test_torn_result_file_publishes_incomplete_evidence(tmp_path, monkeypatch): from workflow_bench.release_report import main diff --git a/eval/tests/test_workflow_bench.py b/eval/tests/test_workflow_bench.py index 2c5ec7899d..4ebd8bc521 100644 --- a/eval/tests/test_workflow_bench.py +++ b/eval/tests/test_workflow_bench.py @@ -333,11 +333,12 @@ def test_platform_ci_preserves_required_check_names_with_complete_execution_gate for shard in range(1, total + 1) } assert names.isdisjoint(native_names) - assert set(gate["needs"]) == {"cross-platform", "test-completeness"} + assert set(gate["needs"]) == {"cross-platform", "test-completeness", "scope-resolution-benchmark"} assert gate["if"] == "always()" assert not gate.get("continue-on-error", False) assert not jobs["cross-platform"].get("continue-on-error", False) assert not jobs["test-completeness"].get("continue-on-error", False) + assert not jobs["scope-resolution-benchmark"].get("continue-on-error", False) assert gate["permissions"] == {} assert len(gate["steps"]) == 1 step = gate["steps"][0] @@ -347,22 +348,87 @@ def test_platform_ci_preserves_required_check_names_with_complete_execution_gate assert step["env"] == { "NATIVE_RESULT": "${{ needs.cross-platform.result }}", "EXECUTION_RESULT": "${{ needs.test-completeness.result }}", + "SCOPE_BENCH_RESULT": "${{ needs.scope-resolution-benchmark.result }}", } +def test_test_artifact_retries_cannot_hide_missing_evidence(ci_test_jobs): + repo_root = Path(__file__).resolve().parents[2] + action_path = ".github/actions/upload-test-artifact/action.yml" + action = yaml.safe_load((repo_root / action_path).read_text()) + uploads = [step for step in action["runs"]["steps"] if "uses" in step] + assert len(uploads) == 3 + first, second, final = uploads + assert first["if"] == "${{ always() }}" + assert second["if"] == "${{ !cancelled() && steps.first.outcome == 'failure' }}" + assert final["if"] == "${{ !cancelled() && steps.second.outcome == 'failure' }}" + assert first["id"] == "first" and second["id"] == "second" + assert first["continue-on-error"] is True + assert second["continue-on-error"] is True + assert not final.get("continue-on-error", False) + assert not first["with"].get("overwrite", False) + assert second["with"]["overwrite"] is True + assert final["with"]["overwrite"] is True + for step in uploads: + assert re.fullmatch(r"actions/upload-artifact@[a-f0-9]{40}", step["uses"]) + assert step["with"]["if-no-files-found"] == "error" + for key in ("name", "path", "retention-days", "include-hidden-files"): + assert step["with"][key] == "${{ inputs." + key + " }}" + + evidence_jobs = { + "tests", "coverage-merge", "cross-platform", "benchmarks", + "scope-resolution-benchmark", "eval-tests", "test-completeness", + "eval-containment-windows", "eval-containment-linux", "tool-accuracy", + } + for name in evidence_jobs: + job = ci_test_jobs[name] + reports = [ + step for step in job["steps"] + if step.get("uses") == "./.github/actions/upload-test-artifact" + ] + assert reports, f"{name} must publish execution evidence" + assert not job.get("continue-on-error", False) + for step in reports: + assert not step.get("continue-on-error", False) + assert step["with"]["name"] and step["with"]["path"] + + artifact_names = set() + for job in ci_test_jobs.values(): + for step in job.get("steps", []): + assert not step.get("uses", "").startswith("actions/upload-artifact@") + if step.get("uses") != "./.github/actions/upload-test-artifact": + continue + name = step["with"]["name"] + assert name not in artifact_names, f"Retry could overwrite another job: {name}" + artifact_names.add(name) + for axis in job.get("strategy", {}).get("matrix", {}): + if axis not in {"include", "exclude"}: + assert "${{ matrix." + axis + " }}" in name, ( + f"Artifact {name} must distinguish matrix axis {axis}" + ) + + @pytest.mark.parametrize("native_result", ["success", "failure", "cancelled", "skipped", ""]) @pytest.mark.parametrize("execution_result", ["success", "failure", "cancelled", "skipped", ""]) -def test_required_platform_check_fails_unless_every_dependency_passed(ci_test_jobs, native_result, execution_result): +@pytest.mark.parametrize("scope_bench_result", ["success", "failure", "cancelled", "skipped", ""]) +def test_required_platform_check_fails_unless_every_dependency_passed( + ci_test_jobs, native_result, execution_result, scope_bench_result +): step = ci_test_jobs["protected-platform-checks"]["steps"][0] result = subprocess.run( ["bash", "--noprofile", "--norc", "-e", "-o", "pipefail", "-c", step["run"]], - env={**os.environ, "NATIVE_RESULT": native_result, "EXECUTION_RESULT": execution_result}, + env={ + **os.environ, + "NATIVE_RESULT": native_result, + "EXECUTION_RESULT": execution_result, + "SCOPE_BENCH_RESULT": scope_bench_result, + }, capture_output=True, text=True, timeout=10, check=False, ) - expected = 0 if native_result == execution_result == "success" else 1 + expected = 0 if native_result == execution_result == scope_bench_result == "success" else 1 assert result.returncode == expected, result.stdout + result.stderr diff --git a/eval/tests/test_workflow_bench_sessions.py b/eval/tests/test_workflow_bench_sessions.py index f203f0d437..b599f916b2 100644 --- a/eval/tests/test_workflow_bench_sessions.py +++ b/eval/tests/test_workflow_bench_sessions.py @@ -463,6 +463,23 @@ def test_graph_enabled_cell_retains_its_graph_registry_and_runtime(monkeypatch, assert sandbox_calls[0]["read_only_mounts"] == [dependencies, runtime, registry] +def test_baseline_cell_mounts_only_the_endpoint_and_dependencies(monkeypatch, tmp_path): + ctx, clone, dependencies, runtime, registry, _, _, sandbox_calls = _probe_cell_provisioning(monkeypatch, tmp_path) + endpoint = runner.ReadOnlyMount(tmp_path / "mcp.sock", "/run/gitnexus-mcp.sock") + servers = [] + + def endpoint_context(**kwargs): + servers.append(kwargs) + return nullcontext(endpoint) + + monkeypatch.setattr(runner, "isolated_mcp", endpoint_context) + runner.run_cell(ctx, 0, "baseline") + assert servers[0]["clone"] == clone + assert servers[0]["mounts"] == [dependencies, runtime, registry] + assert sandbox_calls[0]["read_only_mounts"] == [dependencies, endpoint] + assert sandbox_calls[0]["gitnexus_cli_available"] is False + + def test_nomcp_cell_does_not_require_an_available_graph(monkeypatch, tmp_path): ctx, _, dependencies, _, _, _, _, sandbox_calls = _probe_cell_provisioning(monkeypatch, tmp_path) ctx = replace(ctx, graph_snapshot=None, graph_snapshot_error=RuntimeError("graph unavailable")) diff --git a/eval/workflow_bench/README.md b/eval/workflow_bench/README.md index d8132d118e..2610816ef4 100644 --- a/eval/workflow_bench/README.md +++ b/eval/workflow_bench/README.md @@ -228,10 +228,19 @@ are disabled in the no-tool arm, and repository/plugin hooks are disabled in both arms. It fails closed when Bubblewrap is unavailable. It retains the repository source and ordinary test dependencies required by the tasks; rebuilding tools from that source is not prevented. The comparison therefore measures access to the -provided GitNexus tools and their readable compiled runtime on these GitNexus -development tasks. That runtime can contain later fixes absent from a task's -historical base, so the comparison cannot isolate tool assistance from access -to those implementations. +provided GitNexus tools on these GitNexus development tasks. The MCP baseline +receives only a per-cell Unix socket: its candidate runtime, shared package, +registry, and host launcher are outside the agent filesystem. The host records +`runtime_exposure: stdio-only` for this arm and `none` for the no-tool arm. +Release and PR comparison validation reject missing or incompatible receipts. +Older measurements exposed readable compiled runtime code, including later +task implementations; they remain historical evidence and cannot satisfy this +isolated comparison contract. Workflow/CLI arms retain their runtime mounts and +are labeled `readable`. + +The [24 October evidence report](measurement-2026-10-24.md) retains the latest +historical measurements, current tool-accuracy result, and post-merge rerun +procedure. Those historical agent results do not show an accuracy or cost gain. This corpus uses a **fresh index at each task base**. A nightly stale Hermes index is a separate condition and must not be pooled with it. Import the @@ -253,7 +262,9 @@ MCP configuration. Bash children do not inherit the model credential and their network sandbox denies all domains. -The candidate MCP server runs in a separate nested Bubblewrap boundary. Its +The release baseline's candidate MCP server runs in a sibling Bubblewrap +boundary, reached by a stdio socket connector. Workflow/CLI arms retain a nested +server boundary. In both cases its workspace (including the graph), registry, compiled runtime and shared package mounts are read-only. Its home and temporary directories are private tmpfs, and it has a fresh PID namespace and `/proc`, no network or capabilities, and @@ -262,6 +273,13 @@ cannot write patches that would be credited to the agent; the agent retains its writable workspace for implementation tasks. Mutating MCP tools are not granted in any phase. +The cell owns the socket listener and its servers through the existing managed +process supervisor and an outer PID namespace. Each connection starts one +server; reconnects are sequential. Server failures invalidate the cell, and +teardown reaps detached descendants before removing the socket. Native canaries +in `test_proposer_sandbox.py` run in the required Linux containment job; a local +namespace skip does not prove isolation. + Prebuilt task `.gitnexus` assets are rejected. For each task commit, the harness creates the deterministic parentless snapshot first, removes every analyzer-visible path or stored source reference to the benchmark harness, diff --git a/eval/workflow_bench/mcp_transport.py b/eval/workflow_bench/mcp_transport.py new file mode 100644 index 0000000000..3958fe2608 --- /dev/null +++ b/eval/workflow_bench/mcp_transport.py @@ -0,0 +1,161 @@ +"""Per-cell stdio endpoint; candidate runtime files stay outside the agent.""" + +from __future__ import annotations + +import json +import shutil +import socket +import subprocess +import sys +import tempfile +import threading +from contextlib import ExitStack, contextmanager +from pathlib import Path +from typing import Iterator, Sequence + +from .process_control import ManagedProcessResult, run_managed +from .proposer_sandbox import ( + SANDBOX_GITNEXUS, + SANDBOX_GITNEXUS_REGISTRY, + SANDBOX_HOME, + SANDBOX_MCP_SOCKET, + SANDBOX_NODE, + SANDBOX_TMP, + SANDBOX_WORKSPACE, + ReadOnlyMount, + SandboxError, + bwrap_base_args, + pid_namespace_command, +) + +def serve_stdio(endpoint: Path, failure: Path, command: Sequence[str]) -> None: + """Connect each client socket directly to one server's stdin/stdout. + + The trusted owner runs in an owned PID namespace. The command establishes + the candidate's separate filesystem, network and process boundaries. + No MCP parsing, shell expansion, or concurrent server fan-out happens here. + """ + try: + with socket.socket(socket.AF_UNIX) as listener: + listener.bind(str(endpoint)) + endpoint.chmod(0o600) + listener.listen(1) + print("ready", flush=True) + while True: + connection, _ = listener.accept() + with connection: + try: + with subprocess.Popen( + command, stdin=connection, stdout=connection, close_fds=True, + ) as server: + returncode = server.wait() + if returncode: + raise RuntimeError(f"MCP server exited with status {returncode}") + try: + pending = connection.recv(1, socket.MSG_PEEK | socket.MSG_DONTWAIT) + except BlockingIOError: + pending = b"client still connected" + except ConnectionResetError: + pending = b"" + if pending: + raise RuntimeError("MCP server exited before client EOF") + except Exception as exc: + # Persist failure before EOF lets the client finish its cell. + failure.write_text(f"{type(exc).__name__}: {exc}") + raise + except Exception as exc: + failure.write_text(f"{type(exc).__name__}: {exc}") + raise + + +def server_command(*, clone: Path, mounts: Sequence[ReadOnlyMount], bwrap_bin: Path) -> list[str]: + """Build the credential-free sibling server from host-validated inputs.""" + node = Path(shutil.which("node") or "/usr/bin/node").resolve() + command = [str(bwrap_bin), *bwrap_base_args(unshare_network=True, cap_drop_all=True), + "--ro-bind", str(clone), SANDBOX_WORKSPACE, + "--ro-bind", str(node), SANDBOX_NODE] + for mount in mounts: + command += ["--ro-bind", str(mount.source), mount.target] + command += ["--tmpfs", "/run", "--tmpfs", SANDBOX_TMP, + "--tmpfs", "/home", "--dir", SANDBOX_HOME, "--clearenv"] + environment = { + "HOME": SANDBOX_HOME, "TMPDIR": SANDBOX_TMP, + "GITNEXUS_HOME": SANDBOX_GITNEXUS_REGISTRY, + "GITNEXUS_MCP_ALLOWED_REPOS": SANDBOX_WORKSPACE, + "GITNEXUS_MCP_DEFAULT_REPO": SANDBOX_WORKSPACE, + "PATH": "/usr/local/bin:/usr/bin:/bin", "LANG": "C.UTF-8", + "GIT_TERMINAL_PROMPT": "0", + } + for key, value in environment.items(): + command += ["--setenv", key, value] + return [*command, "--chdir", SANDBOX_WORKSPACE, "--", SANDBOX_NODE, + f"{SANDBOX_GITNEXUS}/dist/cli/index.js", "mcp"] + + +def connector_config() -> str: + return json.dumps({"mcpServers": {"gitnexus": { + "type": "stdio", "command": "/usr/bin/socat", + "args": ["STDIO", f"UNIX-CONNECT:{SANDBOX_MCP_SOCKET}"], + }}}, sort_keys=True, separators=(",", ":")) + + +@contextmanager +def isolated_mcp(*, clone: Path, mounts: Sequence[ReadOnlyMount], bwrap_bin: Path) -> Iterator[ReadOnlyMount]: + """Own the socket and every server until the complete model session ends.""" + # A short, private host path also stays below Linux's Unix-socket path limit. + with ExitStack() as cleanup: + root = Path(tempfile.mkdtemp(prefix="wf-mcp-")) + endpoint, failure = root / "mcp.sock", root / "failure" + ready, stop = threading.Event(), threading.Event() + outcomes: list[ManagedProcessResult | Exception] = [] + command = pid_namespace_command([ + sys.executable, "-m", "workflow_bench.mcp_transport", str(endpoint), str(failure), + *server_command(clone=clone, mounts=mounts, bwrap_bin=bwrap_bin), + ], bwrap_bin=bwrap_bin) + + def run() -> None: + try: + outcomes.append(run_managed( + command, timeout=24 * 60 * 60, require_pid_namespace=True, + env={"PATH": "/usr/local/bin:/usr/bin:/bin", "LANG": "C.UTF-8", + "PYTHONPATH": str(Path(__file__).resolve().parent.parent)}, + cancel_event=stop, stdout_observer=lambda _chunk: ready.set(), + )) + except Exception as exc: + outcomes.append(exc) + finally: + ready.set() + + worker = threading.Thread(target=run, name="mcp-transport", daemon=True) + cleanup.callback(lambda: shutil.rmtree(root) if not worker.is_alive() else None) + worker.start() + primary: BaseException | None = None + try: + if not ready.wait(10) or not endpoint.exists() or outcomes: + raise SandboxError(f"MCP transport failed to start: {outcomes!r}") + yield ReadOnlyMount(endpoint, SANDBOX_MCP_SOCKET) + if outcomes or failure.exists(): + raise SandboxError(f"MCP transport failed: {failure.read_text() if failure.exists() else outcomes!r}") + except BaseException as exc: + primary = exc + raise + finally: + stop.set() + worker.join(timeout=15) + error = None + if worker.is_alive(): + error = f"MCP transport supervisor did not stop; backing paths retained at {root}" + elif failure.exists(): + error = f"MCP transport failed: {failure.read_text()}" + elif not outcomes or isinstance(outcomes[0], Exception): + error = f"MCP transport supervision failed: {outcomes!r}" + elif outcomes[0].state not in ("cancelled",): + error = f"MCP transport exited unexpectedly: {outcomes[0]!r}" + if error: + if primary is None: + raise SandboxError(error) + primary.add_note(error) + + +if __name__ == "__main__": + serve_stdio(Path(sys.argv[1]), Path(sys.argv[2]), sys.argv[3:]) diff --git a/eval/workflow_bench/measurement-2026-10-24.json b/eval/workflow_bench/measurement-2026-10-24.json new file mode 100644 index 0000000000..7c52948626 --- /dev/null +++ b/eval/workflow_bench/measurement-2026-10-24.json @@ -0,0 +1,1212 @@ +{ + "historical": true, + "source_run": "https://github.com/abhigyanpatwari/GitNexus/actions/runs/40015796596", + "reports": { + "candidate": { + "runtime_sha": "62a6f67083fcd1f85634a49b118b4faf3fd5198d", + "harness_sha": "466d56280a37cb3dae9cdce8788937964824a3d5", + "task_set_digest": "51daf0758e8bafc30f0a9c94b254ee2b1592be1d569f2d64a7b3031ff7488c16", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "runs": 3, + "tasks": { + "trivial-status-json-alias": { + "sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "90105c7840b1ff13a5160da2358c0b29877dc6e74b63bdadf5a5a9b08f3315c7" + }, + "inv-feature-c-include-provenance": { + "sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "0fdf26865f1ac41876b6af1fcad729124e293ef9b55c97c9b99fcabce4fd95ea" + }, + "inv-feature-list-repos-filter": { + "sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "4a9ef06e50560bee3bfccc4f6bf30ad3e8f72ae375eddf47a0bfef19df966d14" + }, + "cross-module-parse-retry": { + "sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "39396d4593cf6bfa6cf838d55a90bbb21f45b20ba969c33feb8d05f8cce92d02" + } + }, + "schema": "gitnexus.release-evaluation/v1", + "generated_at": "2026-10-24T00:34:15.542969+00:00", + "complete": true, + "problems": [], + "per_run": [ + { + "task": "trivial-status-json-alias", + "run": 0, + "arm": "baseline_nomcp", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "90105c7840b1ff13a5160da2358c0b29877dc6e74b63bdadf5a5a9b08f3315c7", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 0.8601, + "duration_s": 319.4, + "input_tokens": 54, + "cache_creation_input_tokens": 54251, + "cache_read_input_tokens": 717501, + "output_tokens": 6480 + }, + { + "task": "trivial-status-json-alias", + "run": 0, + "arm": "baseline", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "90105c7840b1ff13a5160da2358c0b29877dc6e74b63bdadf5a5a9b08f3315c7", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 1.2159, + "duration_s": 407.8, + "input_tokens": 54, + "cache_creation_input_tokens": 81848, + "cache_read_input_tokens": 1050301, + "output_tokens": 7156 + }, + { + "task": "trivial-status-json-alias", + "run": 1, + "arm": "baseline_nomcp", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "90105c7840b1ff13a5160da2358c0b29877dc6e74b63bdadf5a5a9b08f3315c7", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 0.7967, + "duration_s": 321.8, + "input_tokens": 48, + "cache_creation_input_tokens": 50844, + "cache_read_input_tokens": 564499, + "output_tokens": 7859 + }, + { + "task": "trivial-status-json-alias", + "run": 1, + "arm": "baseline", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "90105c7840b1ff13a5160da2358c0b29877dc6e74b63bdadf5a5a9b08f3315c7", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 1.7795, + "duration_s": 405.9, + "input_tokens": 96, + "cache_creation_input_tokens": 85654, + "cache_read_input_tokens": 1962444, + "output_tokens": 10500 + }, + { + "task": "trivial-status-json-alias", + "run": 2, + "arm": "baseline_nomcp", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "90105c7840b1ff13a5160da2358c0b29877dc6e74b63bdadf5a5a9b08f3315c7", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 0.9767, + "duration_s": 261.1, + "input_tokens": 54, + "cache_creation_input_tokens": 62891, + "cache_read_input_tokens": 819460, + "output_tokens": 6946 + }, + { + "task": "trivial-status-json-alias", + "run": 2, + "arm": "baseline", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "90105c7840b1ff13a5160da2358c0b29877dc6e74b63bdadf5a5a9b08f3315c7", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 1.1557, + "duration_s": 385.0, + "input_tokens": 63, + "cache_creation_input_tokens": 70647, + "cache_read_input_tokens": 1000642, + "output_tokens": 8542 + }, + { + "task": "inv-feature-c-include-provenance", + "run": 0, + "arm": "baseline_nomcp", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "0fdf26865f1ac41876b6af1fcad729124e293ef9b55c97c9b99fcabce4fd95ea", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 2.2548, + "duration_s": 342.9, + "input_tokens": 99, + "cache_creation_input_tokens": 102077, + "cache_read_input_tokens": 2449500, + "output_tokens": 15662 + }, + { + "task": "inv-feature-c-include-provenance", + "run": 0, + "arm": "baseline", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "0fdf26865f1ac41876b6af1fcad729124e293ef9b55c97c9b99fcabce4fd95ea", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 5.3164, + "duration_s": 601.7, + "input_tokens": 135, + "cache_creation_input_tokens": 202129, + "cache_read_input_tokens": 6693294, + "output_tokens": 28232 + }, + { + "task": "inv-feature-c-include-provenance", + "run": 1, + "arm": "baseline_nomcp", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "0fdf26865f1ac41876b6af1fcad729124e293ef9b55c97c9b99fcabce4fd95ea", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 2.9411, + "duration_s": 479.5, + "input_tokens": 559, + "cache_creation_input_tokens": 129574, + "cache_read_input_tokens": 3121264, + "output_tokens": 22713 + }, + { + "task": "inv-feature-c-include-provenance", + "run": 1, + "arm": "baseline", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "0fdf26865f1ac41876b6af1fcad729124e293ef9b55c97c9b99fcabce4fd95ea", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 2.77, + "duration_s": 352.8, + "input_tokens": 69, + "cache_creation_input_tokens": 164365, + "cache_read_input_tokens": 2536346, + "output_tokens": 18967 + }, + { + "task": "inv-feature-c-include-provenance", + "run": 2, + "arm": "baseline_nomcp", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "0fdf26865f1ac41876b6af1fcad729124e293ef9b55c97c9b99fcabce4fd95ea", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 4.5127, + "duration_s": 664.7, + "input_tokens": 1718, + "cache_creation_input_tokens": 141945, + "cache_read_input_tokens": 5821552, + "output_tokens": 28246 + }, + { + "task": "inv-feature-c-include-provenance", + "run": 2, + "arm": "baseline", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "0fdf26865f1ac41876b6af1fcad729124e293ef9b55c97c9b99fcabce4fd95ea", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 2.6367, + "duration_s": 465.7, + "input_tokens": 279, + "cache_creation_input_tokens": 135405, + "cache_read_input_tokens": 2486802, + "output_tokens": 21826 + }, + { + "task": "inv-feature-list-repos-filter", + "run": 0, + "arm": "baseline_nomcp", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "4a9ef06e50560bee3bfccc4f6bf30ad3e8f72ae375eddf47a0bfef19df966d14", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 2.2716, + "duration_s": 511.6, + "input_tokens": 2621, + "cache_creation_input_tokens": 77766, + "cache_read_input_tokens": 2262735, + "output_tokens": 25645 + }, + { + "task": "inv-feature-list-repos-filter", + "run": 0, + "arm": "baseline", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "4a9ef06e50560bee3bfccc4f6bf30ad3e8f72ae375eddf47a0bfef19df966d14", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 2.953, + "duration_s": 364.7, + "input_tokens": 324, + "cache_creation_input_tokens": 125985, + "cache_read_input_tokens": 3339609, + "output_tokens": 19766 + }, + { + "task": "inv-feature-list-repos-filter", + "run": 1, + "arm": "baseline_nomcp", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "4a9ef06e50560bee3bfccc4f6bf30ad3e8f72ae375eddf47a0bfef19df966d14", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 3.3959, + "duration_s": 626.7, + "input_tokens": 2493, + "cache_creation_input_tokens": 112659, + "cache_read_input_tokens": 3780944, + "output_tokens": 31555 + }, + { + "task": "inv-feature-list-repos-filter", + "run": 1, + "arm": "baseline", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "4a9ef06e50560bee3bfccc4f6bf30ad3e8f72ae375eddf47a0bfef19df966d14", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 3.159, + "duration_s": 463.4, + "input_tokens": 171, + "cache_creation_input_tokens": 103164, + "cache_read_input_tokens": 3986392, + "output_tokens": 20805 + }, + { + "task": "inv-feature-list-repos-filter", + "run": 2, + "arm": "baseline_nomcp", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "4a9ef06e50560bee3bfccc4f6bf30ad3e8f72ae375eddf47a0bfef19df966d14", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 3.6101, + "duration_s": 1085.6, + "input_tokens": 323, + "cache_creation_input_tokens": 148649, + "cache_read_input_tokens": 4111000, + "output_tokens": 24959 + }, + { + "task": "inv-feature-list-repos-filter", + "run": 2, + "arm": "baseline", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "4a9ef06e50560bee3bfccc4f6bf30ad3e8f72ae375eddf47a0bfef19df966d14", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 2.6612, + "duration_s": 377.6, + "input_tokens": 3536, + "cache_creation_input_tokens": 126703, + "cache_read_input_tokens": 2731099, + "output_tokens": 19445 + }, + { + "task": "cross-module-parse-retry", + "run": 0, + "arm": "baseline_nomcp", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "39396d4593cf6bfa6cf838d55a90bbb21f45b20ba969c33feb8d05f8cce92d02", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 4.7241, + "duration_s": 604.2, + "input_tokens": 563, + "cache_creation_input_tokens": 140418, + "cache_read_input_tokens": 5947974, + "output_tokens": 34787 + }, + { + "task": "cross-module-parse-retry", + "run": 0, + "arm": "baseline", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "39396d4593cf6bfa6cf838d55a90bbb21f45b20ba969c33feb8d05f8cce92d02", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 8.9079, + "duration_s": 829.8, + "input_tokens": 353, + "cache_creation_input_tokens": 226563, + "cache_read_input_tokens": 13170789, + "output_tokens": 36187 + }, + { + "task": "cross-module-parse-retry", + "run": 1, + "arm": "baseline_nomcp", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "39396d4593cf6bfa6cf838d55a90bbb21f45b20ba969c33feb8d05f8cce92d02", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 5.7595, + "duration_s": 752.2, + "input_tokens": 311, + "cache_creation_input_tokens": 163110, + "cache_read_input_tokens": 7786402, + "output_tokens": 33813 + }, + { + "task": "cross-module-parse-retry", + "run": 1, + "arm": "baseline", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "39396d4593cf6bfa6cf838d55a90bbb21f45b20ba969c33feb8d05f8cce92d02", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 4.4676, + "duration_s": 813.7, + "input_tokens": 746, + "cache_creation_input_tokens": 144869, + "cache_read_input_tokens": 5081193, + "output_tokens": 40714 + }, + { + "task": "cross-module-parse-retry", + "run": 2, + "arm": "baseline_nomcp", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "39396d4593cf6bfa6cf838d55a90bbb21f45b20ba969c33feb8d05f8cce92d02", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 4.992, + "duration_s": 1434.0, + "input_tokens": 2186, + "cache_creation_input_tokens": 150371, + "cache_read_input_tokens": 6492405, + "output_tokens": 31803 + }, + { + "task": "cross-module-parse-retry", + "run": 2, + "arm": "baseline", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "39396d4593cf6bfa6cf838d55a90bbb21f45b20ba969c33feb8d05f8cce92d02", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 8.0877, + "duration_s": 1556.2, + "input_tokens": 315, + "cache_creation_input_tokens": 236142, + "cache_read_input_tokens": 11492978, + "output_tokens": 34551 + } + ], + "arms": { + "baseline_nomcp": { + "cells": 12, + "solved": 12, + "mean_cost_usd": 3.091275, + "mean_wall_s": 616.975 + }, + "baseline": { + "cells": 12, + "solved": 12, + "mean_cost_usd": 3.7592166666666667, + "mean_wall_s": 585.3583333333333 + } + }, + "paired": { + "solve_delta": 0, + "mean_cost_change_pct": 21.607319525654194, + "mean_wall_change_pct": -5.124464794629713 + } + }, + "stable": { + "runtime_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "harness_sha": "466d56280a37cb3dae9cdce8788937964824a3d5", + "task_set_digest": "51daf0758e8bafc30f0a9c94b254ee2b1592be1d569f2d64a7b3031ff7488c16", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "runs": 3, + "tasks": { + "trivial-status-json-alias": { + "sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "90105c7840b1ff13a5160da2358c0b29877dc6e74b63bdadf5a5a9b08f3315c7" + }, + "inv-feature-c-include-provenance": { + "sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "0fdf26865f1ac41876b6af1fcad729124e293ef9b55c97c9b99fcabce4fd95ea" + }, + "inv-feature-list-repos-filter": { + "sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "4a9ef06e50560bee3bfccc4f6bf30ad3e8f72ae375eddf47a0bfef19df966d14" + }, + "cross-module-parse-retry": { + "sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "39396d4593cf6bfa6cf838d55a90bbb21f45b20ba969c33feb8d05f8cce92d02" + } + }, + "schema": "gitnexus.release-evaluation/v1", + "generated_at": "2026-10-24T00:34:15.377904+00:00", + "complete": true, + "problems": [], + "per_run": [ + { + "task": "trivial-status-json-alias", + "run": 0, + "arm": "baseline_nomcp", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "90105c7840b1ff13a5160da2358c0b29877dc6e74b63bdadf5a5a9b08f3315c7", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 0.7794, + "duration_s": 209.8, + "input_tokens": 42, + "cache_creation_input_tokens": 56525, + "cache_read_input_tokens": 592095, + "output_tokens": 5196 + }, + { + "task": "trivial-status-json-alias", + "run": 0, + "arm": "baseline", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "90105c7840b1ff13a5160da2358c0b29877dc6e74b63bdadf5a5a9b08f3315c7", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 0.945, + "duration_s": 312.1, + "input_tokens": 42, + "cache_creation_input_tokens": 69816, + "cache_read_input_tokens": 705418, + "output_tokens": 6229 + }, + { + "task": "trivial-status-json-alias", + "run": 1, + "arm": "baseline_nomcp", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "90105c7840b1ff13a5160da2358c0b29877dc6e74b63bdadf5a5a9b08f3315c7", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 0.966, + "duration_s": 760.7, + "input_tokens": 78, + "cache_creation_input_tokens": 48367, + "cache_read_input_tokens": 985430, + "output_tokens": 6826 + }, + { + "task": "trivial-status-json-alias", + "run": 1, + "arm": "baseline", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "90105c7840b1ff13a5160da2358c0b29877dc6e74b63bdadf5a5a9b08f3315c7", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 1.3409, + "duration_s": 406.0, + "input_tokens": 90, + "cache_creation_input_tokens": 62393, + "cache_read_input_tokens": 1485484, + "output_tokens": 8311 + }, + { + "task": "trivial-status-json-alias", + "run": 2, + "arm": "baseline_nomcp", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "90105c7840b1ff13a5160da2358c0b29877dc6e74b63bdadf5a5a9b08f3315c7", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 0.9274, + "duration_s": 462.1, + "input_tokens": 54, + "cache_creation_input_tokens": 59154, + "cache_read_input_tokens": 694309, + "output_tokens": 8410 + }, + { + "task": "trivial-status-json-alias", + "run": 2, + "arm": "baseline", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "90105c7840b1ff13a5160da2358c0b29877dc6e74b63bdadf5a5a9b08f3315c7", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 1.0308, + "duration_s": 265.0, + "input_tokens": 48, + "cache_creation_input_tokens": 73846, + "cache_read_input_tokens": 870782, + "output_tokens": 5347 + }, + { + "task": "inv-feature-c-include-provenance", + "run": 0, + "arm": "baseline_nomcp", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "0fdf26865f1ac41876b6af1fcad729124e293ef9b55c97c9b99fcabce4fd95ea", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 2.8105, + "duration_s": 1108.7, + "input_tokens": 123, + "cache_creation_input_tokens": 108080, + "cache_read_input_tokens": 3227177, + "output_tokens": 20830 + }, + { + "task": "inv-feature-c-include-provenance", + "run": 0, + "arm": "baseline", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "0fdf26865f1ac41876b6af1fcad729124e293ef9b55c97c9b99fcabce4fd95ea", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 5.2765, + "duration_s": 736.7, + "input_tokens": 2880, + "cache_creation_input_tokens": 181957, + "cache_read_input_tokens": 6750719, + "output_tokens": 29981 + }, + { + "task": "inv-feature-c-include-provenance", + "run": 1, + "arm": "baseline_nomcp", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "0fdf26865f1ac41876b6af1fcad729124e293ef9b55c97c9b99fcabce4fd95ea", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 3.8868, + "duration_s": 1211.0, + "input_tokens": 171, + "cache_creation_input_tokens": 112091, + "cache_read_input_tokens": 4902649, + "output_tokens": 29363 + }, + { + "task": "inv-feature-c-include-provenance", + "run": 1, + "arm": "baseline", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "0fdf26865f1ac41876b6af1fcad729124e293ef9b55c97c9b99fcabce4fd95ea", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 3.9381, + "duration_s": 588.2, + "input_tokens": 393, + "cache_creation_input_tokens": 153289, + "cache_read_input_tokens": 4674868, + "output_tokens": 25625 + }, + { + "task": "inv-feature-c-include-provenance", + "run": 2, + "arm": "baseline_nomcp", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "0fdf26865f1ac41876b6af1fcad729124e293ef9b55c97c9b99fcabce4fd95ea", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 2.1343, + "duration_s": 368.1, + "input_tokens": 389, + "cache_creation_input_tokens": 92506, + "cache_read_input_tokens": 2215318, + "output_tokens": 17863 + }, + { + "task": "inv-feature-c-include-provenance", + "run": 2, + "arm": "baseline", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "0fdf26865f1ac41876b6af1fcad729124e293ef9b55c97c9b99fcabce4fd95ea", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 5.5732, + "duration_s": 717.5, + "input_tokens": 180, + "cache_creation_input_tokens": 168774, + "cache_read_input_tokens": 7475148, + "output_tokens": 31194 + }, + { + "task": "inv-feature-list-repos-filter", + "run": 0, + "arm": "baseline_nomcp", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "4a9ef06e50560bee3bfccc4f6bf30ad3e8f72ae375eddf47a0bfef19df966d14", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 1.9724, + "duration_s": 455.4, + "input_tokens": 105, + "cache_creation_input_tokens": 67341, + "cache_read_input_tokens": 1818058, + "output_tokens": 25680 + }, + { + "task": "inv-feature-list-repos-filter", + "run": 0, + "arm": "baseline", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "4a9ef06e50560bee3bfccc4f6bf30ad3e8f72ae375eddf47a0bfef19df966d14", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 2.9823, + "duration_s": 524.1, + "input_tokens": 413, + "cache_creation_input_tokens": 120788, + "cache_read_input_tokens": 3197003, + "output_tokens": 25074 + }, + { + "task": "inv-feature-list-repos-filter", + "run": 1, + "arm": "baseline_nomcp", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "4a9ef06e50560bee3bfccc4f6bf30ad3e8f72ae375eddf47a0bfef19df966d14", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 1.2148, + "duration_s": 265.8, + "input_tokens": 2533, + "cache_creation_input_tokens": 56933, + "cache_read_input_tokens": 931884, + "output_tokens": 15214 + }, + { + "task": "inv-feature-list-repos-filter", + "run": 1, + "arm": "baseline", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "4a9ef06e50560bee3bfccc4f6bf30ad3e8f72ae375eddf47a0bfef19df966d14", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 3.0637, + "duration_s": 406.6, + "input_tokens": 437, + "cache_creation_input_tokens": 125557, + "cache_read_input_tokens": 3662273, + "output_tokens": 17825 + }, + { + "task": "inv-feature-list-repos-filter", + "run": 2, + "arm": "baseline_nomcp", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "4a9ef06e50560bee3bfccc4f6bf30ad3e8f72ae375eddf47a0bfef19df966d14", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 1.7031, + "duration_s": 380.2, + "input_tokens": 601, + "cache_creation_input_tokens": 70224, + "cache_read_input_tokens": 1627510, + "output_tokens": 17897 + }, + { + "task": "inv-feature-list-repos-filter", + "run": 2, + "arm": "baseline", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "4a9ef06e50560bee3bfccc4f6bf30ad3e8f72ae375eddf47a0bfef19df966d14", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 1.7256, + "duration_s": 364.3, + "input_tokens": 2425, + "cache_creation_input_tokens": 84220, + "cache_read_input_tokens": 1556455, + "output_tokens": 16354 + }, + { + "task": "cross-module-parse-retry", + "run": 0, + "arm": "baseline_nomcp", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "39396d4593cf6bfa6cf838d55a90bbb21f45b20ba969c33feb8d05f8cce92d02", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 8.1963, + "duration_s": 1556.2, + "input_tokens": 1806, + "cache_creation_input_tokens": 188015, + "cache_read_input_tokens": 12149859, + "output_tokens": 37491 + }, + { + "task": "cross-module-parse-retry", + "run": 0, + "arm": "baseline", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "39396d4593cf6bfa6cf838d55a90bbb21f45b20ba969c33feb8d05f8cce92d02", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 8.8275, + "duration_s": 1775.9, + "input_tokens": 4943, + "cache_creation_input_tokens": 209697, + "cache_read_input_tokens": 13003539, + "output_tokens": 39618 + }, + { + "task": "cross-module-parse-retry", + "run": 1, + "arm": "baseline_nomcp", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "39396d4593cf6bfa6cf838d55a90bbb21f45b20ba969c33feb8d05f8cce92d02", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 8.9686, + "duration_s": 1408.0, + "input_tokens": 2635, + "cache_creation_input_tokens": 201014, + "cache_read_input_tokens": 13604688, + "output_tokens": 35870 + }, + { + "task": "cross-module-parse-retry", + "run": 1, + "arm": "baseline", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "39396d4593cf6bfa6cf838d55a90bbb21f45b20ba969c33feb8d05f8cce92d02", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 8.9339, + "duration_s": 1359.5, + "input_tokens": 330, + "cache_creation_input_tokens": 216286, + "cache_read_input_tokens": 13145230, + "output_tokens": 40315 + }, + { + "task": "cross-module-parse-retry", + "run": 2, + "arm": "baseline_nomcp", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "39396d4593cf6bfa6cf838d55a90bbb21f45b20ba969c33feb8d05f8cce92d02", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 5.4686, + "duration_s": 888.1, + "input_tokens": 535, + "cache_creation_input_tokens": 160231, + "cache_read_input_tokens": 7102745, + "output_tokens": 36526 + }, + { + "task": "cross-module-parse-retry", + "run": 2, + "arm": "baseline", + "model": "gpt-5.6-sol", + "effort": "xhigh", + "task_base_sha": "c4ecf398de637cf779ab2238e69958cfd5d601ce", + "oracle_digest": "39396d4593cf6bfa6cf838d55a90bbb21f45b20ba969c33feb8d05f8cce92d02", + "sandbox_backend": "bwrap", + "sandbox_dependency_content_digest": "7a3e0c761591e79068655997f4f2d6d5b75dd1126781c6387f4aa1be5bea141e", + "ok": true, + "resolved": true, + "authored_tests_passed": true, + "oracle_passed": true, + "error_kind": null, + "transcript_missing": false, + "cost_usd": 13.2384, + "duration_s": 1295.2, + "input_tokens": 2897, + "cache_creation_input_tokens": 222817, + "cache_read_input_tokens": 20977371, + "output_tokens": 53704 + } + ], + "arms": { + "baseline_nomcp": { + "cells": 12, + "solved": 12, + "mean_cost_usd": 3.2523500000000003, + "mean_wall_s": 756.1750000000001 + }, + "baseline": { + "cells": 12, + "solved": 12, + "mean_cost_usd": 4.739658333333334, + "mean_wall_s": 729.2583333333333 + } + }, + "paired": { + "solve_delta": 0, + "mean_cost_change_pct": 45.73026683270046, + "mean_wall_change_pct": -3.5595816665013706 + } + } + } +} diff --git a/eval/workflow_bench/measurement-2026-10-24.md b/eval/workflow_bench/measurement-2026-10-24.md new file mode 100644 index 0000000000..aa59a52fef --- /dev/null +++ b/eval/workflow_bench/measurement-2026-10-24.md @@ -0,0 +1,82 @@ +# Agent evaluation evidence, 24 October 2026 + +The latest completed comparison does **not** demonstrate an accuracy gain or +cost saving. Its MCP arm could read compiled code containing later task fixes, +so it also cannot isolate the effect of tool assistance. + +## Historical measurements + +[Release evaluation run 40015796596](https://github.com/abhigyanpatwari/GitNexus/actions/runs/40015796596) +started on 23 October and completed on 24 October. The sanitized artifact is +`release-agent-evaluation-62a6f67083fcd1f85634a49b118b4faf3fd5198d` +(artifact ID `12541246950`). Both JSON reports contain all 24 expected cells; +their totals were independently recomputed from all 48 per-run records. +The [sanitized source reports](measurement-2026-10-24.json) are retained here +so these observations remain reproducible after the workflow artifact expires. + +- Candidate: `62a6f67083fcd1f85634a49b118b4faf3fd5198d`. +- Stable runtime and task base: `c4ecf398de637cf779ab2238e69958cfd5d601ce`. +- Harness: `466d56280a37cb3dae9cdce8788937964824a3d5`. +- Model: `gpt-5.6-sol`, effort `xhigh`. +- Task-set digest: `51daf0758e8bafc30f0a9c94b254ee2b1592be1d569f2d64a7b3031ff7488c16`. +- Four tasks, three repetitions per arm. Both arms use the same task pins and + hidden oracles; the no-GitNexus arm receives no supplied graph or tools. + +| Runtime | Arm | Solved | Mean reported cost | Mean agent time | +| --- | --- | --- | --- | --- | +| Candidate | No GitNexus | 12/12 | $3.0913 | 617.0s | +| Candidate | MCP, readable runtime | 12/12 | $3.7592 | 585.4s | +| Stable | No GitNexus | 12/12 | $3.2524 | 756.2s | +| Stable | MCP, readable runtime | 12/12 | $4.7397 | 729.3s | + +Candidate MCP cost increased **21.6%** and agent time decreased **5.1%**. +Stable MCP cost increased **45.7%** and agent time decreased **3.6%**. +Accuracy was unchanged in both comparisons. Cost comes from session reports, +not invoices; indexing, grading, and infrastructure are excluded. Three +repetitions on four development tasks do not establish significance or a +general product benefit. The release gate checks quality against stable; a +passing gate is not evidence of savings against no GitNexus. + +## Deterministic tool accuracy + +At source revision `d8a256a03a101a767dc4e1118913c679af740336`, the existing +tool-accuracy corpus passes **32/32**, with no allowances or execution failures. +This includes the Python receiver, lexical scope, and summary lower-bound +checks discussed in issues #3497–#3499. It verifies fixed tool answers, not +coding-agent success or cost. + +Reproduce from `gitnexus/`: + +```sh +node --import tsx bench/tool-accuracy/run.ts --check --out /tmp/tool-accuracy +``` + +The local run needed a compatible C++ runtime to load the native parser. Its +first attempt could not load `GLIBCXX_3.4.31`; that attempt was an execution +failure, not a measured tool result. + +## Corrected comparison and remaining work + +The harness correction moves the release baseline's MCP runtime into a +sibling read-only sandbox. The coding agent receives only a stdio socket. +Host-generated rows record `runtime_exposure`, and release/PR validation +rejects missing or incompatible receipts. Workflow arms that intentionally +expose the CLI retain their different boundary. + +The protected Release evaluation workflow executes main's trusted harness, +including PR previews. A fresh isolated comparison therefore requires this +correction to merge first. After merge, dispatch `release-evaluation.yml` on +`main` with `candidate_ref` set to the full merged commit SHA, model +`gpt-5.6-sol`, effort `xhigh`, and `runner_only=false`. The existing workflow +runs all four tasks three times per arm for candidate and stable, publishes +sanitized reports, and stops its runner. + +Verify all 48 unique cells, the exact runtime/harness/task bindings, both arm +receipts, unsuccessful outcomes, and cost/time totals. Publish the result even +if it shows no gain. Historical artifacts cannot substitute for this run. + +Keep [issue #3500](https://github.com/abhigyanpatwari/GitNexus/issues/3500) +open until the clean measurement is published. A broader SWE-bench or reporter +corpus, including separate fresh/stale-index conditions, remains necessary +before making claims beyond this small task set. The reporter paused their +rerun offer in [discussion #3493](https://github.com/abhigyanpatwari/GitNexus/discussions/3493#discussioncomment-18772530). diff --git a/eval/workflow_bench/pr_evaluation.py b/eval/workflow_bench/pr_evaluation.py index c09405ba2e..401aa482c5 100644 --- a/eval/workflow_bench/pr_evaluation.py +++ b/eval/workflow_bench/pr_evaluation.py @@ -321,6 +321,7 @@ def compare_candidate( for field in ("model", "effort", "task_base_sha", "oracle_digest", "sandbox_dependency_content_digest") ) and row.get("sandbox_backend") == "bwrap" + and row.get("runtime_exposure") == "stdio-only" and row.get("ok") is True and all(type(row.get(field)) is bool for field in ("resolved", "authored_tests_passed", "oracle_passed")) and row["resolved"] == (row["authored_tests_passed"] and row["oracle_passed"]) diff --git a/eval/workflow_bench/proposer_sandbox.py b/eval/workflow_bench/proposer_sandbox.py index c17afd19aa..dd2608df02 100644 --- a/eval/workflow_bench/proposer_sandbox.py +++ b/eval/workflow_bench/proposer_sandbox.py @@ -38,6 +38,7 @@ SANDBOX_CLAUDE = "/opt/claude/claude" SANDBOX_SHELL_PREFIX = "/opt/claude/shell-prefix" SANDBOX_PYTHON3 = "/opt/claude/python3" SANDBOX_GITNEXUS_CLI = "/opt/claude/gitnexus" +SANDBOX_MCP_SOCKET = "/run/gitnexus-mcp.sock" SANDBOX_GIT_EXCLUDES = "/opt/claude/git-excludes" SANDBOX_NODE = "/opt/claude/node" SANDBOX_BWRAP = "/opt/claude/bwrap" @@ -1219,6 +1220,7 @@ def prepare_sandbox( preflight: bool = True, backend: str = "bwrap", gitnexus_available: bool = True, + gitnexus_cli_available: bool = True, ) -> Iterator[SandboxSession]: """Create private host backing dirs and one virtualized command.""" @@ -1235,6 +1237,7 @@ def prepare_sandbox( SANDBOX_GITNEXUS_SHARED, SANDBOX_GITNEXUS_REGISTRY, SANDBOX_GITNEXUS_CLI, + SANDBOX_MCP_SOCKET, f"{SANDBOX_WORKSPACE}/.gitnexus", ) for mount in read_only_mounts: @@ -1260,7 +1263,8 @@ def prepare_sandbox( for directory in (home, temp): directory.mkdir(mode=0o700) directory.chmod(0o700) - shell_prefix = _create_shell_prefix_wrapper(private_root, gitnexus_available=gitnexus_available) + cli_available = gitnexus_available and gitnexus_cli_available + shell_prefix = _create_shell_prefix_wrapper(private_root, gitnexus_available=cli_available) python3_wrapper = _create_python3_wrapper(private_root) git_excludes = _create_git_excludes(private_root) # Claude may discover user-level skills below HOME. Keep the rest of HOME @@ -1280,7 +1284,7 @@ def prepare_sandbox( *read_only_mounts, *( (ReadOnlyMount(source=bwrap, target=SANDBOX_BWRAP),) - if backend == "bwrap" and gitnexus_available + if backend == "bwrap" and cli_available else () ), ReadOnlyMount(source=user_skills, target=SANDBOX_USER_SKILLS), @@ -1288,7 +1292,7 @@ def prepare_sandbox( ReadOnlyMount(source=python3_wrapper, target=SANDBOX_PYTHON3), *( (ReadOnlyMount(source=_create_gitnexus_wrapper(private_root), target=SANDBOX_GITNEXUS_CLI),) - if gitnexus_available + if cli_available else baseline_mounts ), ReadOnlyMount(source=git_excludes, target=SANDBOX_GIT_EXCLUDES), diff --git a/eval/workflow_bench/release_report.py b/eval/workflow_bench/release_report.py index 030d04c34d..3ceeb089a7 100644 --- a/eval/workflow_bench/release_report.py +++ b/eval/workflow_bench/release_report.py @@ -32,6 +32,7 @@ ROW_FIELDS = ( "task_base_sha", "oracle_digest", "sandbox_backend", + "runtime_exposure", DEPENDENCY_CONTENT_BINDING_FIELD, "ok", "resolved", @@ -126,6 +127,7 @@ def build_report(rows: list[Any], metadata: dict[str, Any], *, now: datetime | N and row.get("model") == report["model"] and row.get("effort") == report["effort"] and row.get("sandbox_backend") == "bwrap" + and row.get("runtime_exposure") == ("none" if arm == "baseline_nomcp" else "stdio-only") and row.get("ok") is True and type(row.get("resolved")) is bool and type(row.get("authored_tests_passed")) is bool @@ -192,7 +194,14 @@ def render_markdown(report: dict[str, Any]) -> str: lines += [ "", "Negative agent outcomes remain in the denominator. Indexing and grading are excluded from agent cost/time.", - "The MCP arm also has readable compiled runtime code; this comparison includes that access and cannot isolate tool assistance from access to later fixes.", + ( + "The MCP arm receives a stdio connection; the candidate runtime and registry are absent from the agent filesystem." + if report["complete"] and report.get("per_run") and all( + row.get("runtime_exposure") == ("none" if row.get("arm") == "baseline_nomcp" else "stdio-only") + for row in report["per_run"] + ) + else "Runtime isolation is unproven. Historical MCP cells had readable compiled runtime code and cannot isolate tool assistance from access to later fixes." + ), "This small pinned task set is release evidence; it does not establish general gains or statistical significance.", "", ] diff --git a/eval/workflow_bench/runner.py b/eval/workflow_bench/runner.py index 90994de34c..011d639385 100644 --- a/eval/workflow_bench/runner.py +++ b/eval/workflow_bench/runner.py @@ -36,6 +36,7 @@ from __future__ import annotations import argparse from concurrent.futures import ThreadPoolExecutor, wait +from contextlib import ExitStack import hashlib import json import os @@ -57,6 +58,8 @@ from typing import Any import yaml +from .mcp_transport import connector_config, isolated_mcp + from .comparator_reuse import ( REUSE_EXCLUDED_ERROR_KINDS, CellKey, @@ -458,6 +461,7 @@ def run_arm( enforce_phase_boundary: bool = False, ce_plugin_dir: str | None = None, oracle_snapshot: TaskOracleSnapshot | None = None, + mcp_config_json: str | None = None, ) -> dict[str, Any]: sessions: list[dict[str, Any]] = [] environment_builder = getattr(sandbox, "environment", build_sandbox_environment) @@ -491,7 +495,7 @@ def run_arm( "require_pid_namespace": getattr(sandbox, "require_pid_namespace", True), "settings_json": sandbox.settings_json, "strict_mcp_config": True, - "mcp_config_json": host_text(sandbox_mcp_config(unsafe_host=backend == "host-unsafe")), + "mcp_config_json": mcp_config_json or host_text(sandbox_mcp_config(unsafe_host=backend == "host-unsafe")), "transcript_projects": sandbox.transcript_projects, "transcript_cwd": Path(SANDBOX_WORKSPACE), "transcript_wait_seconds": 5, @@ -1189,6 +1193,9 @@ def run_cell(ctx: TaskCellContext, run_idx: int, arm: str) -> dict[str, Any]: cleanup_error: OSError | None = None execution_arm = CANDIDATE_ARMS.get(arm, arm) gitnexus_available = execution_arm != "baseline_nomcp" + isolated_baseline = execution_arm == "baseline" and ctx.sandbox_backend == "bwrap" + runtime_exposure = "none" if not gitnexus_available else "readable" + resources = ExitStack() try: if ctx.asset_snapshot_error is not None: raise RuntimeError(f"task asset snapshot preparation failed: {ctx.asset_snapshot_error}") @@ -1222,6 +1229,12 @@ def run_cell(ctx: TaskCellContext, run_idx: int, arm: str) -> dict[str, Any]: else [] ) ce_mounts = ce_plugin_mounts_for_arm(execution_arm, ctx.ce_plugin_snapshot) + if isolated_baseline: + endpoint = resources.enter_context(isolated_mcp( + clone=worktree, mounts=[*dependency_mounts, *gitnexus_mounts], bwrap_bin=ctx.bwrap_bin, + )) + gitnexus_mounts = [endpoint] + runtime_exposure = "stdio-only" with prepare_sandbox( clone=worktree, claude_bin=args.claude_bin, @@ -1234,6 +1247,7 @@ def run_cell(ctx: TaskCellContext, run_idx: int, arm: str) -> dict[str, Any]: preflight=False, backend=ctx.sandbox_backend, gitnexus_available=gitnexus_available, + gitnexus_cli_available=not isolated_baseline, ) as sandbox: # Capture the BASE (pre-overlay) skill digest — identical # for the incumbent and candidate arms — then run the @@ -1314,6 +1328,7 @@ def run_cell(ctx: TaskCellContext, run_idx: int, arm: str) -> dict[str, Any]: enforce_phase_boundary=True, ce_plugin_dir=ce_plugin_dir_for_arm(execution_arm, ctx.ce_plugin_snapshot), oracle_snapshot=ctx.oracle_snapshot, + mcp_config_json=connector_config() if isolated_baseline else None, ) if execution_arm in ("review", "ce_review"): review_source = review_output_path(sandbox, REVIEW_OUTPUT) @@ -1345,6 +1360,7 @@ def run_cell(ctx: TaskCellContext, run_idx: int, arm: str) -> dict[str, Any]: after_digest=after_work_digest, ) patch_bytes = capture_patch(sandbox, worktree, orig_sha) + resources.close() record["arm"] = arm record.update( { @@ -1387,6 +1403,11 @@ def run_cell(ctx: TaskCellContext, run_idx: int, arm: str) -> dict[str, Any]: detail = redact_text(str(exc), credential_secrets(args)) print(f"[{task['id']}][{arm}][run {run_idx}] infra-error: {detail}") finally: + try: + resources.close() + except (SandboxError, OSError, RuntimeError) as exc: + record = infra_error_record(exc) + record["arm"] = arm if worktree is not None and worktree.exists(): try: remove_clone(worktree) @@ -1408,6 +1429,7 @@ def run_cell(ctx: TaskCellContext, run_idx: int, arm: str) -> dict[str, Any]: "class": task.get("class", ""), "run": run_idx, "sandbox_backend": ctx.sandbox_backend, + "runtime_exposure": runtime_exposure, "task_asset_snapshot_digest": (ctx.asset_snapshot.digest if ctx.asset_snapshot is not None else None), "task_asset_manifest_digest": ( ctx.asset_snapshot.manifest_digest if ctx.asset_snapshot is not None else None diff --git a/gitnexus-shared/src/scope-resolution/finalize-algorithm.ts b/gitnexus-shared/src/scope-resolution/finalize-algorithm.ts index 1106d86192..2ee32c3a78 100644 --- a/gitnexus-shared/src/scope-resolution/finalize-algorithm.ts +++ b/gitnexus-shared/src/scope-resolution/finalize-algorithm.ts @@ -298,7 +298,7 @@ export function finalize(input: FinalizeInput, hooks: FinalizeHooks): FinalizeOu // ── Phase 2: Tarjan SCC → reverse-topological list of SCCs. const sccs = tarjanSccs(graph); - // ── Phase 2.5: precompute the per-file re-export closure (iterative, + // ── Phase 2.5: prepare the per-file re-export closure (iterative, // SCC-condensed). Eliminates the recursive crawl that the per-edge // `tryFinalize` call site used to do; lookups are O(1) afterwards. // See `buildReexportClosures` for the algorithm. @@ -322,15 +322,20 @@ export function finalize(input: FinalizeInput, hooks: FinalizeHooks): FinalizeOu ambiguousByFile.set(filePath, new Set(byName.keys())); } const topLevelOnly = hooks.namedImportsBindTopLevelOnly === true; - const reexportClosures = buildReexportClosures( - input.files, - byFilePath, - moduleEdgeIndex, - ambiguousByFile, - topLevelOnly, - hooks.filterWildcardNames, - input.workspaceIndex, - ); + // Direct imports and unfiltered wildcards never read these closures. Build + // them once, on demand, so those workspaces do not allocate transitive tables + // (and their provenance paths) that are discarded without a single lookup. + let reexportClosures: ReadonlyMap | undefined; + const getReexportClosures = () => + (reexportClosures ??= buildReexportClosures( + input.files, + byFilePath, + moduleEdgeIndex, + ambiguousByFile, + topLevelOnly, + hooks.filterWildcardNames, + input.workspaceIndex, + )); // ── Phase 3: process SCCs in reverse-topological order (leaves first). // Within each SCC, run a bounded fixpoint that resolves intra-SCC edges. @@ -369,7 +374,7 @@ export function finalize(input: FinalizeInput, hooks: FinalizeHooks): FinalizeOu if (drafts === undefined) continue; for (const draft of drafts) { if (draft.finalized !== null) continue; - const finalized = tryFinalize(draft, byFilePath, reexportClosures, topLevelOnly); + const finalized = tryFinalize(draft, byFilePath, getReexportClosures, topLevelOnly); if (finalized !== null) { draft.finalized = finalized; progressed = true; @@ -422,7 +427,7 @@ export function finalize(input: FinalizeInput, hooks: FinalizeHooks): FinalizeOu byFilePath, hooks, input.workspaceIndex, - reexportClosures, + getReexportClosures, ); for (const e of expanded) { if ( @@ -692,7 +697,7 @@ function extractExportedName(parsed: ParsedImport): string { function tryFinalize( draft: ImportEdgeDraft, byFilePath: Map, - reexportClosures: ReadonlyMap, + getReexportClosures: () => ReadonlyMap, topLevelOnly: boolean, ): ImportEdge | null { const targetFile = draft.targetFile; @@ -754,7 +759,7 @@ function tryFinalize( // already encodes every name reachable through that file's named and // wildcard re-exports — including transitively through cyclic SCCs — // so the lookup is O(1) and never recurses. - const followed = lookupReexportedName(reexportClosures, targetFile, importedName); + const followed = lookupReexportedName(getReexportClosures(), targetFile, importedName); if (followed === null) { // Target resolvable but the name isn't exported — keep trying in case a // re-export inside the target's SCC surfaces it in a later iteration. @@ -1605,7 +1610,7 @@ function expandWildcard( byFilePath: Map, hooks: FinalizeHooks, workspace: WorkspaceIndex, - reexportClosures: ReadonlyMap, + getReexportClosures: () => ReadonlyMap, ): readonly ImportEdge[] { if (edge.targetModuleScope === undefined || edge.targetFile === null) { return [edge]; // unresolvable wildcard survives as a single unlinked edge @@ -1614,7 +1619,9 @@ function expandWildcard( if (target === undefined) return [edge]; const targetClosure = - hooks.filterWildcardNames === undefined ? undefined : reexportClosures.get(edge.targetFile); + hooks.filterWildcardNames === undefined + ? undefined + : getReexportClosures().get(edge.targetFile); const names = hooks.filterWildcardNames?.( edge.targetModuleScope, diff --git a/gitnexus-web/package-lock.json b/gitnexus-web/package-lock.json index 62adbae7f7..ebcb82e178 100644 --- a/gitnexus-web/package-lock.json +++ b/gitnexus-web/package-lock.json @@ -4989,9 +4989,9 @@ "license": "Unlicense" }, "node_modules/fast-uri": { - "version": "3.1.8", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.8.tgz", - "integrity": "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==", + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", "dev": true, "funding": [ { diff --git a/gitnexus/bench/callable-value-flow/measure.mjs b/gitnexus/bench/callable-value-flow/measure.mjs index e0a5f320b2..6897ef9602 100644 --- a/gitnexus/bench/callable-value-flow/measure.mjs +++ b/gitnexus/bench/callable-value-flow/measure.mjs @@ -15,7 +15,7 @@ * same-named callable in the file. * * For a synthetic corpus at two scales it reports: - * - elapsed_ms_small / elapsed_ms_large (fastest of REPS, see `fastest`) + a scaling ratio + * - elapsed_ms_small / elapsed_ms_large (median of window minima) + a scaling ratio * `(t_large/t_small)/(LARGE/SMALL)`: ~1.0 linear, ~3.x quadratic; * - `callable_only_ms_large`, the same corpus with the PRE-#2693 def * population, so the cost the widening actually added stays visible as @@ -48,8 +48,9 @@ const BASELINE_PATH = path.resolve(__dirname, 'baselines.json'); const SMALL = 250; const LARGE = 800; -const REPS = 15; -const WARMUP = 5; +const REPS = 7; +const WARMUP = 2; +const WINDOW_MS = 1000; /** * Deterministic synthetic corpus — no randomness, so the fingerprint is stable. @@ -144,34 +145,23 @@ function callableOnlyScopes(scopes) { return { defs: { byId } }; } -/** - * MIN, not median. Both scales are timed in one process, and every source of - * error here is additive — scheduler preemption, GC, a noisy neighbour on a - * shared CI runner. The fastest observed run is the closest estimate of the - * uncontended cost, so the derived ratios stay comparable across machines - * instead of tracking whatever else the box was doing. (Measured directly: the - * same build reported an overhead of 1.65 idle and 2.03 while a test shard was - * running — a median-based gate would have to be loosened until it could no - * longer detect the regression it exists to catch.) - */ -function fastest(values) { - return Math.min(...values); +function median(values) { + return [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)]; } function timeIndex(scopes, nodeLookup, graph) { - // Warm up before timing: the first calls carry JIT compilation of the whole - // resolve chain, and the widened and callable-only runs would otherwise be - // measured at different optimisation tiers — which alone moved the reported - // overhead by ~30%. - for (let w = 0; w < WARMUP; w++) buildGraphTargetIndex(scopes, nodeLookup, undefined, graph); - const samples = []; + // A short handful of calls can all overlap JIT, GC or scheduler pauses. + // Keep the uncontended-cost estimator, but give each variant a full window + // to reach it. Retaining only the minimum also bounds sampling memory. + const start = performance.now(); + let best = Infinity; let last; - for (let r = 0; r < REPS; r++) { + do { const t0 = performance.now(); last = buildGraphTargetIndex(scopes, nodeLookup, undefined, graph); - samples.push(performance.now() - t0); - } - return { ms: fastest(samples), result: last }; + best = Math.min(best, performance.now() - t0); + } while (performance.now() - start < WINDOW_MS); + return { ms: best, result: last }; } function fingerprint(targets) { @@ -179,29 +169,46 @@ function fingerprint(targets) { return crypto.createHash('sha256').update(lines.join('\n')).digest('hex'); } -const scales = {}; -for (const [name, fileCount] of [ +const cases = [ ['small', SMALL], ['large', LARGE], -]) { - const { graph, scopes, nodeLookup } = buildCorpus(fileCount); - const widened = timeIndex(scopes, nodeLookup, graph); - const callableOnly = timeIndex(callableOnlyScopes(scopes), nodeLookup, graph); - scales[name] = { - files: fileCount, - defs: scopes.defs.byId.size, - ms: widened.ms, - callable_only_ms: callableOnly.ms, - targets: widened.result.size, - callable_only_targets: callableOnly.result.size, - fingerprint: fingerprint(widened.result), +].map(([name, files]) => ({ name, files, ...buildCorpus(files) })); +const variants = cases.flatMap((corpus) => [ + corpus, + { ...corpus, scopes: callableOnlyScopes(corpus.scopes) }, +]); +const samples = variants.map(() => []); +const results = []; +// Measure all four variants in each round, reversing their order to avoid +// consistently favouring one tier or scale. Discard complete warmup rounds. +// Pair ratios within rounds so a change in runner load does not compare a +// quiet control period with a busy widened period (or small with large). +for (let round = 0; round < WARMUP + REPS; round++) { + for (const i of round % 2 === 0 ? [0, 1, 2, 3] : [3, 2, 1, 0]) { + const { scopes, nodeLookup, graph } = variants[i]; + const timed = timeIndex(scopes, nodeLookup, graph); + results[i] = timed.result; + if (round >= WARMUP) samples[i].push(timed.ms); + } +} + +const scales = {}; +for (const [i, corpus] of cases.entries()) { + scales[corpus.name] = { + files: corpus.files, + defs: corpus.scopes.defs.byId.size, + ms: median(samples[i * 2]), + callable_only_ms: median(samples[i * 2 + 1]), + targets: results[i * 2].size, + callable_only_targets: results[i * 2 + 1].size, + fingerprint: fingerprint(results[i * 2]), }; } -const scalingRatio = scales.large.ms / scales.small.ms / (LARGE / SMALL); +const scalingRatio = median(samples[2].map((ms, i) => ms / samples[0][i] / (LARGE / SMALL))); // How much slower the widened gate is than the pre-#2693 one on the same // corpus. 1.0 = free; 2.0 = the widening doubled the index build. -const wideningOverhead = scales.large.ms / scales.large.callable_only_ms; +const wideningOverhead = median(samples[2].map((ms, i) => ms / samples[3][i])); const report = { small: scales.small, diff --git a/gitnexus/bench/cfg/baselines.json b/gitnexus/bench/cfg/baselines.json index af5f9a800d..dbcacad358 100644 --- a/gitnexus/bench/cfg/baselines.json +++ b/gitnexus/bench/cfg/baselines.json @@ -1,4 +1,14 @@ { + "guard-free-arguments": { + "fingerprint": "819f475c96ced034846e1c7d8aa08613386b258f6df276a1e4058944fffa9231", + "scaling_budget": 1.8, + "disk_bytes_budget": 1.2, + "heap_budget": 1.3, + "rd_scaling_budget": 2.0, + "facts_large_min": 8000, + "disk_bytes_large_max": 6000000, + "_note": "#3703 review: 1000/4000 guard-free functions with const composition and argument forwarding exercise value-fact capture even without predicates. Initial normalized time/disk/heap/def-use ratios: 0.878/1.012/0.999/0.834; large payload 5,306,959 bytes. A separate five-pair comparison at the reviewed head versus the merge base measured +11.26% collection time and +27.0% serialized bytes on the same argument-heavy shape (different file/spacing). This exceeds the plan's proposed 5% guard-free target; the earlier ~1% samples do not cover this capture path. Keep the cost explicit; this gate checks scaling and payload growth, not a validated <=5% overhead claim. Existing scenario budgets remain unchanged." + }, "straight-line": { "fingerprint": "792229965a726d2c6b527f9ee65440a2b3023839ee71cb51522fc30e2f2cb454", "scaling_budget": 1.5, @@ -38,25 +48,25 @@ "disk_bytes_budget": 1.2, "rd_scaling_budget": 2.0, "facts_large_min": 150, - "_note": "#2201: N nested loops carrying ONE variable end-to-end (depth 40->160) -- the pathology the dense worklist is superlinear on and whose block-visit total drives it past the blocks×64 ceiling (it would TRUNCATE to empty). rd is measured under the PRODUCTION blocks×64 budget (rdProductionBudget) to prove the ceiling stops firing: the depth-INDEPENDENT SSA solver (phi-nodes capture loop merges statically; no fixpoint iteration) computes the full facts (measured 164 at large) with rd_scaling ~0.68 (linear in depth; measured ~0.57ms at depth 160). facts_large_min tightened 100->150 (#2201 review R7): a partial-truncation regression that still cleared the old floor of 100 (but lost facts of the measured 164) now fails, with ~9% headroom under 164 for noise; the companion rd_all_computed gate also catches any non-'computed' status. rd_scaling_budget 2.0 catches a regression back to superlinear. No heap_budget -- the deep-nest CFG payload is tiny and the retained-heap delta is GC-noise-dominated. Re-baseline the fingerprint only on an intentional CFG/visitor change. FU-C re-fingerprinted: BindingEntry.formalIndex joins the binding facts canon (CALL_SUMMARY formal-position keying); CFG topology unchanged." + "_note": "#2201: N nested loops carrying ONE variable end-to-end (depth 40->160) -- the pathology the dense worklist is superlinear on and whose block-visit total drives it past the blocks\u00d764 ceiling (it would TRUNCATE to empty). rd is measured under the PRODUCTION blocks\u00d764 budget (rdProductionBudget) to prove the ceiling stops firing: the depth-INDEPENDENT SSA solver (phi-nodes capture loop merges statically; no fixpoint iteration) computes the full facts (measured 164 at large) with rd_scaling ~0.68 (linear in depth; measured ~0.57ms at depth 160). facts_large_min tightened 100->150 (#2201 review R7): a partial-truncation regression that still cleared the old floor of 100 (but lost facts of the measured 164) now fails, with ~9% headroom under 164 for noise; the companion rd_all_computed gate also catches any non-'computed' status. rd_scaling_budget 2.0 catches a regression back to superlinear. No heap_budget -- the deep-nest CFG payload is tiny and the retained-heap delta is GC-noise-dominated. Re-baseline the fingerprint only on an intentional CFG/visitor change. FU-C re-fingerprinted: BindingEntry.formalIndex joins the binding facts canon (CALL_SUMMARY formal-position keying); CFG topology unchanged." }, "wide-merge": { - "fingerprint": "4135a740376068c3f2dedc4751c6588cbe9ae36026ddc9f2ae9112b188980cda", + "fingerprint": "1b724ea967c2805d643cea6511628e8d248f47431e1db55591a23da3e2808df1", "scaling_budget": 1.8, "disk_bytes_budget": 1.2, "heap_budget": 1.3, "rd_scaling_budget": 2.0, "facts_large_min": 24000, - "_note": "#2201 review R7: N bindings, EACH assigned in a 3-way branch (a wide multi-operand phi per binding) inside a loop, then all used after the merge. Distinct from dense-bindings (one CHAINED redef per `if`): every binding fans into its OWN wide phi, so this exercises phi-placement + renaming + the reachByScc condensation across MANY independent wide merges. N bindings x constant arms => O(N) facts (measured 26008 at the large size), so the gate is rd_scaling LINEARITY: measured ~1.07 (time 9.3->39.8ms over the 4x size step); budget 2.0 catches a regression to the per-binding-rescan O(N^2) class -- the recurring solver antipattern the reachByScc alias fast path (review R2) guards against. rd is measured under the PRODUCTION blocks×64 budget (rdProductionBudget): all functions report 'computed' (the SSA path does not truncate here), and facts_large_min 24000 (measured 26008, ~7% headroom) + the rd_all_computed gate assert the wide merges compute fully. fp_blocks 82 / fp_edges 112 at FP_SIZE=15. Re-baseline the fingerprint only on an intentional CFG/harvest-shape change. #2227 U1 re-fingerprinted: SiteRecord.at call-site anchor [line,col] joins the statement-facts canon (resolved-callee-id stack); CFG topology unchanged. FU-C re-fingerprinted: BindingEntry.formalIndex joins the binding facts canon (CALL_SUMMARY formal-position keying); CFG topology unchanged." + "_note": "#2201 review R7: N bindings, EACH assigned in a 3-way branch (a wide multi-operand phi per binding) inside a loop, then all used after the merge. Distinct from dense-bindings (one CHAINED redef per `if`): every binding fans into its OWN wide phi, so this exercises phi-placement + renaming + the reachByScc condensation across MANY independent wide merges. N bindings x constant arms => O(N) facts (measured 26008 at the large size), so the gate is rd_scaling LINEARITY: measured ~1.07 (time 9.3->39.8ms over the 4x size step); budget 2.0 catches a regression to the per-binding-rescan O(N^2) class -- the recurring solver antipattern the reachByScc alias fast path (review R2) guards against. rd is measured under the PRODUCTION blocks\u00d764 budget (rdProductionBudget): all functions report 'computed' (the SSA path does not truncate here), and facts_large_min 24000 (measured 26008, ~7% headroom) + the rd_all_computed gate assert the wide merges compute fully. fp_blocks 82 / fp_edges 112 at FP_SIZE=15. Re-baseline the fingerprint only on an intentional CFG/harvest-shape change. #2227 U1 re-fingerprinted: SiteRecord.at call-site anchor [line,col] joins the statement-facts canon (resolved-callee-id stack); CFG topology unchanged. FU-C re-fingerprinted: BindingEntry.formalIndex joins the binding facts canon (CALL_SUMMARY formal-position keying); CFG topology unchanged. #3490: additive normalized argument-value facts; CFG topology unchanged; budgets retained." }, "fact-fanout": { - "fingerprint": "57fa834df795d8dba99947cdfba2bb86b3f9111d8bf86d38b77c155273ae5c93", + "fingerprint": "f06409f4c6b3f9ef8caeb04d702ffa3ca3b387fba1a86aaab0419b9695e78de8", "scaling_budget": 1.8, "disk_bytes_budget": 1.2, "heap_budget": 1.3, "rd_scaling_budget": 3.0, "facts_large_max": 16000, - "_note": "#2082 M2 / #2083 M3 U1: N switch-arm defs of one variable + N later uses -- facts are O(defs x uses) BY SPEC, so the gate is BOUNDEDNESS, not linearity: with the production fact limit engaged (DEFAULT_PDG_MAX_REACHING_DEF_FACTS_PER_FUNCTION=16000) the materialized fact count stays pinned at the limit as N grows (facts_large_max), and rd time stays bounded (measured ~1.4). Losing the maxFacts early-stop shows as facts_large exploding quadratically. M3 U1 re-fingerprinted (u{i}(x) call sites); disk_large 996737->1107627 (+11.1%). #2227 U1 re-fingerprinted: SiteRecord.at call-site anchor [line,col] joins the statement-facts canon (resolved-callee-id stack); CFG topology unchanged. FU-C re-fingerprinted: BindingEntry.formalIndex joins the binding facts canon (CALL_SUMMARY formal-position keying); CFG topology unchanged." + "_note": "#2082 M2 / #2083 M3 U1: N switch-arm defs of one variable + N later uses -- facts are O(defs x uses) BY SPEC, so the gate is BOUNDEDNESS, not linearity: with the production fact limit engaged (DEFAULT_PDG_MAX_REACHING_DEF_FACTS_PER_FUNCTION=16000) the materialized fact count stays pinned at the limit as N grows (facts_large_max), and rd time stays bounded (measured ~1.4). Losing the maxFacts early-stop shows as facts_large exploding quadratically. M3 U1 re-fingerprinted (u{i}(x) call sites); disk_large 996737->1107627 (+11.1%). #2227 U1 re-fingerprinted: SiteRecord.at call-site anchor [line,col] joins the statement-facts canon (resolved-callee-id stack); CFG topology unchanged. FU-C re-fingerprinted: BindingEntry.formalIndex joins the binding facts canon (CALL_SUMMARY formal-position keying); CFG topology unchanged. #3490: additive normalized argument-value facts; CFG topology unchanged; budgets retained." }, "taint-dense": { "fingerprint": "f4570c7ae8fde4b7e63b51b4ea641417f911b4267f1f9f2eafadc520020dbf15", @@ -78,5 +88,45 @@ "heap_budget": 1.3, "rd_scaling_budget": 2.0, "_note": "#2195 U7: the first NON-TS scaling scenario -- the C-family analogue of `branchy`, driven through the Go grammar + Go CFG visitor (lang:'go'). ONE Go function with N sequential `if`s (block/edge growth in a single CFG). The `go:` key namespace keeps it out of the TS baseline keyspace (no collision/re-baseline of a TS scenario). Measured time ~1.08, disk ~1.03, heap ~1.0, rd ~1.06 (budgets mirror the TS `branchy` scenario: scaling 1.8 absorbs single-CFG noise + catches a ~4.0 quadratic). Cross-check: fp_blocks 32 / fp_edges 46 are IDENTICAL to the TS branchy fingerprint shape -- the Go visitor builds the same per-`if` block/edge topology. CFG-only (Go has no registered taint model), so no taint gates. Re-baseline the fingerprint only on an intentional Go CFG/harvest-shape change. #2227 U1 re-fingerprinted: SiteRecord.at call-site anchor [line,col] joins the statement-facts canon (resolved-callee-id stack); Go CFG topology unchanged." + }, + "guarded-commands": { + "fingerprint": "02fe82d392ab2e6d842a47a4d9b982cf9a99e9a6199f15e9c09185b715186727", + "scaling_budget": 1.8, + "disk_bytes_budget": 1.2, + "heap_budget": 1.3, + "rd_scaling_budget": 2.0, + "_note": "#3490: bounded guard/value refinement. Production analysis asserts expected findings, forward effects, fallback at caps, and JSON replay equivalence; normalized 4x-size ratios guard linear scaling." + }, + "guard-bypass": { + "fingerprint": "8a47f79c6d8a6fcb3a47cc05dc79936a7f4daf8b0e8947a852522a4def619225", + "scaling_budget": 1.8, + "disk_bytes_budget": 1.2, + "heap_budget": 1.3, + "rd_scaling_budget": 2.0, + "_note": "#3490: bounded guard/value refinement. Production analysis asserts expected findings, forward effects, fallback at caps, and JSON replay equivalence; normalized 4x-size ratios guard linear scaling." + }, + "guard-forwarders": { + "fingerprint": "5121f44d067c58c6b4e40df6306fd237c0ea4edf9f860e8cb4d666aa5502e773", + "scaling_budget": 1.8, + "disk_bytes_budget": 1.2, + "heap_budget": 1.3, + "rd_scaling_budget": 2.0, + "_note": "#3490: bounded guard/value refinement. Production analysis asserts expected findings, forward effects, fallback at caps, and JSON replay equivalence; normalized 4x-size ratios guard linear scaling." + }, + "guard-capped": { + "fingerprint": "c7694d17d006ff15db094d588726bbbb9776de1181d3bf0f1e769d876a423de9", + "scaling_budget": 1.8, + "disk_bytes_budget": 1.2, + "heap_budget": 1.3, + "rd_scaling_budget": 2.0, + "_note": "#3490: bounded guard/value refinement. Production analysis asserts expected findings, forward effects, fallback at caps, and JSON replay equivalence; normalized 4x-size ratios guard linear scaling." + }, + "guard-discriminants": { + "fingerprint": "2d04158a9c8eae54f567ffad7f585b5e84b059da2386756e9b703ac8c4e3a0f1", + "scaling_budget": 1.8, + "disk_bytes_budget": 1.2, + "heap_budget": 1.3, + "rd_scaling_budget": 2.0, + "_note": "#3490: bounded guard/value refinement. Production analysis asserts expected findings, forward effects, fallback at caps, and JSON replay equivalence; normalized 4x-size ratios guard linear scaling." } } diff --git a/gitnexus/bench/cfg/compare-guard-overhead.mjs b/gitnexus/bench/cfg/compare-guard-overhead.mjs new file mode 100644 index 0000000000..ae4cb9e019 --- /dev/null +++ b/gitnexus/bench/cfg/compare-guard-overhead.mjs @@ -0,0 +1,154 @@ +/** + * Compare guard-free CFG collection with another source checkout. + * Run with --expose-gc --import tsx; both checkouts need installed dependencies. + * Parsing, serialization, and correctness checks stay outside the timed region. + */ +import fs from 'node:fs'; +import path from 'node:path'; +import crypto from 'node:crypto'; +import { createRequire } from 'node:module'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { parseArgs } from 'node:util'; + +const { values } = parseArgs({ + options: { + baseline: { type: 'string' }, + candidate: { type: 'string' }, + workload: { type: 'string', default: 'arguments' }, + pairs: { type: 'string', default: '15' }, + out: { type: 'string' }, + check: { type: 'boolean', default: false }, + help: { type: 'boolean', default: false }, + }, +}); +if (values.help) { + console.log(`Usage: node --expose-gc --import tsx bench/cfg/compare-guard-overhead.mjs + --baseline /path/to/reference/gitnexus [--candidate /path/to/current/gitnexus] + [--workload arguments|transitive|direct] [--pairs 15] [--out result.json] [--check] + +--check requires at least five pairs, samples >=100ms, and <=5% median overhead. +Exact legacy facts, function coverage, and value forwarding are always checked.`); + process.exit(0); +} +if (!values.baseline || !global.gc) throw new Error('Supply --baseline and run with --expose-gc'); +const pairs = Number(values.pairs); +if (!Number.isSafeInteger(pairs) || pairs < 1) + throw new Error('--pairs must be a positive integer'); +if (!['arguments', 'transitive', 'direct'].includes(values.workload)) { + throw new Error('Unknown workload'); +} +const candidate = path.resolve( + values.candidate ?? path.join(path.dirname(fileURLToPath(import.meta.url)), '../..'), +); +const baseline = path.resolve(values.baseline); +const require = createRequire(path.join(candidate, 'package.json')); +const Parser = require('tree-sitter'); +const grammar = require('tree-sitter-typescript').typescript; +const load = (root, relative) => + import(pathToFileURL(path.join(root, 'src/core/ingestion', relative)).href); +const versions = []; +for (const root of [baseline, candidate]) { + const { collectFunctionCfgs } = await load(root, 'cfg/collect.ts'); + const { createTypeScriptCfgVisitor } = await load(root, 'cfg/visitors/typescript.ts'); + versions.push({ collect: collectFunctionCfgs, visitor: createTypeScriptCfgVisitor() }); +} +const count = 4000; +const source = Array.from({ length: count }, (_, i) => { + if (values.workload === 'arguments') { + return `function f${i}(x:string){ const y="prefix "+x; return consume${i}(y); }`; + } + if (values.workload === 'direct') { + return `function f${i}(x:string){ return consume${i}("prefix "+x); }`; + } + return `function f${i}(x:string){ const a="prefix "+x; const b=a+" suffix"; return consume${i}(b); }`; +}).join(''); +const parser = new Parser(); +parser.setLanguage(grammar); +const tree = parser.parse(source, undefined, { bufferSize: 1024 * 1024 }); +const collect = (version) => version.collect(tree.rootNode, version.visitor, 'perf.ts', 0).cfgs; +for (let rep = 0; rep < 3; rep++) for (const version of versions) collect(version); + +const median = (numbers) => [...numbers].sort((a, b) => a - b)[Math.floor(numbers.length / 2)]; +const samples = [[], []]; +const heaps = [[], []]; +const bytes = []; +for (let rep = 0; rep < pairs; rep++) { + for (const index of rep % 2 ? [1, 0] : [0, 1]) { + global.gc(); + const before = process.memoryUsage().heapUsed; + const start = process.hrtime.bigint(); + const cfgs = collect(versions[index]); + samples[index].push(Number(process.hrtime.bigint() - start) / 1e6); + heaps[index].push(process.memoryUsage().heapUsed - before); + bytes[index] = Buffer.byteLength(JSON.stringify(cfgs)); + } +} + +// Gather outputs separately; do not retain previous CFG arrays during timing. +const outputs = versions.map(collect); +const legacy = (cfgs) => + JSON.stringify(cfgs, (key, value) => + ['refinement', 'refinementSafe', 'primitiveBindings'].includes(key) ? undefined : value, + ); +const hash = (value) => crypto.createHash('sha256').update(value).digest('hex'); +const { createFunctionRefinement } = await load(candidate, 'taint/guard-refinement.ts'); +const expectedParts = [ + { kind: 'literal', value: 'prefix ' }, + { kind: 'input' }, + ...(values.workload === 'transitive' ? [{ kind: 'literal', value: ' suffix' }] : []), +]; +const flatten = (effect) => (effect?.kind === 'concat' ? effect.parts.flatMap(flatten) : [effect]); +let effects = 0; +for (const cfg of outputs[1]) { + const refinement = createFunctionRefinement(cfg); + for (const block of cfg.blocks) { + for ( + let statementIndex = 0; + statementIndex < (block.statements?.length ?? 0); + statementIndex++ + ) { + const statement = block.statements[statementIndex]; + for (let site = 0; site < (statement.sites?.length ?? 0); site++) { + if (!statement.sites[site].callee?.startsWith('consume')) continue; + const effect = refinement.argument(block.index, statementIndex, site, 0, 0); + if ( + effect?.kind === 'concat' && + JSON.stringify(flatten(effect)) === JSON.stringify(expectedParts) && + refinement.defaultShell(block.index, statementIndex, site) + ) + effects++; + } + } + } +} +const medians = samples.map(median); +const result = { + workload: values.workload, + pairs, + time_overhead_pct: (medians[1] / medians[0] - 1) * 100, + serialized_overhead_pct: (bytes[1] / bytes[0] - 1) * 100, + legacy_equal: hash(legacy(outputs[0])) === hash(legacy(outputs[1])) ? 1 : 0, + functions_complete: outputs[1].length === count ? 1 : 0, + forwarding_complete: effects === count ? 1 : 0, + samples_ms: samples, + medians_ms: medians, + bytes, + // An after-collection heap delta is diagnostic; it is not peak heap. + heap_growth_medians: heaps.map(median), + base_hash: hash(legacy(outputs[0])), + source_hashes: [baseline, candidate].map((root) => + hash(fs.readFileSync(path.join(root, 'src/core/ingestion/cfg/visitors/typescript-harvest.ts'))), + ), +}; +const json = JSON.stringify(result, null, 2) + '\n'; +if (values.out) fs.writeFileSync(values.out, json); +console.log(json); +if (!result.legacy_equal || !result.functions_complete || !result.forwarding_complete) { + process.exitCode = 1; +} +if ( + values.check && + (pairs < 5 || samples.flat().some((ms) => ms < 100) || result.time_overhead_pct > 5) +) { + process.exitCode = 1; +} diff --git a/gitnexus/bench/cfg/measure.mjs b/gitnexus/bench/cfg/measure.mjs index 209afae550..54f73dcc78 100644 --- a/gitnexus/bench/cfg/measure.mjs +++ b/gitnexus/bench/cfg/measure.mjs @@ -59,6 +59,8 @@ import { DEFAULT_PDG_MAX_TAINT_HOPS, } from '../../src/core/ingestion/taint/propagate.ts'; import { encodeTaintPath } from '../../src/core/ingestion/taint/path-codec.ts'; +import { createMemoizedRefinement } from '../../src/core/ingestion/taint/guard-refinement.ts'; +import { harvestFunctionSummary } from '../../src/core/ingestion/taint/summary-harvest.ts'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const BASELINE_PATH = path.resolve(__dirname, 'baselines.json'); @@ -114,6 +116,83 @@ function langToolkit(langId) { // ---- synthetic generators (one cost dimension each) ---- const SCENARIOS = [ + { + name: 'guard-free-arguments', + small: 1000, + large: 4000, + gen: (n) => + Array.from( + { length: n }, + (_, i) => `function f${i}(x: string) { const y = 'prefix ' + x; return consume${i}(y); }`, + ).join('\n'), + }, + { + name: 'guarded-commands', + small: 60, + large: 240, + guard: { findingsPerFunction: 0 }, + gen: (n) => + Array.from( + { length: n }, + (_, i) => `function guarded${i}(req: any) { + const value: string = req.query.ref; + if (!/^[0-9a-f]{7,40}$/.test(value)) return; + execSync('git show ' + value); + }`, + ).join('\n'), + }, + { + name: 'guard-bypass', + small: 60, + large: 240, + guard: { findingsPerFunction: 1 }, + gen: (n) => + Array.from( + { length: n }, + (_, i) => `function bypass${i}(req: any, flag: boolean) { + const value: string = req.query.ref; + if (flag) { if (!/^[0-9a-f]{7,40}$/.test(value)) return; } + execSync('git show ' + value); + }`, + ).join('\n'), + }, + { + name: 'guard-forwarders', + small: 60, + large: 240, + guard: { findingsPerFunction: 0, forwarding: true }, + gen: (n) => + Array.from( + { length: n }, + (_, i) => `function forwarder${i}(value: string) { + if (!/^[0-9a-f]{7,40}$/.test(value)) return; + forward(value); + }`, + ).join('\n'), + }, + { + name: 'guard-capped', + small: 80, + large: 320, + guard: { findingsPerFunction: 1, fallback: true }, + gen: (n) => + `function capped(req: any) { const value: string = req.query.ref;\n` + + Array.from({ length: n }, () => 'if (!/^[0-9a-f]{7,40}$/.test(value)) return;').join('\n') + + `\nexecSync('git show ' + value); }`, + }, + { + name: 'guard-discriminants', + small: 100, + large: 400, + guard: { findingsPerFunction: 0 }, + gen: (n) => + Array.from( + { length: n }, + (_, i) => `function discriminant${i}(kind: string) { + if (kind === 'read') return 1; return 2; + }`, + ).join('\n'), + }, { name: 'straight-line', // One function, N coalescing simple statements → all fold into one basic @@ -388,6 +467,7 @@ function measureReachingDefs(cfgs, reps, maxFacts, blockVisitsMul = 0) { function measureTaint(cfgs, reps, cap, taintModel) { const importIndex = buildTaintImportIndex([]); // bench callees are globals const pass = () => { + const refine = createMemoizedRefinement(); let analyzed = 0; let kept = 0; let dropped = 0; @@ -398,10 +478,16 @@ function measureTaint(cfgs, reps, cap, taintModel) { const du = computeReachingDefs(c, { maxFacts: DEFAULT_PDG_MAX_REACHING_DEF_FACTS_PER_FUNCTION, }); - const flows = computeTaintFlows(c, du, matches, { - maxFindingsPerFunction: cap, - maxHops: DEFAULT_PDG_MAX_TAINT_HOPS, - }); + const flows = computeTaintFlows( + c, + du, + matches, + { + maxFindingsPerFunction: cap, + maxHops: DEFAULT_PDG_MAX_TAINT_HOPS, + }, + refine(c), + ); if (flows.status !== 'computed') continue; analyzed++; kept += flows.findings.length; @@ -428,6 +514,61 @@ function measureTaint(cfgs, reps, cap, taintModel) { return { ms: median(samples), ...out }; } +// Use the production policy and matching/solver path; only the fixture's global +// spelling replaces import resolution, which is covered by integration tests. +const GUARD_MODEL = { + ...TS_JS_TAINT_MODEL, + sinks: TS_JS_TAINT_MODEL.sinks + .filter((entry) => entry.name === 'execSync') + .map((entry) => ({ ...entry, module: undefined, global: true })), +}; + +function measureGuards(cfgs, reps) { + const imports = buildTaintImportIndex([]); + const pass = (input) => { + const refine = createMemoizedRefinement(); + let visits = 0, + fallbacks = 0, + findings = 0, + forwardEffects = 0; + for (const cfg of input) { + const refinement = refine(cfg); + visits += refinement.guards.visits; + if (refinement.guards.status === 'fallback') fallbacks++; + const matches = matchFunctionSites(cfg, GUARD_MODEL, imports); + const du = computeReachingDefs(cfg); + if (matches.hasSource && matches.hasSink) + findings += computeTaintFlows(cfg, du, matches, undefined, refinement).findings.length; + forwardEffects += harvestFunctionSummary( + cfg, + du, + matches, + refinement, + ).facts.paramToCallArg.filter( + (edge) => edge.calleeName === 'forward' && edge.valueEffect?.kind === 'restrict', + ).length; + } + return { visits, fallbacks, findings, forwardEffects }; + }; + pass(cfgs); + const samples = []; + let result; + for (let i = 0; i < reps; i++) { + const start = process.hrtime.bigint(); + result = pass(cfgs); + samples.push(Number(process.hrtime.bigint() - start) / 1e6); + } + const replay = JSON.parse(JSON.stringify(cfgs)); + const start = process.hrtime.bigint(); + const replayResult = pass(replay); + return { + ms: median(samples), + ...result, + replayMs: Number(process.hrtime.bigint() - start) / 1e6, + replayEqual: JSON.stringify(result) === JSON.stringify(replayResult), + }; +} + // ---- memory growth: retained heap of the cfgSideChannel payload ---- // Needs `node --expose-gc` to force collection for a clean delta; without it the @@ -559,7 +700,33 @@ function measureScenario(scenario) { }; } + let guardMetrics = {}; + if (scenario.guard) { + const guarded = measureGuards(large.cfgs, REPS); + guardMetrics = { + guard_ms_large: Number(guarded.ms.toFixed(3)), + guard_visits: guarded.visits, + guard_fallbacks: guarded.fallbacks, + guard_findings: guarded.findings, + guard_forward_effects: guarded.forwardEffects, + guard_replay_ms: Number(guarded.replayMs.toFixed(3)), + guard_replay_equal: guarded.replayEqual, + guard_functions: large.cfgs.length, + }; + if ( + guarded.findings !== large.cfgs.length * scenario.guard.findingsPerFunction || + !guarded.replayEqual || + (scenario.guard.fallback ? guarded.fallbacks !== large.cfgs.length : guarded.visits === 0) || + (scenario.guard.forwarding && guarded.forwardEffects < large.cfgs.length) || + guarded.visits > large.cfgs.length * 50_000 + ) { + throw new Error( + `${scenario.name}: refinement correctness/budget/replay gate failed: ${JSON.stringify(guarded)}`, + ); + } + } return { + ...guardMetrics, ...taintMetrics, scenario: scenario.name, elapsed_ms_small: Number(small.ms.toFixed(3)), diff --git a/gitnexus/bench/scope-resolution/README.md b/gitnexus/bench/scope-resolution/README.md new file mode 100644 index 0000000000..7f853847a0 --- /dev/null +++ b/gitnexus/bench/scope-resolution/README.md @@ -0,0 +1,53 @@ +# Scope-resolution measurements + +Run from `gitnexus/` after `npm run build`: + +```sh +node --import tsx bench/scope-resolution/measure.mts --check --output /tmp/scope-resolution.json +``` + +CI runs every language in both `SupportedLanguages` and `SCOPE_RESOLVERS`, serially. +Missing corpus or resolver entries fail the inventory check. Each language has +100- and 1,000-entity workloads with 20 generated members or procedures per entity, +plus callers and helpers. Rust also needs a root +module file; Objective-C has a header and implementation per entity. Java adds an +isolated producer file and exercises transitive factory returns and repeated +unreachable return-name lookups. Swift uses same-module visibility; COBOL exercises +program references and procedure pointers. Other arms import the preceding file and call through its +return value. These generated sources exercise the analyzer; they are not builds +or representative application benchmarks. + +Every sample runs in a fresh process through real parsing with one worker and the +production scope-resolution pass. COBOL also runs its standalone structural parser. +Configuration files are written to a temporary workspace and loaded through the resolver's normal +configuration hook. No production heap, file-count, or propagation limit is imposed. + +The JSON artifact and GitHub job summary report the median of three samples: + +- Parsing and scope-resolution wall time separately. +- JavaScript heap immediately after parsing and after resolution. These are endpoint + samples, not peak heap or retained heap after garbage collection. +- Process peak RSS through resolution, including worker memory. This is the OS + high-water mark, not a timer that can miss synchronous allocation spikes. +- Module and total type-binding counts, node/edge counts, and cross-file calls. +- An order-independent fingerprint of node identities and complete relationship + endpoints, types, confidence and reasons. Equal counts alone are insufficient. + +The check requires every source to reach scope resolution, nonempty declarations +and cross-file calls, identical graph fingerprints between trials, and equality +with committed graph baselines. Type-binding counts must be deterministic and must +not exceed the recorded counts; reductions are allowed. These measured allocation +budgets catch redundant table growth even when the graph stays identical. Runtime +and heap/RSS are measurements, without uncalibrated +absolute performance thresholds. Compare the same workload on the same machine +before choosing an optimization. + +For a smaller diagnostic run: + +```sh +node --import tsx bench/scope-resolution/measure.mts --language java --sizes 10,100 --methods 20 --repetitions 3 +``` + +To establish baselines after reviewing a fixture, semantic, or allocation change, +run the default all-language workload with `--record` instead of `--check` and inspect +`baselines.json`. CI never records or accepts a new baseline automatically. diff --git a/gitnexus/bench/scope-resolution/baselines.json b/gitnexus/bench/scope-resolution/baselines.json new file mode 100644 index 0000000000..5d13bfa004 --- /dev/null +++ b/gitnexus/bench/scope-resolution/baselines.json @@ -0,0 +1,290 @@ +{ + "c/100/20": { + "fingerprint": "3c289f3c87de79d760e25b42eb7341796995d1bcb732909412cb28162cbf4f1b", + "nodes": 2399, + "edges": 2596, + "crossFileCalls": 198, + "moduleTypeBindings": 2099, + "typeBindings": 4198 + }, + "c/1000/20": { + "fingerprint": "74232bcf783b979e34479a8333e6bc87f812037b9500fb672b5dc8d416fbe08a", + "nodes": 23999, + "edges": 25996, + "crossFileCalls": 1998, + "moduleTypeBindings": 20999, + "typeBindings": 41998 + }, + "cobol/100/20": { + "fingerprint": "36c3fe6374ed108ea36ecfa38ecf2ba625623b4aae6de9d74220243c31434376", + "nodes": 2598, + "edges": 2796, + "crossFileCalls": 99, + "moduleTypeBindings": 0, + "typeBindings": 0 + }, + "cobol/1000/20": { + "fingerprint": "6b76194c20ee0897a52ac21300c2e159db93997137c00b92dfb09db44cf7a54c", + "nodes": 25998, + "edges": 27996, + "crossFileCalls": 999, + "moduleTypeBindings": 0, + "typeBindings": 0 + }, + "cpp/100/20": { + "fingerprint": "10a7fdf36be1221ab73184a1900b90180c7a1cf1d45a4dc5584ea6c4c2418448", + "nodes": 2299, + "edges": 2694, + "crossFileCalls": 198, + "moduleTypeBindings": 197, + "typeBindings": 2296 + }, + "cpp/1000/20": { + "fingerprint": "2dfe2d47dfebec5fbee15a9e6cce1c8b254f3594efec9a28ad82a941d43f3b8d", + "nodes": 22999, + "edges": 26994, + "crossFileCalls": 1998, + "moduleTypeBindings": 1997, + "typeBindings": 22996 + }, + "csharp/100/20": { + "fingerprint": "031987488f1dfbaf7d157c451a4b02fd679eed1f984212f74933d7d41c71bfd1", + "nodes": 2399, + "edges": 2596, + "crossFileCalls": 198, + "moduleTypeBindings": 2099, + "typeBindings": 4297 + }, + "csharp/1000/20": { + "fingerprint": "120f6cfec8eab8d476a5aa64b3d58b024005bf420911d2282153bdc1e1f980d4", + "nodes": 23999, + "edges": 25996, + "crossFileCalls": 1998, + "moduleTypeBindings": 20999, + "typeBindings": 42997 + }, + "dart/100/20": { + "fingerprint": "133b7b9c3eb4229d9ff673069cddacba530e32cd9011e26d590b9627f7815196", + "nodes": 2299, + "edges": 2496, + "crossFileCalls": 198, + "moduleTypeBindings": 4079, + "typeBindings": 6277 + }, + "dart/1000/20": { + "fingerprint": "f8a78d11b836ea73a662236f2ae57cb607025ec5fd1ab2a7c96ac491850426fb", + "nodes": 22999, + "edges": 24996, + "crossFileCalls": 1998, + "moduleTypeBindings": 40979, + "typeBindings": 62977 + }, + "go/100/20": { + "fingerprint": "33d0980b813bed5a8ac4a34ca44c50033b2517c966565f90f72057f422dc6a1f", + "nodes": 2299, + "edges": 4496, + "crossFileCalls": 198, + "moduleTypeBindings": 101099, + "typeBindings": 103198 + }, + "go/1000/20": { + "fingerprint": "7e0fff39a068ed15651614aa5df5baa1614a72014a0df2b2e926330d4fc9de42", + "nodes": 22999, + "edges": 44996, + "crossFileCalls": 1998, + "moduleTypeBindings": 10010999, + "typeBindings": 10031998 + }, + "java/100/20": { + "fingerprint": "cbfe462b1ba57dba73b8aa81e536bd2441c0680725963b0e9f2007bab8e77695", + "nodes": 2697, + "edges": 3188, + "crossFileCalls": 493, + "moduleTypeBindings": 4277, + "typeBindings": 7069 + }, + "java/1000/20": { + "fingerprint": "5d1b01e266a3d22c3e11376fd8900b82ef2d6d28ca1737a5dd0c7e925ebb233b", + "nodes": 26997, + "edges": 31988, + "crossFileCalls": 4993, + "moduleTypeBindings": 42977, + "typeBindings": 70969 + }, + "javascript/100/20": { + "fingerprint": "c3c3cd272d2cbbe704bbb2bd3ce8b3b153c3156f812c946fd5a4c70ff7eaa39c", + "nodes": 2299, + "edges": 2496, + "crossFileCalls": 198, + "moduleTypeBindings": 0, + "typeBindings": 2099 + }, + "javascript/1000/20": { + "fingerprint": "959f154fe61efb1966389a36731c8aa051be96d385b950c75a77f9b323044bcc", + "nodes": 22999, + "edges": 24996, + "crossFileCalls": 1998, + "moduleTypeBindings": 0, + "typeBindings": 20999 + }, + "kotlin/100/20": { + "fingerprint": "a27beaf18a1c48a93b1bee23a89de35e5afa4659980cbf30b1181c33d24cce0d", + "nodes": 2299, + "edges": 2496, + "crossFileCalls": 198, + "moduleTypeBindings": 2099, + "typeBindings": 4297 + }, + "kotlin/1000/20": { + "fingerprint": "f6b03d2de2fb25597c9f68f5f4ad821d1bcf7b52a2bada5923e8de1c620c84bc", + "nodes": 22999, + "edges": 24996, + "crossFileCalls": 1998, + "moduleTypeBindings": 20999, + "typeBindings": 42997 + }, + "objective-c/100/20": { + "fingerprint": "3cebcee9eac578cfde569eef48e45ac4427f822f5a3b3e7291cb4ee40d894e48", + "nodes": 4996, + "edges": 7492, + "crossFileCalls": 99, + "moduleTypeBindings": 0, + "typeBindings": 0 + }, + "objective-c/1000/20": { + "fingerprint": "1cde787c33fc9f44bdb1d5f23291044b615f4d245df2beba1222aaf3435cd07f", + "nodes": 49996, + "edges": 74992, + "crossFileCalls": 999, + "moduleTypeBindings": 0, + "typeBindings": 0 + }, + "php/100/20": { + "fingerprint": "e2b9b779517483da80c4a32575e745a497b601a60fa374b4081dfacacc14a6c9", + "nodes": 2399, + "edges": 2596, + "crossFileCalls": 198, + "moduleTypeBindings": 101099, + "typeBindings": 103297 + }, + "php/1000/20": { + "fingerprint": "f7abaf180b0404e942f0d9d27d3e9f7c20a6e098c1cbe7d2221d615ecb6674eb", + "nodes": 23999, + "edges": 25996, + "crossFileCalls": 1998, + "moduleTypeBindings": 10010999, + "typeBindings": 10032997 + }, + "python/100/20": { + "fingerprint": "58adb2bc6b7ac24ab3dcd500ec3cd577d3e6853fd1a8e84f658f423677d6df50", + "nodes": 2299, + "edges": 2397, + "crossFileCalls": 99, + "moduleTypeBindings": 0, + "typeBindings": 4099 + }, + "python/1000/20": { + "fingerprint": "cba608259275ea5a0b7ece3e9b76680afe2c0c385f482d8a7325164fc4b4f8f0", + "nodes": 22999, + "edges": 23997, + "crossFileCalls": 999, + "moduleTypeBindings": 0, + "typeBindings": 40999 + }, + "ruby/100/20": { + "fingerprint": "a2472fd7ca5b2493d24a354b65cd605946b19a00d65df9d5d9788d44da50865c", + "nodes": 2299, + "edges": 2397, + "crossFileCalls": 99, + "moduleTypeBindings": 0, + "typeBindings": 2099 + }, + "ruby/1000/20": { + "fingerprint": "9163eb4d316d339dc2169f9e60262019c4f81d31314b38e44f692e04baebf703", + "nodes": 22999, + "edges": 23997, + "crossFileCalls": 999, + "moduleTypeBindings": 0, + "typeBindings": 20999 + }, + "rust/100/20": { + "fingerprint": "c3221b201eedd52cf0d4a9bda609b7a4ff60033520cfec854dff47d185b0770d", + "nodes": 2500, + "edges": 4894, + "crossFileCalls": 198, + "moduleTypeBindings": 2099, + "typeBindings": 6698 + }, + "rust/1000/20": { + "fingerprint": "ec5d974b2ace8565d8946614b8da1246d8b5736415bbf48954289f52c01eb870", + "nodes": 25000, + "edges": 48994, + "crossFileCalls": 1998, + "moduleTypeBindings": 20999, + "typeBindings": 66998 + }, + "swift/100/20": { + "fingerprint": "ce08be70302793b51c6816bc0842562565a9bb21bc87ff72eb01f6312bba2323", + "nodes": 2300, + "edges": 2497, + "crossFileCalls": 198, + "moduleTypeBindings": 2099, + "typeBindings": 4297 + }, + "swift/1000/20": { + "fingerprint": "87d6dc9bd2db62a716fdcfd347475c89561520e0eaafb456b3ae16720ac390d4", + "nodes": 23000, + "edges": 24997, + "crossFileCalls": 1998, + "moduleTypeBindings": 20999, + "typeBindings": 42997 + }, + "typescript/100/20": { + "fingerprint": "48c3afe1d2e1e2750e0ed5d8139aa009f264a997de5a084e696b5175b5a4f2cd", + "nodes": 2299, + "edges": 4496, + "crossFileCalls": 198, + "moduleTypeBindings": 2000, + "typeBindings": 4099 + }, + "typescript/1000/20": { + "fingerprint": "f7efff0e855bc68220f4d19891dcade1c9d0df4bcb2b845a3310c83c212edca7", + "nodes": 22999, + "edges": 44996, + "crossFileCalls": 1998, + "moduleTypeBindings": 20000, + "typeBindings": 40999 + }, + "vue/100/20": { + "fingerprint": "a619b08a4c7098f13bf4708d6fb56f49f7e3723efb2092b2f5d84d9a53668627", + "nodes": 2299, + "edges": 4397, + "crossFileCalls": 99, + "moduleTypeBindings": 2000, + "typeBindings": 4099 + }, + "vue/1000/20": { + "fingerprint": "fd95d70ec20fe0c15eb1a545d2648cf0df27c1e2f2fd0288a64229be6a598e60", + "nodes": 22999, + "edges": 43997, + "crossFileCalls": 999, + "moduleTypeBindings": 20000, + "typeBindings": 40999 + }, + "zig/100/20": { + "fingerprint": "b623955c7d86a6884abdba939ea4ad620446b268cffd0b101c9f96b1424cc236", + "nodes": 2299, + "edges": 2694, + "crossFileCalls": 198, + "moduleTypeBindings": 99, + "typeBindings": 4198 + }, + "zig/1000/20": { + "fingerprint": "812ed4d8f7a8cd3958950a55759cbc73e34fd134e8a02920e71e0c9e2211ed9f", + "nodes": 22999, + "edges": 26994, + "crossFileCalls": 1998, + "moduleTypeBindings": 999, + "typeBindings": 41998 + } +} diff --git a/gitnexus/bench/scope-resolution/corpus.mts b/gitnexus/bench/scope-resolution/corpus.mts new file mode 100644 index 0000000000..5f38eb3ec5 --- /dev/null +++ b/gitnexus/bench/scope-resolution/corpus.mts @@ -0,0 +1,219 @@ +import { SupportedLanguages } from 'gitnexus-shared'; + +export interface SourceFile { + path: string; + content: string; +} + +type Generator = (i: number, methods: number) => SourceFile | SourceFile[]; +const members = (count: number, source: (j: number) => string) => + Array.from({ length: count }, (_, j) => source(j)).join('\n'); +const previous = (i: number, source: (p: number) => string) => (i > 0 ? source(i - 1) : ''); + +const script = (i: number, count: number, typed: boolean, extension: string): string => + `${previous(i, (p) => `import { C${p} } from './C${p}.${extension}';`)} +export class C${i} { +${members(count, (j) => ` make${i}_${j}()${typed ? `: C${i}` : ''} { return this; }`)} +${previous(i, (p) => ` usePrevious() { return new C${p}().make${p}_0().make${p}_1(); }`)} +}`; + +// Each arm has one chain of cross-file uses and distinct method names. Swift +// uses same-module visibility; COBOL uses program calls and procedure pointers. +export const generators = { + javascript: (i, n) => ({ path: `src/C${i}.js`, content: script(i, n, false, 'js') }), + typescript: (i, n) => ({ path: `src/C${i}.ts`, content: script(i, n, true, 'js') }), + vue: (i, n) => ({ + path: `src/C${i}.vue`, + content: `\n`, + }), + python: (i, n) => ({ + path: `src/c${i}.py`, + content: `${previous(i, (p) => `from c${p} import C${p}`)} +class C${i}: +${members(n, (j) => ` def make${i}_${j}(self) -> "C${i}":\n return self`)} +${previous(i, (p) => ` def use_previous(self):\n return C${p}().make${p}_0().make${p}_1()`)} +`, + }), + java: (i, n) => ({ + path: `src/p${i}/C${i}.java`, + content: `package p${i}; +${previous(i, (p) => `import p${p}.C${p};`)} +public class C${i} { +${members(n, (j) => ` public C${i} make${i}_${j}() { return this; }`)} +${previous(i, (p) => ` public C${p} previous${i}() { return new C${p}(); }`)} +${previous(i, (p) => ` public C${p} usePrevious(C${p} value) { return value.make${p}_0().make${p}_1(); }`)} +${i > 1 ? ` public void useTransitive(C${i - 1} value) { var older = value.previous${i - 1}(); older.make${i - 2}_0(); }` : ''} + public void externalUsage(external.Client client) { client.externalBuild(); } +}`, + }), + c: (i, n) => ({ + path: `src/C${i}.h`, + content: `#pragma once +${previous(i, (p) => `#include "C${p}.h"`)} +typedef struct C${i} { int value; } C${i}; +${members(n, (j) => `static inline C${i}* make${i}_${j}(C${i}* value) { return value; }`)} +${previous(i, (p) => `static inline C${p}* usePrevious${i}(C${p}* value) { return make${p}_1(make${p}_0(value)); }`)} +`, + }), + cpp: (i, n) => ({ + path: `src/C${i}.hpp`, + content: `#pragma once +${previous(i, (p) => `#include "C${p}.hpp"`)} +class C${i} { public: +${members(n, (j) => ` C${i}* make${i}_${j}() { return this; }`)} +}; +${previous(i, (p) => `inline C${p}* usePrevious${i}(C${p}* value) { return value->make${p}_0()->make${p}_1(); }`)} +`, + }), + 'objective-c': (i, n) => [ + { + path: `src/C${i}.h`, + content: `#import +${previous(i, (p) => `#import "C${p}.h"`)} +@interface C${i} : NSObject +${members(n, (j) => `- (C${i} *)make${i}_${j};`)} +${previous(i, (p) => `- (C${p} *)usePrevious:(C${p} *)value;`)} +@end +`, + }, + { + path: `src/C${i}.m`, + content: `#import "C${i}.h" +@implementation C${i} +${members(n, (j) => `- (C${i} *)make${i}_${j} { return self; }`)} +${previous(i, (p) => `- (C${p} *)usePrevious:(C${p} *)value { return [[value make${p}_0] make${p}_1]; }`)} +@end +`, + }, + ], + csharp: (i, n) => ({ + path: `src/P${i}/C${i}.cs`, + content: `${previous(i, (p) => `using P${p};`)} +namespace P${i} { +public class C${i} { +${members(n, (j) => ` public C${i} Make${i}_${j}() { return this; }`)} +${previous(i, (p) => ` public C${p} UsePrevious(C${p} value) { return value.Make${p}_0().Make${p}_1(); }`)} +}} +`, + }), + go: (i, n) => ({ + path: `src/p${i}/c${i}.go`, + content: `package p${i} +${previous(i, (p) => `import "bench/src/p${p}"`)} +type C${i} struct {} +${members(n, (j) => `func (value *C${i}) Make${i}_${j}() *C${i} { return value }`)} +${previous(i, (p) => `func UsePrevious(value *p${p}.C${p}) *p${p}.C${p} { return value.Make${p}_0().Make${p}_1() }`)} +`, + }), + ruby: (i, n) => ({ + path: `src/c${i}.rb`, + content: `${previous(i, (p) => `require_relative 'c${p}'`)} +class C${i} +${members(n, (j) => ` def make${i}_${j}()\n self\n end`)} +${previous(i, (p) => ` def use_previous()\n C${p}.new.make${p}_0().make${p}_1()\n end`)} +end +`, + }), + rust: (i, n) => ({ + path: `src/c${i}.rs`, + content: `${previous(i, (p) => `use crate::c${p}::C${p};`)} +pub struct C${i} {} +impl C${i} { +${members(n, (j) => ` pub fn make${i}_${j}(&self) -> C${i} { C${i} {} }`)} +} +${previous(i, (p) => `pub fn use_previous(value: C${p}) -> C${p} { value.make${p}_0().make${p}_1() }`)} +`, + }), + php: (i, n) => ({ + path: `src/P${i}/C${i}.php`, + content: ` `use Bench\\P${p}\\C${p};`)} +class C${i} { +${members(n, (j) => ` public function make${i}_${j}(): C${i} { return $this; }`)} +${previous(i, (p) => ` public function usePrevious(C${p} $value): C${p} { return $value->make${p}_0()->make${p}_1(); }`)} +} +`, + }), + kotlin: (i, n) => ({ + path: `src/p${i}/C${i}.kt`, + content: `package p${i} +${previous(i, (p) => `import p${p}.C${p}`)} +class C${i} { +${members(n, (j) => ` fun make${i}_${j}(): C${i} = this`)} +${previous(i, (p) => ` fun usePrevious(value: C${p}): C${p} = value.make${p}_0().make${p}_1()`)} +} +`, + }), + swift: (i, n) => ({ + path: `Sources/Bench/C${i}.swift`, + content: `class C${i} { +${members(n, (j) => ` func make${i}_${j}() -> C${i} { return self }`)} +${previous(i, (p) => ` func usePrevious(_ value: C${p}) -> C${p} { return value.make${p}_0().make${p}_1() }`)} +} +`, + }), + dart: (i, n) => ({ + path: `lib/c${i}.dart`, + content: `${previous(i, (p) => `import 'c${p}.dart';`)} +class C${i} { +${members(n, (j) => ` C${i} make${i}_${j}() { return this; }`)} +${previous(i, (p) => ` C${p} usePrevious(C${p} value) { return value.make${p}_0().make${p}_1(); }`)} +} +`, + }), + cobol: (i, n) => ({ + path: `src/C${i}.cbl`, + content: ` IDENTIFICATION DIVISION. + PROGRAM-ID. C${i}. + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 TARGET-PTR USAGE PROCEDURE-POINTER. + PROCEDURE DIVISION. + MAIN-PARA. +${previous(i, (p) => ` SET TARGET-PTR TO ENTRY 'C${p}'\n CALL TARGET-PTR`)} + PERFORM MAKE-${i}-0 + GOBACK. +${members(n, (j) => ` MAKE-${i}-${j}.\n CONTINUE.`)} +`, + }), + zig: (i, n) => ({ + path: `src/c${i}.zig`, + content: `${previous(i, (p) => `const previous = @import("c${p}.zig");`)} +pub const C${i} = struct { +${members(n, (j) => ` pub fn make${i}_${j}(self: C${i}) C${i} { return self; }`)} +}; +${previous(i, (p) => `pub fn usePrevious(value: previous.C${p}) previous.C${p} { return value.make${p}_0().make${p}_1(); }`)} +`, + }), +} satisfies Record; + +export function corpus(language: SupportedLanguages, count: number, methods: number) { + const files: SourceFile[] = Array.from({ length: count }, (_, i) => + generators[language](i, methods), + ).flat(); + const config: SourceFile[] = []; + if (language === SupportedLanguages.Java) { + // The shared name is indexed, but unreachable from every chain file. + // Repeated misses must not re-walk the whole import chain per caller. + files.push({ + path: 'src/aux/Auxiliary.java', + content: + 'package aux; public class Auxiliary { public Auxiliary externalBuild() { return this; } }', + }); + } else if (language === SupportedLanguages.Go) { + config.push({ path: 'go.mod', content: 'module bench\n\ngo 1.22\n' }); + } else if (language === SupportedLanguages.Rust) { + files.push({ path: 'src/lib.rs', content: members(count, (i) => `pub mod c${i};`) }); + config.push({ + path: 'Cargo.toml', + content: '[package]\nname = "bench"\nversion = "0.1.0"\nedition = "2021"\n', + }); + } else if (language === SupportedLanguages.PHP) { + config.push({ + path: 'composer.json', + content: JSON.stringify({ autoload: { 'psr-4': { 'Bench\\': 'src/' } } }), + }); + } + return { files, config }; +} diff --git a/gitnexus/bench/scope-resolution/measure.mts b/gitnexus/bench/scope-resolution/measure.mts new file mode 100644 index 0000000000..0ff4fd9e28 --- /dev/null +++ b/gitnexus/bench/scope-resolution/measure.mts @@ -0,0 +1,300 @@ +/** Real worker parsing + scope resolution, in a fresh process per sample. */ +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, + appendFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { basename, dirname, join } from 'node:path'; +import { performance } from 'node:perf_hooks'; +import { fileURLToPath } from 'node:url'; +import { SupportedLanguages } from 'gitnexus-shared'; +import { SCOPE_RESOLVERS } from '../../src/core/ingestion/scope-resolution/pipeline/registry.js'; +import { runScopeResolution } from '../../src/core/ingestion/scope-resolution/pipeline/run.js'; +import { processCobol } from '../../src/core/ingestion/cobol-processor.js'; +import { generateId } from '../../src/lib/utils.js'; +import { parseFilesWithWorkers } from '../../test/helpers/worker-parse.js'; +import { corpus, generators } from './corpus.mjs'; + +const HERE = dirname(fileURLToPath(import.meta.url)); +const BASELINES = join(HERE, 'baselines.json'); +const MARKER = 'SCOPE_BENCH_RESULT '; +const digest = (rows: string[]) => + createHash('sha256').update(rows.sort().join('\n')).digest('hex'); + +async function sample(language: SupportedLanguages, count: number, methods: number) { + const { files, config } = corpus(language, count, methods); + const dir = mkdtempSync(join(tmpdir(), 'gitnexus-scope-bench-')); + try { + for (const file of [...files, ...config]) { + mkdirSync(dirname(join(dir, file.path)), { recursive: true }); + writeFileSync(join(dir, file.path), file.content); + } + const resolver = SCOPE_RESOLVERS.get(language); + assert.ok(resolver, `No scope resolver registered for ${language}`); + const resolutionConfig = await resolver.loadResolutionConfig?.(dir); + const parseStarted = performance.now(); + const { graph, model, data } = await parseFilesWithWorkers(files, { poolSize: 1 }); + // The normal pipeline creates these during structure processing, before + // either parser runs. The worker helper only supplies symbol nodes. + for (const file of files) { + graph.addNode({ + id: generateId('File', file.path), + label: 'File', + properties: { name: basename(file.path), filePath: file.path }, + }); + } + // COBOL's structural graph is emitted by its standalone production parser. + if (language === SupportedLanguages.Cobol) { + processCobol(graph, files, new Set(files.map((file) => file.path))); + } + const parseMs = performance.now() - parseStarted; + const heapAfterParse = process.memoryUsage().heapUsed; + let parsedFileCount = 0; + let moduleTypeBindings = 0; + let typeBindings = 0; + const resolveStarted = performance.now(); + runScopeResolution( + { + graph, + model, + files, + resolutionConfig, + preExtractedParsedFiles: new Map(data.parsedFiles.map((file) => [file.filePath, file])), + onResolved: ({ parsedFiles }) => { + parsedFileCount = parsedFiles.length; + for (const file of parsedFiles) { + for (const scope of file.scopes) { + typeBindings += scope.typeBindings.size; + if (scope.id === file.moduleScope) moduleTypeBindings += scope.typeBindings.size; + } + } + }, + }, + resolver, + ); + const resolveMs = performance.now() - resolveStarted; + const heapAfterResolve = process.memoryUsage().heapUsed; + const peakRssBytes = process.resourceUsage().maxRSS * 1024; + assert.equal(parsedFileCount, files.length, `${language}: scope extraction omitted files`); + assert.ok(graph.nodeCount > files.length, `${language}: no declarations parsed`); + let calls = 0; + let crossFileCalls = 0; + const edges: string[] = []; + for (const edge of graph.iterRelationships()) { + edges.push( + JSON.stringify([edge.sourceId, edge.targetId, edge.type, edge.confidence, edge.reason]), + ); + if (edge.type !== 'CALLS') continue; + calls++; + const source = graph.getNode(edge.sourceId); + const target = graph.getNode(edge.targetId); + if ( + source !== undefined && + target !== undefined && + source.properties.filePath !== target.properties.filePath + ) + crossFileCalls++; + } + assert.ok(crossFileCalls > 0, `${language}: cross-file workload resolved no calls`); + const nodes = [...graph.iterNodes()].map((node) => + JSON.stringify([node.id, node.label, node.properties.name, node.properties.filePath]), + ); + return { + language, + entities: count, + files: files.length, + methodsPerEntity: methods, + parseMs, + resolveMs, + heapAfterParse, + heapAfterResolve, + peakRssBytes, + moduleTypeBindings, + typeBindings, + nodes: graph.nodeCount, + edges: graph.relationshipCount, + calls, + crossFileCalls, + fingerprint: digest([...nodes, ...edges]), + }; + } finally { + rmSync(dir, { recursive: true, force: true }); + } +} + +const args = process.argv.slice(2); +if (args[0] === '--worker') { + const result = await sample(args[1] as SupportedLanguages, Number(args[2]), Number(args[3])); + console.log(MARKER + JSON.stringify(result)); +} else { + const value = (flag: string, fallback: string) => { + const index = args.indexOf(flag); + return index < 0 ? fallback : args[index + 1]; + }; + const languages = Object.values(SupportedLanguages).sort(); + assert.deepEqual(Object.keys(generators).sort(), languages, 'Missing benchmark language'); + assert.deepEqual([...SCOPE_RESOLVERS.keys()].sort(), languages, 'Resolver inventory changed'); + const selected = value('--language', 'all'); + assert.ok( + selected === 'all' || languages.includes(selected as SupportedLanguages), + 'Unknown language', + ); + const sizes = value('--sizes', '100,1000').split(',').map(Number); + const repetitions = Number(value('--repetitions', '3')); + const methods = Number(value('--methods', '20')); + assert.ok( + [...sizes, repetitions, methods].every((n) => Number.isSafeInteger(n) && n >= 2), + 'Sizes, repetitions and methods must be integers >= 2', + ); + const check = args.includes('--check'); + const record = args.includes('--record'); + assert.ok(!(check && record), '--check cannot record new baselines'); + if (record) assert.equal(selected, 'all', '--record requires all languages'); + const baselines = check ? JSON.parse(readFileSync(BASELINES, 'utf8')) : {}; + const results: Awaited>[] = []; + const trials: Awaited>[] = []; + const failures: string[] = []; + const records: Record< + string, + { + fingerprint: string; + nodes: number; + edges: number; + crossFileCalls: number; + moduleTypeBindings: number; + typeBindings: number; + } + > = {}; + for (const language of languages.filter((lang) => selected === 'all' || lang === selected)) { + for (const count of sizes) { + const samples: Awaited>[] = []; + for (let trial = 0; trial < repetitions; trial++) { + const child = spawnSync( + process.execPath, + [ + '--import', + 'tsx', + fileURLToPath(import.meta.url), + '--worker', + language, + String(count), + String(methods), + ], + { + encoding: 'utf8', + maxBuffer: 16 * 1024 * 1024, + env: { ...process.env, GITNEXUS_LOG_LEVEL: 'error' }, + }, + ); + const line = child.stdout?.split('\n').find((line) => line.startsWith(MARKER)); + if (child.status !== 0 || !line) { + const failure = `${language}/${count}: ${child.error?.message || child.stderr || child.signal || `exit ${child.status}`}`; + failures.push(failure); + console.error(failure); + break; + } + samples.push(JSON.parse(line.slice(MARKER.length))); + } + trials.push(...samples); + if (samples.length !== repetitions) continue; + if (new Set(samples.map((item) => item.fingerprint)).size !== 1) + failures.push(`${language}/${count}: nondeterministic graph`); + for (const field of ['moduleTypeBindings', 'typeBindings'] as const) { + if (new Set(samples.map((item) => item[field])).size !== 1) + failures.push(`${language}/${count}: nondeterministic ${field}`); + } + const result = { ...samples[0] }; + for (const key of [ + 'parseMs', + 'resolveMs', + 'heapAfterParse', + 'heapAfterResolve', + 'peakRssBytes', + ] as const) { + const values = samples.map((item) => item[key]).sort((a, b) => a - b); + result[key] = + (values[Math.floor((values.length - 1) / 2)] + values[Math.floor(values.length / 2)]) / 2; + } + const key = `${language}/${count}/${methods}`; + records[key] = { + fingerprint: result.fingerprint, + nodes: result.nodes, + edges: result.edges, + crossFileCalls: result.crossFileCalls, + moduleTypeBindings: result.moduleTypeBindings, + typeBindings: result.typeBindings, + }; + if (check) { + const baseline = baselines[key]; + if ( + !baseline || + (['fingerprint', 'nodes', 'edges', 'crossFileCalls'] as const).some( + (field) => records[key][field] !== baseline[field], + ) + ) + failures.push(`${key}: graph differs from committed baseline`); + for (const field of ['moduleTypeBindings', 'typeBindings'] as const) { + if (!Number.isSafeInteger(baseline?.[field]) || result[field] > baseline[field]) + failures.push( + `${key}: ${field} exceeds measured baseline (${result[field]} > ${baseline?.[field]})`, + ); + } + } + results.push(result); + console.log(JSON.stringify(result)); + } + } + const scaling = [...new Set(results.map((r) => r.language))].map((language) => { + const rows = results.filter((r) => r.language === language).sort((a, b) => a.files - b.files); + const small = rows[0]; + const large = rows[rows.length - 1]; + const fileRatio = large.files / small.files; + return { + language, + fileRatio, + normalizedResolveRatio: large.resolveMs / small.resolveMs / fileRatio, + heapRatio: large.heapAfterResolve / small.heapAfterResolve, + moduleBindingRatio: + small.moduleTypeBindings === 0 ? null : large.moduleTypeBindings / small.moduleTypeBindings, + }; + }); + const report = { + node: process.version, + platform: process.platform, + arch: process.arch, + parsingWorkers: 1, + repetitions, + results, + scaling, + trials, + failures, + }; + const output = value('--output', ''); + if (output) writeFileSync(output, JSON.stringify(report, null, 2) + '\n'); + const table = [ + '## Scope-resolution benchmark', + '', + 'Medians from fresh processes. Heap is sampled after each phase; RSS is the process high-water mark through resolution. These are synthetic workloads.', + '', + '| Language | Files | Parse ms | Resolve ms | Heap after resolve MiB | Peak RSS MiB | Module type bindings | Cross-file calls |', + '| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |', + ...results.map( + (r) => + `| ${r.language} | ${r.files} | ${r.parseMs.toFixed(1)} | ${r.resolveMs.toFixed(1)} | ${(r.heapAfterResolve / 2 ** 20).toFixed(1)} | ${(r.peakRssBytes / 2 ** 20).toFixed(1)} | ${r.moduleTypeBindings} | ${r.crossFileCalls} |`, + ), + '', + ...failures.map((failure) => `- FAILED: ${failure}`), + '', + ].join('\n'); + console.log(table); + if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, table); + assert.equal(failures.length, 0, failures.join('\n')); + if (record) writeFileSync(BASELINES, JSON.stringify(records, null, 2) + '\n'); +} diff --git a/gitnexus/bench/tool-accuracy/README.md b/gitnexus/bench/tool-accuracy/README.md index 8cab471911..ad415d0603 100644 --- a/gitnexus/bench/tool-accuracy/README.md +++ b/gitnexus/bench/tool-accuracy/README.md @@ -30,7 +30,7 @@ errors always exit nonzero. `--check` additionally enforces the regression gate. | Fixture / checks | Public repro | Fixed-answer contract | | -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `rename/` | [#3486](https://github.com/abhigyanpatwari/GitNexus/issues/3486) | All three Writer.close references; zero edits to comments, strings or unrelated homonyms; typed DeferredWriter.flush parameters refuse without edits or source changes. | +| `rename/` | [#3486](https://github.com/abhigyanpatwari/GitNexus/issues/3486) | All three Writer.close references; zero edits to comments, strings or unrelated homonyms; typed DeferredWriter.flush parameters refuse without edits or source changes. | | `src/server/`, `test/stub.test.ts` | [#3487](https://github.com/abhigyanpatwari/GitNexus/issues/3487) | Server beats a same-path test stub; `app.all` has method `*`; Map.get is absent; helper-registered literal route is present. | | `src/web/` | [#3488](https://github.com/abhigyanpatwari/GitNexus/issues/3488) | Both the base-URL template passed to a configured wrapper and a direct literal fetch link their consumer files. | | `src/security.ts`, `src/server/inline.ts` | [#3489](https://github.com/abhigyanpatwari/GitNexus/issues/3489), [#3490](https://github.com/abhigyanpatwari/GitNexus/issues/3490), [#3491](https://github.com/abhigyanpatwari/GitNexus/issues/3491) | Named and inline unsafe handlers reach the sink; guarded and constant commands have zero taint; statement and function-hop lines are 1-based. | @@ -66,7 +66,10 @@ checks and all four #3499 checks, and their allowances were removed: **18/31 pass, 13 fail**. The JSON report records every desired and actual answer independently of gate status. Inline-callback taint now passes and its allowance is removed. Guard -taint remains a documented limitation and a visible known gap. +taint now passes for the modeled immutable SHA predicate and Git data-argument +use (#3490), and its allowance is removed. The current corpus passes **32/32** +fixed answers with no known-gap allowances. Unsupported guard forms remain +conservative findings; this does not claim complete guard coverage. `known-gaps.json` is an explicit, reviewed list of failing check IDs with issue, reason and observed baseline answers. There is no wildcard, skip, automatic diff --git a/gitnexus/bench/tool-accuracy/known-gaps.json b/gitnexus/bench/tool-accuracy/known-gaps.json index 5e9b867b7f..5080dff24a 100644 --- a/gitnexus/bench/tool-accuracy/known-gaps.json +++ b/gitnexus/bench/tool-accuracy/known-gaps.json @@ -1,12 +1,5 @@ { "schemaVersion": 1, "baselineSourceSha": "dd096e690c06e5d54ab3595c63b83f15e04b6191", - "gaps": [ - { - "id": "explain.guard", - "issue": 3490, - "reason": "Guard-style sanitizers are a documented taint limitation (#3490).", - "baselineActual": ["handleGuarded -> runGit command-injection"] - } - ] + "gaps": [] } diff --git a/gitnexus/package-lock.json b/gitnexus/package-lock.json index adf193fcca..0557ffacf6 100644 --- a/gitnexus/package-lock.json +++ b/gitnexus/package-lock.json @@ -74,6 +74,7 @@ "@babel/parser": "^8.0.0", "@babel/traverse": "^8.0.0", "@babel/types": "^8.0.0", + "@mermaid-js/tiny": "11.17.2", "@types/busboy": "^1.5.4", "@types/cli-progress": "^3.11.6", "@types/cors": "^2.8.17", @@ -82,6 +83,7 @@ "@types/proxy-addr": "^2.0.3", "@vitest/coverage-v8": "^5.0.0", "gitnexus-shared": "file:../gitnexus-shared", + "jsdom": "26.1.0", "tsx": "^4.0.0", "typescript": "^7.0.2", "vitest": "^5.0.0" @@ -97,6 +99,27 @@ "typescript": "^7.0.2" } }, + "node_modules/@asamuzakjp/css-color": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-3.2.0.tgz", + "integrity": "sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@csstools/css-calc": "^2.1.3", + "@csstools/css-color-parser": "^3.0.9", + "@csstools/css-parser-algorithms": "^3.0.4", + "@csstools/css-tokenizer": "^3.0.3", + "lru-cache": "^10.4.3" + } + }, + "node_modules/@asamuzakjp/css-color/node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "dev": true, + "license": "ISC" + }, "node_modules/@babel/code-frame": { "version": "8.0.6", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-8.0.6.tgz", @@ -233,6 +256,121 @@ "node": ">=18" } }, + "node_modules/@csstools/color-helpers": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.1.0.tgz", + "integrity": "sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@csstools/css-calc": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-2.1.4.tgz", + "integrity": "sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-color-parser": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-3.1.0.tgz", + "integrity": "sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "dependencies": { + "@csstools/color-helpers": "^5.1.0", + "@csstools/css-calc": "^2.1.4" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-parser-algorithms": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-3.0.5.tgz", + "integrity": "sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-tokenizer": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-3.0.4.tgz", + "integrity": "sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/@eagleoutice/tree-sitter-r": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/@eagleoutice/tree-sitter-r/-/tree-sitter-r-1.1.2.tgz", @@ -848,6 +986,13 @@ "integrity": "sha512-+eawOlIgy680F0kBzPUNFhMZGtJ1YmqM6l4+Crf4IkImjYrO/mqPwRMh352g23uIaQKFItcQ64I7KMaJxHgAVA==", "license": "MIT" }, + "node_modules/@mermaid-js/tiny": { + "version": "11.17.2", + "resolved": "https://registry.npmjs.org/@mermaid-js/tiny/-/tiny-11.17.2.tgz", + "integrity": "sha512-PmFr1c5cSfNf5AngLLR98DrbvR4U5KeD7I+hQkGqG5w5Veu3QT4dG0qu9f99cpn/sKj2XxRBK0q7EL6hr9NY/A==", + "dev": true, + "license": "MIT" + }, "node_modules/@modelcontextprotocol/sdk": { "version": "1.32.1", "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.32.1.tgz", @@ -1033,9 +1178,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1054,9 +1196,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1075,9 +1214,6 @@ "ppc64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1096,9 +1232,6 @@ "s390x" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1117,9 +1250,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1138,9 +1268,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1854,6 +1981,16 @@ "node": ">= 0.6" } }, + "node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, "node_modules/ajv": { "version": "8.18.0", "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz", @@ -1959,10 +2096,20 @@ "license": "MIT" }, "node_modules/argparse": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", - "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", - "license": "Python-2.0" + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-3.0.3.tgz", + "integrity": "sha512-Sn98ftV3KfsO8xfLPHG6oT8y+b0yvbrLgZjgPDXsharNY15tTAjqIsIju4S32nl6/iEUNNE4v+yL2Zhm8ooP3w==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], + "license": "PSF-2.0" }, "node_modules/array-back": { "version": "6.2.3", @@ -2014,18 +2161,18 @@ } }, "node_modules/body-parser": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz", - "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.4.0.tgz", + "integrity": "sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==", "license": "MIT", "dependencies": { "bytes": "^3.1.2", - "content-type": "^2.0.0", + "content-type": "^2.1.0", "debug": "^4.4.3", "http-errors": "^2.0.1", - "iconv-lite": "^0.7.2", + "iconv-lite": "^0.7.3", "on-finished": "^2.4.1", - "qs": "^6.15.2", + "qs": "^6.16.1", "raw-body": "^3.0.2", "type-is": "^2.1.0" }, @@ -2038,9 +2185,9 @@ } }, "node_modules/body-parser/node_modules/content-type": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz", - "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==", + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", "license": "MIT", "engines": { "node": ">=18" @@ -2388,6 +2535,34 @@ "node": ">= 8" } }, + "node_modules/cssstyle": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-4.6.0.tgz", + "integrity": "sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/css-color": "^3.2.0", + "rrweb-cssom": "^0.8.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/data-urls": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz", + "integrity": "sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^14.0.0" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/dateformat": { "version": "4.6.3", "resolved": "https://registry.npmjs.org/dateformat/-/dateformat-4.6.3.tgz", @@ -2414,6 +2589,13 @@ } } }, + "node_modules/decimal.js": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", + "dev": true, + "license": "MIT" + }, "node_modules/deep-extend": { "version": "0.6.0", "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", @@ -2487,6 +2669,19 @@ "once": "^1.4.0" } }, + "node_modules/entities": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", + "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, "node_modules/es-define-property": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", @@ -2734,9 +2929,9 @@ "license": "MIT" }, "node_modules/fast-uri": { - "version": "3.1.8", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.8.tgz", - "integrity": "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==", + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", "funding": [ { "type": "github", @@ -3098,6 +3293,19 @@ "node": ">=16.9.0" } }, + "node_modules/html-encoding-sniffer": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz", + "integrity": "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-encoding": "^3.1.1" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/http-errors": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", @@ -3118,10 +3326,38 @@ "url": "https://opencollective.com/express" } }, + "node_modules/http-proxy-agent": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", + "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, "node_modules/iconv-lite": { - "version": "0.7.2", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz", - "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==", + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", "license": "MIT", "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" @@ -3156,9 +3392,9 @@ "license": "ISC" }, "node_modules/ip-address": { - "version": "10.7.2", - "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.2.tgz", - "integrity": "sha512-7H/2gFSIitxc0hG3nOI1glS8QLo/EHBFFLk8vEUjXY/xu0AdL8jZ9U1IzO2PUm0d2D/ofQcAifb0g6OBkt8U7w==", + "version": "10.7.4", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.4.tgz", + "integrity": "sha512-DWBMKyeM25D70nrIiTkgQth59/G+naKOTep6huF9j+GmeK3DMD60Zvxg5d5qQnz+38AHgou6ean2LECX+lrKDg==", "license": "MIT", "engines": { "node": ">= 12" @@ -3182,6 +3418,13 @@ "node": ">=8" } }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "dev": true, + "license": "MIT" + }, "node_modules/is-promise": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", @@ -3235,9 +3478,9 @@ "license": "MIT" }, "node_modules/js-yaml": { - "version": "5.4.3", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-5.4.3.tgz", - "integrity": "sha512-yzzNtgczwgoVHNigCyKTXcQJU4Y8t/ikU4UxXW0BvrLfHTGWZhsNcOT2s/a7vn81/4KqVnNmHjaUEPlvWnNwVw==", + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-5.5.0.tgz", + "integrity": "sha512-paNr4LFIFPjeeSmwNYdrb8FafLLG/Cr2Af3GjbsHJ5CxIjH4r0c2emlmRdAtpPAieP1gRVzk6buBbVP5gBMGAg==", "funding": [ { "type": "github", @@ -3250,12 +3493,52 @@ ], "license": "MIT", "dependencies": { - "argparse": "^2.0.1" + "argparse": "^3.0.3" }, "bin": { "js-yaml": "bin/js-yaml.mjs" } }, + "node_modules/jsdom": { + "version": "26.1.0", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-26.1.0.tgz", + "integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cssstyle": "^4.2.1", + "data-urls": "^5.0.0", + "decimal.js": "^10.5.0", + "html-encoding-sniffer": "^4.0.0", + "http-proxy-agent": "^7.0.2", + "https-proxy-agent": "^7.0.6", + "is-potential-custom-element-name": "^1.0.1", + "nwsapi": "^2.2.16", + "parse5": "^7.2.1", + "rrweb-cssom": "^0.8.0", + "saxes": "^6.0.0", + "symbol-tree": "^3.2.4", + "tough-cookie": "^5.1.1", + "w3c-xmlserializer": "^5.0.0", + "webidl-conversions": "^7.0.0", + "whatwg-encoding": "^3.1.1", + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^14.1.1", + "ws": "^8.18.0", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "canvas": "^3.0.0" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, "node_modules/jsesc": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", @@ -3456,9 +3739,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -3481,9 +3761,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -3506,9 +3783,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -3531,9 +3805,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -3599,9 +3870,9 @@ "license": "MIT" }, "node_modules/lru-cache": { - "version": "11.5.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.1.tgz", - "integrity": "sha512-RPimw/7aMdv2oqRrxKwvZXcPfwBrn/JZ2xYcY9Hus/6LaS3VOAKVWKWgNLCFSiOm1ESXinjsDlidVU7JlnCN2A==", + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", "license": "BlueOak-1.0.0", "engines": { "node": "20 || >=22" @@ -3851,6 +4122,13 @@ "node-gyp-build-test": "build-test.js" } }, + "node_modules/nwsapi": { + "version": "2.2.28", + "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.28.tgz", + "integrity": "sha512-IlVB7OS7qrOsVYlpnFIkETjMwT9jwvmocJmmM+GZU/PAB3uGi9Ezd7vcWhWBUnSc0ya4ppmQITOyP1ez9gg8cg==", + "dev": true, + "license": "MIT" + }, "node_modules/object-assign": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", @@ -3946,6 +4224,19 @@ "obliterator": "^2.0.1" } }, + "node_modules/parse5": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz", + "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^6.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, "node_modules/parseurl": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", @@ -4186,10 +4477,20 @@ "once": "^1.3.1" } }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/qs": { - "version": "6.16.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.0.tgz", - "integrity": "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==", + "version": "6.16.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.1.tgz", + "integrity": "sha512-5Px6J7rfHBAGUhNQ3es4YzcOdBBw0SDcVtThJml4RdnKw4tKs2epA0kPZ+K8X+WiHktT93RHVcQ/3ym5aTCgtg==", "license": "BSD-3-Clause", "dependencies": { "es-define-property": "^1.0.1", @@ -4348,6 +4649,13 @@ "url": "https://opencollective.com/express" } }, + "node_modules/rrweb-cssom": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.8.0.tgz", + "integrity": "sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==", + "dev": true, + "license": "MIT" + }, "node_modules/safe-stable-stringify": { "version": "2.5.0", "resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz", @@ -4363,6 +4671,19 @@ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", "license": "MIT" }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "dev": true, + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, "node_modules/secure-json-parse": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-4.1.0.tgz", @@ -4661,6 +4982,13 @@ "node": ">=8" } }, + "node_modules/symbol-tree": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", + "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", + "dev": true, + "license": "MIT" + }, "node_modules/table-layout": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/table-layout/-/table-layout-4.1.1.tgz", @@ -4749,6 +5077,26 @@ "node": ">=14.0.0" } }, + "node_modules/tldts": { + "version": "6.1.86", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.86.tgz", + "integrity": "sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^6.1.86" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "6.1.86", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-6.1.86.tgz", + "integrity": "sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==", + "dev": true, + "license": "MIT" + }, "node_modules/toidentifier": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", @@ -4758,6 +5106,32 @@ "node": ">=0.6" } }, + "node_modules/tough-cookie": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-5.1.2.tgz", + "integrity": "sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^6.1.32" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz", + "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/tree-sitter": { "version": "0.25.1", "resolved": "https://registry.npmjs.org/tree-sitter/-/tree-sitter-0.25.1.tgz", @@ -5327,6 +5701,80 @@ } } }, + "node_modules/w3c-xmlserializer": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", + "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/whatwg-encoding": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz", + "integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==", + "deprecated": "Use @exodus/bytes instead for a more spec-conformant and faster implementation", + "dev": true, + "license": "MIT", + "dependencies": { + "iconv-lite": "0.6.3" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-encoding/node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/whatwg-mimetype": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz", + "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-url": { + "version": "14.2.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz", + "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tr46": "^5.1.0", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/which": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/which/-/which-6.0.1.tgz", @@ -5387,6 +5835,38 @@ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", "license": "ISC" }, + "node_modules/ws": { + "version": "8.22.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz", + "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, "node_modules/xml-naming": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/xml-naming/-/xml-naming-0.3.0.tgz", @@ -5402,6 +5882,13 @@ "node": ">=16.0.0" } }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "dev": true, + "license": "MIT" + }, "node_modules/y18n": { "version": "5.0.8", "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", @@ -5448,9 +5935,9 @@ } }, "node_modules/zod": { - "version": "4.3.6", - "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz", - "integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==", + "version": "4.6.7", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", + "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==", "license": "MIT", "funding": { "url": "https://github.com/sponsors/colinhacks" diff --git a/gitnexus/package.json b/gitnexus/package.json index de41608b79..1127004539 100644 --- a/gitnexus/package.json +++ b/gitnexus/package.json @@ -45,7 +45,8 @@ "vendor/**/README.md", "vendor/leiden/index.cjs", "vendor/leiden/utils.cjs", - "vendor/lbug-fts/manifest.json" + "vendor/lbug-fts/manifest.json", + "vendor/lbug-vector/manifest.json" ], "scripts": { "build": "node scripts/build.js", @@ -124,6 +125,7 @@ "@babel/parser": "^8.0.0", "@babel/traverse": "^8.0.0", "@babel/types": "^8.0.0", + "@mermaid-js/tiny": "11.17.2", "@types/busboy": "^1.5.4", "@types/cli-progress": "^3.11.6", "@types/cors": "^2.8.17", @@ -132,6 +134,7 @@ "@types/proxy-addr": "^2.0.3", "@vitest/coverage-v8": "^5.0.0", "gitnexus-shared": "file:../gitnexus-shared", + "jsdom": "26.1.0", "tsx": "^4.0.0", "typescript": "^7.0.2", "vitest": "^5.0.0" diff --git a/gitnexus/scripts/cross-platform-shard.ts b/gitnexus/scripts/cross-platform-shard.ts index 84aad0fe33..a8c7656b81 100644 --- a/gitnexus/scripts/cross-platform-shard.ts +++ b/gitnexus/scripts/cross-platform-shard.ts @@ -59,13 +59,13 @@ export const WINDOWS_WEIGHTS_SEC: Readonly> = { 'test/integration/rename-provider-c.test.ts': 202, 'test/integration/rename-provider-cobol.test.ts': 75, 'test/integration/rename-provider-cpp.test.ts': 250, - 'test/integration/rename-provider-csharp.test.ts': 200, + 'test/integration/rename-provider-csharp.test.ts': 266, 'test/integration/rename-provider-dart.test.ts': 425, 'test/integration/rename-provider-go.test.ts': 221, 'test/integration/rename-provider-java.test.ts': 300, 'test/integration/rename-provider-javascript.test.ts': 225, 'test/integration/rename-provider-kotlin.test.ts': 300, - 'test/integration/rename-provider-objective-c.test.ts': 285, + 'test/integration/rename-provider-objective-c.test.ts': 386, 'test/integration/rename-provider-php.test.ts': 100, 'test/integration/rename-provider-python.test.ts': 375, // Windows CI runs on 2026-10-17 (attempt 1: 749.5 s, rerun: 599.5 s): @@ -88,7 +88,12 @@ export const WINDOWS_WEIGHTS_SEC: Readonly> = { // Windows persisted-fixture profile above. Replace with observed CI timing. 'test/integration/rename-preview-plan.test.ts': 175, 'test/integration/mcp-index-generation.test.ts': 201, - 'test/unit/incremental-dirty-recovery.test.ts': 76, + // Windows run 39934695864 timed out after undercharged native suites; + // 40172490240 supplies the query-symbol and dirty-recovery measurements. + 'test/integration/incremental-method-integrity.test.ts': 145, + 'test/integration/fts-repair-warm-session.test.ts': 62, + 'test/integration/query-symbol-integrity.test.ts': 34, + 'test/unit/incremental-dirty-recovery.test.ts': 128, // Re-measured after the analyze --watch e2e landed in #3072. The previous // 361 s entry undercharged this suite and left shard 1 close to the watchdog. 'test/integration/cli-e2e.test.ts': 621, diff --git a/gitnexus/scripts/cross-platform-tests.ts b/gitnexus/scripts/cross-platform-tests.ts index 5195d48449..242b61e5ea 100644 --- a/gitnexus/scripts/cross-platform-tests.ts +++ b/gitnexus/scripts/cross-platform-tests.ts @@ -343,6 +343,7 @@ const WORKER_THREADS = [ // Native callback parsing and exact caller/summary ownership (#3489). 'test/integration/cfg/interproc-taint.test.ts', 'test/integration/function-local-identity.test.ts', + 'test/integration/java-imported-return-types.test.ts', 'test/unit/community-processor.test.ts', 'test/integration/worker-pool.test.ts', 'test/integration/parse-impl-quarantine-cache-skip.test.ts', diff --git a/gitnexus/src/cli/ai-context.ts b/gitnexus/src/cli/ai-context.ts index 4f93e13dc8..7440829b5c 100644 --- a/gitnexus/src/cli/ai-context.ts +++ b/gitnexus/src/cli/ai-context.ts @@ -347,7 +347,24 @@ async function upsertGitNexusSection( return 'created'; } - const existingContent = await fs.readFile(filePath, 'utf-8'); + // The block is generated with LF. A file checked out with CRLF (Windows, + // `core.autocrlf`) used to get the block written in LF inside its CRLF + // prose, so git saw mixed endings and a dirty tree after every reindex + // (#3688). The file's own ending is kept: the content is normalised to LF + // for the marker search and the comparisons below, and written back in the + // ending it had. + const rawContent = await fs.readFile(filePath, 'utf-8'); + const eol = detectLineEnding(rawContent); + const existingContent = rawContent.replace(/\r\n/g, '\n'); + // A file the previous writer left with mixed endings (CRLF prose, LF block) + // compares equal once normalised, so the paths below that keep the file as + // it is would leave the mixed bytes in place. Such a file is written back + // once, in its own ending, with its text untouched. + const repairLineEndings = async (): Promise<'updated' | 'preserved'> => { + if (rawContent === toLineEnding(existingContent, eol)) return 'preserved'; + await writeWithLineEnding(filePath, existingContent, eol); + return 'updated'; + }; // Check if GitNexus section already exists. Matching is restricted // to markers that occupy their own line so that inline prose @@ -407,37 +424,56 @@ async function upsertGitNexusSection( // Count-only delta — leave the committed lean block alone (#2907). A // project rename, or --no-stats dropping the parenthetical, still writes. if (stripVolatileCounts(updatedSection) === stripVolatileCounts(existingSection)) { - return 'preserved'; + return repairLineEndings(); } const before = existingContent.substring(0, startIdx); const after = existingContent.substring(endIdx + GITNEXUS_END_MARKER.length); - await fs.writeFile(filePath, (before + updatedSection + after).trim() + '\n', 'utf-8'); + await writeWithLineEnding(filePath, (before + updatedSection + after).trim() + '\n', eol); return 'updated'; } // Keep marker present but no stats line matched. Section is preserved // unchanged on disk; return a distinct status so callers/CLI output // don't mis-report this as 'updated' (which would imply a write). - return 'preserved'; + return repairLineEndings(); } // No keep marker — replace existing section with full verbose content, // unless the counts are the only thing that moved (#2907). if (stripVolatileCounts(existingSection) === stripVolatileCounts(content)) { - return 'preserved'; + return repairLineEndings(); } const before = existingContent.substring(0, startIdx); const after = existingContent.substring(endIdx + GITNEXUS_END_MARKER.length); const newContent = before + content + after; - await fs.writeFile(filePath, newContent.trim() + '\n', 'utf-8'); + await writeWithLineEnding(filePath, newContent.trim() + '\n', eol); return 'updated'; } // Append new section const newContent = existingContent.trim() + '\n\n' + content + '\n'; - await fs.writeFile(filePath, newContent, 'utf-8'); + await writeWithLineEnding(filePath, newContent, eol); return 'appended'; } +/** The line ending of the first line break in `content`; LF when there is none. */ +function detectLineEnding(content: string): '\n' | '\r\n' { + const firstBreak = content.indexOf('\n'); + return firstBreak > 0 && content[firstBreak - 1] === '\r' ? '\r\n' : '\n'; +} + +function toLineEnding(lfContent: string, eol: '\n' | '\r\n'): string { + return eol === '\n' ? lfContent : lfContent.replace(/\n/g, eol); +} + +/** Write LF text in the file's own line ending. */ +async function writeWithLineEnding( + filePath: string, + lfContent: string, + eol: '\n' | '\r\n', +): Promise { + await fs.writeFile(filePath, toLineEnding(lfContent, eol), 'utf-8'); +} + /** * Some agents read skills from a repo-local `.agents/skills/` directory and * prefer it over the global `~/.agents/skills/` install. When the repo contains diff --git a/gitnexus/src/core/ingestion/cfg/collect.ts b/gitnexus/src/core/ingestion/cfg/collect.ts index 0c4e0ce35e..a629d9a49e 100644 --- a/gitnexus/src/core/ingestion/cfg/collect.ts +++ b/gitnexus/src/core/ingestion/cfg/collect.ts @@ -124,6 +124,7 @@ export function collectFunctionCfgs( // Site anchors must match the coordinate space of scope reference captures. siteCoordinates: 'source' | 'parse-buffer' = 'source', ): CollectedCfgs { + visitor = visitor.forFile?.(root, filePath) ?? visitor; const cfgs: FunctionCfg[] = []; let tooManyLines = 0; let tooDeeplyNested = 0; diff --git a/gitnexus/src/core/ingestion/cfg/types.ts b/gitnexus/src/core/ingestion/cfg/types.ts index abd50cc045..07bb8bd617 100644 --- a/gitnexus/src/core/ingestion/cfg/types.ts +++ b/gitnexus/src/core/ingestion/cfg/types.ts @@ -1,3 +1,5 @@ +import type { StatementValueFacts } from '../taint/value-refinement.js'; + /** * CFG data model — plain, JSON-serializable types (issue #2081, M1). * @@ -199,6 +201,8 @@ export interface StatementFacts { readonly uses: readonly number[]; readonly mayDefs?: readonly number[]; readonly sites?: readonly SiteRecord[]; + /** Optional normalized value/predicate structure; absent on legacy channels. */ + readonly refinement?: StatementValueFacts; } /** A basic block: a maximal straight-line run of statements between leaders. */ @@ -278,6 +282,10 @@ export interface FunctionCfg { * {@link BasicBlockData.statements}. Present iff statement facts are. */ readonly bindings?: readonly BindingEntry[]; + /** Provider checked unsupported effects, including invisible closure writes. */ + readonly refinementSafe?: boolean; + /** Exact primitive-string declaration contracts, never assertion-derived. */ + readonly primitiveBindings?: readonly number[]; } /** @@ -287,6 +295,8 @@ export interface FunctionCfg { * `undefined` when the node is not a CFG-bearing function (the caller skips it). */ export interface CfgVisitor { + /** File-bound worker context, released after collection. Existing providers need no hook. */ + forFile?(root: TNode, filePath: string): CfgVisitor; buildFunctionCfg(fnNode: TNode, filePath: string): FunctionCfg | undefined; /** diff --git a/gitnexus/src/core/ingestion/cfg/visitors/typescript-harvest.ts b/gitnexus/src/core/ingestion/cfg/visitors/typescript-harvest.ts index 82fdd9d096..f6ddb064af 100644 --- a/gitnexus/src/core/ingestion/cfg/visitors/typescript-harvest.ts +++ b/gitnexus/src/core/ingestion/cfg/visitors/typescript-harvest.ts @@ -38,6 +38,14 @@ * NOTE: nothing serialized here may carry a field named `nodeId` — the durable * parsedfile-store reviver dedups objects keyed on that field name. */ +import { + hasDefaultShellArguments, + readPredicate, + readValueExpression, + type RefinementFileContext, +} from './typescript-refinement.js'; +import type { FunctionCfg } from '../types.js'; +import type { StatementValueFacts, ValueExpression } from '../../taint/value-refinement.js'; import type { SyntaxNode } from '../../utils/ast-helpers.js'; import type { BindingEntry, SiteArgOccurrence, SiteRecord, StatementFacts } from '../types.js'; @@ -114,7 +122,34 @@ interface Scope { readonly table: Map; } +const UNSAFE_REFINEMENT_NODES = new Set([ + 'try_statement', + 'await_expression', + 'yield_expression', + 'with_statement', +]); +const PREDICATE_NODES = new Set([ + 'parenthesized_expression', + 'unary_expression', + 'binary_expression', + 'call_expression', +]); + export class TsHarvester { + private refinementSafe = true; + private primitiveBindings?: Set; + private hasRefinementFacts = false; + private needsValueFacts = false; + private shapeCount = 0; + private predicateCount = 0; + private captureShapes = false; + private readonly checkDynamicNames: boolean; + private readonly hasGuardCandidate: boolean; + private activeShapes?: { + sites?: Map; + definitions?: NonNullable[number][]; + calls?: NonNullable[number][]; + }; private readonly bindings: BindingEntry[] = []; /** Scope-opening node id → its scope. */ private readonly scopeByNode = new Map(); @@ -123,13 +158,16 @@ export class TsHarvester { private readonly synthetic = new Map(); private readonly fnId: number; /** - * Innermost enclosing scope per visited node id, filled during the prescan + * Innermost enclosing scope per identifier id, filled during the prescan * (which already touches every named node once). Makes phase-2 resolution * O(scope-chain) instead of O(AST-depth) per identifier — a deeply-chained * single-statement expression (generated code) otherwise turns the * parent-chain walk quadratic (tri-review perf finding). */ private readonly nearestScopeCache = new Map(); + /** Adjacent def/use and value-shape reads share the completed scope tables. */ + private lastResolvedNodeId?: number; + private lastResolvedBinding?: number; /** * >0 while walking a conditionally-evaluated subexpression (short-circuit * right operand, ternary arm, logical-assignment target, case test). Defs @@ -148,13 +186,29 @@ export class TsHarvester { */ private readonly resultDefTargets = new Map(); - constructor(private readonly fnNode: SyntaxNode) { + constructor( + private readonly fnNode: SyntaxNode, + private readonly refinementContext?: RefinementFileContext, + ) { + const source = fnNode.text; + this.checkDynamicNames = + source.includes('eval') || source.includes('arguments') || source.includes('\\'); + this.hasGuardCandidate = + source.includes('test') || source.includes('===') || source.includes('!=='); + if ( + fnNode.type.includes('generator') || + (source.includes('async') && fnNode.children.some((child) => child.type === 'async')) + ) + this.refinementSafe = false; this.fnId = fnNode.id; - this.scopeByNode.set(fnNode.id, this.root); + this.scopeByNode.set(this.fnId, this.root); this.declareParams(fnNode); const body = fnNode.childForFieldName('body'); if (body) - this.prescan(body, body.type === 'statement_block' ? this.openScope(body) : this.root); + this.prescan( + body, + body.type === 'statement_block' ? this.openScope(body, this.root) : this.root, + ); } /** The completed binding table — pass to `CfgBuilder.finish`. */ @@ -162,23 +216,30 @@ export class TsHarvester { return this.bindings; } - // ── phase 1: declaration pre-scan ──────────────────────────────────────── - - private openScope(node: SyntaxNode): Scope { - const existing = this.scopeByNode.get(node.id); - if (existing) return existing; - const scope: Scope = { parent: this.nearestScopeOf(node), table: new Map() }; - this.scopeByNode.set(node.id, scope); - return scope; + decorate(cfg: FunctionCfg): FunctionCfg { + if (!this.refinementSafe) return { ...cfg, refinementSafe: false }; + if (!this.hasRefinementFacts) return cfg; + return { + ...cfg, + refinementSafe: this.refinementSafe, + ...(this.primitiveBindings?.size ? { primitiveBindings: [...this.primitiveBindings] } : {}), + }; } - private nearestScopeOf(node: SyntaxNode): Scope { - for (let p = node.parent; p; p = p.parent) { - const s = this.scopeByNode.get(p.id); - if (s) return s; - if (p.id === this.fnId) break; - } - return this.root; + private addPrimitiveBinding(binding: number): void { + if ((this.primitiveBindings?.size ?? 0) >= 256) this.refinementSafe = false; + else (this.primitiveBindings ??= new Set()).add(binding); + } + + // ── phase 1: declaration pre-scan ──────────────────────────────────────── + + private openScope(node: SyntaxNode, parent: Scope): Scope { + const id = node.id; + const existing = this.scopeByNode.get(id); + if (existing) return existing; + const scope: Scope = { parent, table: new Map() }; + this.scopeByNode.set(id, scope); + return scope; } private declare( @@ -189,6 +250,9 @@ export class TsHarvester { formalIndex?: number, ): void { const target = hoistToRoot ? this.root : scope; + // Parameters are outside the body prescan. Their scope is already known; + // retain it so parameter facts need not climb through their AST wrappers. + if (kind === 'param') this.nearestScopeCache.set(nameNode.id, this.root); const name = nameNode.text; // `var` multi-declaration (and a param + `var` of the same name) is ONE // binding — first declaration in source order is canonical. The dedup is @@ -196,10 +260,11 @@ export class TsHarvester { // `var x` still gets its own entry in its own scope. if (target.table.has(name)) return; target.table.set(name, this.bindings.length); + const position = nameNode.startPosition; this.bindings.push({ name, - declLine: nameNode.startPosition.row + 1, - declColumn: nameNode.startPosition.column, + declLine: position.row + 1, + declColumn: position.column, kind, // Carry the enclosing formal position for params so the PDG call-summary // consumer joins by FORMAL slot, never the flattened binding ordinal. A @@ -220,13 +285,25 @@ export class TsHarvester { // several inner names, but ALL inherit this one formal index, so the PDG // call-summary never misattributes an inner name to a later formal's slot. let formalIndex = 0; - for (let i = 0; i < params.namedChildCount; i++) { + for (let i = 0, count = params.namedChildCount; i < count; i++) { const p = params.namedChild(i); if (!p) continue; // TS wraps each param (required_parameter/optional_parameter, field // `pattern`); plain JS puts the pattern directly in formal_parameters. const pattern = p.childForFieldName('pattern') ?? p; this.declarePattern(pattern, 'param', this.root, true, formalIndex); + // A formal index identifies the argument slot, not a value extracted + // from it. Extraction/default/rest effects are not modeled as identity. + if (pattern.type !== 'identifier') this.refinementSafe = false; + if ( + this.hasGuardCandidate && + pattern.type === 'identifier' && + p.type === 'required_parameter' && + p.childForFieldName('type')?.text.replace(/\s/g, '') === ':string' + ) { + this.addPrimitiveBinding(this.root.table.get(pattern.text)!); + } + if (p.childForFieldName('value')) this.refinementSafe = false; formalIndex++; } } @@ -280,9 +357,22 @@ export class TsHarvester { } private prescan(node: SyntaxNode, scope: Scope): void { - this.nearestScopeCache.set(node.id, scope); const t = node.type; + // Only names are resolved. Reading native ids and caching scopes for + // structural/literal nodes adds work without helping either fact walk. + if (t.includes('identifier')) this.nearestScopeCache.set(node.id, scope); + if (UNSAFE_REFINEMENT_NODES.has(t)) this.refinementSafe = false; + if (this.checkDynamicNames && t === 'identifier') { + const name = node.text; + // The legacy binding table does not canonicalize escaped identifier spellings. + if (name === 'arguments' || name === 'eval' || name.includes('\\')) + this.refinementSafe = false; + } + // Well-formed literal internals contain no declarations/references. Error + // recovery can place identifiers inside them; retain that ordinary walk. + if (t === 'identifier' || ((t === 'string' || t === 'regex') && !node.hasError)) return; if (NESTED_FUNCTION_TYPES.has(t) && node.id !== this.fnId) { + this.refinementSafe = false; // A nested function's NAME binds in the enclosing scope; its body is opaque. if (FUNCTION_DECL_TYPES.has(t)) { const name = node.childForFieldName('name'); @@ -292,11 +382,12 @@ export class TsHarvester { } let childScope = scope; - if (SCOPE_TYPES.has(t)) childScope = this.openScope(node); + if (SCOPE_TYPES.has(t)) childScope = this.openScope(node, scope); switch (t) { case 'lexical_declaration': { const kind = node.child(0)?.type === 'const' ? 'const' : 'let'; + if (kind === 'const') this.needsValueFacts = true; this.declareDeclarators(node, kind, childScope, false); break; } @@ -329,7 +420,9 @@ export class TsHarvester { break; } - for (let i = 0; i < node.namedChildCount; i++) { + const childCount = node.namedChildCount; + if (t === 'arguments' && childCount > 0) this.needsValueFacts = true; + for (let i = 0; i < childCount; i++) { const c = node.namedChild(i); if (c) this.prescan(c, childScope); } @@ -341,7 +434,7 @@ export class TsHarvester { scope: Scope, hoistToRoot: boolean, ): void { - for (let i = 0; i < declNode.namedChildCount; i++) { + for (let i = 0, count = declNode.namedChildCount; i < count; i++) { const d = declNode.namedChild(i); if (d?.type !== 'variable_declarator') continue; const name = d.childForFieldName('name'); @@ -357,8 +450,42 @@ export class TsHarvester { */ facts(node: SyntaxNode): StatementFacts { const acc = new FactAccumulator(node.startPosition.row + 1); - this.walkValue(node, acc); - return acc.finish(); + if (!this.refinementSafe || (!this.hasGuardCandidate && !this.needsValueFacts)) { + this.walkValue(node, acc); + return acc.finish(); + } + const prior = this.activeShapes; + const priorCapture = this.captureShapes; + this.activeShapes = undefined; + this.captureShapes = true; + try { + this.walkValue(node, acc); + const shapes = this.activeShapes; + let predicate = + this.hasGuardCandidate && PREDICATE_NODES.has(node.type) + ? readPredicate( + node, + (identifier) => this.resolve(identifier), + this.refinementContext, + (call) => shapes?.sites?.get(call.id), + ) + : undefined; + if (predicate && ++this.predicateCount > 64) { + this.refinementSafe = false; + predicate = undefined; + } + if (!predicate && !shapes?.definitions?.length && !shapes?.calls?.length) return acc.finish(); + this.hasRefinementFacts = true; + const refinement: StatementValueFacts = { + ...(predicate ? { predicate } : {}), + ...(shapes?.definitions?.length ? { definitions: shapes.definitions } : {}), + ...(shapes?.calls?.length ? { calls: shapes.calls } : {}), + }; + return acc.finish(refinement); + } finally { + this.activeShapes = prior; + this.captureShapes = priorCapture; + } } /** @@ -391,7 +518,7 @@ export class TsHarvester { if (params.type === 'identifier') { this.def(params, acc); } else { - for (let i = 0; i < params.namedChildCount; i++) { + for (let i = 0, count = params.namedChildCount; i < count; i++) { const p = params.namedChild(i); if (!p) continue; const pattern = p.childForFieldName('pattern') ?? p; @@ -413,13 +540,15 @@ export class TsHarvester { } private resolve(nameNode: SyntaxNode): number { + const nodeId = nameNode.id; + if (nodeId === this.lastResolvedNodeId) return this.lastResolvedBinding!; const name = nameNode.text; - // Fast path: the prescan cached every visited node's innermost scope, so + // Fast path: the prescan cached every visited identifier's innermost scope, so // resolution walks the SCOPE chain (shallow), not the AST parent chain // (arbitrarily deep in chained expressions). The parent-chain walk remains // as fallback for the few nodes the prescan never visits (e.g. a nested // function declaration's own name node). - const cached = this.nearestScopeCache.get(nameNode.id); + const cached = this.nearestScopeCache.get(nodeId); let startScope: Scope | null = cached ?? null; if (!startScope) { for (let p: SyntaxNode | null = nameNode; p; p = p.parent) { @@ -436,7 +565,11 @@ export class TsHarvester { } for (let s: Scope | null = startScope; s; s = s.parent) { const idx = s.table.get(name); - if (idx !== undefined) return idx; + if (idx !== undefined) { + this.lastResolvedNodeId = nodeId; + this.lastResolvedBinding = idx; + return idx; + } } // No in-function declaration — synthetic module-level binding, shared by // defs and uses so `notDeclared = 1; use(notDeclared)` still forms a fact. @@ -446,6 +579,8 @@ export class TsHarvester { this.synthetic.set(name, idx); this.bindings.push({ name, declLine: 0, declColumn: 0, kind: 'module', synthetic: true }); } + this.lastResolvedNodeId = nodeId; + this.lastResolvedBinding = idx; return idx; } @@ -493,6 +628,7 @@ export class TsHarvester { return; } + if ((t === 'string' || t === 'regex') && !node.hasError) return; switch (t) { case 'identifier': case 'shorthand_property_identifier': @@ -500,11 +636,12 @@ export class TsHarvester { return; case 'lexical_declaration': case 'variable_declaration': - for (let i = 0; i < node.namedChildCount; i++) { + for (let i = 0, count = node.namedChildCount; i < count; i++) { const d = node.namedChild(i); if (d?.type !== 'variable_declarator') continue; const name = d.childForFieldName('name'); const value = d.childForFieldName('value'); + let declaredBinding: number | undefined; // A bare `var x;` mid-function is hoisted and writes NOTHING at // runtime — harvesting it as a def would fabricate a kill of the // live def (`x = source(); var x; sink(x)` must keep source→sink; @@ -512,9 +649,33 @@ export class TsHarvester { if (name && (value || t === 'lexical_declaration')) { const snap = acc.defSnapshot(); this.walkDefPattern(name, acc); - if (value) this.registerResultDefs(value, acc.defsSince(snap)); + if (value) { + const defs = acc.defsSince(snap); + this.registerResultDefs(value, defs); + if (defs.length === 1) declaredBinding = defs[0]; + } } if (value) this.walkValue(value, acc); + if ( + this.captureShapes && + value && + declaredBinding !== undefined && + this.bindings[declaredBinding]?.kind === 'const' && + name?.type === 'identifier' + ) { + const shapes = (this.activeShapes ??= {}); + if (++this.shapeCount > 256) this.refinementSafe = false; + else + (shapes.definitions ??= []).push({ + binding: declaredBinding, + value: readValueExpression(value, (identifier) => this.resolve(identifier)), + }); + if ( + this.hasGuardCandidate && + d.childForFieldName('type')?.text.replace(/\s/g, '') === ':string' + ) + this.addPrimitiveBinding(declaredBinding); + } } return; case 'assignment_expression': { @@ -632,7 +793,7 @@ export class TsHarvester { // arg 0 with `x` (review fix). Defs/uses stay byte-identical to the old // default descent; only the sites layer narrows. const operands: SyntaxNode[] = []; - for (let i = 0; i < node.namedChildCount; i++) { + for (let i = 0, count = node.namedChildCount; i < count; i++) { const c = node.namedChild(i); if (c) operands.push(c); } @@ -644,7 +805,7 @@ export class TsHarvester { return; } default: - for (let i = 0; i < node.namedChildCount; i++) { + for (let i = 0, count = node.namedChildCount; i < count; i++) { const c = node.namedChild(i); if (c) this.walkValue(c, acc); } @@ -735,7 +896,31 @@ export class TsHarvester { const argsNode = node.childForFieldName('arguments'); // `node` IS the call_expression/new_expression — the SAME node the // scope-extractor anchors `@reference.call.*` (its `atRange`) on (KTD7). - const siteIdx = acc.openCallSite(kind, [node.startPosition.row + 1, node.startPosition.column]); + const position = node.startPosition; + const siteIdx = acc.openCallSite(kind, [position.row + 1, position.column]); + let capturedArgs: SyntaxNode[] | undefined; + let argumentValues: ValueExpression[] | undefined; + if (argsNode?.type === 'arguments' && argsNode.namedChildCount > 0 && this.captureShapes) { + const shapes = (this.activeShapes ??= {}); + if (this.hasGuardCandidate) (shapes.sites ??= new Map()).set(node.id, siteIdx); + if (++this.shapeCount > 256) this.refinementSafe = false; + else { + const args = (capturedArgs = argsNode.namedChildren.filter( + (argument) => argument.type !== 'comment', + )); + if (args.length > 32) this.refinementSafe = false; + else { + argumentValues = args.map((argument) => + readValueExpression(argument, (identifier) => this.resolve(identifier)), + ); + (shapes.calls ??= []).push({ + site: siteIdx, + arguments: argumentValues, + ...(hasDefaultShellArguments(args) ? { defaultShell: true } : {}), + }); + } + } + } acc.pushFrame(siteIdx); let calleePath: string | undefined; if (calleeNode) { @@ -773,9 +958,8 @@ export class TsHarvester { this.walkValue(argsNode, acc); } else if (argsNode) { let pos = 0; - for (let i = 0; i < argsNode.namedChildCount; i++) { - const arg = argsNode.namedChild(i); - if (!arg || arg.type === 'comment') continue; + for (const arg of capturedArgs ?? argsNode.namedChildren) { + if (arg.type === 'comment') continue; acc.setFrameArg(pos); if (arg.type === 'spread_element') { acc.setSiteSpread(siteIdx, pos); @@ -787,7 +971,11 @@ export class TsHarvester { // resolves require'd aliases like ESM imports (plan KTD7). acc.setSiteRequireArg(siteIdx, stringLiteralText(arg)); } - this.walkValue(arg, acc); + const value = argumentValues?.[pos]; + // Value capture already resolved a bare identifier against the same + // completed scopes. Still record its use in the active call frame. + if (arg.type === 'identifier' && value?.kind === 'binding') acc.addUse(value.binding); + else this.walkValue(arg, acc); } pos++; } @@ -1101,7 +1289,7 @@ class FactAccumulator { list.push(via === undefined ? bindingIdx : [bindingIdx, via]); } - finish(): StatementFacts { + finish(refinement?: StatementValueFacts): StatementFacts { return { line: this.line, defs: this.defs, @@ -1112,6 +1300,7 @@ class FactAccumulator { // Sites likewise omit-when-empty (#2083 M3 U1): flag-off runs never // harvest, and most fact-bearing statements carry no calls. ...(this.sites.length > 0 ? { sites: this.sites.map(finalizeSite) } : {}), + ...(refinement ? { refinement } : {}), }; } } diff --git a/gitnexus/src/core/ingestion/cfg/visitors/typescript-refinement.ts b/gitnexus/src/core/ingestion/cfg/visitors/typescript-refinement.ts new file mode 100644 index 0000000000..2cb8d0aa77 --- /dev/null +++ b/gitnexus/src/core/ingestion/cfg/visitors/typescript-refinement.ts @@ -0,0 +1,298 @@ +import type { SyntaxNode } from '../../utils/ast-helpers.js'; +import { + MAX_VALUE_BYTES, + MAX_VALUE_NODES, + parseAnchoredAsciiPattern, + type StringRestriction, + type ValueExpression, +} from '../../taint/value-refinement.js'; + +export interface PredicateFact { + readonly site?: number; + readonly subject: number; + readonly accepts: boolean; + readonly restriction: StringRestriction; + readonly establishesPrimitive?: boolean; +} + +export interface RefinementFileContext { + readonly validators: ReadonlyMap; + readonly enabled: boolean; +} + +const UNKNOWN_EXPRESSION: ValueExpression = Object.freeze({ kind: 'unknown' }); +const UNCERTAIN_RUNTIME_ROOTS = new Set([ + 'RegExp', + 'eval', + 'Function', + 'globalThis', + 'global', + 'window', + 'self', +]); + +function regexRestriction(node: SyntaxNode): StringRestriction | undefined { + if (node.type !== 'regex' || node.text.length > MAX_VALUE_BYTES) return; + const pattern = node.childForFieldName('pattern'); + const flags = + node.childForFieldName('flags')?.text ?? node.text.slice(node.text.lastIndexOf('/') + 1); + return pattern ? parseAnchoredAsciiPattern(pattern.text, flags) : undefined; +} + +/** One bounded file scan; every non-test reference invalidates a mutable RegExp object. */ +export function createRefinementFileContext(root: SyntaxNode): RefinementFileContext { + if (!/\.\s*test\b/.test(root.text)) return { validators: new Map(), enabled: false }; + const candidates = new Map(); + const identifiers: SyntaxNode[] = []; + const pending = [root]; + let visits = 0; + let bytes = 0; + let enabled = true; + while (pending.length) { + if (++visits > 100_000) return { validators: new Map(), enabled: false }; + const node = pending.pop()!; + if (node.type.includes('identifier')) identifiers.push(node); + if (node.type === 'regex') { + const declaration = node.parent; + const lexical = declaration?.parent; + const indexedInitializer = + declaration?.type === 'variable_declarator' && + declaration.childForFieldName('value')?.id === node.id && + declaration.childForFieldName('name')?.type === 'identifier' && + lexical?.type === 'lexical_declaration' && + lexical.parent?.type === 'program' && + lexical.firstChild?.text === 'const'; + const member = node.parent; + const call = member?.parent; + const directTest = + member?.type === 'member_expression' && + member.childForFieldName('object')?.id === node.id && + member.childForFieldName('property')?.text === 'test' && + call?.type === 'call_expression' && + call.childForFieldName('function')?.id === member.id; + if (!indexedInitializer && !directTest) enabled = false; + } + if (node.type === 'identifier') { + const name = node.text; + if (name.includes('\\') || UNCERTAIN_RUNTIME_ROOTS.has(name)) enabled = false; + } + if ( + node.type === 'variable_declarator' && + node.parent?.type === 'lexical_declaration' && + node.parent.parent?.type === 'program' && + node.parent.firstChild?.text === 'const' + ) { + const name = node.childForFieldName('name'); + const value = node.childForFieldName('value'); + const restriction = value && regexRestriction(value); + if (name?.type === 'identifier' && value?.type === 'regex') { + bytes += value!.text.length; + if (candidates.size >= 256 || bytes > 8192) + return { validators: new Map(), enabled: false }; + if (candidates.has(name.text)) enabled = false; + candidates.set(name.text, { declaration: name.id, restriction }); + } + } + for (let i = node.namedChildCount - 1; i >= 0; i--) { + const child = node.namedChild(i); + if (child) pending.push(child); + } + } + for (const node of identifiers) { + if (++visits > 100_000) return { validators: new Map(), enabled: false }; + const candidate = candidates.get(node.text); + if (!candidate || node.id === candidate.declaration) continue; + const member = node.parent; + const call = member?.parent; + if ( + node.type !== 'identifier' || + member?.type !== 'member_expression' || + member.childForFieldName('object')?.id !== node.id || + member.childForFieldName('property')?.text !== 'test' || + call?.type !== 'call_expression' || + call.childForFieldName('function')?.id !== member.id + ) + enabled = false; + } + const validators = new Map(); + if (enabled) + for (const [name, candidate] of candidates) { + if (candidate.restriction) validators.set(name, candidate.restriction); + } + return { validators, enabled }; +} + +function unwrap(node: SyntaxNode): SyntaxNode { + while ( + ['parenthesized_expression', 'as_expression', 'non_null_expression', 'type_assertion'].includes( + node.type, + ) + ) { + const inner = node.childForFieldName('expression') ?? node.firstNamedChild; + if (!inner || inner.id === node.id) break; + node = inner; + } + return node; +} + +/** Preserve only exact string/binding composition, with a fixed traversal budget. */ +export function readValueExpression( + node: SyntaxNode, + resolve: (identifier: SyntaxNode) => number, +): ValueExpression { + let remaining = MAX_VALUE_NODES; + let bytes = 0; + let exhausted = false; + const visit = (raw: SyntaxNode): ValueExpression => { + if (--remaining < 0) { + exhausted = true; + return UNKNOWN_EXPRESSION; + } + const value = unwrap(raw); + if (value.type === 'identifier') return { kind: 'binding', binding: resolve(value) }; + if (value.type === 'string') { + const text = value.text; + bytes += text.length; + if (bytes > MAX_VALUE_BYTES) { + exhausted = true; + return UNKNOWN_EXPRESSION; + } + return text.length <= MAX_VALUE_BYTES && !text.includes('\\') + ? { kind: 'literal', value: text.slice(1, -1) } + : UNKNOWN_EXPRESSION; + } + if (value.type === 'binary_expression' && value.childForFieldName('operator')?.text === '+') { + const left = value.childForFieldName('left'); + const right = value.childForFieldName('right'); + return left && right + ? { kind: 'concat', parts: [visit(left), visit(right)] } + : UNKNOWN_EXPRESSION; + } + if ( + value.type === 'template_string' && + value.text.length <= MAX_VALUE_BYTES && + !value.text.includes('\\') + ) { + const parts: ValueExpression[] = []; + for (const child of value.namedChildren) { + if (child.type === 'string_fragment') { + bytes += child.text.length; + if (bytes > MAX_VALUE_BYTES) { + exhausted = true; + return UNKNOWN_EXPRESSION; + } + parts.push({ kind: 'literal', value: child.text }); + } else if (child.type === 'template_substitution' && child.firstNamedChild) + parts.push(visit(child.firstNamedChild)); + else return UNKNOWN_EXPRESSION; + } + return { kind: 'concat', parts }; + } + if ( + [ + 'object', + 'new_expression', + 'array', + 'number', + 'true', + 'false', + 'null', + 'regex', + 'function_expression', + 'arrow_function', + ].includes(value.type) + ) + return { kind: 'non-string' }; + return UNKNOWN_EXPRESSION; + }; + const result = visit(node); + return exhausted ? UNKNOWN_EXPRESSION : result; +} + +export function readPredicate( + raw: SyntaxNode, + resolve: (identifier: SyntaxNode) => number, + context: RefinementFileContext | undefined, + siteOf?: (call: SyntaxNode) => number | undefined, +): PredicateFact | undefined { + let node = unwrap(raw); + let accepts = true; + let remaining = 8; + while (node.type === 'unary_expression' && node.firstChild?.text === '!' && remaining-- > 0) { + const argument = node.childForFieldName('argument'); + if (!argument) return; + accepts = !accepts; + node = unwrap(argument); + } + if (remaining <= 0) return; + if (node.type === 'call_expression') { + if (!context?.enabled) return; + const callee = node.childForFieldName('function'); + const object = callee?.childForFieldName('object'); + const args = node.childForFieldName('arguments')?.namedChildren; + if ( + callee?.type !== 'member_expression' || + callee.childForFieldName('property')?.text !== 'test' || + !object || + !args || + args.length !== 1 || + args[0].type !== 'identifier' || + node.text.includes('?.') + ) + return; + const restriction = + object.type === 'regex' + ? regexRestriction(object) + : object.type === 'identifier' + ? context?.validators.get(object.text) + : undefined; + if (restriction) { + const site = siteOf?.(node); + return { + subject: resolve(args[0]), + accepts, + restriction, + ...(site !== undefined ? { site } : {}), + }; + } + } + if (node.type === 'binary_expression') { + const operator = node.childForFieldName('operator')?.text; + const left = node.childForFieldName('left'); + const right = node.childForFieldName('right'); + if (!left || !right || (operator !== '===' && operator !== '!==')) return; + const subject = + left.type === 'identifier' ? left : right.type === 'identifier' ? right : undefined; + const literal = subject?.id === left.id ? right : left; + if (!subject || literal.type !== 'string') return; + const expression = readValueExpression(literal, resolve); + if ( + expression.kind !== 'literal' || + !expression.value || + expression.value.length > MAX_VALUE_BYTES + ) + return; + return { + subject: resolve(subject), + accepts: operator === '===' ? accepts : !accepts, + restriction: { + chars: [...new Set(expression.value)].sort().join(''), + min: expression.value.length, + max: expression.value.length, + }, + establishesPrimitive: true, + }; + } +} + +/** Known ordinary options only; inherited shell settings and spread/getters are unknown. */ +export function hasDefaultShellArguments(args: readonly SyntaxNode[]): boolean { + if (args.length === 1) return true; + if (args.length !== 2 || args[1].type !== 'object') return false; + return args[1].namedChildren.every( + (pair) => + pair.type === 'pair' && + pair.childForFieldName('key')?.text === 'encoding' && + pair.childForFieldName('value')?.type === 'string', + ); +} diff --git a/gitnexus/src/core/ingestion/cfg/visitors/typescript.ts b/gitnexus/src/core/ingestion/cfg/visitors/typescript.ts index 43676591bc..6aa91f7394 100644 --- a/gitnexus/src/core/ingestion/cfg/visitors/typescript.ts +++ b/gitnexus/src/core/ingestion/cfg/visitors/typescript.ts @@ -67,6 +67,10 @@ import { import type { TraversalResult } from '../traversal-result.js'; import type { CfgVisitor, FunctionCfg } from '../types.js'; import { TsHarvester } from './typescript-harvest.js'; +import { + createRefinementFileContext, + type RefinementFileContext, +} from './typescript-refinement.js'; /** TS/JS node types that own a CFG-bearing function body. */ const TS_FUNCTION_TYPES = new Set([ @@ -723,7 +727,11 @@ class TsCfgWalk { } /** Build the CFG for one TS/JS function node (or `undefined` if not a function). */ -function buildFunctionCfg(fnNode: SyntaxNode, filePath: string): FunctionCfg | undefined { +function buildFunctionCfg( + fnNode: SyntaxNode, + filePath: string, + refinementContext?: RefinementFileContext, +): FunctionCfg | undefined { if (!TS_FUNCTION_TYPES.has(fnNode.type)) return undefined; const startLine = startLineOf(fnNode); const endLine = endLineOf(fnNode); @@ -735,7 +743,7 @@ function buildFunctionCfg(fnNode: SyntaxNode, filePath: string): FunctionCfg | u // Phase-1 declaration pre-scan (#2082 M2 U1) — must complete before any // facts are extracted; the CFG walk below is not source-order. - const harvest = new TsHarvester(fnNode); + const harvest = new TsHarvester(fnNode, refinementContext); // Parameters define at ENTRY (facts only — never touch the entry block's // text or span: bench fingerprints and CFG snapshots include block text). @@ -754,18 +762,18 @@ function buildFunctionCfg(fnNode: SyntaxNode, filePath: string): FunctionCfg | u ); builder.edge(builder.entryIndex, blk, 'seq'); builder.edge(blk, builder.exitIndex, 'return'); - return builder.finish(harvest.table()); + return harvest.decorate(builder.finish(harvest.table())); } const walk = new TsCfgWalk(builder, harvest); const res = walk.visitSeq(body.namedChildren.filter((c) => c.type !== 'comment')); if (!res) { builder.edge(builder.entryIndex, builder.exitIndex, 'seq'); // empty body - return builder.finish(harvest.table()); + return harvest.decorate(builder.finish(harvest.table())); } builder.edge(builder.entryIndex, res.entry, 'seq'); builder.connect(res.exits, builder.exitIndex, 'seq'); // normal fall-off → EXIT - return builder.finish(harvest.table()); + return harvest.decorate(builder.finish(harvest.table())); } /** Whether a node is a TS/JS function this visitor builds a CFG for. */ @@ -775,7 +783,14 @@ function isFunction(node: SyntaxNode): boolean { /** The TS/JS CFG visitor (shared by TypeScript and JavaScript). */ export function createTypeScriptCfgVisitor(): CfgVisitor { - return { buildFunctionCfg, isFunction }; + return { + buildFunctionCfg, + isFunction, + forFile(root) { + const context = createRefinementFileContext(root); + return { buildFunctionCfg: (fn, path) => buildFunctionCfg(fn, path, context), isFunction }; + }, + }; } export { TS_FUNCTION_TYPES }; diff --git a/gitnexus/src/core/ingestion/languages/java/scope-resolver.ts b/gitnexus/src/core/ingestion/languages/java/scope-resolver.ts index fc57578434..3879206eea 100644 --- a/gitnexus/src/core/ingestion/languages/java/scope-resolver.ts +++ b/gitnexus/src/core/ingestion/languages/java/scope-resolver.ts @@ -15,6 +15,7 @@ import type { GraphNodeLookup } from '../../scope-resolution/graph-bridge/node-l import { isClassLike, lookupBindingsAt, + lookupNameClaim, namesAtScope, populateClassOwnedMembers, } from '../../scope-resolution/scope/walkers.js'; @@ -110,10 +111,35 @@ function populateJavaCrossFileReturnTypes( indexes: ScopeResolutionIndexes, ): void { const moduleScopeByFile = new Map(); + const moduleReturnTypesByFile = new Map>(); + const returnNames = new Set(); + const importedFamiliesByFile = new Map(); + const ambiguousByFile = new Map>(); + const returnTypeIds = new Map(); + const returnTypeId = (ref: TypeRef): string | undefined => { + if (!returnTypeIds.has(ref)) { + const ids = new Set( + lookupNameClaim(ref.declaredAtScope, ref.rawName, indexes, { purpose: 'type' }) + .bindings.filter((binding) => isClassLike(binding.def.type)) + .map((binding) => binding.def.nodeId), + ); + returnTypeIds.set(ref, ids.size === 1 ? ids.values().next().value : undefined); + } + return returnTypeIds.get(ref); + }; const classScopesByFile = new Map(); for (const parsed of parsedFiles) { const ms = parsed.scopes.find((s) => s.kind === 'Module'); - if (ms !== undefined) moduleScopeByFile.set(parsed.filePath, ms); + if (ms !== undefined) { + moduleScopeByFile.set(parsed.filePath, ms); + // Keep producer facts once. Missing transitive facts are looked up on + // demand below instead of copying every dependency's table (#3695). + const returns = new Map( + [...ms.typeBindings].filter(([, ref]) => ref.source === 'return-annotation'), + ); + moduleReturnTypesByFile.set(parsed.filePath, returns); + for (const name of returns.keys()) returnNames.add(name); + } const cs = parsed.scopes.filter((s) => s.kind === 'Class'); if (cs.length > 0) classScopesByFile.set(parsed.filePath, cs); } @@ -123,6 +149,9 @@ function populateJavaCrossFileReturnTypes( if (importerModule === undefined) continue; const ambiguousMirrors = new Set(); + ambiguousByFile.set(parsed.filePath, ambiguousMirrors); + const importedFamilies: string[][] = []; + importedFamiliesByFile.set(parsed.filePath, importedFamilies); for (const name of namesAtScope(importerModule.id, indexes)) { const refs = lookupBindingsAt(importerModule.id, name, indexes); for (const ref of refs) { @@ -133,16 +162,26 @@ function populateJavaCrossFileReturnTypes( if (sourceModule === undefined) continue; const tb = importerModule.typeBindings as Map; - for (const [srcName, srcRef] of sourceModule.typeBindings) { - if (srcRef.source !== 'return-annotation') continue; - if (ambiguousMirrors.has(srcName)) continue; - const existing = tb.get(srcName); - if (existing !== undefined && existing.rawName !== srcRef.rawName) { - ambiguousMirrors.add(srcName); - tb.delete(srcName); - continue; + const sourceFiles = new Set([ref.def.filePath]); + for (const ancestorId of indexes.methodDispatch.mroFor(ref.def.nodeId)) { + const ancestor = indexes.defs.get(ancestorId); + if (ancestor !== undefined) sourceFiles.add(ancestor.filePath); + } + importedFamilies.push([...sourceFiles]); + const familyNames = new Set(); + for (const sourceFile of sourceFiles) { + for (const [srcName, srcRef] of moduleReturnTypesByFile.get(sourceFile) ?? []) { + if (familyNames.has(srcName)) continue; + familyNames.add(srcName); + if (ambiguousMirrors.has(srcName)) continue; + const existing = tb.get(srcName); + if (existing !== undefined && existing.rawName !== srcRef.rawName) { + ambiguousMirrors.add(srcName); + tb.delete(srcName); + continue; + } + if (existing === undefined) tb.set(srcName, srcRef); } - if (existing === undefined) tb.set(srcName, srcRef); } for (const classScope of classScopesByFile.get(ref.def.filePath) ?? []) { @@ -160,6 +199,58 @@ function populateJavaCrossFileReturnTypes( } } } + } + + for (const parsed of parsedFiles) { + const importerModule = moduleScopeByFile.get(parsed.filePath); + if (importerModule === undefined) continue; + const tb = importerModule.typeBindings as Map; + const needed = new Set(parsed.referenceSites.map((site) => site.name)); + for (const scope of parsed.scopes) { + for (const ref of scope.typeBindings.values()) needed.add(ref.rawName); + } + + for (const name of needed) { + if (tb.has(name) || !returnNames.has(name) || ambiguousByFile.get(parsed.filePath)?.has(name)) + continue; + const pending = [...(importedFamiliesByFile.get(parsed.filePath) ?? [])]; + const visited = new Set([parsed.filePath]); + let candidate: TypeRef | undefined; + let ambiguous = false; + while (pending.length > 0) { + const family = pending.pop(); + if (family === undefined) break; + let found: TypeRef | undefined; + // The first declaration in the MRO owns an overridden method. + for (const file of family) { + found = moduleReturnTypesByFile.get(file)?.get(name); + if (found !== undefined) break; + } + if (found !== undefined) { + if (candidate !== undefined) { + // A simple name can denote different classes in different packages. + // Preserve shared return types only when their producer scopes agree. + const sameType = + candidate.rawName === found.rawName && + (candidate.declaredAtScope === found.declaredAtScope || + (returnTypeId(candidate) !== undefined && + returnTypeId(candidate) === returnTypeId(found))); + if (!sameType) { + ambiguous = true; + break; + } + } + candidate ??= found; + continue; + } + for (const file of family) { + if (visited.has(file)) continue; + visited.add(file); + for (const dependency of importedFamiliesByFile.get(file) ?? []) pending.push(dependency); + } + } + if (!ambiguous && candidate !== undefined) tb.set(name, candidate); + } for (const [name, ref] of importerModule.typeBindings) { const resolved = followChainPostFinalize(ref, importerModule.id, indexes); diff --git a/gitnexus/src/core/ingestion/pipeline-phases/taint-summaries.ts b/gitnexus/src/core/ingestion/pipeline-phases/taint-summaries.ts index 96417ff303..1d311cec1e 100644 --- a/gitnexus/src/core/ingestion/pipeline-phases/taint-summaries.ts +++ b/gitnexus/src/core/ingestion/pipeline-phases/taint-summaries.ts @@ -85,6 +85,11 @@ export const taintSummariesPhase: PipelinePhase = { const maxEdges = ctx.options?.pdgMaxInterprocEdges ?? DEFAULT_PDG_MAX_INTERPROC_EDGES; const solved = solveInterprocTaint(summaryMap, callEdges, { maxFindings, maxHops }); + if (solved.refinementFallback) { + logger.warn( + '[taint-interproc] refinement memory budget exhausted; resumed conservative analysis', + ); + } const emit = emitInterprocTaint(ctx.graph, solved.findings, { maxEdges }, (m) => logger.warn(m), ); diff --git a/gitnexus/src/core/ingestion/scope-resolution/pipeline/run.ts b/gitnexus/src/core/ingestion/scope-resolution/pipeline/run.ts index c5a87e8876..f45f84cf75 100644 --- a/gitnexus/src/core/ingestion/scope-resolution/pipeline/run.ts +++ b/gitnexus/src/core/ingestion/scope-resolution/pipeline/run.ts @@ -67,6 +67,7 @@ import { type TaintEmitLimits, } from '../../taint/emit.js'; import { registerBuiltinTaintModels } from '../../taint/typescript-model.js'; +import { createMemoizedRefinement } from '../../taint/guard-refinement.js'; import { getSourceSinkConfig } from '../../taint/source-sink-registry.js'; import { buildFunctionNodeIndex, @@ -1796,6 +1797,9 @@ export function runScopeResolution( kills: 0, dropped: 0, hopsTruncated: 0, + guardFunctions: 0, + guardFallbacks: 0, + guardVisits: 0, gapExamples: [] as string[], dropExamples: [] as string[], }; @@ -1878,6 +1882,11 @@ export function runScopeResolution( // per (limits) bucket instead of 3–4× (#2227 tri-review). File-scoped: it // is re-created each iteration, so its per-function facts drop with the file. const rdSolve = createMemoizedReachingDefs(); + const refine = createMemoizedRefinement((result) => { + if (result.guards.status === 'computed') taintTotals.guardFunctions++; + if (result.guards.status === 'fallback') taintTotals.guardFallbacks++; + taintTotals.guardVisits += result.guards.visits; + }); const t0 = PROF ? performance.now() : 0; const rd = emitFileReachingDefs( pdgTarget, @@ -1956,6 +1965,7 @@ export function runScopeResolution( (message) => logger.warn(message), // unconditional — R4/R6 rdSolve, taintParsed, + refine, ); if (PROF) taintMs += performance.now() - t1; taintTotals.analyzed += taint.functionsAnalyzed; @@ -1991,6 +2001,7 @@ export function runScopeResolution( : DEFAULT_PDG_MAX_REACHING_DEF_FACTS_PER_FUNCTION, rdSolve, taintParsed, + refine, ); harvestedSummaries.push(...harvest.summaries); summaryUnresolved += harvest.unresolved; @@ -2028,6 +2039,7 @@ export function runScopeResolution( ? `; taint: ${taintTotals.findings} TAINTED, ${taintTotals.kills} SANITIZES ` + `(${taintTotals.analyzed} function(s) analyzed, ` + `${taintTotals.noMatch} skipped: no source/sink match` + + `; guards: ${taintTotals.guardFunctions} analyzed, ${taintTotals.guardFallbacks} fallback, ${taintTotals.guardVisits} visits` + (taintTotals.hopsTruncated > 0 ? `, ${taintTotals.hopsTruncated} finding(s) with truncated hop paths` : '') + diff --git a/gitnexus/src/core/ingestion/taint/emit.ts b/gitnexus/src/core/ingestion/taint/emit.ts index 4bae5f66af..89409459e7 100644 --- a/gitnexus/src/core/ingestion/taint/emit.ts +++ b/gitnexus/src/core/ingestion/taint/emit.ts @@ -64,6 +64,7 @@ */ import type { ParsedFile, ParsedImport } from 'gitnexus-shared'; +import { createFunctionRefinement, type RefinementSolver } from './guard-refinement.js'; import type { KnowledgeGraph } from '../../graph/types.js'; import { generateId } from '../../../lib/utils.js'; import { @@ -154,6 +155,7 @@ const pushExample = (list: string[], anchor: string): void => { * re-validated (`hasTaintSafeSites`). Never throws on well-formed input; * the caller's per-file try isolates the rest. */ + export function emitFileTaint( graph: KnowledgeGraph, cfgs: readonly FunctionCfg[], @@ -166,6 +168,7 @@ export function emitFileTaint( // functions request it, hitting the cache the call-summary harvest warmed. solve: ReachingDefsSolver = computeReachingDefs, parsed?: ParsedFile, + refine: RefinementSolver = createFunctionRefinement, ): TaintEmitResult { const result: TaintEmitResult = { functionsAnalyzed: 0, @@ -215,7 +218,13 @@ export function emitFileTaint( } const defUse = solve(cfg, { maxFacts }); - const flows = computeTaintFlows(cfg, defUse, matches, { maxFindingsPerFunction, maxHops }); + const flows = computeTaintFlows( + cfg, + defUse, + matches, + { maxFindingsPerFunction, maxHops }, + refine(cfg), + ); if (flows.status === 'coverage-gap') { // R4: skipped entirely, counted by reason; aggregate-warned by the // caller (the RD layer already per-function-warned this solver status). diff --git a/gitnexus/src/core/ingestion/taint/guard-refinement.ts b/gitnexus/src/core/ingestion/taint/guard-refinement.ts new file mode 100644 index 0000000000..eb5be4543c --- /dev/null +++ b/gitnexus/src/core/ingestion/taint/guard-refinement.ts @@ -0,0 +1,437 @@ +import type { FunctionCfg } from '../cfg/types.js'; +import { + applyValueEffect, + MAX_VALUE_BYTES, + MAX_VALUE_NODES, + UNKNOWN_VALUE, + type StatementValueFacts, + type StringRestriction, + type ValueEffect, + type ValueExpression, +} from './value-refinement.js'; + +const MAX_REFINEMENT_VISITS = 50_000; +const MAX_REFINEMENT_WORDS = 65_536; + +/** Normalized worker facts. No AST, executable predicates or model callbacks. */ +export interface GuardFacts { + readonly eligible: boolean; + readonly primitiveBindings: readonly number[]; + readonly predicates: readonly { + readonly block: number; + readonly subject: number; + readonly accepts: boolean; + readonly restriction: StringRestriction; + readonly establishesPrimitive?: boolean; + }[]; +} + +export interface GuardRefinements { + readonly status: 'computed' | 'no-guard' | 'fallback'; + readonly visits: number; + at(binding: number, block: number): StringRestriction | undefined; +} + +export interface FunctionRefinement { + readonly guards: GuardRefinements; + argument( + block: number, + statement: number, + site: number, + argument: number, + inputBinding?: number, + ): ValueEffect | undefined; + defaultShell(block: number, statement: number, site: number): boolean; + isPredicate(block: number, statement: number, site: number): boolean; +} + +/** Run/file-owned context shared by the two consumers; no AST or global cache. */ +export function createFunctionRefinement(cfg: FunctionCfg): FunctionRefinement { + if (cfg.refinementSafe !== true) + return cfg.refinementSafe === false ? FALLBACK_REFINEMENT : NO_REFINEMENT; + if (cfg.blocks.length + cfg.edges.length > MAX_REFINEMENT_WORDS) return FALLBACK_REFINEMENT; + let scanVisits = 0; + const predicates: GuardFacts['predicates'][number][] = []; + const definitions = new Map(); + const written = new Set(); + const calls = new Map[number]>(); + const predicateSites = new Set(); + let factCount = 0; + const validBinding = (binding: unknown): binding is number => + ++scanVisits <= MAX_REFINEMENT_VISITS && + Number.isInteger(binding) && + typeof binding === 'number' && + binding >= 0 && + binding < (cfg.bindings?.length ?? 0); + const validExpression = (expression: ValueExpression): boolean => { + let nodes = MAX_VALUE_NODES; + let bytes = 0; + const visit = (value: ValueExpression): boolean => { + if ( + ++scanVisits > MAX_REFINEMENT_VISITS || + !value || + typeof value !== 'object' || + --nodes < 0 + ) + return false; + if (value.kind === 'unknown' || value.kind === 'non-string') return true; + if (value.kind === 'binding') return validBinding(value.binding); + if (value.kind === 'literal') { + if (typeof value.value !== 'string') return false; + bytes += value.value.length; + return bytes <= MAX_VALUE_BYTES; + } + return ( + value.kind === 'concat' && + Array.isArray(value.parts) && + value.parts.length <= MAX_VALUE_NODES && + value.parts.every(visit) + ); + }; + return visit(expression); + }; + if ( + cfg.primitiveBindings !== undefined && + (!Array.isArray(cfg.primitiveBindings) || + cfg.primitiveBindings.length > MAX_REFINEMENT_WORDS || + !cfg.primitiveBindings.every(validBinding)) + ) + return FALLBACK_REFINEMENT; + for (const block of cfg.blocks) + for (let index = 0; index < (block.statements?.length ?? 0); index++) { + if (++scanVisits > MAX_REFINEMENT_VISITS) return FALLBACK_REFINEMENT; + const statement = block.statements![index]; + if ( + !Array.isArray(statement.defs) || + (statement.mayDefs !== undefined && !Array.isArray(statement.mayDefs)) + ) + return FALLBACK_REFINEMENT; + const shape = statement.refinement; + if ( + shape !== undefined && + (!shape || + typeof shape !== 'object' || + (shape.definitions !== undefined && + (!Array.isArray(shape.definitions) || shape.definitions.length > 256)) || + (shape.calls !== undefined && (!Array.isArray(shape.calls) || shape.calls.length > 256))) + ) + return FALLBACK_REFINEMENT; + if (shape?.predicate) { + const predicate = shape.predicate; + if ( + !validBinding(predicate.subject) || + typeof predicate.accepts !== 'boolean' || + (predicate.establishesPrimitive !== undefined && + predicate.establishesPrimitive !== true) || + applyValueEffect( + { kind: 'restrict', value: { kind: 'input' }, restriction: predicate.restriction }, + UNKNOWN_VALUE, + ).kind !== 'string' + ) + return FALLBACK_REFINEMENT; + if (predicate.site !== undefined) { + if ( + !Number.isInteger(predicate.site) || + statement.sites?.[predicate.site]?.kind !== 'call' + ) + return FALLBACK_REFINEMENT; + predicateSites.add(`${block.index}:${index}:${predicate.site}`); + } + if (predicates.length >= 64) return FALLBACK_REFINEMENT; + predicates.push({ ...predicate, block: block.index }); + } + for (const definition of shape?.definitions ?? []) { + if ( + ++factCount > 256 || + !definition || + !validBinding(definition.binding) || + !validExpression(definition.value) + ) + return FALLBACK_REFINEMENT; + if (definitions.has(definition.binding)) written.add(definition.binding); + else definitions.set(definition.binding, definition.value); + } + for (const bindings of [statement.defs, statement.mayDefs ?? []]) + for (const binding of bindings) { + if (++scanVisits > MAX_REFINEMENT_VISITS) return FALLBACK_REFINEMENT; + const entry = cfg.bindings?.[binding]; + if ( + entry?.kind === 'param' + ? block.index !== cfg.entryIndex + : entry?.kind !== 'const' || entry.declLine !== statement.line + ) + written.add(binding); + } + for (const call of shape?.calls ?? []) { + if ( + ++factCount > 256 || + !call || + !Number.isInteger(call.site) || + !statement.sites?.[call.site] || + !Array.isArray(call.arguments) || + call.arguments.length > MAX_VALUE_NODES || + !call.arguments.every(validExpression) || + (call.defaultShell !== undefined && typeof call.defaultShell !== 'boolean') + ) + return FALLBACK_REFINEMENT; + calls.set(`${block.index}:${index}:${call.site}`, call); + } + } + const guards = computeGuardRefinements( + cfg, + { + eligible: cfg.refinementSafe === true, + primitiveBindings: cfg.primitiveBindings ?? [], + predicates, + }, + undefined, + definitions, + ); + const active = cfg.refinementSafe === true && guards.status !== 'fallback'; + return { + guards, + defaultShell: (block, statement, site) => + active && calls.get(`${block}:${statement}:${site}`)?.defaultShell === true, + isPredicate: (block, statement, site) => + active && predicateSites.has(`${block}:${statement}:${site}`), + argument(block, statement, site, argument, inputBinding) { + const expression = calls.get(`${block}:${statement}:${site}`)?.arguments[argument]; + if (!active || !expression) return; + let remaining = MAX_VALUE_NODES; + const seen = new Set(); + let exhausted = false; + const visit = (value: ValueExpression): ValueEffect => { + if (--remaining < 0) { + exhausted = true; + return { kind: 'unknown' }; + } + if (value.kind === 'literal' || value.kind === 'non-string' || value.kind === 'unknown') + return value; + if (value.kind === 'concat') return { kind: 'concat', parts: value.parts.map(visit) }; + if (value.kind !== 'binding') return { kind: 'unknown' }; + const binding = value.binding; + if (written.has(binding) || seen.has(binding)) return { kind: 'unknown' }; + seen.add(binding); + const definition = definitions.get(binding); + const base: ValueEffect = + binding === inputBinding + ? { kind: 'input' } + : definition + ? visit(definition) + : { kind: 'unknown' }; + seen.delete(binding); + const restriction = guards.at(binding, block); + return restriction ? { kind: 'restrict', value: base, restriction } : base; + }; + const result = visit(expression); + return exhausted ? undefined : result; + }, + }; +} + +const NO_GUARDS: GuardRefinements = Object.freeze({ + status: 'no-guard', + visits: 0, + at: () => undefined, +}); + +const NO_REFINEMENT: FunctionRefinement = Object.freeze({ + guards: NO_GUARDS, + argument: () => undefined, + defaultShell: () => false, + isPredicate: () => false, +}); +const FALLBACK_REFINEMENT: FunctionRefinement = Object.freeze({ + ...NO_REFINEMENT, + guards: { ...NO_GUARDS, status: 'fallback' as const }, +}); + +export type RefinementSolver = (cfg: FunctionCfg) => FunctionRefinement; + +export function createMemoizedRefinement( + onCompute?: (result: FunctionRefinement) => void, +): RefinementSolver { + const cache = new WeakMap(); + return (cfg) => { + let result = cache.get(cfg); + if (!result) { + result = createFunctionRefinement(cfg); + cache.set(cfg, result); + onCompute?.(result); + } + return result; + }; +} + +/** + * Removing an accepted edge must make the use unreachable from ENTRY. + * Definitions are the validated value expressions reconstructed by the caller. + * Expanding their uses shares the traversal cap; no certificates survive exhaustion. + */ +export function computeGuardRefinements( + cfg: FunctionCfg, + facts?: GuardFacts, + limits?: { maxVisits?: number; maxGuards?: number; maxWords?: number }, + definitions?: ReadonlyMap, +): GuardRefinements { + if (!facts?.predicates?.length) return NO_GUARDS; + let visits = 0; + const fallback = (): GuardRefinements => ({ status: 'fallback', visits, at: () => undefined }); + const maxVisits = limits?.maxVisits ?? MAX_REFINEMENT_VISITS; + const maxGuards = limits?.maxGuards ?? 64; + const maxWords = limits?.maxWords ?? MAX_REFINEMENT_WORDS; + const count = cfg.blocks.length; + if ( + facts.eligible !== true || + !Array.isArray(facts.predicates) || + !Array.isArray(facts.primitiveBindings) || + facts.predicates.length > maxGuards || + facts.primitiveBindings.length > maxWords || + count + cfg.edges.length > maxWords || + !Number.isInteger(cfg.entryIndex) || + cfg.entryIndex < 0 || + cfg.entryIndex >= count + ) + return fallback(); + + const successors: number[][] = Array.from({ length: count }, () => []); + for (let i = 0; i < cfg.edges.length; i++) { + const edge = cfg.edges[i]; + if ( + !Number.isInteger(edge.from) || + !Number.isInteger(edge.to) || + edge.from < 0 || + edge.from >= count || + edge.to < 0 || + edge.to >= count + ) + return fallback(); + successors[edge.from].push(i); + } + const reachable = (removed = -1): Uint8Array | undefined => { + const seen = new Uint8Array(count); + const pending = [cfg.entryIndex]; + seen[cfg.entryIndex] = 1; + while (pending.length) { + if (++visits > maxVisits) return; + const block = pending.pop()!; + for (const index of successors[block]) { + if (++visits > maxVisits) return; + if (index === removed) continue; + const to = cfg.edges[index].to; + if (!seen[to]) { + seen[to] = 1; + pending.push(to); + } + } + } + return seen; + }; + const original = reachable(); + if (!original) return fallback(); + const primitives = new Set(facts.primitiveBindings); + const written = new Set(); + const uses = new Map>(); + const subjects = new Set(facts.predicates.map((predicate) => predicate.subject)); + for (const block of cfg.blocks) { + for (const statement of block.statements ?? []) { + if (++visits > maxVisits) return fallback(); + if ( + !Array.isArray(statement.defs) || + !Array.isArray(statement.uses) || + (statement.mayDefs !== undefined && !Array.isArray(statement.mayDefs)) + ) + return fallback(); + for (const bindings of [statement.defs, statement.mayDefs ?? []]) + for (const binding of bindings) { + if (++visits > maxVisits) return fallback(); + if (!subjects.has(binding)) continue; + const declaration = cfg.bindings?.[binding]; + const isInitial = + declaration?.kind === 'param' + ? block.index === cfg.entryIndex + : declaration?.kind === 'const' && statement.line === declaration.declLine; + if (!isInitial) written.add(binding); + } + for (const binding of statement.uses) { + // Argument reconstruction expands aliases at the sink. Certify the + // subjects reached through those same definitions at that use block. + const pending: ValueExpression[] = [{ kind: 'binding', binding }]; + const seen = new Set(); + while (pending.length) { + if (++visits > maxVisits) return fallback(); + const value = pending.pop()!; + if (value.kind === 'concat') pending.push(...value.parts); + else if (value.kind === 'binding' && !seen.has(value.binding)) { + seen.add(value.binding); + if (subjects.has(value.binding)) { + let blocks = uses.get(value.binding); + if (!blocks) uses.set(value.binding, (blocks = new Set())); + blocks.add(block.index); + } + const definition = definitions?.get(value.binding); + if (definition) pending.push(definition); + } + } + } + } + } + const certificates = new Map>(); + let words = count + cfg.edges.length; + for (const predicate of facts.predicates) { + if ( + !Number.isInteger(predicate.block) || + !Number.isInteger(predicate.subject) || + !original[predicate.block] || + !cfg.bindings?.[predicate.subject] || + written.has(predicate.subject) || + (!primitives.has(predicate.subject) && !predicate.establishesPrimitive) + ) + continue; + const checked = applyValueEffect( + { kind: 'restrict', value: { kind: 'input' }, restriction: predicate.restriction }, + UNKNOWN_VALUE, + ); + if (checked.kind !== 'string') continue; + const edges = successors[predicate.block]; + // An unlabeled seq leg is the false fallthrough only alongside one true edge. + const explicit = edges.filter( + (index) => cfg.edges[index].kind === (predicate.accepts ? 'cond-true' : 'cond-false'), + ); + const accepted = + explicit.length === 1 + ? explicit[0] + : !predicate.accepts && + explicit.length === 0 && + edges.length === 2 && + edges.some((index) => cfg.edges[index].kind === 'cond-true') + ? edges.find((index) => cfg.edges[index].kind === 'seq') + : undefined; + if (accepted === undefined) continue; + const bypass = reachable(accepted); + if (!bypass) return fallback(); + for (const block of uses.get(predicate.subject) ?? []) { + if (++visits > maxVisits || ++words > maxWords) return fallback(); + if (!original[block] || bypass[block]) continue; + let points = certificates.get(predicate.subject); + if (!points) certificates.set(predicate.subject, (points = new Map())); + const previous = points.get(block); + const restriction = predicate.restriction; + if (!previous) points.set(block, restriction); + else { + const chars = [...new Set(previous.chars)] + .filter((char) => restriction.chars.includes(char)) + .sort() + .join(''); + const min = Math.max(previous.min, restriction.min); + const max = Math.min(previous.max, restriction.max); + if (chars && min <= max) points.set(block, { chars, min, max }); + } + } + } + return { + status: 'computed', + visits, + at: (binding, block) => certificates.get(binding)?.get(block), + }; +} diff --git a/gitnexus/src/core/ingestion/taint/interproc-solver.ts b/gitnexus/src/core/ingestion/taint/interproc-solver.ts index 50d49c4b69..c5659d39dd 100644 --- a/gitnexus/src/core/ingestion/taint/interproc-solver.ts +++ b/gitnexus/src/core/ingestion/taint/interproc-solver.ts @@ -51,6 +51,13 @@ import type { SinkKind } from './source-sink-config.js'; import type { FunctionSummary } from './summary-model.js'; +import { + applyValueEffect, + joinRefinedValues, + provesInertCommand, + UNKNOWN_VALUE, + type RefinedValue, +} from './value-refinement.js'; /** * One resolved call edge from the `CALLS` graph. The join to a summary's @@ -86,6 +93,8 @@ export interface InterprocFinding { } export interface InterprocLimits { + /** Internal proof-payload budget; exhaustion restores baseline taint. */ + readonly maxRefinementBytes?: number; /** Max functions in a single flow's hop chain. `undefined`/0 ⇒ default 32. */ readonly maxHops?: number; /** Max findings overall (post-dedup). `undefined`/0 ⇒ unlimited. */ @@ -93,6 +102,7 @@ export interface InterprocLimits { } export interface InterprocResult { + readonly refinementFallback?: boolean; readonly findings: readonly InterprocFinding[]; /** Findings dropped by `maxFindings` (post-dedup). */ readonly droppedFindings: number; @@ -113,6 +123,7 @@ export const DEFAULT_PDG_MAX_INTERPROC_FINDINGS = 2000; /** A tainted parameter, with the flow that first tainted it (for path reconstruction). */ interface TaintedParam { + readonly value?: RefinedValue; readonly fnId: string; readonly paramIndex: number; readonly sourceFnId: string; @@ -205,6 +216,19 @@ export function solveInterprocTaint( const findingsByKey = new Map(); const tainted = new Map(); const queue: TaintedParam[] = []; + let refinementEnabled = true; + // Queue entries retain earlier values after map replacement, so charge cumulatively. + let refinementBytes = 0; + const refinementBudget = limits?.maxRefinementBytes ?? 64 * 1024 * 1024; + const valueBytes = (value: RefinedValue | undefined): number => + value?.kind === 'string' + ? 32 + + value.parts.reduce( + (total, part) => + total + (typeof part === 'string' ? part.length * 2 : part.chars.length * 2 + 32), + 0, + ) + : 0; const recordFinding = ( sourceFnId: string, @@ -225,6 +249,16 @@ export function solveInterprocTaint( for (const ps of summary.paramToSink) { if (ps.param !== tp.paramIndex) continue; if (tp.neutralized.has(ps.sinkKind)) continue; // sanitised across the boundary (P1-2) + if ( + refinementEnabled && + ps.sinkKind === 'command-injection' && + ps.inertCommandPrefixes && + provesInertCommand( + applyValueEffect(ps.valueEffect, tp.value ?? UNKNOWN_VALUE), + ps.inertCommandPrefixes, + ) + ) + continue; // `tp.hops` already terminates at this (tainted) function — it IS the // source→sink chain, no extra hop to append. recordFinding(tp.sourceFnId, tp.fnId, ps.sinkKind, tp.hops, tp.truncated); @@ -241,20 +275,44 @@ export function solveInterprocTaint( */ const taint = (tp: TaintedParam): void => { const key = pkey(tp.fnId, tp.paramIndex, tp.sourceFnId); - const existing = tainted.get(key); + let existing = tainted.get(key); + let value = refinementEnabled + ? existing + ? joinRefinedValues(existing.value ?? UNKNOWN_VALUE, tp.value ?? UNKNOWN_VALUE) + : (tp.value ?? UNKNOWN_VALUE) + : UNKNOWN_VALUE; + if (refinementEnabled && refinementBytes + valueBytes(value) > refinementBudget) { + refinementEnabled = false; + refinementBytes = 0; + for (const [priorKey, prior] of tainted) { + const widened = { ...prior, value: UNKNOWN_VALUE }; + tainted.set(priorKey, widened); + queue.push(widened); + fireSinks(widened); + } + existing = tainted.get(key); + value = UNKNOWN_VALUE; + } if (existing) { const inter = new Set(); for (const k of existing.neutralized) if (tp.neutralized.has(k)) inter.add(k); - if (inter.size >= existing.neutralized.size) return; // no shrink — cycle-safe - const merged: TaintedParam = { ...existing, neutralized: inter }; + if ( + inter.size >= existing.neutralized.size && + JSON.stringify(value) === JSON.stringify(existing.value ?? UNKNOWN_VALUE) + ) + return; + refinementBytes += valueBytes(value); + const merged: TaintedParam = { ...existing, neutralized: inter, value }; tainted.set(key, merged); queue.push(merged); fireSinks(merged); return; } - tainted.set(key, tp); - queue.push(tp); - fireSinks(tp); + const added = { ...tp, value }; + refinementBytes += valueBytes(value); + tainted.set(key, added); + queue.push(added); + fireSinks(added); }; // ── seeds: every source→callee-arg, resolved against CALLS ──────────────── @@ -278,6 +336,9 @@ export function solveInterprocTaint( hops: seed.hops, truncated: seed.truncated, neutralized: new Set(sc.neutralized ?? []), + value: refinementEnabled + ? applyValueEffect(sc.valueEffect, UNKNOWN_VALUE) + : UNKNOWN_VALUE, }); } } @@ -379,6 +440,9 @@ export function solveInterprocTaint( hops: next.hops, truncated: tp.truncated || next.truncated, neutralized, + value: refinementEnabled + ? applyValueEffect(pc.valueEffect, tp.value ?? UNKNOWN_VALUE) + : UNKNOWN_VALUE, }); } } @@ -395,6 +459,7 @@ export function solveInterprocTaint( const findings = all.length > maxFindings ? all.slice(0, maxFindings) : all; return { + ...(!refinementEnabled ? { refinementFallback: true } : {}), findings, droppedFindings: all.length - findings.length, unmatchedCallSites, diff --git a/gitnexus/src/core/ingestion/taint/propagate.ts b/gitnexus/src/core/ingestion/taint/propagate.ts index 36f093480c..a4212b74a7 100644 --- a/gitnexus/src/core/ingestion/taint/propagate.ts +++ b/gitnexus/src/core/ingestion/taint/propagate.ts @@ -96,6 +96,8 @@ * bypassed sanitizer (`exec(x + escape(x))`) killed nothing. */ +import { createFunctionRefinement, type FunctionRefinement } from './guard-refinement.js'; +import { applyValueEffect, provesInertCommand, UNKNOWN_VALUE } from './value-refinement.js'; import type { FunctionCfg, SiteRecord, StatementFacts } from '../cfg/types.js'; import { pointKey } from '../cfg/reaching-defs.js'; import type { DefUseFact, FunctionDefUse, ProgramPoint } from '../cfg/reaching-defs.js'; @@ -294,11 +296,13 @@ interface TaintState { * Compute taint flows for one function. See the module doc for the two-rule * model, the kind-set exclusion semantics, and the precision floor. */ + export function computeTaintFlows( cfg: FunctionCfg, defUse: FunctionDefUse, matches: FunctionSiteMatches, limits?: TaintLimits, + refinement: FunctionRefinement = createFunctionRefinement(cfg), ): FunctionTaintResult { if (defUse.status !== 'computed') { return { @@ -311,6 +315,22 @@ export function computeTaintFlows( } const bindings = defUse.bindings; + const guardProvesSink = ( + block: number, + statement: number, + site: number, + argument: number, + prefixes: readonly string[] | undefined, + ): boolean => + argument === 0 && + prefixes !== undefined && + refinement.defaultShell(block, statement, site) && + cfg.blocks[block]?.statements?.[statement]?.sites?.[site]?.spread === undefined && + !cfg.blocks[block]?.statements?.[statement]?.sites?.[site]?.template && + provesInertCommand( + applyValueEffect(refinement.argument(block, statement, site, argument), UNKNOWN_VALUE), + prefixes, + ); // ── per-statement context (built lazily; statements revisit often) ──────── const matchByPoint = new Map(); @@ -766,6 +786,17 @@ export function computeTaintFlows( for (const sink of ctx.sinksBySite.get(siteIndex) ?? []) { if (!sink.argPositions.includes(argPos)) continue; const kind = sink.entry.kind; + if ( + kind === 'command-injection' && + guardProvesSink( + ctx.point.blockIndex, + ctx.point.stmtIndex, + siteIndex, + argPos, + sink.entry.inertCommandPrefixes, + ) + ) + continue; if (!sofar.kinds.has(kind)) { recordFinding( kind, @@ -847,6 +878,17 @@ export function computeTaintFlows( for (const sink of sinks) { const kind = sink.entry.kind; for (const argPos of sink.argPositions) { + if ( + kind === 'command-injection' && + guardProvesSink( + ctx.point.blockIndex, + ctx.point.stmtIndex, + siteIndex, + argPos, + sink.entry.inertCommandPrefixes, + ) + ) + continue; const paths = pathsIntoPosition(ctx, b, siteIndex, argPos); if (paths.length === 0) continue; if (E.has(kind)) continue; // suppressed at def time; kill already recorded diff --git a/gitnexus/src/core/ingestion/taint/source-sink-config.ts b/gitnexus/src/core/ingestion/taint/source-sink-config.ts index d7ca28b259..606e664594 100644 --- a/gitnexus/src/core/ingestion/taint/source-sink-config.ts +++ b/gitnexus/src/core/ingestion/taint/source-sink-config.ts @@ -66,6 +66,8 @@ export interface TaintCallableMatcher { * names (`res.send` / `res.write`); exactly `.`, name-based. */ export interface TaintSinkEntry extends TaintCallableMatcher { + /** Reviewed fixed-operation prefixes with one inert data-word argument. */ + readonly inertCommandPrefixes?: readonly string[]; readonly module?: string; readonly global?: boolean; /** Only meaningful with `global`: match `new (…)` sites only. */ diff --git a/gitnexus/src/core/ingestion/taint/summary-harvest-driver.ts b/gitnexus/src/core/ingestion/taint/summary-harvest-driver.ts index 816649489c..cb20808bea 100644 --- a/gitnexus/src/core/ingestion/taint/summary-harvest-driver.ts +++ b/gitnexus/src/core/ingestion/taint/summary-harvest-driver.ts @@ -26,6 +26,7 @@ * remain unresolved rather than attaching a summary to a different function. */ +import { createFunctionRefinement, type RefinementSolver } from './guard-refinement.js'; import type { ParsedFile, ParsedImport, GraphNode } from 'gitnexus-shared'; import type { KnowledgeGraph } from '../../graph/types.js'; import { computeReachingDefs, type ReachingDefsSolver } from '../cfg/reaching-defs.js'; @@ -124,6 +125,7 @@ export interface FileSummaryResult { * `isEmitSafeCfg`-filtered (the same `wellFormed` array fed to `emitFileTaint`). * Pure aside from the read-only graph lookup; never throws on valid input. */ + export function harvestFileSummaries( fnIndex: FunctionNodeIndex, cfgs: readonly FunctionCfg[], @@ -133,6 +135,7 @@ export function harvestFileSummaries( // U12: shared per-file memoized solver (harvest/taint bucket — no maxBlockVisits). solve: ReachingDefsSolver = computeReachingDefs, parsed?: ParsedFile, + refine: RefinementSolver = createFunctionRefinement, ): FileSummaryResult { const importIndex = buildTaintImportIndex(parsedImports, parsed); const summaries: FunctionSummary[] = []; @@ -147,7 +150,7 @@ export function harvestFileSummaries( } const defUse = solve(cfg, { maxFacts }); const matches = matchFunctionSites(cfg, spec, importIndex); - const harvested = harvestFunctionSummary(cfg, defUse, matches); + const harvested = harvestFunctionSummary(cfg, defUse, matches, refine(cfg)); if (harvested.status !== 'computed') { gaps++; continue; diff --git a/gitnexus/src/core/ingestion/taint/summary-harvest.ts b/gitnexus/src/core/ingestion/taint/summary-harvest.ts index 51e2da5f52..33be8eb255 100644 --- a/gitnexus/src/core/ingestion/taint/summary-harvest.ts +++ b/gitnexus/src/core/ingestion/taint/summary-harvest.ts @@ -63,7 +63,9 @@ import type { FunctionCfg, SiteRecord } from '../cfg/types.js'; import { pointKey, type FunctionDefUse, type ProgramPoint } from '../cfg/reaching-defs.js'; -import type { FunctionSiteMatches } from './match.js'; +import type { FunctionSiteMatches, MatchedSinkCall } from './match.js'; +import { createFunctionRefinement, type FunctionRefinement } from './guard-refinement.js'; +import { valueEffectKey } from './value-refinement.js'; import { sinkKindRank, sortSinkKinds, type SinkKind } from './source-sink-config.js'; import type { CallResult, @@ -129,6 +131,7 @@ export function harvestFunctionSummary( cfg: FunctionCfg, defUse: FunctionDefUse, matches: FunctionSiteMatches, + refinement: FunctionRefinement = createFunctionRefinement(cfg), ): HarvestResult { if (defUse.status !== 'computed') { return { status: 'coverage-gap', gapReason: defUse.status, facts: EMPTY_FACTS }; @@ -144,6 +147,25 @@ export function harvestFunctionSummary( const paramIndexOf = new Map(); paramBindings.forEach((e, paramIdx) => paramIndexOf.set(e.idx, paramIdx)); const paramCount = paramBindings.length; + // Legacy flattened ports cannot carry a new proof across an ambiguous formal. + const precisePorts = paramBindings.every((entry, index) => entry.b.formalIndex === index); + const effectAt = ( + block: number, + statement: number, + site: number, + argument: number, + param?: number, + ) => { + if (!precisePorts) return undefined; + const effect = refinement.argument( + block, + statement, + site, + argument, + param === undefined ? undefined : paramBindings[param]?.idx, + ); + return effect?.kind === 'unknown' ? undefined : effect; + }; // ── return points: source block of every `return` CFG edge ──────────────── // The M2 edge-kind invariant: a `return` edge's SOURCE block terminates in @@ -166,8 +188,13 @@ export function harvestFunctionSummary( // call-result seed (#2084 review P1-1): their result semantics are already // modelled (a sanitizer's result rides U2 exclusions; a sink returns void). const modeledSites = new Set(); + const matchedSinks = new Map>(); for (const sm of matches.statements) { const stmtKey = `${sm.blockIndex}:${sm.statementIndex}`; + const siteSinks = new Map(); + for (const sink of sm.sinks) + siteSinks.set(sink.siteIndex, [...(siteSinks.get(sink.siteIndex) ?? []), sink]); + matchedSinks.set(stmtKey, siteSinks); for (const s of sm.sinks) modeledSites.add(`${stmtKey}:${s.siteIndex}`); for (const s of sm.sanitizers) modeledSites.add(`${stmtKey}:${s.siteIndex}`); if (sm.sinks.length > 0) { @@ -433,6 +460,7 @@ export function harvestFunctionSummary( const sinkBySite = sinkPosBySite.get(useKey); const kindBySite = sinkKindByEntry.get(useKey); useStmt.sites?.forEach((site, siteIndex) => { + if (refinement.isPredicate(fact.use.blockIndex, fact.use.stmtIndex, siteIndex)) return; const argHits = occurrencesInArgs(site, b); for (const argPos of argHits) { const callLine = useStmt.line; @@ -445,13 +473,21 @@ export function harvestFunctionSummary( dest: { to: 'callArg', ...(tail ? { toCallee: tail } : {}), argIndex: argPos }, }); } else if (t.seedId >= 0) { - const caKey = `${t.seedId}:${callLine}:${argPos}:${tail ?? ''}`; + const valueEffect = effectAt( + fact.use.blockIndex, + fact.use.stmtIndex, + siteIndex, + argPos, + t.seedId, + ); + const caKey = `${t.seedId}:${callLine}:${argPos}:${tail ?? ''}:${valueEffectKey(valueEffect)}`; if (!paramCallArg.has(caKey)) { paramCallArg.set(caKey, { param: t.seedId, callLine, argIndex: argPos, ...(tail ? { calleeName: tail } : {}), + ...(valueEffect ? { valueEffect } : {}), }); } // Carry the sanitizer exclusions on the path INTO this call arg, @@ -461,13 +497,20 @@ export function harvestFunctionSummary( // Source-seeded: a generated source flowing into a call argument is // a fixpoint SEED (it taints the callee's param). One source kind // today ('remote-input'); when more exist the seed must carry it. - const scKey = `${callLine}:${argPos}:${tail ?? ''}`; + const valueEffect = effectAt( + fact.use.blockIndex, + fact.use.stmtIndex, + siteIndex, + argPos, + ); + const scKey = `${callLine}:${argPos}:${tail ?? ''}:${valueEffectKey(valueEffect)}`; if (!sourceCallArg.has(scKey)) { sourceCallArg.set(scKey, { sourceKind: 'remote-input', callLine, argIndex: argPos, ...(tail ? { calleeName: tail } : {}), + ...(valueEffect ? { valueEffect } : {}), }); } intersectKinds(sourceCallArgKinds, scKey, t.exclusions); @@ -484,10 +527,37 @@ export function harvestFunctionSummary( dest: { to: 'sink', sinkKind: kind }, }); } else if (t.seedId >= 0) { - const sKey = `${t.seedId}:${kind}`; + const sinkEntries = (matchedSinks.get(useKey)?.get(siteIndex) ?? []).filter( + (sink) => sink.entry.kind === kind && sink.argPositions.includes(argPos), + ); + const canRefine = + kind === 'command-injection' && + argPos === 0 && + site.spread === undefined && + !site.template && + refinement.defaultShell(fact.use.blockIndex, fact.use.stmtIndex, siteIndex) && + sinkEntries.length > 0 && + sinkEntries.every((sink) => sink.entry.inertCommandPrefixes); + const prefixes = canRefine + ? sinkEntries[0].entry.inertCommandPrefixes!.filter((prefix) => + sinkEntries.every((sink) => + sink.entry.inertCommandPrefixes!.includes(prefix), + ), + ) + : undefined; + const valueEffect = prefixes?.length + ? effectAt(fact.use.blockIndex, fact.use.stmtIndex, siteIndex, argPos, t.seedId) + : undefined; + const sKey = `${t.seedId}:${kind}:${valueEffectKey(valueEffect)}:${JSON.stringify(prefixes ?? [])}`; if (!paramSink.has(sKey)) { paramSink.add(sKey); - paramSinkOut.push({ param: t.seedId, sinkKind: kind }); + paramSinkOut.push({ + param: t.seedId, + sinkKind: kind, + ...(valueEffect && prefixes?.length + ? { valueEffect, inertCommandPrefixes: prefixes } + : {}), + }); } } } @@ -539,7 +609,10 @@ export function harvestFunctionSummary( ); const paramToSink = paramSinkOut.sort( - (a, b) => a.param - b.param || sinkKindRank(a.sinkKind) - sinkKindRank(b.sinkKind), + (a, b) => + a.param - b.param || + sinkKindRank(a.sinkKind) - sinkKindRank(b.sinkKind) || + valueEffectKey(a.valueEffect).localeCompare(valueEffectKey(b.valueEffect)), ); const sourceToReturn: SourceToReturn[] = diff --git a/gitnexus/src/core/ingestion/taint/summary-model.ts b/gitnexus/src/core/ingestion/taint/summary-model.ts index 386d3a9b91..cd92a7c291 100644 --- a/gitnexus/src/core/ingestion/taint/summary-model.ts +++ b/gitnexus/src/core/ingestion/taint/summary-model.ts @@ -34,6 +34,7 @@ */ import type { SinkKind, SourceKind } from './source-sink-config.js'; +import { valueEffectKey, type ValueEffect } from './value-refinement.js'; /** * Source-relative parameter index (0-based, in declaration order). A @@ -61,6 +62,7 @@ export type ParamIndex = number; * callees of one caller, never as the primary join key. */ export interface ParamToCallArg { + readonly valueEffect?: ValueEffect; readonly param: ParamIndex; readonly callLine: number; readonly argIndex: number; @@ -96,6 +98,8 @@ export interface ParamToReturn { /** `param i` reaches a modelled sink of kind `sinkKind` inside this function. */ export interface ParamToSink { + readonly valueEffect?: ValueEffect; + readonly inertCommandPrefixes?: readonly string[]; readonly param: ParamIndex; readonly sinkKind: SinkKind; } @@ -140,6 +144,7 @@ export interface CallResult { * procedural `source → sink` partial flow whose sink lives in the callee. */ export interface SourceToCallArg { + readonly valueEffect?: ValueEffect; readonly sourceKind: SourceKind; /** Carried for hop display + same-name tie-break; NOT the join key (see * {@link ParamToCallArg} — the solver joins by `calleeName`). */ @@ -227,17 +232,24 @@ export function ownFactsDigest( ...s.paramToCallArg .map( (c) => - `c:${c.param}:${c.callLine}:${c.argIndex}:${c.calleeName ?? ''}:${[...(c.neutralized ?? [])].sort().join(',')}`, + `c:${c.param}:${c.callLine}:${c.argIndex}:${c.calleeName ?? ''}:${[...(c.neutralized ?? [])].sort().join(',')}${c.valueEffect ? ':' + valueEffectKey(c.valueEffect) : ''}`, + ) + .sort(), + ); + parts.push( + ...s.paramToSink + .map( + (k) => + `k:${k.param}:${k.sinkKind}${k.valueEffect ? ':' + valueEffectKey(k.valueEffect) : ''}${k.inertCommandPrefixes ? ':' + JSON.stringify([...k.inertCommandPrefixes].sort()) : ''}`, ) .sort(), ); - parts.push(...s.paramToSink.map((k) => `k:${k.param}:${k.sinkKind}`).sort()); parts.push(...s.sourceToReturn.map((g) => `g:${g.sourceKind}`).sort()); parts.push( ...s.sourceToCallArg .map( (g) => - `s:${g.sourceKind}:${g.callLine}:${g.argIndex}:${g.calleeName ?? ''}:${[...(g.neutralized ?? [])].sort().join(',')}`, + `s:${g.sourceKind}:${g.callLine}:${g.argIndex}:${g.calleeName ?? ''}:${[...(g.neutralized ?? [])].sort().join(',')}${g.valueEffect ? ':' + valueEffectKey(g.valueEffect) : ''}`, ) .sort(), ); diff --git a/gitnexus/src/core/ingestion/taint/typescript-model.ts b/gitnexus/src/core/ingestion/taint/typescript-model.ts index 6ef39cca9d..0a0cbd9d71 100644 --- a/gitnexus/src/core/ingestion/taint/typescript-model.ts +++ b/gitnexus/src/core/ingestion/taint/typescript-model.ts @@ -40,8 +40,20 @@ export const TS_JS_TAINT_MODEL: SourceSinkSanitizerSpec = { sinks: [ // Command execution — shell strings are arg 0; argv-form APIs also treat // the argv array at arg 1 as command/option injection surface. - { name: 'exec', kind: 'command-injection', args: [0], module: 'child_process' }, - { name: 'execSync', kind: 'command-injection', args: [0], module: 'child_process' }, + { + name: 'exec', + kind: 'command-injection', + args: [0], + module: 'child_process', + inertCommandPrefixes: ['git log -1 ', 'git log -1 --format=%s ', 'git show '], + }, + { + name: 'execSync', + kind: 'command-injection', + args: [0], + module: 'child_process', + inertCommandPrefixes: ['git log -1 ', 'git log -1 --format=%s ', 'git show '], + }, { name: 'spawn', kind: 'command-injection', args: [0, 1], module: 'child_process' }, { name: 'spawnSync', kind: 'command-injection', args: [0, 1], module: 'child_process' }, { name: 'execFile', kind: 'command-injection', args: [0, 1], module: 'child_process' }, diff --git a/gitnexus/src/core/ingestion/taint/value-refinement.ts b/gitnexus/src/core/ingestion/taint/value-refinement.ts new file mode 100644 index 0000000000..ae1201d1c2 --- /dev/null +++ b/gitnexus/src/core/ingestion/taint/value-refinement.ts @@ -0,0 +1,245 @@ +/** A deliberately closed string domain. Unknown always preserves ordinary taint. */ +export interface StringRestriction { + readonly chars: string; + readonly min: number; + readonly max: number; +} + +/** Small, provider-normalized expression vocabulary; absent shape stays unknown. */ +export type ValueExpression = + | { readonly kind: 'unknown' | 'non-string' } + | { readonly kind: 'binding'; readonly binding: number } + | { readonly kind: 'literal'; readonly value: string } + | { readonly kind: 'concat'; readonly parts: readonly ValueExpression[] }; + +export interface StatementValueFacts { + readonly predicate?: { + readonly site?: number; + readonly subject: number; + readonly accepts: boolean; + readonly restriction: StringRestriction; + readonly establishesPrimitive?: boolean; + }; + readonly definitions?: readonly { readonly binding: number; readonly value: ValueExpression }[]; + readonly calls?: readonly { + readonly site: number; + readonly arguments: readonly ValueExpression[]; + readonly defaultShell?: boolean; + }[]; +} + +export type ValueEffect = + | { readonly kind: 'unknown' | 'input' | 'non-string' } + | { readonly kind: 'literal'; readonly value: string } + | { readonly kind: 'concat'; readonly parts: readonly ValueEffect[] } + | { + readonly kind: 'restrict'; + readonly value: ValueEffect; + readonly restriction: StringRestriction; + }; + +export type RefinedValue = + | { readonly kind: 'unknown' | 'non-string' } + | { readonly kind: 'string'; readonly parts: readonly (string | StringRestriction)[] }; + +export const UNKNOWN_VALUE: RefinedValue = Object.freeze({ kind: 'unknown' }); +export const MAX_VALUE_NODES = 32; +export const MAX_VALUE_BYTES = 256; + +function validRestriction(value: StringRestriction): boolean { + return ( + typeof value?.chars === 'string' && + value.chars.length > 0 && + value.chars.length <= 128 && + [...value.chars].every((c) => c.charCodeAt(0) < 128) && + Number.isInteger(value.min) && + Number.isInteger(value.max) && + value.min >= 0 && + value.max >= value.min && + value.max <= MAX_VALUE_BYTES + ); +} + +/** Parse a linear, fully anchored ASCII subset; never execute a repository regex. */ +export function parseAnchoredAsciiPattern( + pattern: string, + flags: string, +): StringRestriction | undefined { + if ( + flags !== '' || + pattern.length > MAX_VALUE_BYTES || + !pattern.startsWith('^') || + !pattern.endsWith('$') + ) + return; + const body = pattern.slice(1, -1); + let index = 0; + let min = 0; + let max = 0; + const alphabet = new Set(); + while (index < body.length) { + const chars: string[] = []; + if (body[index] === '[') { + const end = body.indexOf(']', index + 1); + if (end < 0) return; + const raw = body.slice(index + 1, end); + if (!raw || /[^A-Za-z0-9-]/.test(raw)) return; + for (let i = 0; i < raw.length; i++) { + if (raw[i] === '-') return; + if (raw[i + 1] === '-') { + const first = raw.charCodeAt(i); + const last = raw.charCodeAt(i + 2); + if (!Number.isFinite(last) || last < first || last - first > 127) return; + for (let c = first; c <= last; c++) chars.push(String.fromCharCode(c)); + i += 2; + } else chars.push(raw[i]); + } + index = end + 1; + } else { + const char = body[index++]; + if (!/[A-Za-z0-9]/.test(char)) return; + chars.push(char); + } + let lo = 1; + let hi = 1; + if (body[index] === '{') { + const end = body.indexOf('}', index); + if (end < 0) return; + const match = /^(\d{1,3})(?:,(\d{1,3}))?$/.exec(body.slice(index + 1, end)); + if (!match) return; + lo = Number(match[1]); + hi = Number(match[2] ?? match[1]); + if (hi < lo || hi > MAX_VALUE_BYTES) return; + index = end + 1; + } + min += lo; + max += hi; + if (max > MAX_VALUE_BYTES) return; + for (const char of chars) alphabet.add(char); + } + if (alphabet.size === 0 || min === 0) return; + return { chars: [...alphabet].sort().join(''), min, max }; +} + +/** A bounded transfer. Missing, malformed, oversized and incompatible effects are unknown. */ +export function applyValueEffect( + effect: ValueEffect | undefined, + input: RefinedValue, +): RefinedValue { + // A contradicted primitive contract must not revive at a later typed boundary. + if (input.kind === 'non-string') return input; + let remaining = MAX_VALUE_NODES; + let exhausted = false; + const visit = (node: ValueEffect | undefined): RefinedValue => { + if (!node) return UNKNOWN_VALUE; + if (--remaining < 0) { + exhausted = true; + return UNKNOWN_VALUE; + } + switch (node.kind) { + case 'input': + return input; + case 'non-string': + return { kind: 'non-string' }; + case 'unknown': + return UNKNOWN_VALUE; + case 'literal': + return typeof node.value === 'string' && node.value.length <= MAX_VALUE_BYTES + ? { kind: 'string', parts: [node.value] } + : UNKNOWN_VALUE; + case 'restrict': { + if (!validRestriction(node.restriction)) return UNKNOWN_VALUE; + const prior = visit(node.value); + return prior.kind === 'non-string' ? prior : { kind: 'string', parts: [node.restriction] }; + } + case 'concat': { + if (!Array.isArray(node.parts) || node.parts.length > MAX_VALUE_NODES) return UNKNOWN_VALUE; + const parts: (string | StringRestriction)[] = []; + let bytes = 0; + for (const part of node.parts) { + const value = visit(part); + if (value.kind !== 'string') return value; + for (const segment of value.parts) { + bytes += typeof segment === 'string' ? segment.length : segment.max; + if (bytes > MAX_VALUE_BYTES || parts.length >= MAX_VALUE_NODES) return UNKNOWN_VALUE; + if (typeof segment === 'string' && typeof parts.at(-1) === 'string') { + parts[parts.length - 1] = String(parts.at(-1)) + segment; + } else parts.push(segment); + } + } + return { kind: 'string', parts }; + } + default: + return UNKNOWN_VALUE; + } + }; + const result = visit(effect); + return exhausted ? UNKNOWN_VALUE : result; +} + +/** Guarantees weaken across routes. Different shapes widen immediately (including recursion). */ +export function joinRefinedValues(left: RefinedValue, right: RefinedValue): RefinedValue { + if (left.kind === 'non-string') return left; + if (right.kind === 'non-string') return right; + if (left.kind !== 'string' || right.kind !== 'string') { + return UNKNOWN_VALUE; + } + if (left.parts.length !== right.parts.length) return UNKNOWN_VALUE; + const parts: (string | StringRestriction)[] = []; + for (let i = 0; i < left.parts.length; i++) { + const a = left.parts[i]; + const b = right.parts[i]; + if (typeof a === 'string' || typeof b === 'string') { + if (a !== b) return UNKNOWN_VALUE; + parts.push(a); + } else { + parts.push({ + chars: [...new Set(a.chars + b.chars)].sort().join(''), + min: Math.min(a.min, b.min), + max: Math.max(a.max, b.max), + }); + } + } + return { kind: 'string', parts }; +} + +/** Operation/argument roles, not a blanket executable exemption. */ +export function provesInertCommand(value: RefinedValue, prefixes: readonly string[]): boolean { + if (value.kind !== 'string' || value.parts.length !== 2) return false; + const [prefix, argument] = value.parts; + return ( + typeof prefix === 'string' && + prefixes.includes(prefix) && + typeof argument !== 'string' && + validRestriction(argument) && + argument.min > 0 && + // ASCII letters/digits cannot introduce a shell operator, whitespace or option. + /^[A-Za-z0-9]+$/.test(argument.chars) + ); +} + +/** Canonical bounded identity, independent of JSON property insertion order. */ +export function valueEffectKey(effect: ValueEffect | undefined): string { + if (!effect) return ''; + let remaining = MAX_VALUE_NODES; + const encode = (value: ValueEffect): unknown => { + if (--remaining < 0) return '?'; + switch (value.kind) { + case 'literal': + return ['literal', value.value]; + case 'concat': + return ['concat', ...value.parts.map(encode)]; + case 'restrict': + return [ + 'restrict', + encode(value.value), + [...new Set(value.restriction.chars)].sort().join(''), + value.restriction.min, + value.restriction.max, + ]; + default: + return [value.kind]; + } + }; + return JSON.stringify(encode(effect)); +} diff --git a/gitnexus/src/core/lbug/extension-loader.ts b/gitnexus/src/core/lbug/extension-loader.ts index 575b3587d9..93a922769f 100644 --- a/gitnexus/src/core/lbug/extension-loader.ts +++ b/gitnexus/src/core/lbug/extension-loader.ts @@ -13,6 +13,7 @@ import { nodePlatformTuple, resolveFtsVersionPair, resolveVendoredFtsPath, + resolveVendoredVectorPath, } from './vendored-extension-path.js'; import { logger } from '../logger.js'; @@ -219,8 +220,8 @@ export const installDuckDbExtensionOutOfProcess = async ( * Centralized lifecycle manager for optional LadybugDB extensions. * * Tries `LOAD` first — it is per-connection, idempotent, and never - * touches the network. For FTS, a packaged vendored path is path-LOADed - * before the named `LOAD EXTENSION fts`. If `LOAD` fails and the active + * touches the network. For FTS and VECTOR, a packaged vendored path is + * path-LOADed before the named `LOAD EXTENSION`. If `LOAD` fails and the active * policy permits, the manager runs a single bounded out-of-process * `INSTALL` attempt per process and retries `LOAD`. Capability outcomes * are cached so unavailable extensions degrade search features without @@ -289,10 +290,13 @@ export class ExtensionManager { return false; } - if (name === 'fts') { + const isVector = name.toLowerCase() === 'vector'; + if (name === 'fts' || isVector) { const tuple = opts.platformTuple ?? nodePlatformTuple(); const vendorRoot = opts.vendorRoot ?? defaultVendorRoot(); - const vendored = resolveVendoredFtsPath({ vendorRoot, tuple }); + const vendored = isVector + ? resolveVendoredVectorPath({ vendorRoot, tuple }) + : resolveVendoredFtsPath({ vendorRoot, tuple }); if (vendored) { attempts.push({ source: 'vendored', tuple }); const vendoredError = await this.tryLoadPath(query, vendored); @@ -301,7 +305,7 @@ export class ExtensionManager { return true; } lastInspectPath = vendored; - } else if (isUnsupportedFtsTuple(tuple, vendorRoot)) { + } else if (name === 'fts' && isUnsupportedFtsTuple(tuple, vendorRoot)) { attempts.push({ source: 'vendored', tuple }); this.markUnavailable( name, diff --git a/gitnexus/src/core/lbug/native-check.ts b/gitnexus/src/core/lbug/native-check.ts index 7f4d81b3fe..33d7e8e5d5 100644 --- a/gitnexus/src/core/lbug/native-check.ts +++ b/gitnexus/src/core/lbug/native-check.ts @@ -3,7 +3,7 @@ import path from 'path'; import { createRequire } from 'node:module'; import { spawnSync, type SpawnSyncReturns } from 'node:child_process'; import { escapeCypherString } from './cypher-escape.js'; -import { resolveVendoredFtsPath } from './vendored-extension-path.js'; +import { resolveVendoredFtsPath, resolveVendoredVectorPath } from './vendored-extension-path.js'; /** Cap the out-of-process native load probe so a hung filesystem cannot wedge a * CLI startup gate (same bounding rationale as the extension probe below). */ @@ -505,7 +505,7 @@ export async function probeFtsExtensionLoad( export async function probeVectorExtensionLoad( timeoutMs: number = DEFAULT_FTS_PROBE_TIMEOUT_MS, ): Promise { - return await probeExtensionLoad('vector', timeoutMs); + return await probeExtensionLoad('vector', timeoutMs, resolveVendoredVectorPath()); } /** @@ -529,7 +529,7 @@ async function probeExtensionLoad( }); const statements: string[] = []; - if (extension === 'fts' && vendoredPath) { + if (vendoredPath) { statements.push(`LOAD EXTENSION '${escapeCypherString(path.resolve(vendoredPath))}'`); } statements.push(`LOAD EXTENSION ${extension}`); diff --git a/gitnexus/src/core/lbug/vendored-extension-path.ts b/gitnexus/src/core/lbug/vendored-extension-path.ts index ce57069819..b18bb51f98 100644 --- a/gitnexus/src/core/lbug/vendored-extension-path.ts +++ b/gitnexus/src/core/lbug/vendored-extension-path.ts @@ -130,3 +130,21 @@ export const resolveVendoredFtsPath = (opts?: { if (!existsSync(candidate)) return null; return validateVendoredExtensionPath(candidate, vendorRoot); }; + +/** VECTOR builds must match the core pin; the CDN's compatibility path can drift. */ +export const resolveVendoredVectorPath = (opts?: { + tuple?: string; + vendorRoot?: string; +}): string | null => { + const vendorRoot = opts?.vendorRoot ?? defaultVendorRoot(); + const tuple = opts?.tuple ?? nodePlatformTuple(); + const candidate = path.resolve( + vendorRoot, + 'lbug-vector', + 'prebuilds', + tuple, + 'libvector.lbug_extension', + ); + if (!existsSync(candidate)) return null; + return validateVendoredExtensionPath(candidate, vendorRoot); +}; diff --git a/gitnexus/src/core/wiki/generator.ts b/gitnexus/src/core/wiki/generator.ts index d1f3aaabc7..92e656fce4 100644 --- a/gitnexus/src/core/wiki/generator.ts +++ b/gitnexus/src/core/wiki/generator.ts @@ -904,9 +904,11 @@ export class WikiGenerator { const overviewEnd = content.indexOf('### Architecture'); const overview = overviewEnd > 0 ? content.slice(0, overviewEnd).trim() : content.slice(0, 800).trim(); - childDocs.push(`#### ${child.name}\n${overview}`); + childDocs.push(`#### ${child.name} (\`${child.slug}.md\`)\n${overview}`); } catch { - childDocs.push(`#### ${child.name}\n(Documentation not yet generated)`); + childDocs.push( + `#### ${child.name} (\`${child.slug}.md\`)\n(Documentation not yet generated)`, + ); } } @@ -944,9 +946,9 @@ export class WikiGenerator { const overviewEnd = content.indexOf('### Architecture'); const overview = overviewEnd > 0 ? content.slice(0, overviewEnd).trim() : content.slice(0, 600).trim(); - moduleSummaries.push(`#### ${node.name}\n${overview}`); + moduleSummaries.push(`#### ${node.name} (\`${node.slug}.md\`)\n${overview}`); } catch { - moduleSummaries.push(`#### ${node.name}\n(Documentation pending)`); + moduleSummaries.push(`#### ${node.name} (\`${node.slug}.md\`)\n(Documentation pending)`); } } diff --git a/gitnexus/src/core/wiki/mermaid-sanitizer.ts b/gitnexus/src/core/wiki/mermaid-sanitizer.ts index c8d443c782..74198ea6fb 100644 --- a/gitnexus/src/core/wiki/mermaid-sanitizer.ts +++ b/gitnexus/src/core/wiki/mermaid-sanitizer.ts @@ -6,9 +6,37 @@ const UNSAFE_EDGE_LABEL_RE = /[()[\]{}<>]/; const UNSAFE_NODE_ID_RE = /[^A-Za-z0-9_-]/; const NODE_ID_RE = /^[A-Za-z0-9_.:/()-]+$/; -const LINE_PREFIX_RE = /^(\s*(?:(?:[-A-Za-z0-9_]+)\s*:\s*)?)(.*)$/; -const EDGE_RE = - /(\s*(?:[ox])?(?:--+|==+|\.\.+)(?:[>|ox])?\|[^|\n]*\|(?:[>|ox])?|\s*(?:[ox])?(?:--+|==+|\.\.+)(?:[>|ox])?|\s*<--+>?\s*)/g; +const LINE_PREFIX_RE = /^(\s*)(.*)$/; +// One link between two node references, in the forms Mermaid accepts: a +// plain, thick or dotted link (`-->`, `===`, `-.->`), a piped label after it +// (`-->|text|`), or a label inside it (`-- text -->`, `== text ==>`, +// `-. text .->`). The labelled forms are matched whole, so their text is +// never taken for a node reference (#3705). Dots mean a link only in the +// dotted syntax: a plain run of dots is text. +// +// A labelled link opens with a bare `--`, `==` or `-.` followed by its text, +// with or without a space (`-- text -->`, `--text-->`). A complete link never +// opens one. Mermaid's lexer takes the longer match, so `--` followed by +// `-`, `>`, `x` or `o` is a link with a tail (`---`, `-->`, `--x`, `--o`), +// whatever comes after it: `A --xfile.ts --> B` is a chain of three nodes, +// and `file.ts` reaches the node sanitizer like any other reference. +const LINK_HEAD = '(?:--+|==+|-\\.+-?)'; +const LABEL_OPENER = '(?:--|==|-\\.)(?![-=.>|xo])'; +const EDGE_RE = new RegExp( + '(' + + [ + // `-- text -->`, `--text-->`, `== text ==>`, `-. text .->` + `\\s*(?:[ox<])?${LABEL_OPENER}[^\\n]*?\\s*(?:--+|==+|\\.+-+)(?:[>ox])?`, + // `-->|text|` + `\\s*(?:[ox<])?${LINK_HEAD}(?:[>|ox])?\\|[^|\\n]*\\|(?:[>|ox])?`, + // `-->`, `---`, `-.->`, `==>` + `\\s*(?:[ox<])?${LINK_HEAD}(?:[>|ox])?`, + '\\s*<--+>?\\s*', + ].join('|') + + ')', + 'g', +); +const EDGE_AT_RE = new RegExp(EDGE_RE.source, 'y'); export function sanitizeMermaidMarkdown(markdown: string): string { return markdown.replace(MERMAID_FENCE_RE, (_match, diagram: string) => { @@ -17,50 +45,191 @@ export function sanitizeMermaidMarkdown(markdown: string): string { } export function sanitizeMermaidDiagram(diagram: string): string { + const frontmatter = diagram.match(/^\s*---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/)?.[0] ?? ''; + const body = diagram.slice(frontmatter.length); + const prelude = body.match(/^(?:\s|%%\{[\s\S]*?\}%%|%%[^\n]*(?:\n|$))*/)?.[0] ?? ''; + const content = body.slice(prelude.length); + if (!/^(?:graph|flowchart)\s/.test(content)) return diagram; + + // Mask before splitting lines so multiline labels remain a single token. + const { masked, labels } = maskLabels(content); + const lines = masked.split('\n'); + const usedIds = new Set(); + const labeledIds = new Set(); + for (const line of lines) { + sanitizeMermaidLine( + line, + (id, hasLabel) => { + usedIds.add(id); + if (hasLabel) labeledIds.add(id); + return id; + }, + labeledIds, + labels, + ); + } const aliases = new Map(); let nextAlias = 1; const aliasFor = (id: string): string => { + if (!UNSAFE_NODE_ID_RE.test(id)) return id; const existing = aliases.get(id); if (existing) return existing; - const base = id.replace(/[^A-Za-z0-9_-]/g, '_').replace(/^_+|_+$/g, '') || 'node'; + let base = id.replace(/[^A-Za-z0-9_-]/g, '_').replace(/^_+|_+$/g, '') || 'node'; + if ( + /^(?:style|classDef|class|click|linkStyle|direction|accTitle|accDescr|end)(?:-|$)/.test(base) + ) { + base = `node_${base}`; + } let alias = base; - while ([...aliases.values()].includes(alias)) { + while (usedIds.has(alias)) { nextAlias += 1; alias = `${base}_${nextAlias}`; } aliases.set(id, alias); + usedIds.add(alias); return alias; }; - return diagram - .split('\n') - .map((line) => sanitizeMermaidLine(line, aliasFor)) - .join('\n'); + return ( + frontmatter + + prelude + + lines + .map((line) => unmaskLabels(sanitizeMermaidLine(line, aliasFor, labeledIds, labels), labels)) + .join('\n') + ); } -function sanitizeMermaidLine(line: string, aliasFor: (id: string) => string): string { - let sanitized = replaceLiteralLineBreaksInLabels(line); - sanitized = quoteUnsafeEdgeLabels(sanitized); - - const prefixMatch = sanitized.match(LINE_PREFIX_RE); - if (!prefixMatch) return sanitized; +function sanitizeMermaidLine( + line: string, + aliasFor: (id: string, hasLabel?: boolean) => string, + labeledIds: ReadonlySet, + labels: string[], +): string { + const prefixMatch = line.match(LINE_PREFIX_RE); + if (!prefixMatch) return line; const prefix = prefixMatch[1]; const body = prefixMatch[2]; - if (isDirectiveLine(body)) return sanitized; + const header = body.match(/^((?:graph|flowchart)\s+\w+\s*;)(.*)$/); + if (header) { + return prefix + header[1] + sanitizeMermaidLine(header[2], aliasFor, labeledIds, labels); + } + const reference = body.match(/^((?:style|class|click)\s+)([^\s]+)(.*)$/); + if (reference) { + const ids = reference[2].split(',').map((id) => aliasFor(id)); + return prefix + reference[1] + ids.join(',') + reference[3]; + } + const subgraph = body.match(/^(subgraph\s+)([A-Za-z0-9_.:/-]+)(\s*(?:\[.*\])?\s*)$/); + if (subgraph) { + const [, keyword, id, suffix] = subgraph; + const alias = aliasFor(id, true); + const label = alias !== id && !suffix.trim() ? `["${escapeMermaidLabel(id)}"]` : ''; + return prefix + keyword + alias + label + suffix; + } + if (isDirectiveLine(body)) return line; + // Text inside quotes and inside node shapes is a label, not syntax: it is + // hidden from the split so a `...` or a `--` in it cannot read as a link, + // and from the node sanitizer so it cannot read as a node (#3705). const parts = body.split(EDGE_RE); - if (parts.length === 1) return sanitized; - for (let i = 0; i < parts.length; i += 2) { - parts[i] = sanitizeNodeReference(parts[i], aliasFor); + for (let i = 0; i < parts.length; i += 1) { + if (i % 2 === 1) { + parts[i] = quoteUnsafeEdgeLabels(unmaskLabels(parts[i], labels)); + } else { + const nodes = parts[i].split(/([&;])/); + for (let j = 0; j < nodes.length; j += 2) { + nodes[j] = sanitizeNodeReference(nodes[j], aliasFor, labels, labeledIds); + } + parts[i] = replaceLiteralLineBreaksInLabels(unmaskLabels(nodes.join(''), labels)); + } } return prefix + parts.join(''); } +const MASK = '\u0000'; +const MASK_RE = /\u0000(\d+)\u0000/g; +const OPENERS: Record = { '[': ']', '(': ')', '{': '}' }; + +/** + * Replace the inside of every quoted string and every bracketed label with a + * placeholder, keeping the delimiters, so the shape of the line survives and + * the node sanitizer still sees where an inline label starts. + */ +function maskLabels(body: string): { masked: string; labels: string[] } { + const labels: string[] = []; + // Protect quoted link text before recognising links; a quoted arrow is text. + body = body.replace(/%%[^\n]*|"[^"]*"/g, (quoted) => { + if (quoted.startsWith('%%')) return quoted; + const index = labels.push(quoted.slice(1, -1)) - 1; + return '"' + MASK + index + MASK + '"'; + }); + let masked = ''; + let i = 0; + while (i < body.length) { + if (body.startsWith('%%', i)) { + const end = body.indexOf('\n', i); + const next = end === -1 ? body.length : end; + masked += body.slice(i, next); + i = next; + continue; + } + // Consume complete links before looking for shapes. A `>` in List + // belongs to the link label, not to an asymmetric node shape. + EDGE_AT_RE.lastIndex = i; + const edge = EDGE_AT_RE.exec(body); + if (edge) { + masked += edge[0]; + i += edge[0].length; + continue; + } + const char = body[i]; + const closer = + OPENERS[char] ?? (char === '>' && /[A-Za-z0-9_]/.test(body[i - 1] ?? '') ? ']' : undefined); + if (closer) { + const end = findLabelEnd(body, i, closer, char); + if (end === -1) { + masked += body.slice(i); + break; + } + masked += char + MASK + labels.length + MASK + body[end]; + labels.push(unmaskLabels(body.slice(i + 1, end), labels)); + i = end + 1; + continue; + } + masked += char; + i += 1; + } + return { masked, labels }; +} + +/** Index of the delimiter that closes the one at `start`, or -1. */ +function findLabelEnd(body: string, start: number, closer: string, opener: string): number { + let depth = 0; + for (let i = start + 1; i < body.length; i += 1) { + const char = body[i]; + if (char === '"') { + const quoteEnd = body.indexOf('"', i + 1); + if (quoteEnd === -1) return -1; + i = quoteEnd; + continue; + } + if (char === opener && opener !== '>') depth += 1; + else if (char === closer) { + if (depth === 0) return i; + depth -= 1; + } + } + return -1; +} + +function unmaskLabels(masked: string, labels: string[]): string { + return masked.replace(MASK_RE, (_match, index: string) => labels[Number(index)] ?? ''); +} + function replaceLiteralLineBreaksInLabels(line: string): string { return line.replace(NODE_LABEL_RE, (label) => label.replace(/\\n/g, '
')); } @@ -79,22 +248,57 @@ function quoteUnsafeEdgeLabels(line: string): string { }); } -function sanitizeNodeReference(segment: string, aliasFor: (id: string) => string): string { - const match = segment.match(/^(\s*)([A-Za-z0-9_.:/()-]+)(.*?)(\s*)$/); +// A masked, empty pair of parentheses right after an id: `doc()`, a +// call-shaped id the sanitizer has always repaired, not a round node. The +// member chain that may follow (`foo().bar`) belongs to the same id. +const EMPTY_PARENS_RE = /^\(\u0000(\d+)\u0000\)/; +const MEMBER_CHAIN_RE = /^(?:(?!:::)[A-Za-z0-9_.:/-])+/; + +function sanitizeNodeReference( + segment: string, + aliasFor: (id: string, hasLabel?: boolean) => string, + labels: string[], + labeledIds: ReadonlySet, +): string { + // The id stops where a node shape opens (`[`, `(`, `{`): `A(Start)` is the + // node `A` with a round label, and the label is already masked. + const match = segment.match(/^(\s*)((?:(?!:::)[A-Za-z0-9_.:/-])+)(.*?)(\s*)$/); if (!match) return segment; - const [, leading, id, suffix, trailing] = match; - if (!NODE_ID_RE.test(id) || !UNSAFE_NODE_ID_RE.test(id)) return segment; - const hasInlineLabel = - suffix.trim().startsWith('[') || suffix.trim().startsWith('(') || suffix.trim().startsWith('{'); + const leading = match[1]; + const trailing = match[4]; + let id = match[2]; + let suffix = match[3]; + for (;;) { + const emptyParens = suffix.match(EMPTY_PARENS_RE); + if (!emptyParens || labels[Number(emptyParens[1])] !== '') break; + id += '()'; + suffix = suffix.slice(emptyParens[0].length); + const members = suffix.match(MEMBER_CHAIN_RE); + if (members) { + id += members[0]; + suffix = suffix.slice(members[0].length); + } + } + if (!NODE_ID_RE.test(id)) return segment; + const hasInlineLabel = /^[\[({>]/.test(suffix.trim()) || suffix.trim().startsWith('@{'); + const alias = aliasFor(id, hasInlineLabel); + if (!UNSAFE_NODE_ID_RE.test(id)) return segment; - if (hasInlineLabel) return `${leading}${aliasFor(id)}${suffix}${trailing}`; + const metadata = suffix.match(/^\s*@\{\u0000(\d+)\u0000\}/); + if (metadata) { + const content = labels[Number(metadata[1])]; + if (!/(?:^|,)\s*label\s*:/.test(content.replace(/"[^"]*"|'[^']*'/g, ''))) { + suffix = suffix.replace(metadata[0], `@{ label: "${escapeMermaidLabel(id)}", ${content} }`); + } + } + if (hasInlineLabel || labeledIds.has(id)) return `${leading}${alias}${suffix}${trailing}`; - return `${leading}${aliasFor(id)}["${escapeMermaidLabel(id)}"]${suffix}${trailing}`; + return `${leading}${alias}["${escapeMermaidLabel(id)}"]${suffix}${trailing}`; } function escapeMermaidLabel(label: string): string { - return label.replace(/\\/g, '\\\\').replace(/"/g, '\\"'); + return label.replace(/"/g, '#quot;'); } function isDirectiveLine(line: string): boolean { @@ -104,16 +308,10 @@ function isDirectiveLine(line: string): boolean { trimmed.startsWith('%%') || trimmed.startsWith('graph ') || trimmed.startsWith('flowchart ') || - trimmed.startsWith('sequenceDiagram') || - trimmed.startsWith('classDiagram') || - trimmed.startsWith('stateDiagram') || - trimmed.startsWith('erDiagram') || - trimmed.startsWith('journey') || - trimmed.startsWith('gantt') || - trimmed.startsWith('pie ') || - trimmed.startsWith('mindmap') || - trimmed.startsWith('timeline') || trimmed.startsWith('subgraph ') || + /^(?:style|classDef|class|click|linkStyle|direction|accTitle|accDescr)(?:\s|:|$)/.test( + trimmed, + ) || trimmed === 'end' ); } diff --git a/gitnexus/src/core/wiki/prompts.ts b/gitnexus/src/core/wiki/prompts.ts index 57c19077e8..29b64bd518 100644 --- a/gitnexus/src/core/wiki/prompts.ts +++ b/gitnexus/src/core/wiki/prompts.ts @@ -83,7 +83,7 @@ Shared execution flows: {{CROSS_PROCESSES}} --- -Write a concise overview of this module group. Explain its purpose, how the sub-modules fit together, and the key workflows that span them. Link to sub-module pages (e.g. \`[Sub-module Name](sub-module-slug.md)\`) rather than repeating their content. Use whatever structure fits best.`; +Write a concise overview of this module group. Explain its purpose, how the sub-modules fit together, and the key workflows that span them. Link to sub-module pages using the exact file names given (e.g. \`[Sub-module Name](sub-module-slug.md)\`) rather than repeating their content. Use whatever structure fits best.`; // ─── Overview Prompt ────────────────────────────────────────────────── @@ -115,7 +115,7 @@ Key system flows: {{TOP_PROCESSES}} --- -Write a clear overview of this project: what it does, how it's architected, and the key end-to-end flows. Include a simple Mermaid architecture diagram (max 10 nodes, big-picture only). Link to module pages (e.g. \`[Module Name](module-slug.md)\`) naturally in the text rather than listing them in a table. If project config was provided, include brief setup instructions. Structure the page however reads best.`; +Write a clear overview of this project: what it does, how it's architected, and the key end-to-end flows. Include a simple Mermaid architecture diagram (max 10 nodes, big-picture only). Link to module pages naturally in the text using the exact file names given (e.g. \`[Module Name](module-slug.md)\`) rather than listing them in a table. If project config was provided, include brief setup instructions. Structure the page however reads best.`; // ─── Template Substitution Helper ───────────────────────────────────── diff --git a/gitnexus/src/mcp/local/local-backend.ts b/gitnexus/src/mcp/local/local-backend.ts index 6ca3a967a5..c993efeba2 100644 --- a/gitnexus/src/mcp/local/local-backend.ts +++ b/gitnexus/src/mcp/local/local-backend.ts @@ -32,6 +32,7 @@ import { getLbugDbIdentity, } from '../../core/lbug/pool-adapter.js'; import { queryClassBeanMetadata } from './bean-metadata.js'; +import { GUARD_TAINT_LIMITATION } from '../taint-limitations.js'; import { querySpringAopMetadata } from './aop-metadata.js'; import { SYMBOL_IDENTITY_RECOVERY_SUGGESTION, @@ -6279,7 +6280,10 @@ export class LocalBackend { findings: pageFindings, totalFindings: totalFindings + interprocTotal, ...(truncated ? { truncated: true } : {}), - note: 'Intra-procedural (TAINTED, statement hops) AND cross-function (TAINT_PATH, function hops, `interprocedural: true`) flows are modeled, including sources read inside inline callbacks and returned handlers. Captured closure-variable, property/field, and implicit flows are NOT modeled; absence of a finding is not proof of safety. Cross-function findings are context-insensitive and may over-attribute among same-named callees. All line numbers are 1-based; for cross-function findings, `source.line`, `sink.line` and `hops[].line` are the declaration lines of the functions, not statement lines. SANITIZES (kill) edges are queryable via cypher.', + note: + 'Intra-procedural (TAINTED, statement hops) AND cross-function (TAINT_PATH, function hops, `interprocedural: true`) flows are modeled, including sources read inside inline callbacks and returned handlers. Captured closure-variable, property/field, and implicit flows are NOT modeled; absence of a finding is not proof of safety. ' + + GUARD_TAINT_LIMITATION + + ' Cross-function findings are context-insensitive and may over-attribute among same-named callees. All line numbers are 1-based; for cross-function findings, `source.line`, `sink.line` and `hops[].line` are the declaration lines of the functions, not statement lines. SANITIZES (kill) edges are queryable via cypher.', }; } diff --git a/gitnexus/src/mcp/taint-limitations.ts b/gitnexus/src/mcp/taint-limitations.ts new file mode 100644 index 0000000000..0b31fcd5fd --- /dev/null +++ b/gitnexus/src/mcp/taint-limitations.ts @@ -0,0 +1,2 @@ +export const GUARD_TAINT_LIMITATION = + 'Modeled guards can refine unchanged primitive-string values for reviewed sink uses. Imported and wrapper validators, reassigned values, and unsupported predicates or sink uses remain conservative findings. Declared string types are analysis assumptions, not runtime validation.'; diff --git a/gitnexus/src/mcp/tools.ts b/gitnexus/src/mcp/tools.ts index 4efd832957..9d30cf4abc 100644 --- a/gitnexus/src/mcp/tools.ts +++ b/gitnexus/src/mcp/tools.ts @@ -7,6 +7,7 @@ import type { ToolAnnotations } from '@modelcontextprotocol/sdk/types.js'; import { REL_TYPES } from 'gitnexus-shared'; +import { GUARD_TAINT_LIMITATION } from './taint-limitations.js'; import { CONTEXT_RELATION_TYPES, CONTEXT_RESPONSE_SECTIONS, @@ -751,7 +752,8 @@ CONTRACT CAVEATS (absent flows are NOT proof of safety): - Cross-function matching is by callee NAME (context-insensitive): when one caller invokes two distinct same-named callees, a flow into one over-attributes to both — a cross-function finding does not prove the taint reached every same-named function (sound over-report, never a missed flow). - Sources read inside inline callbacks and returned handlers can flow through helper functions. Captured closure-variable flows are not modeled (e.g. const y = source(); arr.forEach(() => sink(y))). - Property/field flows are not tracked (obj.x = taint; sink(obj.y) has no chain). -- Guard-style sanitizers (if (isValid(x))) and implicit/control-dependence flows are not modeled. +- ${GUARD_TAINT_LIMITATION} +- Implicit/control-dependence flows are not modeled. - CommonJS aliasing is partially modeled (require('') joins resolve; dynamic requires do not). - Exception-path over-approximation can produce false-positive noise. diff --git a/gitnexus/test/helpers/cfg-harness.ts b/gitnexus/test/helpers/cfg-harness.ts index eb7b5c04c4..9c894626c5 100644 --- a/gitnexus/test/helpers/cfg-harness.ts +++ b/gitnexus/test/helpers/cfg-harness.ts @@ -53,17 +53,22 @@ export function makeCfgHarness( }; const cfgOf = (code: string, index = 0): FunctionCfg => { - const fn = collectFunctions(parse(code))[index]; + const root = parse(code); + const bound = visitor.forFile?.(root, filePath) ?? visitor; + const fn = collectFunctions(root)[index]; if (!fn) throw new Error(`no function at index ${index}`); - const cfg = visitor.buildFunctionCfg(fn, filePath); + const cfg = bound.buildFunctionCfg(fn, filePath); if (!cfg) throw new Error('buildFunctionCfg returned undefined'); return cfg; }; - const cfgsOf = (code: string): FunctionCfg[] => - collectFunctions(parse(code)) - .map((fn) => visitor.buildFunctionCfg(fn, filePath)) + const cfgsOf = (code: string): FunctionCfg[] => { + const root = parse(code); + const bound = visitor.forFile?.(root, filePath) ?? visitor; + return collectFunctions(root) + .map((fn) => bound.buildFunctionCfg(fn, filePath)) .filter((c): c is FunctionCfg => c !== undefined); + }; return { parse, collectFunctions, cfgOf, cfgsOf }; } diff --git a/gitnexus/test/integration/cfg/guard-taint.test.ts b/gitnexus/test/integration/cfg/guard-taint.test.ts new file mode 100644 index 0000000000..f478916516 --- /dev/null +++ b/gitnexus/test/integration/cfg/guard-taint.test.ts @@ -0,0 +1,188 @@ +import { describe, expect, it } from 'vitest'; +import fs from 'node:fs'; +import path from 'node:path'; +import { runPipelineFromRepo } from '../../../src/core/ingestion/pipeline.js'; +import { createTempDirPool } from '../../helpers/temp-dir-pool.js'; + +const repos = createTempDirPool('gn-guard-taint-'); + +describe('guard-aware command taint (#3490)', () => { + it('preserves alias proofs across blocks and retains destructuring findings in real workers', async () => { + const repo = repos.dir(); + fs.writeFileSync( + path.join(repo, 'aliases.ts'), + ` +import {execSync} from 'node:child_process'; +function indexed({9: command}: any) { execSync(command); } +function defaulted(context: any, {command = context.query.command}: any) { execSync(command); } +function forward(command: string, log: boolean) { + const alias = command; + if (log) console.log('validated'); + execSync(alias); +} +export function handleIndexed(req: any) { + const ref: string = req.query.ref; + if (!/^[a-z]{1,40}$/.test(ref)) return; + indexed('git show ' + ref); +} +export function handleDefaulted(req: any) { + const ref: string = req.query.ref; + if (!/^[a-z]{1,40}$/.test(ref)) return; + defaulted(req, 'git show ' + ref); +} +export function handleAlias(req: any, log: boolean) { + const ref: string = req.query.ref; + if (!/^[0-9a-f]{7,40}$/.test(ref)) return; + const args = 'show ' + ref; + const command = 'git ' + args; + if (log) console.log('validated'); + execSync(command); + forward(command, log); +} +export function handleBypass(req: any, log: boolean) { + const ref: string = req.query.ref; + if (log) { if (!/^[0-9a-f]{7,40}$/.test(ref)) return; } + const command = 'git show ' + ref; + if (log) console.log('unchecked'); + execSync(command); + forward(command, log); +} +`, + ); + const result = await runPipelineFromRepo(repo, () => {}, { pdg: true, workerPoolSize: 1 }); + const paths = [...result.graph.iterRelationships()] + .filter((edge) => edge.type === 'TAINT_PATH') + .map((edge) => result.graph.getNode(edge.sourceId)?.properties.name); + expect(paths).toContain('handleIndexed'); + expect(paths).toContain('handleDefaulted'); + expect(paths).toContain('handleBypass'); + expect(paths).not.toContain('handleAlias'); + const localSources = [...result.graph.iterRelationships()] + .filter((edge) => edge.type === 'TAINTED') + .map((edge) => result.graph.getNode(edge.sourceId)?.properties.startLine); + const source = fs.readFileSync(path.join(repo, 'aliases.ts'), 'utf8').split('\n'); + // TAINTED starts at the request read, immediately after the declaration. + const aliasLine = + source.findIndex((line) => line.startsWith('export function handleAlias')) + 2; + const bypassLine = + source.findIndex((line) => line.startsWith('export function handleBypass')) + 2; + expect(localSources).not.toContain(aliasLine); + expect(localSources).toContain(bypassLine); + }, 120_000); + + it('retains findings for bypasses, mutation, uncertain types and unsupported sink uses', async () => { + const cases: Record = { + bypass: + 'const value: string = req.query.ref; if (flag) { if (!/^[0-9a-f]{7,40}$/.test(value)) return; } execSync("git show " + value);', + reassigned: + 'let value: string = req.query.ref; if (!/^[0-9a-f]{7,40}$/.test(value)) return; value = req.query.other; execSync("git show " + value);', + wrongValue: + 'const value: string = req.query.ref; const other: string = "abcdef0"; if (!/^[0-9a-f]{7,40}$/.test(other)) return; execSync("git show " + value);', + lateGuard: + 'const value: string = req.query.ref; execSync("git show " + value); if (!/^[0-9a-f]{7,40}$/.test(value)) return;', + partialPattern: + 'const value: string = req.query.ref; if (!/^[0-9a-f]{7,40}/.test(value)) return; execSync("git show " + value);', + multiline: + 'const value: string = req.query.ref; if (!/^[0-9a-f]{7,40}$/m.test(value)) return; execSync("git show " + value);', + customShell: + 'const value: string = req.query.ref; if (!/^[0-9a-f]{7,40}$/.test(value)) return; execSync("git show " + value, {shell: "custom-shell"});', + interpreter: + 'const value: string = req.query.ref; if (!/^[0-9a-f]{7,40}$/.test(value)) return; execSync("bash -c " + value);', + executable: + 'const value: string = req.query.ref; if (!/^[0-9a-f]{7,40}$/.test(value)) return; spawn(value, []);', + extraInput: + 'const value: string = req.query.ref; if (!/^[0-9a-f]{7,40}$/.test(value)) return; execSync("git show " + value + req.query.other);', + caught: + 'const value: string = req.query.ref; try { if (!/^[0-9a-f]{7,40}$/.test(value)) throw new Error(); } catch {} execSync("git show " + value);', + unknownObject: + 'const value: any = req.query.ref; if (!/^[0-9a-f]{7,40}$/.test(value)) return; execSync("git show " + value);', + suspended: + 'const value: string = req.query.ref; if (!/^[0-9a-f]{7,40}$/.test(value)) return; await pending(); execSync("git show " + value);', + }; + const repo = repos.dir(); + fs.writeFileSync( + path.join(repo, 'unsafe.ts'), + 'import {execSync, spawn} from "node:child_process";\n' + + Object.entries(cases) + .map( + ([name, body]) => + `export ${name === 'suspended' ? 'async ' : ''}function ${name}(req: any, flag: boolean) { ${body} }`, + ) + .join('\n') + + String.raw` +function escapedValue(value: string, req: any) { + if (!/^[0-9a-f]{7,40}$/.test(value)) return; + \u0076alue = req.query.other; + execSync('git show ' + value); +} +export function handleEscaped(req: any) { escapedValue(req.query.ref, req); } +`, + ); + const result = await runPipelineFromRepo(repo, () => {}, { pdg: true, workerPoolSize: 1 }); + const crossSources = [...result.graph.iterRelationships()] + .filter((edge) => edge.type === 'TAINT_PATH') + .map((edge) => result.graph.getNode(edge.sourceId)?.properties.name); + expect(crossSources).toContain('handleEscaped'); + const sourceLines = [...result.graph.iterRelationships()] + .filter((edge) => edge.type === 'TAINTED') + .map((edge) => Number(result.graph.getNode(edge.sourceId)?.properties.startLine)); + for (const [index, name] of Object.keys(cases).entries()) { + expect(sourceLines, `missing conservative finding for ${name}`).toContain(index + 2); + } + }, 120_000); + + it('preserves a validated value across command construction without hiding unsafe siblings', async () => { + const repo = repos.dir(); + fs.writeFileSync( + path.join(repo, 'commands.ts'), + `import { execSync } from 'node:child_process'; +const SHA_RE = /^[0-9a-f]{7,40}$/; +function runGit(args: string) { return execSync('git ' + args); } +function commitSubject(ref: string) { + if (!SHA_RE.test(ref)) throw new Error('invalid sha'); + return runGit('log -1 --format=%s ' + ref).trim(); +} +function showRevision(ref: string) { + if (!/^[0-9a-f]{7,40}$/.test(ref)) return; + return runGit('show ' + ref); +} +export function handleGuarded(req: any) { return commitSubject(req.query.ref as string); } +export function handleShow(req: any) { return showRevision(req.query.ref as string); } +export function handleUnsafe(req: any) { return runGit('blame ' + req.query.ref); } +export function handleInterpreter(req: any) { + const value: string = req.query.ref; + if (!SHA_RE.test(value)) return; + execSync('bash -c ' + value); +} +export function handleLocal(req: any) { + const ref: string = req.query.ref; + if (!SHA_RE.test(ref)) return; + execSync('git log -1 ' + ref); +} +export function handleWrongBranch(req: any) { + const ref: string = req.query.ref; + if (SHA_RE.test(ref)) return; + execSync('git log -1 ' + ref); +} +export function handleLiteral(req: any) { + const ref = req.query.ref; + if (ref !== 'abcdef0') return; + execSync('git show ' + ref); +} +`, + ); + const result = await runPipelineFromRepo(repo, () => {}, { pdg: true, workerPoolSize: 1 }); + const edges = [...result.graph.iterRelationships()]; + const crossFunctionSources = edges + .filter((edge) => edge.type === 'TAINT_PATH') + .map((edge) => result.graph.getNode(edge.sourceId)?.properties.name); + expect(crossFunctionSources).toContain('handleUnsafe'); + expect(crossFunctionSources).not.toContain('handleGuarded'); + expect(crossFunctionSources).not.toContain('handleShow'); + const localFindings = edges.filter((edge) => edge.type === 'TAINTED'); + const localSourceLines = localFindings.map( + (edge) => result.graph.getNode(edge.sourceId)?.properties.startLine, + ); + expect([...new Set(localSourceLines)].sort((a, b) => Number(a) - Number(b))).toEqual([16, 26]); + }, 120_000); +}); diff --git a/gitnexus/test/integration/java-imported-return-types.test.ts b/gitnexus/test/integration/java-imported-return-types.test.ts new file mode 100644 index 0000000000..111f425a99 --- /dev/null +++ b/gitnexus/test/integration/java-imported-return-types.test.ts @@ -0,0 +1,186 @@ +import { describe, it, expect } from 'vitest'; +import { javaScopeResolver } from '../../src/core/ingestion/languages/java/scope-resolver.js'; +import { runScopeResolution } from '../../src/core/ingestion/scope-resolution/pipeline/run.js'; +import { parseFilesWithWorkers } from '../helpers/worker-parse.js'; + +describe('Java imported return types through worker parsing', () => { + it.each([ + { reverse: false, returns: 'same spelling' }, + { reverse: true, returns: 'same spelling' }, + { reverse: false, returns: 'different spelling' }, + { reverse: true, returns: 'different spelling' }, + { reverse: false, returns: 'same class' }, + { reverse: true, returns: 'same class' }, + ])( + 'compares transitive return identities ($returns, reverse=$reverse)', + async ({ reverse, returns }) => { + const otherType = returns === 'different spelling' ? 'OtherNode' : 'Node'; + const shared = returns === 'same class'; + const files = [ + { + path: 'a/Node.java', + content: 'package a; public class Node { public void visitA() {} }', + }, + { + path: 'a/TreeA.java', + content: 'package a; public class TreeA { public Node next() { return new Node(); } }', + }, + { + path: `b/${otherType}.java`, + content: `package b; public class ${otherType} { public void visitB() {} }`, + }, + { + path: 'b/TreeB.java', + content: `package b; ${shared ? 'import a.Node;' : ''} public class TreeB { public ${otherType} next() { return new ${otherType}(); } }`, + }, + { + path: 'mid/Mid.java', + content: + 'package mid; import a.TreeA; import b.TreeB; public class Mid { public TreeA makeA() { return new TreeA(); } }', + }, + { + path: 'app/App.java', + content: + 'package app; import mid.Mid; public class App { public void run() { Mid mid = new Mid(); var a = mid.makeA(); var n = a.next(); n.visitA(); n.visitB(); } }', + }, + ]; + // No same-package competitor in the positive case: both producers return a.Node. + if (shared) files.splice(2, 1); + if (reverse) files.reverse(); + javaScopeResolver.loadResolutionConfig?.(''); + const { graph, model, data } = await parseFilesWithWorkers(files); + runScopeResolution( + { + graph, + model, + files, + preExtractedParsedFiles: new Map(data.parsedFiles.map((file) => [file.filePath, file])), + onResolved: ({ parsedFiles }) => { + const app = parsedFiles.find((file) => file.filePath === 'app/App.java'); + const next = app?.scopes + .find((scope) => scope.id === app.moduleScope) + ?.typeBindings.get('next'); + if (shared) expect(next?.rawName).toBe('Node'); + else expect(next).toBeUndefined(); + }, + }, + javaScopeResolver, + ); + const targets = [...graph.iterRelationshipsByType('CALLS')] + .filter((edge) => edge.sourceId === 'Method:app/App.java:App.run#0') + .map((edge) => edge.targetId); + expect(targets).not.toContain(`Method:b/${otherType}.java:${otherType}.visitB#0`); + if (shared) expect(targets).toContain('Method:a/Node.java:Node.visitA#0'); + }, + ); + + it.each([ + { reverse: false, cycle: false }, + { reverse: true, cycle: false }, + { reverse: false, cycle: true }, + { reverse: true, cycle: true }, + ])( + 'resolves a 12-file factory chain (reverse=$reverse, cycle=$cycle)', + async ({ reverse, cycle }) => { + const count = 12; + const files = Array.from({ length: count }, (_, i) => ({ + path: `p${i}/C${i}.java`, + content: `package p${i}; +${i + 1 < count ? `import p${i + 1}.C${i + 1};` : cycle ? 'import p0.C0;' : ''} +public class C${i} { +${i + 1 < count ? `public C${i + 1} next${i}() { return new C${i + 1}(); }` : 'public void finish() {}'} +}`, + })); + files.push({ + path: 'app/App.java', + content: `package app; import p0.C0; public class App { public void run() { +C0 value0 = new C0(); +${Array.from({ length: count - 1 }, (_, i) => `var value${i + 1} = value${i}.next${i}();`).join('\n')} +value${count - 1}.finish(); +} }`, + }); + if (reverse) files.reverse(); + javaScopeResolver.loadResolutionConfig?.(''); + const { graph, model, data } = await parseFilesWithWorkers(files); + runScopeResolution( + { + graph, + model, + files, + preExtractedParsedFiles: new Map(data.parsedFiles.map((file) => [file.filePath, file])), + }, + javaScopeResolver, + ); + const targets = [...graph.iterRelationshipsByType('CALLS')] + .filter((edge) => edge.sourceId === 'Method:app/App.java:App.run#0') + .map((edge) => edge.targetId); + expect(targets).toEqual( + expect.arrayContaining( + Array.from( + { length: count }, + (_, i) => `Method:p${i}/C${i}.java:C${i}.${i + 1 < count ? `next${i}` : 'finish'}#0`, + ), + ), + ); + }, + ); + + it.each([ + { order: 'forward', override: false }, + { order: 'reverse', override: false }, + { order: 'forward', override: true }, + { order: 'reverse', override: true }, + ])( + 'resolves inherited return calls ($order, override=$override)', + async ({ order, override }) => { + const files = [ + { + path: 'p0/Foo.java', + content: 'package p0; public class Foo { public void fooMethod() {} }', + }, + { + path: 'p0/Base.java', + content: + 'package p0; public class Base { public Foo baseMethod() { return new Foo(); } }', + }, + { + path: 'p1/ChildFoo.java', + content: + 'package p1; import p0.Foo; public class ChildFoo extends Foo { public void childOnly() {} }', + }, + { + path: 'p1/C1.java', + content: `package p1; import p0.Base; public class C1 extends Base { +${override ? 'public ChildFoo baseMethod() { return new ChildFoo(); }' : ''} +}`, + }, + { + path: 'p2/App.java', + content: `package p2; import p1.C1; public class App { public void run() { +C1 c = new C1(); var r = c.baseMethod(); r.${override ? 'childOnly' : 'fooMethod'}(); +} }`, + }, + ]; + if (order === 'reverse') files.reverse(); + javaScopeResolver.loadResolutionConfig?.(''); + const { graph, model, data } = await parseFilesWithWorkers(files); + runScopeResolution( + { + graph, + model, + files, + preExtractedParsedFiles: new Map(data.parsedFiles.map((file) => [file.filePath, file])), + }, + javaScopeResolver, + ); + const target = override + ? 'Method:p1/ChildFoo.java:ChildFoo.childOnly#0' + : 'Method:p0/Foo.java:Foo.fooMethod#0'; + expect([...graph.iterRelationshipsByType('CALLS')]).toEqual( + expect.arrayContaining([ + expect.objectContaining({ sourceId: 'Method:p2/App.java:App.run#0', targetId: target }), + ]), + ); + }, + ); +}); diff --git a/gitnexus/test/integration/taint-explain.test.ts b/gitnexus/test/integration/taint-explain.test.ts index 95768990f8..09f7078bd7 100644 --- a/gitnexus/test/integration/taint-explain.test.ts +++ b/gitnexus/test/integration/taint-explain.test.ts @@ -156,6 +156,8 @@ withTestLbugDB( expect(vuln.pathIncomplete).toBeUndefined(); // The intra-procedural contract caveat reaches the consumer. expect(result.note).toMatch(/intra-procedural/i); + expect(result.note).toContain('Imported and wrapper validators'); + expect(result.note).toContain('not runtime validation'); }); it('anchorless enumerate is deterministic across calls', async () => { diff --git a/gitnexus/test/unit/ai-context.test.ts b/gitnexus/test/unit/ai-context.test.ts index 8a4a836d23..6030e9eca3 100644 --- a/gitnexus/test/unit/ai-context.test.ts +++ b/gitnexus/test/unit/ai-context.test.ts @@ -406,6 +406,208 @@ describe('generateAIContextFiles', () => { expect(starts).toBe(1); }); + describe('line endings (#3688)', () => { + const crlf = (lines: string[]) => lines.join('\r\n') + '\r\n'; + const stats = { nodes: 10, edges: 20, processes: 3 }; + + async function withRepo(run: (dir: string, storage: string) => Promise) { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'gn-crlf-')); + const storage = path.join(dir, '.gitnexus'); + await fs.mkdir(storage, { recursive: true }); + try { + await run(dir, storage); + } finally { + await fs.rm(dir, { recursive: true, force: true }); + } + } + + const loneLfCount = (content: string) => content.replace(/\r\n/g, '').split('\n').length - 1; + + it('writes the block in CRLF when it replaces a section in a CRLF file', async () => { + await withRepo(async (dir, storage) => { + const file = path.join(dir, 'CLAUDE.md'); + await fs.writeFile( + file, + crlf([ + '# Hand-written guide', + '', + 'Keep this paragraph.', + '', + '', + 'old block', + '', + '', + 'And this one.', + ]), + 'utf-8', + ); + + await generateAIContextFiles(dir, storage, 'CrlfProject', stats); + + const content = await fs.readFile(file, 'utf-8'); + expect(content).toContain('Keep this paragraph.\r\n'); + expect(content).toContain('And this one.'); + expect(content).toContain('\r\n'); + expect(content).toContain('CrlfProject'); + expect(content).not.toContain('old block'); + expect(loneLfCount(content)).toBe(0); + }); + }); + + it('appends the block in CRLF to a CRLF file that has no section yet', async () => { + await withRepo(async (dir, storage) => { + const file = path.join(dir, 'AGENTS.md'); + await fs.writeFile(file, crlf(['# Agents', '', 'Hand-written.']), 'utf-8'); + + await generateAIContextFiles(dir, storage, 'CrlfProject', stats); + + const content = await fs.readFile(file, 'utf-8'); + expect(content.startsWith('# Agents\r\n')).toBe(true); + expect(content).toContain(''); + expect(loneLfCount(content)).toBe(0); + }); + }); + + it('leaves a CRLF file alone when only the counts moved', async () => { + await withRepo(async (dir, storage) => { + const file = path.join(dir, 'CLAUDE.md'); + await fs.writeFile(file, crlf(['# Guide', '', 'Hand-written.']), 'utf-8'); + await generateAIContextFiles(dir, storage, 'CrlfProject', stats); + // As git hands the file back on a CRLF checkout: block included. + const committed = (await fs.readFile(file, 'utf-8')).replace(/\r?\n/g, '\r\n'); + await fs.writeFile(file, committed, 'utf-8'); + + await generateAIContextFiles(dir, storage, 'CrlfProject', { + nodes: 11, + edges: 21, + processes: 4, + }); + + expect(await fs.readFile(file, 'utf-8')).toBe(committed); + }); + }); + + it.each([false, true])('repairs mixed endings once with noStats=%s', async (noStats) => { + await withRepo(async (dir, storage) => { + // Build the block as the previous writer wrote it: LF, inside CRLF prose. + const file = path.join(dir, 'CLAUDE.md'); + await fs.writeFile(file, '# Guide\n', 'utf-8'); + const options = { noStats, skipSkills: true }; + await generateAIContextFiles(dir, storage, 'CrlfProject', stats, undefined, options); + const lfFile = await fs.readFile(file, 'utf-8'); + const block = lfFile.slice(lfFile.indexOf('')); + const mixed = crlf(['# Guide', '', 'Hand-written, kept as is.', '']) + block; + await fs.writeFile(file, mixed, 'utf-8'); + expect(mixed).toContain('\r\n'); + expect(mixed.replace(/\r\n/g, '')).toContain('\n'); + + // Counts moved, so the block itself is left alone: the file is still + // written once, uniformly in its own ending. + const first = await generateAIContextFiles( + dir, + storage, + 'CrlfProject', + { nodes: 11, edges: 21, processes: 4 }, + undefined, + options, + ); + const repaired = await fs.readFile(file, 'utf-8'); + expect(first.files).toContain('CLAUDE.md (updated)'); + expect(loneLfCount(repaired)).toBe(0); + expect(repaired).toContain('Hand-written, kept as is.\r\n'); + expect(repaired.replace(/\r\n/g, '\n')).toBe(mixed.replace(/\r\n/g, '\n')); + + // A fixed old mtime proves the repeat does not rewrite identical bytes. + const oldTime = new Date('2000-01-01T00:00:00Z'); + await fs.utimes(file, oldTime, oldTime); + const beforeRepeat = await fs.stat(file); + const second = await generateAIContextFiles( + dir, + storage, + 'CrlfProject', + { nodes: 12, edges: 22, processes: 5 }, + undefined, + options, + ); + expect(second.files).toContain('CLAUDE.md (preserved)'); + expect(await fs.readFile(file, 'utf-8')).toBe(repaired); + expect((await fs.stat(file)).mtimeMs).toBe(beforeRepeat.mtimeMs); + }); + }); + + it.each([ + { + name: 'count-only change', + line: 'Indexed as **CrlfProject** (1 symbols, 2 relationships, 3 execution flows). Custom.', + noStats: false, + }, + { + name: 'no stats line', + line: 'A custom block without a generated stats line.', + noStats: false, + }, + { name: 'count-free stats line', line: 'Indexed as **CrlfProject**. Custom.', noStats: true }, + ])('repairs a mixed keep block once: $name', async ({ line, noStats }) => { + await withRepo(async (dir, storage) => { + const block = [ + '', + '', + line, + '| query | Find flows |', + '', + '', + ].join('\n'); + const mixed = + crlf(['# Guide', '', 'Keep this prose.', '']) + block + crlf(['', 'Keep this footer.']); + const expected = mixed.replace(/\r?\n/g, '\r\n'); + const files = ['AGENTS.md', 'CLAUDE.md']; + for (const name of files) await fs.writeFile(path.join(dir, name), mixed, 'utf-8'); + const options = { noStats, skipSkills: true }; + const first = await generateAIContextFiles( + dir, + storage, + 'CrlfProject', + stats, + undefined, + options, + ); + for (const name of files) { + expect(first.files).toContain(`${name} (updated)`); + expect(await fs.readFile(path.join(dir, name), 'utf-8')).toBe(expected); + } + const oldTime = new Date('2000-01-01T00:00:00Z'); + for (const name of files) await fs.utimes(path.join(dir, name), oldTime, oldTime); + const mtimes = await Promise.all( + files.map(async (name) => (await fs.stat(path.join(dir, name))).mtimeMs), + ); + const second = await generateAIContextFiles( + dir, + storage, + 'CrlfProject', + { nodes: 11, edges: 21, processes: 4 }, + undefined, + options, + ); + for (const [i, name] of files.entries()) { + expect(second.files).toContain(`${name} (preserved)`); + expect(await fs.readFile(path.join(dir, name), 'utf-8')).toBe(expected); + expect((await fs.stat(path.join(dir, name))).mtimeMs).toBe(mtimes[i]); + } + }); + }); + + it('keeps an LF file in LF', async () => { + await withRepo(async (dir, storage) => { + const file = path.join(dir, 'CLAUDE.md'); + await fs.writeFile(file, '# Guide\n\nHand-written.\n', 'utf-8'); + + await generateAIContextFiles(dir, storage, 'LfProject', stats); + + expect(await fs.readFile(file, 'utf-8')).not.toContain('\r'); + }); + }); + }); + it('preserves custom section when gitnexus:keep is present', async () => { const claudeMdPath = path.join(tmpDir, 'CLAUDE.md'); @@ -1270,36 +1472,47 @@ Indexed as **Idem** (1 symbols, 2 relationships, 3 execution flows). Custom. } }); - it('CRLF file with keep marker: stats line updates without corrupting content (#1508 review F5)', async () => { - // upsertGitNexusSection writes with .trim() + '\n', so the saved file uses LF - // line endings throughout — CRLF in the seed input is not preserved. - const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'gn-keep-crlf-')); - try { - const claudePath = path.join(dir, 'CLAUDE.md'); - const crlfContent = - '# Project\r\n' + - '\r\n' + - '\r\n' + - '\r\n' + - 'Indexed as **CRLFOldName** (5 symbols, 6 relationships, 7 execution flows). Custom CRLF.\r\n' + - '\r\n'; - await fs.writeFile(claudePath, crlfContent, 'utf-8'); + it.each([false, true])( + 'CRLF keep block updates preserve endings with noStats=%s (#1508)', + async (noStats) => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'gn-keep-crlf-')); + try { + const claudePath = path.join(dir, 'CLAUDE.md'); + const crlfContent = + '# Project\r\n' + + '\r\n' + + '\r\n' + + '\r\n' + + 'Indexed as **CRLFOldName** (5 symbols, 6 relationships, 7 execution flows). Custom CRLF.\r\n' + + '\r\n'; + await fs.writeFile(claudePath, crlfContent, 'utf-8'); - const stats = { nodes: 50, edges: 60, processes: 7 }; - await generateAIContextFiles(dir, path.join(dir, '.gitnexus'), 'CRLFTest', stats); + const stats = { nodes: 50, edges: 60, processes: 7 }; + const generated = await generateAIContextFiles( + dir, + path.join(dir, '.gitnexus'), + 'CRLFTest', + stats, + undefined, + { noStats, skipSkills: true }, + ); - const result = await fs.readFile(claudePath, 'utf-8'); - // Stats updated correctly - expect(result).toContain('50 symbols'); - expect(result).toContain('60 relationships'); - // Custom prose preserved - expect(result).toContain('Custom CRLF'); - // No verbose template injected - expect(result).not.toContain('## Always Do'); - } finally { - await fs.rm(dir, { recursive: true, force: true }); - } - }); + const result = await fs.readFile(claudePath, 'utf-8'); + const statsLine = noStats + ? 'Indexed as **CRLFTest**' + : 'Indexed as **CRLFTest** (50 symbols, 60 relationships, 7 execution flows)'; + expect(generated.files).toContain('CLAUDE.md (updated)'); + expect(result).toBe( + crlfContent.replace( + 'Indexed as **CRLFOldName** (5 symbols, 6 relationships, 7 execution flows)', + statsLine, + ), + ); + } finally { + await fs.rm(dir, { recursive: true, force: true }); + } + }, + ); it('noStats + keep marker: stats line drops the volatile counts (#1706)', async () => { // #1706: --no-stats must win in the keep-marker path too. A lean block diff --git a/gitnexus/test/unit/cfg/harvest.test.ts b/gitnexus/test/unit/cfg/harvest.test.ts index 79bfcbbb76..17e8cdf124 100644 --- a/gitnexus/test/unit/cfg/harvest.test.ts +++ b/gitnexus/test/unit/cfg/harvest.test.ts @@ -475,6 +475,56 @@ function siteFact(cfg: FunctionCfg, line?: number): StatementFacts { } describe('M3 U1 — taint-site harvest: call sites', () => { + it.each([2, 33])('preserves every repeated argument occurrence with %i arguments', (count) => { + const cfg = cfgOf(`function f(x) { exec(${Array(count).fill('x').join(',')}); }`); + const fact = siteFact(cfg, 1); + const x = bindingIdx(cfg, 'x'); + expect(fact.sites![0].args).toEqual(Array.from({ length: count }, () => [x])); + expect(fact.uses.filter((binding) => binding === x)).toHaveLength(1); + if (count > 32) expect(cfg.refinementSafe).toBe(false); + else + expect(fact.refinement?.calls?.[0].arguments).toEqual( + Array(count).fill({ kind: 'binding', binding: x }), + ); + }); + + it('retains ordinary call occurrences after exhausting the value-shape budget', () => { + const cfg = cfgOf(`function f(x) { ${'exec(x);'.repeat(257)} }`); + const facts = allFacts(cfg).filter((fact) => + fact.sites?.some((site) => site.callee === 'exec'), + ); + const x = bindingIdx(cfg, 'x'); + expect(facts).toHaveLength(257); + expect( + facts.every((fact) => fact.uses.includes(x) && fact.sites![0].args?.[0]?.[0] === x), + ).toBe(true); + expect(facts[0].refinement?.calls).toHaveLength(1); + expect(facts[256].refinement).toBeUndefined(); + expect(cfg.refinementSafe).toBe(false); + }); + + it.each(['label: function g() {}', 'if (condition) function g() {}'])( + 'resolves a declaration beneath a non-scope parent: %s', + (declaration) => { + const cfg = cfgOf(`function f(g) { + { + let g = source(); + ${declaration} + use(g); + } + use(g); +}`); + const [outer, inner] = bindingIdxs(cfg, 'g'); + expect(bindingIdxs(cfg, 'g')).toHaveLength(2); + const facts = allFacts(cfg); + const declared = facts.filter((fact) => fact.line === 4).flatMap((fact) => fact.defs); + expect(declared).toContain(inner); + expect(declared).not.toContain(outer); + expect(facts.find((fact) => fact.line === 5)?.uses).toContain(inner); + expect(facts.find((fact) => fact.line === 7)?.uses).toContain(outer); + }, + ); + it('exec(a, b) → one call site mapping position 0→[a], 1→[b]', () => { const cfg = cfgOf(`function f(a, b) { exec(a, b); }`); const sites = siteFact(cfg, 1).sites!; diff --git a/gitnexus/test/unit/cfg/typescript-refinement.test.ts b/gitnexus/test/unit/cfg/typescript-refinement.test.ts new file mode 100644 index 0000000000..2b6470cb0c --- /dev/null +++ b/gitnexus/test/unit/cfg/typescript-refinement.test.ts @@ -0,0 +1,160 @@ +import { describe, expect, it } from 'vitest'; +import { cfgOf, parse } from '../../helpers/ts-cfg-harness.js'; +import { + createRefinementFileContext, + readPredicate, + readValueExpression, +} from '../../../src/core/ingestion/cfg/visitors/typescript-refinement.js'; +import type { SyntaxNode } from '../../../src/core/ingestion/utils/ast-helpers.js'; + +import { collectFunctionCfgs } from '../../../src/core/ingestion/cfg/collect.js'; +import { createTypeScriptCfgVisitor } from '../../../src/core/ingestion/cfg/visitors/typescript.js'; +import { createFunctionRefinement } from '../../../src/core/ingestion/taint/guard-refinement.js'; +import { + applyValueEffect, + provesInertCommand, + UNKNOWN_VALUE, +} from '../../../src/core/ingestion/taint/value-refinement.js'; + +function find(root: SyntaxNode, type: string): SyntaxNode { + if (root.type === type) return root; + for (const child of root.namedChildren) { + try { + return find(child, type); + } catch { + /* next subtree */ + } + } + throw new Error(`No ${type}`); +} + +function predicate(source: string) { + const root = parse(source); + return readPredicate( + find(root, 'if_statement').childForFieldName('condition')!, + () => 0, + createRefinementFileContext(root), + ); +} + +describe('normalized predicate and expression facts', () => { + it.each(['"prefix\narguments"', '/prefix\narguments/'])( + 'preserves error-recovery uses and conservative fallback inside %s', + (literal) => { + const cfg = cfgOf(`function f(x) { const value = ${literal}; consume(x, value); }`); + const recovered = cfg.bindings!.findIndex((binding) => binding.name === 'arguments'); + expect(recovered).toBeGreaterThanOrEqual(0); + expect( + cfg.blocks.flatMap((block) => (block.statements ?? []).flatMap((s) => s.uses)), + ).toContain(recovered); + expect(cfg.refinementSafe).toBe(false); + expect(createFunctionRefinement(cfg).guards.status).toBe('fallback'); + }, + ); + + it.each([ + '{command}', + '{9: command}', + '[command]', + '[, command]', + '...command', + '{command = fallback()}', + '{nested: {command}}', + ])('keeps non-identity formal bindings conservative: %s', (pattern) => { + const cfg = cfgOf(`function f(${pattern}: any) { consume(command); }`); + expect(cfg.refinementSafe).toBe(false); + expect(createFunctionRefinement(cfg).guards.status).toBe('fallback'); + }); + + it('preserves guard and value identity through embedded coordinate mappings', () => { + const root = parse(`const SHA_RE = /^[0-9a-f]{7,40}$/; +function f(ref: string) { + if (!SHA_RE.test(ref)) return; + consume('git show ' + ref); +}`); + for (const mapLine of [undefined, (row: number) => row + 12]) { + const { cfgs } = collectFunctionCfgs( + root, + createTypeScriptCfgVisitor(), + 'Component.vue', + 0, + 12, + mapLine, + ); + expect(cfgs).toHaveLength(1); + const cfg = cfgs[0]; + expect(cfg.functionStartLine).toBe(14); + const refinement = createFunctionRefinement(cfg); + const values = cfg.blocks.flatMap((block) => + (block.statements ?? []).flatMap((statement, index) => + (statement.sites ?? []).flatMap((site, siteIndex) => + site.callee === 'consume' + ? [ + applyValueEffect( + refinement.argument(block.index, index, siteIndex, 0), + UNKNOWN_VALUE, + ), + ] + : [], + ), + ), + ); + expect(values).toHaveLength(1); + expect(provesInertCommand(values[0], ['git show '])).toBe(true); + } + }); + + it('resolves the immutable module validator and its accepted polarity', () => { + const fact = predicate( + 'const SHA_RE = /^[0-9a-f]{7,40}$/; function f(ref: string) { if (!SHA_RE.test(ref)) return; }', + ); + expect(fact).toMatchObject({ subject: 0, accepts: false, restriction: { min: 7, max: 40 } }); + }); + + it('recognizes an inline regex validator without treating it as a named callee', () => { + expect( + predicate('function f(ref: string) { if (!/^[0-9a-f]{7,40}$/.test(ref)) return; }'), + ).toMatchObject({ subject: 0, accepts: false, restriction: { min: 7, max: 40 } }); + }); + + it.each([ + 'const SHA_RE = /^[0-9a-f]{7,40}$/m; function f(ref: string) { if (!SHA_RE.test(ref)) return; }', + 'const SHA_RE = /^[0-9a-f]{7,40}$/; SHA_RE.test = other; function f(ref: string) { if (!SHA_RE.test(ref)) return; }', + 'const SHA_RE = /^[0-9a-f]{7,40}$/; function f(SHA_RE: any, ref: string) { if (!SHA_RE.test(ref)) return; }', + 'const SHA_RE = /^[0-9a-f]{7,40}$/; export { SHA_RE }; function f(ref: string) { if (!SHA_RE.test(ref)) return; }', + 'import { SHA_RE } from "./patterns"; function f(ref: string) { if (!SHA_RE.test(ref)) return; }', + '/x/.constructor.prototype.test = () => true; function f(ref: string) { if (!/^[0-9a-f]{7,40}$/.test(ref)) return; }', + 'const OTHER = /x/; OTHER.constructor.prototype.test = () => true; function f(ref: string) { if (!/^[0-9a-f]{7,40}$/.test(ref)) return; }', + 'const SHA_RE = /^[0-9a-f]{7,40}$/; mutate(SHA_RE); function f(ref: string) { if (!/^[0-9a-f]{7,40}$/.test(ref)) return; }', + String.raw`\u0067lobalThis.RegExp.prototype.test = () => true; function f(ref: string) { if (!/^[0-9a-f]{7,40}$/.test(ref)) return; }`, + 'globalThis.RegExp.prototype.test = () => true; function f(ref: string) { if (!/^[0-9a-f]{7,40}$/.test(ref)) return; }', + 'eval("RegExp.prototype.test = () => true"); function f(ref: string) { if (!/^[0-9a-f]{7,40}$/.test(ref)) return; }', + ])('retains unknown validator identity, mutation and unsupported flags: %s', (source) => { + expect(predicate(source)).toBeUndefined(); + }); + + it('strict literal equality establishes a primitive without a cast assumption', () => { + expect(predicate('function f(ref: any) { if (ref !== "abcdef0") return; }')).toMatchObject({ + subject: 0, + accepts: false, + establishesPrimitive: true, + }); + }); + + it('normalizes exact literal concatenation and rejects unknown transformations', () => { + const expression = find(parse('const value = "git " + args;'), 'binary_expression'); + expect(readValueExpression(expression, () => 2)).toEqual({ + kind: 'concat', + parts: [ + { kind: 'literal', value: 'git ' }, + { kind: 'binding', binding: 2 }, + ], + }); + expect( + readValueExpression(find(parse('transform(args);'), 'call_expression'), () => 2), + ).toEqual({ kind: 'unknown' }); + expect( + readValueExpression(find(parse('new Wrapper(args);'), 'new_expression'), () => 2), + ).toEqual({ kind: 'non-string' }); + }); +}); diff --git a/gitnexus/test/unit/cjk-segmentation.test.ts b/gitnexus/test/unit/cjk-segmentation.test.ts index 25ce7f12af..eee9d32327 100644 --- a/gitnexus/test/unit/cjk-segmentation.test.ts +++ b/gitnexus/test/unit/cjk-segmentation.test.ts @@ -74,38 +74,50 @@ describe('segmentCjkSpans', () => { expect(outputBytes).toBeLessThan(expectedBytes * 1.05); }); - it('scales linearly on realistic interleaved CJK/non-CJK content, not quadratically', () => { - // Regression guard: an earlier implementation indexed into the growing - // accumulated output string once per run boundary, which forces V8 to - // flatten its internal rope representation on every access — O(n^2) on - // content that alternates CJK and non-CJK runs (ordinary source code - // with inline CJK comments, the feature's actual target). A single-run - // input (like the growth-factor test above) never exercises this path, - // since there is only one run boundary regardless of size. - const unit = '采购订单自动审批流程 // approve the request after manual review\n'; - const build = (totalBytes: number) => unit.repeat(Math.ceil(totalBytes / unit.length)); + it.skipIf(!process.env.GITNEXUS_BENCH)( + 'scales linearly on realistic interleaved CJK/non-CJK content, not quadratically', + () => { + // Regression guard: an earlier implementation indexed into the growing + // accumulated output string once per run boundary, which forces V8 to + // flatten its internal rope representation on every access — O(n^2) on + // content that alternates CJK and non-CJK runs (ordinary source code + // with inline CJK comments, the feature's actual target). A single-run + // input (like the growth-factor test above) never exercises this path, + // since there is only one run boundary regardless of size. + const unit = '采购订单自动审批流程 // approve the request after manual review\n'; + const build = (totalBytes: number) => unit.repeat(Math.ceil(totalBytes / unit.length)); - const small = build(64 * 1024); - const large = build(512 * 1024); // 8x the input size + const small = build(64 * 1024); + const large = build(512 * 1024); // 8x the input size - const timeOf = (input: string) => { - const start = performance.now(); - segmentCjkSpans(input); - return performance.now() - start; - }; + const timeOf = (input: string) => { + const start = performance.now(); + segmentCjkSpans(input); + return performance.now() - start; + }; - // Warm up the JIT before measuring either size. - timeOf(small); - timeOf(large); + // run-benchmarks.ts discovers this opt-in test and runs it serially. + // Sample both sizes after warmup: one scheduler pause must not look like + // the quadratic regression this guard is intended to catch. + const smallSamples: number[] = []; + const largeSamples: number[] = []; + for (let sample = 0; sample < 10; sample++) { + const smallMs = timeOf(small); + const largeMs = timeOf(large); + if (sample >= 3) { + smallSamples.push(smallMs); + largeSamples.push(largeMs); + } + } + const smallMs = Math.min(...smallSamples); + const largeMs = Math.min(...largeSamples); - const smallMs = timeOf(small); - const largeMs = timeOf(large); - - // Linear scaling means ~8x input takes roughly ~8x time, with headroom - // for noise; quadratic scaling would mean ~64x time. 20x catches the - // regression while tolerating CI timing variance. - expect(largeMs).toBeLessThan(Math.max(smallMs, 1) * 20); - }); + // Linear scaling means ~8x input takes roughly ~8x time, with headroom + // for noise; quadratic scaling would mean ~64x time. 20x catches the + // regression while tolerating CI timing variance. + expect(largeMs).toBeLessThan(Math.max(smallMs, 1) * 20); + }, + ); }); describe('containsCjkIdeograph', () => { diff --git a/gitnexus/test/unit/cross-platform-shard.test.ts b/gitnexus/test/unit/cross-platform-shard.test.ts index 95c5153465..7dcc5a8f12 100644 --- a/gitnexus/test/unit/cross-platform-shard.test.ts +++ b/gitnexus/test/unit/cross-platform-shard.test.ts @@ -151,13 +151,29 @@ describe('cross-platform shard partition', () => { const loads = allShards(ALL_CROSS_PLATFORM, SHARD_TOTAL).map((files) => files.reduce((sum, file) => sum + Math.max(weightOf(file), (observed[file] ?? 0) + floor), 0), ); - // Leave at least two minutes for hosted-runner variation. Merely + // Leave at least three minutes for hosted-runner variation. Merely // fitting under 20 minutes left the previous partition prone to timeout. - // The ceiling was 17 minutes until the R rename provider suite (measured - // ~600 s on Windows) was charged its real weight: the table total grew by - // ~520 s, so even a perfect ten-way split averages ~1047 s per shard; the 695 s added by splitting the R - // suite into two files made it eleven shards. - expect(Math.max(...loads)).toBeLessThanOrEqual(18 * 60); + expect(Math.max(...loads)).toBeLessThanOrEqual(17 * 60); + }); + + it('leaves watchdog headroom for the October 23 native-suite timeout', () => { + // Windows run 39934695864: shard 10 timed out with Kotlin still pending. + // Use its completed suite times, plus the October 25 green run 40172490240 + // for query-symbol-integrity and incremental-dirty-recovery. These measured + // costs must remain independent of the scheduling hints being tested. + const observed: Readonly> = { + 'test/integration/rename-provider-objective-c.test.ts': 385.174, + 'test/integration/rename-provider-csharp.test.ts': 265.99, + 'test/integration/incremental-method-integrity.test.ts': 144.974, + 'test/integration/fts-repair-warm-session.test.ts': 61.015, + 'test/integration/query-symbol-integrity.test.ts': 33.892, + 'test/unit/incremental-dirty-recovery.test.ts': 127.8, + }; + const floor = weightOf('test/unmeasured.test.ts'); + const loads = allShards(ALL_CROSS_PLATFORM, SHARD_TOTAL).map((files) => + files.reduce((sum, file) => sum + Math.max(weightOf(file), (observed[file] ?? 0) + floor), 0), + ); + expect(Math.max(...loads)).toBeLessThanOrEqual(17 * 60); }); it('keeps each shard within a shard of the ideal weight', () => { diff --git a/gitnexus/test/unit/lbug-extension-loader.test.ts b/gitnexus/test/unit/lbug-extension-loader.test.ts index 79e76e77e5..7a245d225f 100644 --- a/gitnexus/test/unit/lbug-extension-loader.test.ts +++ b/gitnexus/test/unit/lbug-extension-loader.test.ts @@ -135,9 +135,9 @@ describe('ExtensionManager — install policies', () => { const manager = new ExtensionManager({ policy: 'auto', installExtension, warn }); const query = vi.fn().mockRejectedValue(new Error('Extension "vector" not found')); - await expect(manager.ensure(query, 'vector', 'VECTOR', { installTimeoutMs: 10 })).resolves.toBe( - false, - ); + await expect( + manager.ensure(query, 'vector', 'VECTOR', { ...noVendored, installTimeoutMs: 10 }), + ).resolves.toBe(false); expect(query.mock.calls.map(([sql]) => sql)).toEqual(['LOAD EXTENSION vector']); expect(warn).toHaveBeenCalledWith( @@ -690,7 +690,54 @@ describe('ExtensionManager — vendored-first FTS (U2)', () => { expect(String(query.mock.calls[0][0])).not.toContain('vendor-evil'); }); - it('does not try a vendored path for VECTOR and records no tuple', async () => { + it.each(['vector', 'VECTOR'])( + 'loads packaged %s before a broken home-cache copy', + async (name) => { + const vendorRoot = makeRoot(); + const dir = path.join(vendorRoot, 'lbug-vector', 'prebuilds', 'linux-x64'); + mkdirSync(dir, { recursive: true }); + const artifact = path.join(dir, 'libvector.lbug_extension'); + writeFileSync(artifact, 'placeholder'); + const loadPackaged = `LOAD EXTENSION '${escapeCypherString(realpathSync(artifact))}'`; + const query = vi.fn(async (sql: string) => { + if (sql !== loadPackaged) throw new Error('cached VECTOR has an undefined native symbol'); + return {}; + }); + const installExtension = vi.fn(); + const manager = new ExtensionManager({ + policy: 'load-only', + installExtension, + warn: noopWarn, + }); + + await expect( + manager.ensure(query, name, 'VECTOR', { vendorRoot, platformTuple: 'linux-x64' }), + ).resolves.toBe(true); + expect(query.mock.calls.map(([sql]) => sql)).toEqual([loadPackaged]); + expect(installExtension).not.toHaveBeenCalled(); + expect(manager.getCapabilities()[0]?.attempts).toEqual([ + { source: 'vendored', tuple: 'linux-x64' }, + ]); + }, + ); + + it('does not load packaged VECTOR under the never policy', async () => { + const vendorRoot = makeRoot(); + const dir = path.join(vendorRoot, 'lbug-vector', 'prebuilds', 'linux-x64'); + mkdirSync(dir, { recursive: true }); + writeFileSync(path.join(dir, 'libvector.lbug_extension'), 'placeholder'); + const query = vi.fn(); + const installExtension = vi.fn(); + const manager = new ExtensionManager({ policy: 'never', installExtension, warn: noopWarn }); + + await expect( + manager.ensure(query, 'VECTOR', 'VECTOR', { vendorRoot, platformTuple: 'linux-x64' }), + ).resolves.toBe(false); + expect(query).not.toHaveBeenCalled(); + expect(installExtension).not.toHaveBeenCalled(); + }); + + it('falls back to named VECTOR when no packaged VECTOR artifact exists', async () => { const vendorRoot = makeRoot(); writeVendorArtifact(vendorRoot, 'linux-x64'); const query = vi.fn().mockResolvedValue({}); diff --git a/gitnexus/test/unit/native-check-probe.test.ts b/gitnexus/test/unit/native-check-probe.test.ts index 8cb6f5d9af..cfadc43cdb 100644 --- a/gitnexus/test/unit/native-check-probe.test.ts +++ b/gitnexus/test/unit/native-check-probe.test.ts @@ -1,5 +1,7 @@ import path from 'node:path'; import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { resolveVendoredVectorPath } from '../../src/core/lbug/vendored-extension-path.js'; +import { escapeCypherString } from '../../src/core/lbug/cypher-escape.js'; /** * Unit coverage for probeFtsExtensionLoad (#2374, PR #2375): the doctor FTS @@ -136,12 +138,24 @@ describe('probeFtsExtensionLoad (#2374)', () => { }); describe('probeVectorExtensionLoad (#2623 follow-up)', () => { - it('issues LOAD EXTENSION vector and reports loaded on success — no platform short-circuit', async () => { + it('probes the same packaged VECTOR artifact as the runtime', async () => { h.query.mockResolvedValue(closeable()); await expect(probeVectorExtensionLoad()).resolves.toEqual({ loaded: true }); - // The probe must really attempt the LOAD (the old code refused Windows - // before ever touching the engine; the artifact ships for win_amd64 too). - expect(h.query).toHaveBeenCalledWith('LOAD EXTENSION vector'); + const vendoredPath = resolveVendoredVectorPath(); + expect(h.query).toHaveBeenCalledWith( + vendoredPath + ? `LOAD EXTENSION '${escapeCypherString(path.resolve(vendoredPath))}'` + : 'LOAD EXTENSION vector', + ); + }); + + it('falls back to named VECTOR when the packaged binary cannot load', async () => { + h.query.mockImplementation(async (sql) => { + if (sql !== 'LOAD EXTENSION vector') throw new Error('packaged binary unavailable'); + return closeable(); + }); + await expect(probeVectorExtensionLoad()).resolves.toEqual({ loaded: true }); + expect(h.query).toHaveBeenLastCalledWith('LOAD EXTENSION vector'); }); it('reports the collapsed reason when LOAD fails', async () => { diff --git a/gitnexus/test/unit/parse-cache-identity.test.ts b/gitnexus/test/unit/parse-cache-identity.test.ts index 2138afd5e9..13df2bf983 100644 --- a/gitnexus/test/unit/parse-cache-identity.test.ts +++ b/gitnexus/test/unit/parse-cache-identity.test.ts @@ -39,6 +39,8 @@ describe('parse cache artifact identity', () => { 'src/core/ingestion/languages/new-provider.ts', 'src/core/ingestion/preprocess.ts', 'src/core/ingestion/workers/helper.ts', + 'src/core/ingestion/taint/guard-refinement.ts', + 'src/core/ingestion/taint/value-refinement.ts', 'src/core/ingestion/languages/cobol/flow-source.ts', 'node_modules/gitnexus-shared/src/index.ts', 'node_modules/gitnexus-shared/dist/index.js', diff --git a/gitnexus/test/unit/parsedfile-store.test.ts b/gitnexus/test/unit/parsedfile-store.test.ts index d7a1279f90..10bb3838b3 100644 --- a/gitnexus/test/unit/parsedfile-store.test.ts +++ b/gitnexus/test/unit/parsedfile-store.test.ts @@ -6,6 +6,7 @@ import { tmpdir } from 'os'; import path from 'path'; import type { ParsedFile } from 'gitnexus-shared'; import { TEST_PARSE_IDENTITY } from '../helpers/cache-identity.js'; +import { cfgsOf } from '../helpers/ts-cfg-harness.js'; import { clearParsedFileStore, persistParsedFileChunk, @@ -76,6 +77,27 @@ function makeStoreEntry(filePath: string, overrides: Record): P } describe('parsedfile-store', () => { + it('preserves normalized guard and value facts through the disk seal', async () => { + const dir = await mkdtemp(path.join(tmpdir(), 'pfstore-guard-')); + try { + const cfgs = cfgsOf(`function guarded(ref: string) { + if (!/^[0-9a-f]{7,40}$/.test(ref)) return; + consume('git show ' + ref); + }`); + expect(cfgs[0].refinementSafe).toBe(true); + expect( + cfgs[0].blocks.some((block) => + block.statements?.some((statement) => statement.refinement?.predicate), + ), + ).toBe(true); + const file: ParsedFile = { ...makeParsedFile('guard.ts'), cfgSideChannel: cfgs }; + await persistParsedFileChunk(dir, 'guard-facts', [file]); + const loaded = await loadParsedFilesForPaths(dir, new Set(['guard.ts'])); + expect(loaded.get('guard.ts')?.cfgSideChannel).toEqual(cfgs); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }); it('round-trips ParsedFiles (incl. Scope Maps) and filters by requested paths', async () => { const dir = await mkdtemp(path.join(tmpdir(), 'pfstore-')); try { diff --git a/gitnexus/test/unit/scope-resolution/imported-return-types.test.ts b/gitnexus/test/unit/scope-resolution/imported-return-types.test.ts index 078588f867..1a4df7c7ea 100644 --- a/gitnexus/test/unit/scope-resolution/imported-return-types.test.ts +++ b/gitnexus/test/unit/scope-resolution/imported-return-types.test.ts @@ -18,15 +18,16 @@ * 4. **Cyclic SCC partial fixpoint** — the pass does not throw and * makes best-effort progress. * - * The tests use the real TypeScript scope-resolver to keep them + * The TypeScript fixtures use the real scope-resolver to keep them * close to production behavior — synthetic ParsedFiles would have * to fabricate `Scope.typeBindings` correctly, defeating the - * purpose. Each fixture is small (4 files max) and runs in <100ms. + * purpose. Java fixtures also cover import-chain storage and traversal order. */ import { describe, it, expect } from 'vitest'; import { extractParsedFile } from '../../../src/core/ingestion/scope-extractor-bridge.js'; import { typescriptScopeResolver } from '../../../src/core/ingestion/languages/typescript/scope-resolver.js'; +import { javaScopeResolver } from '../../../src/core/ingestion/languages/java/scope-resolver.js'; import { finalizeScopeModel } from '../../../src/core/ingestion/finalize-orchestrator.js'; import { buildWorkspaceResolutionIndex } from '../../../src/core/ingestion/scope-resolution/workspace-index.js'; import { propagateImportedReturnTypes } from '../../../src/core/ingestion/scope-resolution/passes/imported-return-types.js'; @@ -46,6 +47,73 @@ interface InMemoryFile { readonly content: string; } +function runJavaPropagation(files: readonly InMemoryFile[]): ParsedFile[] { + javaScopeResolver.loadResolutionConfig?.(''); + const parsedFiles = files.map((file) => { + const parsed = extractParsedFile(javaScopeResolver.languageProvider, file.content, file.path); + if (parsed === undefined) throw new Error(`scope extraction failed for ${file.path}`); + javaScopeResolver.populateOwners(parsed); + return parsed; + }); + const paths = new Set(files.map((file) => file.path)); + const indexes = finalizeScopeModel(parsedFiles, { + hooks: { + resolveImportTarget: (target, fromFile) => + javaScopeResolver.resolveImportTarget(target, fromFile, paths, undefined, { parsedFiles }), + mergeBindings: javaScopeResolver.mergeBindings, + }, + }); + propagateImportedReturnTypes(parsedFiles, indexes, buildWorkspaceResolutionIndex(parsedFiles)); + const populate = javaScopeResolver.populateRangeBindings; + if (populate === undefined) throw new Error('Java return-type hook is missing'); + populate(parsedFiles, indexes, { fileContents: new Map() }); + return parsedFiles; +} + +function moduleTypeBindings(file: ParsedFile): Scope['typeBindings'] { + const module = file.scopes.find((scope) => scope.id === file.moduleScope); + if (module === undefined) throw new Error(`no module scope for ${file.filePath}`); + return module.typeBindings; +} + +describe('Java imported method return types', () => { + const chain = (count: number): InMemoryFile[] => + Array.from({ length: count }, (_, i) => ({ + path: `p${i}/C${i}.java`, + content: `package p${i}; +${i > 0 ? `import p${i - 1}.C${i - 1};` : ''} +public class C${i} { public C${i} create${i}() { return this; } }`, + })); + + it('keeps return-type storage proportional to direct imports along a long import chain', () => { + const files = runJavaPropagation(chain(64)); + let bindingCount = 0; + for (const [i, file] of files.entries()) { + const types = moduleTypeBindings(file); + expect(types.get(`create${i}`)?.rawName).toBe(`C${i}`); + if (i > 0) expect(types.get(`create${i - 1}`)?.rawName).toBe(`C${i - 1}`); + bindingCount += types.size; + } + // Re-copying previously imported methods makes this n * (n + 1) / 2. + expect(bindingCount).toBe(2 * files.length - 1); + }); + + it('does not change imported return-type visibility with file traversal order', () => { + const input = chain(4); + const forward = runJavaPropagation(input); + const reversed = runJavaPropagation([...input].reverse()); + const bindings = (files: ParsedFile[]) => + files + .map((file) => ({ + path: file.filePath, + names: [...moduleTypeBindings(file).keys()].sort(), + })) + .sort((a, b) => a.path.localeCompare(b.path)); + expect(bindings(forward)).toEqual(bindings(reversed)); + expect(moduleTypeBinding(forward, 'p3/C3.java', 'create0')).toBeUndefined(); + }); +}); + function parseAll(files: readonly InMemoryFile[]): ParsedFile[] { const parsed: ParsedFile[] = []; for (const f of files) { diff --git a/gitnexus/test/unit/taint/disk-scope.test.ts b/gitnexus/test/unit/taint/disk-scope.test.ts index b220cc28ea..fdb4767911 100644 --- a/gitnexus/test/unit/taint/disk-scope.test.ts +++ b/gitnexus/test/unit/taint/disk-scope.test.ts @@ -96,7 +96,12 @@ describe('taint emission after the disk scope seal', () => { expect(sinks(1)).toEqual([]); expect(sinks(2)).toEqual([ { param: 0, sinkKind: 'command-injection' }, - { param: 1, sinkKind: 'command-injection' }, + { + param: 1, + sinkKind: 'command-injection', + valueEffect: { kind: 'input' }, + inertCommandPrefixes: ['git log -1 ', 'git log -1 --format=%s ', 'git show '], + }, ]); expect(sinks(3)).toEqual([]); }); diff --git a/gitnexus/test/unit/taint/guard-refinement.test.ts b/gitnexus/test/unit/taint/guard-refinement.test.ts new file mode 100644 index 0000000000..f9fe3e0697 --- /dev/null +++ b/gitnexus/test/unit/taint/guard-refinement.test.ts @@ -0,0 +1,145 @@ +import { describe, expect, it } from 'vitest'; +import { cfgOf, parse } from '../../helpers/ts-cfg-harness.js'; +import { + computeGuardRefinements, + createFunctionRefinement, + type GuardFacts, +} from '../../../src/core/ingestion/taint/guard-refinement.js'; + +function fixture(body = 'if (!valid(x)) return; consume(x);') { + const cfg = cfgOf(`function f(x: string) { ${body} }`); + const subject = cfg.bindings!.findIndex((binding) => binding.name === 'x'); + const condition = cfg.blocks.find((block) => block.text.includes('valid(x)'))!.index; + const sink = cfg.blocks.find((block) => block.text.includes('consume(x)'))!.index; + const facts: GuardFacts = { + eligible: true, + primitiveBindings: [subject], + predicates: [ + { + block: condition, + subject, + accepts: false, + restriction: { chars: 'abcdef0123456789', min: 7, max: 40 }, + }, + ], + }; + return { cfg, subject, sink, facts }; +} + +describe('accepted-edge guard proof', () => { + it('discards malformed optional call facts without breaking baseline analysis', () => { + const cfg = cfgOf( + 'function f(x: string) { if (!/^[0-9a-f]{7,40}$/.test(x)) return; consume("git show " + x); }', + ); + const malformed = { + ...cfg, + blocks: cfg.blocks.map((block) => ({ + ...block, + statements: block.statements?.map((statement) => ({ + ...statement, + ...(statement.refinement?.calls + ? { + refinement: { + ...statement.refinement, + calls: statement.refinement.calls.map((call) => ({ ...call, site: 9999 })), + }, + } + : {}), + })), + })), + }; + const refinement = createFunctionRefinement(malformed); + expect(refinement.argument(4, 0, 0, 0)).toBeUndefined(); + expect(refinement.isPredicate(2, 0, 0)).toBe(false); + expect( + createFunctionRefinement({ ...cfg, refinementSafe: undefined }).argument(4, 0, 0, 0), + ).toBeUndefined(); + }); + it('charges large statement operand lists against the traversal budget', () => { + const { cfg, facts } = fixture(); + const oversized = { + ...cfg, + blocks: cfg.blocks.map((block) => ({ + ...block, + statements: block.statements?.map((statement) => ({ + ...statement, + uses: Array(1000).fill(0), + })), + })), + }; + const proof = computeGuardRefinements(oversized, facts, { maxVisits: 128 }); + expect(proof.status).toBe('fallback'); + expect(proof.visits).toBeLessThanOrEqual(129); + }); + + it.each(['if (!/^[0-9a-f]{7,40}$/.test(ref)) return;', 'if (ref !== "abcdef0") return;'])( + 'rejects a proof when an escaped spelling can hide a write: %s', + (guard) => { + const source = + 'function f(ref:string) {' + + guard + + String.raw` \u0072ef = input(); consume('git show ' + ref); }`; + expect(parse(source).hasError).toBe(false); + const cfg = cfgOf(source); + expect(cfg.refinementSafe).toBe(false); + expect(createFunctionRefinement(cfg).guards.status).toBe('fallback'); + }, + ); + + it('certifies only uses dominated by the accepted edge', () => { + const { cfg, facts, subject, sink } = fixture(); + const proof = computeGuardRefinements(cfg, facts); + expect(proof.status).toBe('computed'); + expect(proof.at(subject, sink)?.min).toBe(7); + expect(proof.at(subject, cfg.entryIndex)).toBeUndefined(); + }); + + it('does not borrow validation from the rejected edge', () => { + const { cfg, facts, subject, sink } = fixture('if (valid(x)) return; consume(x);'); + const predicates = facts.predicates.map((predicate) => ({ ...predicate, accepts: true })); + expect( + computeGuardRefinements(cfg, { ...facts, predicates }).at(subject, sink), + ).toBeUndefined(); + }); + + it('rejects a guard with a bypass path', () => { + const { cfg, facts, subject, sink } = fixture( + 'if (flag) { if (!valid(x)) return; } consume(x);', + ); + expect(computeGuardRefinements(cfg, facts).at(subject, sink)).toBeUndefined(); + }); + + it('charges transitive alias expansion to the same traversal budget', () => { + const { cfg, facts, subject } = fixture(); + const aliases = new Map( + Array.from({ length: 200 }, (_, index) => [ + subject + index, + { kind: 'binding' as const, binding: subject + index + 1 }, + ]), + ); + const proof = computeGuardRefinements(cfg, facts, { maxVisits: 128 }, aliases); + expect(proof.status).toBe('fallback'); + expect(proof.visits).toBeLessThanOrEqual(129); + expect(proof.at(subject, cfg.entryIndex)).toBeUndefined(); + }); + + it('does not certify reassigned parameters or unknown primitive identity', () => { + const { cfg, facts, subject, sink } = fixture( + 'if (!valid(x)) return; x = input(); consume(x);', + ); + expect(computeGuardRefinements(cfg, facts).at(subject, sink)).toBeUndefined(); + expect( + computeGuardRefinements(cfg, { ...facts, primitiveBindings: [] }).at(subject, sink), + ).toBeUndefined(); + }); + + it('retains no proof after a traversal budget failure or unsupported region', () => { + const { cfg, facts, subject, sink } = fixture(); + const capped = computeGuardRefinements(cfg, facts, { maxVisits: 1 }); + expect(capped.status).toBe('fallback'); + expect(capped.at(subject, sink)).toBeUndefined(); + expect( + computeGuardRefinements(cfg, { ...facts, eligible: false }).at(subject, sink), + ).toBeUndefined(); + }); +}); diff --git a/gitnexus/test/unit/taint/interproc-solver.test.ts b/gitnexus/test/unit/taint/interproc-solver.test.ts index 47e15ab2a7..34591fccd9 100644 --- a/gitnexus/test/unit/taint/interproc-solver.test.ts +++ b/gitnexus/test/unit/taint/interproc-solver.test.ts @@ -42,6 +42,144 @@ function summary( const map = (...ss: FunctionSummary[]) => new Map(ss.map((s) => [s.fnId, s])); +describe('guard value composition', () => { + it('caps retained worklist payload across weakening alternatives', () => { + const source = summary('source', { + paramCount: 0, + sourceToCallArg: ['a', 'b', 'c'].map((chars) => ({ + sourceKind: 'remote-input', + callLine: 1, + argIndex: 0, + calleeName: 'sink', + valueEffect: { + kind: 'concat', + parts: [ + { kind: 'literal', value: 'git show ' }, + { kind: 'restrict', value: { kind: 'input' }, restriction: { chars, min: 1, max: 1 } }, + ], + }, + })), + }); + const sink = summary('sink', { + paramToSink: [ + { + param: 0, + sinkKind: 'command-injection', + inertCommandPrefixes: ['git show '], + valueEffect: { kind: 'input' }, + }, + ], + }); + const result = solveInterprocTaint( + map(source, sink), + [{ callerId: source.fnId, calleeId: sink.fnId, calleeName: 'sink' }], + { maxRefinementBytes: 150 }, + ); + expect(result.refinementFallback).toBe(true); + expect(result.findings).toHaveLength(1); + }); + + const safeValue = { + kind: 'concat', + parts: [ + { kind: 'literal', value: 'git show ' }, + { + kind: 'restrict', + value: { kind: 'input' }, + restriction: { chars: '0123456789abcdef', min: 7, max: 40 }, + }, + ], + } as const; + const source = (id: string, unsafe = false) => + summary(id, { + paramCount: 0, + sourceToCallArg: [ + { + sourceKind: 'remote-input', + callLine: 1, + argIndex: 0, + calleeName: 'sink', + valueEffect: safeValue, + }, + ...(unsafe + ? [{ sourceKind: 'remote-input' as const, callLine: 2, argIndex: 0, calleeName: 'sink' }] + : []), + ], + }); + const sink = () => + summary('sink', { + paramToSink: [ + { + param: 0, + sinkKind: 'command-injection', + valueEffect: { kind: 'input' }, + inertCommandPrefixes: ['git show '], + }, + ], + }); + + it('suppresses only the source whose complete command meets the sink contract', () => { + const safe = source('safe'); + const unsafe = summary('unsafe', { + sourceToCallArg: [ + { sourceKind: 'remote-input', callLine: 1, argIndex: 0, calleeName: 'sink' }, + ], + }); + const result = solveInterprocTaint(map(safe, unsafe, sink()), [ + { callerId: 'safe', calleeId: 'sink', calleeName: 'sink' }, + { callerId: 'unsafe', calleeId: 'sink', calleeName: 'sink' }, + ]); + expect(result.findings.map((finding) => finding.sourceFnId)).toEqual(['unsafe']); + }); + + it('keeps a mixed safe/unsafe route from the same source reported', () => { + const mixed = source('mixed', true); + const result = solveInterprocTaint(map(mixed, sink()), [ + { callerId: 'mixed', calleeId: 'sink', calleeName: 'sink' }, + ]); + expect(result.findings).toHaveLength(1); + }); + + it('reconsiders earlier clean states when the global proof budget is exhausted', () => { + const result = solveInterprocTaint( + map(source('first'), source('second'), sink()), + [ + { callerId: 'first', calleeId: 'sink', calleeName: 'sink' }, + { callerId: 'second', calleeId: 'sink', calleeName: 'sink' }, + ], + { maxRefinementBytes: 150 }, + ); + expect(result.refinementFallback).toBe(true); + expect(result.findings.map((finding) => finding.sourceFnId)).toEqual(['first', 'second']); + }); + + it('widens recursive command growth instead of enumerating paths', () => { + const recursive = sink(); + const result = solveInterprocTaint( + map(source('source'), { + ...recursive, + paramToCallArg: [ + { + param: 0, + callLine: 3, + argIndex: 0, + calleeName: 'sink', + valueEffect: { + kind: 'concat', + parts: [{ kind: 'literal', value: 'again ' }, { kind: 'input' }], + }, + }, + ], + }), + [ + { callerId: 'source', calleeId: 'sink', calleeName: 'sink' }, + { callerId: 'sink', calleeId: 'sink', calleeName: 'sink' }, + ], + ); + expect(result.findings).toHaveLength(1); + }); +}); + describe('solveInterprocTaint — seed path respects maxHops (#2084 review P2-7)', () => { it('caps the seed path at maxHops:1 (truncated prefix, not a 2-entry path)', () => { const A = summary('Function:a.ts:A', { diff --git a/gitnexus/test/unit/taint/lexical-imports.test.ts b/gitnexus/test/unit/taint/lexical-imports.test.ts index fdd6c61a8c..6064788634 100644 --- a/gitnexus/test/unit/taint/lexical-imports.test.ts +++ b/gitnexus/test/unit/taint/lexical-imports.test.ts @@ -276,7 +276,12 @@ function unrelated(req, value) { expect(harvested.gaps).toBe(0); expect( harvested.summaries.find((summary) => summary.fnId === 'function:0')?.paramToSink, - ).toContainEqual({ param: 1, sinkKind: 'command-injection' }); + ).toContainEqual({ + param: 1, + sinkKind: 'command-injection', + valueEffect: { kind: 'input' }, + inertCommandPrefixes: ['git log -1 ', 'git log -1 --format=%s ', 'git show '], + }); expect( harvested.summaries.find((summary) => summary.fnId === 'function:1')?.paramToSink, ).toEqual([]); diff --git a/gitnexus/test/unit/taint/propagate.test.ts b/gitnexus/test/unit/taint/propagate.test.ts index 3ab4692403..6c90673db4 100644 --- a/gitnexus/test/unit/taint/propagate.test.ts +++ b/gitnexus/test/unit/taint/propagate.test.ts @@ -546,6 +546,36 @@ describe('multi-source identity — distinct sources do not merge at one def', ( // ── kind-set exclusion model (real built-in model) ────────────────────────── describe('kind-set exclusions — sanitizers neutralize their kinds only', () => { + it.each([ + ['direct alias', 'const command = "git show " + ref;', 'command', 0], + [ + 'transitive alias', + 'const args = "show " + ref; const command = "git " + args;', + 'command', + 0, + ], + ['template alias', 'const command = `git show ${ref}`;', 'command', 0], + ['unsafe template', 'const command = `git show ;${ref}`;', 'command', 1], + ['bypassed guard', 'const command = "git show " + ref;', 'command', 1], + ['mutated subject', 'ref = req.query.other; const command = "git show " + ref;', 'command', 1], + ['mutated alias', 'let command = "git show " + ref; command = req.query.other;', 'command', 1], + ])('keeps certificate semantics across blocks: %s', (name, definition, argument, findings) => { + const guard = 'if (!/^[0-9a-f]{7,40}$/.test(ref)) return;'; + const r = analyze( + `import {execSync} from 'node:child_process'; +function f(req: any, log: boolean) { + ${name === 'mutated subject' ? 'let' : 'const'} ref: string = req.query.ref; + ${name === 'bypassed guard' ? `if (log) { ${guard} }` : guard} + ${definition} + if (log) console.log('validated'); + execSync(${argument}); +}`, + { spec: TS_JS_TAINT_MODEL }, + ); + expect(r.status).toBe('computed'); + expect(r.findings).toHaveLength(findings); + }); + it('built-in model catches argv-form child_process command sinks', () => { const r = analyze( `import { execFileSync } from 'node:child_process'; diff --git a/gitnexus/test/unit/taint/summary-model.test.ts b/gitnexus/test/unit/taint/summary-model.test.ts index 7ceda74d9e..e6a6ba3c21 100644 --- a/gitnexus/test/unit/taint/summary-model.test.ts +++ b/gitnexus/test/unit/taint/summary-model.test.ts @@ -28,6 +28,31 @@ const baseFacts: Facts = { }; describe('ownFactsDigest', () => { + it('includes value effects and sink-use contracts in summary identity', () => { + const restricted: Facts = { + ...baseFacts, + paramToSink: [ + { + param: 0, + sinkKind: 'command-injection', + valueEffect: { kind: 'input' }, + inertCommandPrefixes: ['git show ', 'git log -1 '], + }, + ], + }; + const other: Facts = { + ...restricted, + paramToSink: [{ ...restricted.paramToSink[0], valueEffect: { kind: 'unknown' } }], + }; + const reordered: Facts = { + ...restricted, + paramToSink: [ + { ...restricted.paramToSink[0], inertCommandPrefixes: ['git log -1 ', 'git show '] }, + ], + }; + expect(ownFactsDigest(restricted)).not.toBe(ownFactsDigest(other)); + expect(ownFactsDigest(restricted)).toBe(ownFactsDigest(reordered)); + }); it('is stable for identical facts', () => { expect(ownFactsDigest(baseFacts)).toBe(ownFactsDigest({ ...baseFacts })); }); diff --git a/gitnexus/test/unit/taint/value-refinement.test.ts b/gitnexus/test/unit/taint/value-refinement.test.ts new file mode 100644 index 0000000000..3f99854b82 --- /dev/null +++ b/gitnexus/test/unit/taint/value-refinement.test.ts @@ -0,0 +1,98 @@ +import { describe, expect, it } from 'vitest'; +import { + applyValueEffect, + joinRefinedValues, + parseAnchoredAsciiPattern, + provesInertCommand as evaluateCommand, + UNKNOWN_VALUE, + type ValueEffect, + type RefinedValue, +} from '../../../src/core/ingestion/taint/value-refinement.js'; + +const provesInertCommand = (value: RefinedValue) => + evaluateCommand(value, ['git log -1 ', 'git log -1 --format=%s ', 'git show ']); + +describe('bounded value refinements', () => { + const restriction = { chars: '0123456789abcdef', min: 7, max: 40 }; + const validated: ValueEffect = { kind: 'restrict', value: { kind: 'input' }, restriction }; + const prefix = (text: string, value: ValueEffect): ValueEffect => ({ + kind: 'concat', + parts: [{ kind: 'literal', value: text }, value], + }); + + it('composes validator and literal construction across function boundaries', () => { + const args = applyValueEffect(prefix('log -1 ', validated), UNKNOWN_VALUE); + const command = applyValueEffect(prefix('git ', { kind: 'input' }), args); + expect(provesInertCommand(command)).toBe(true); + expect( + provesInertCommand( + applyValueEffect(prefix('git log -1 --format=%s ', validated), UNKNOWN_VALUE), + ), + ).toBe(true); + expect( + provesInertCommand(applyValueEffect(prefix('git show ', validated), UNKNOWN_VALUE)), + ).toBe(true); + }); + + it.each(['bash -c ', 'git -c alias.foo=!sh foo ', 'git ', 'env '])( + 'does not certify executable or interpreter selection: %s', + (text) => + expect(provesInertCommand(applyValueEffect(prefix(text, validated), UNKNOWN_VALUE))).toBe( + false, + ), + ); + + it('keeps an independent unknown contribution unsafe', () => { + const effect: ValueEffect = { + kind: 'concat', + parts: [prefix('git log -1 ', validated), { kind: 'unknown' }], + }; + expect(provesInertCommand(applyValueEffect(effect, UNKNOWN_VALUE))).toBe(false); + }); + + it('weakens safe/unsafe joins and recursive template growth to unknown', () => { + const safe = applyValueEffect(prefix('git show ', validated), UNKNOWN_VALUE); + expect(joinRefinedValues(safe, UNKNOWN_VALUE)).toEqual(UNKNOWN_VALUE); + const growing = applyValueEffect(prefix('again ', { kind: 'input' }), safe); + expect(joinRefinedValues(safe, growing)).toEqual(UNKNOWN_VALUE); + }); + + it('does not turn a known incompatible object into a primitive proof', () => { + const incompatible: RefinedValue = { kind: 'non-string' }; + const first = applyValueEffect(validated, incompatible); + expect(first).toEqual(incompatible); + for (const value of [first, joinRefinedValues(incompatible, UNKNOWN_VALUE)]) { + const second = applyValueEffect(prefix('git show ', validated), value); + expect(provesInertCommand(second)).toBe(false); + } + expect(joinRefinedValues(UNKNOWN_VALUE, incompatible)).toEqual(incompatible); + expect(applyValueEffect(prefix('git show ', { kind: 'input' }), incompatible)).toEqual( + incompatible, + ); + }); + + it('discards all proof when an expression exceeds its budget', () => { + let effect: ValueEffect = validated; + for (let i = 0; i < 40; i++) effect = { kind: 'restrict', value: effect, restriction }; + expect(applyValueEffect(effect, UNKNOWN_VALUE)).toEqual(UNKNOWN_VALUE); + }); + + it('parses only the bounded, fully anchored ASCII predicate subset', () => { + expect(parseAnchoredAsciiPattern('^[0-9a-f]{7,40}$', '')).toEqual(restriction); + expect(parseAnchoredAsciiPattern('^[a-z][0-9]{2}$', '')).toEqual({ + chars: '0123456789abcdefghijklmnopqrstuvwxyz', + min: 3, + max: 3, + }); + for (const [pattern, flags] of [ + ['[0-9a-f]{7,40}', ''], + ['^[0-9a-f]+$', ''], + ['^[^;]+$', ''], + ['^[0-9a-f]{7,40}$', 'g'], + ['^[0-9a-f]{7,40}$', 'm'], + ['^(a+)+$', ''], + ['^[a-z]{1,999999999}$', ''], + ]) + expect(parseAnchoredAsciiPattern(pattern, flags)).toBeUndefined(); + }); +}); diff --git a/gitnexus/test/unit/tools.test.ts b/gitnexus/test/unit/tools.test.ts index 1439ebcda1..6467a60044 100644 --- a/gitnexus/test/unit/tools.test.ts +++ b/gitnexus/test/unit/tools.test.ts @@ -489,7 +489,14 @@ describe('GITNEXUS_TOOLS', () => { 'sources read inside inline callbacks and returned handlers can flow through helper functions', ); expect(d.toLowerCase()).toContain('property/field'); - expect(d.toLowerCase()).toContain('guard-style'); + expect(d.toLowerCase()).toContain( + 'modeled guards can refine unchanged primitive-string values', + ); + expect(d.toLowerCase()).toContain('imported and wrapper validators'); + expect(d.toLowerCase()).toContain( + 'unsupported predicates or sink uses remain conservative findings', + ); + expect(d.toLowerCase()).toContain('declared string types are analysis assumptions'); expect(d.toLowerCase()).toContain('cross-function'); expect(d.toLowerCase()).toContain('commonjs'); expect(d.toLowerCase()).toContain('exception'); diff --git a/gitnexus/test/unit/vector-artifact-coverage.test.ts b/gitnexus/test/unit/vector-artifact-coverage.test.ts new file mode 100644 index 0000000000..9413db8d10 --- /dev/null +++ b/gitnexus/test/unit/vector-artifact-coverage.test.ts @@ -0,0 +1,37 @@ +import { createHash } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, it } from 'vitest'; +import { resolveVendoredVectorPath } from '../../src/core/lbug/vendored-extension-path.js'; + +const vendorRoot = fileURLToPath(new URL('../../vendor/', import.meta.url)); +const manifest = JSON.parse( + readFileSync(new URL('../../vendor/lbug-vector/manifest.json', import.meta.url), 'utf8'), +) as { + coreVersion: string; + artifacts: Array<{ tuple: string; sha256: string }>; +}; +const pkg = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8')) as { + dependencies: Record; + files: string[]; +}; + +describe('packaged VECTOR artifacts', () => { + it('pins the artifacts to the installed core version and includes their provenance in npm', () => { + expect(manifest.coreVersion).toBe(pkg.dependencies['@ladybugdb/core']); + expect(pkg.files).toContain('vendor/lbug-vector/manifest.json'); + expect(manifest.artifacts.map(({ tuple }) => tuple).sort()).toEqual([ + 'darwin-arm64', + 'darwin-x64', + 'linux-arm64', + 'linux-x64', + 'win32-x64', + ]); + }); + + it.each(manifest.artifacts)('ships the verified $tuple binary', ({ tuple, sha256 }) => { + const artifact = resolveVendoredVectorPath({ vendorRoot, tuple }); + if (artifact === null) throw new Error(`Missing packaged VECTOR artifact for ${tuple}`); + expect(createHash('sha256').update(readFileSync(artifact)).digest('hex')).toBe(sha256); + }); +}); diff --git a/gitnexus/test/unit/vendored-extension-path.test.ts b/gitnexus/test/unit/vendored-extension-path.test.ts index ca380f0320..0c180e33c6 100644 --- a/gitnexus/test/unit/vendored-extension-path.test.ts +++ b/gitnexus/test/unit/vendored-extension-path.test.ts @@ -9,6 +9,7 @@ import { readFtsArtifactManifest, resolveFtsVersionPair, resolveVendoredFtsPath, + resolveVendoredVectorPath, isUnsupportedFtsTuple, validateVendoredExtensionPath, } from '../../src/core/lbug/vendored-extension-path.js'; @@ -77,6 +78,28 @@ describe('resolveVendoredFtsPath', () => { }); }); +describe('resolveVendoredVectorPath', () => { + it('resolves only the requested platform artifact', () => { + const vendorRoot = makeVendorRoot(); + const dir = join(vendorRoot, 'lbug-vector', 'prebuilds', 'linux-x64'); + mkdirSync(dir, { recursive: true }); + const artifact = join(dir, 'libvector.lbug_extension'); + writeFileSync(artifact, 'placeholder'); + + expect(resolveVendoredVectorPath({ vendorRoot, tuple: 'linux-x64' })).toBe(artifact); + expect(resolveVendoredVectorPath({ vendorRoot, tuple: 'win32-arm64' })).toBeNull(); + }); + + it('rejects a tuple that escapes the vendor root', () => { + const parent = makeVendorRoot(); + const vendorRoot = join(parent, 'vendor'); + mkdirSync(vendorRoot); + writeFileSync(join(parent, 'libvector.lbug_extension'), 'outside'); + + expect(resolveVendoredVectorPath({ vendorRoot, tuple: '../../..' })).toBeNull(); + }); +}); + describe('resolveFtsVersionPair', () => { it('reads expected from the manifest and found from a Ladybug home path', () => { const vendorRoot = makeVendorRoot(); diff --git a/gitnexus/test/unit/wiki-generator-slugs.test.ts b/gitnexus/test/unit/wiki-generator-slugs.test.ts new file mode 100644 index 0000000000..22e5d8be12 --- /dev/null +++ b/gitnexus/test/unit/wiki-generator-slugs.test.ts @@ -0,0 +1,222 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { WikiGenerator, type ModuleTreeNode } from '../../src/core/wiki/generator.js'; + +const { + callLLMMock, + getIntraModuleCallEdgesMock, + getProcessesForFilesMock, + getInterModuleEdgesForOverviewMock, + getAllProcessesMock, +} = vi.hoisted(() => ({ + callLLMMock: vi.fn(), + getIntraModuleCallEdgesMock: vi.fn().mockResolvedValue([]), + getProcessesForFilesMock: vi.fn().mockResolvedValue([]), + getInterModuleEdgesForOverviewMock: vi.fn().mockResolvedValue([]), + getAllProcessesMock: vi.fn().mockResolvedValue([]), +})); + +vi.mock('../../src/core/wiki/graph-queries.js', () => ({ + initWikiDb: vi.fn().mockResolvedValue(undefined), + closeWikiDb: vi.fn().mockResolvedValue(undefined), + touchWikiDb: vi.fn(), + pinWikiDb: vi.fn(() => vi.fn()), + getFilesWithExports: vi.fn().mockResolvedValue([]), + getAllFiles: vi.fn().mockResolvedValue([]), + getIntraModuleCallEdges: getIntraModuleCallEdgesMock, + getInterModuleCallEdges: vi.fn().mockResolvedValue({ incoming: [], outgoing: [] }), + getProcessesForFiles: getProcessesForFilesMock, + getAllProcesses: getAllProcessesMock, + getInterModuleEdgesForOverview: getInterModuleEdgesForOverviewMock, +})); + +vi.mock('../../src/core/wiki/llm-client.js', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + callLLM: callLLMMock, + }; +}); + +describe('WikiGenerator slug propagation in prompts', () => { + let tmpRepoDir: string; + let tmpStorageDir: string; + let tmpWikiDir: string; + + beforeEach(async () => { + tmpRepoDir = await fs.mkdtemp(path.join(os.tmpdir(), 'wiki-slugs-repo-')); + tmpStorageDir = path.join(tmpRepoDir, '.gitnexus'); + tmpWikiDir = path.join(tmpStorageDir, 'wiki'); + await fs.mkdir(tmpWikiDir, { recursive: true }); + + await fs.writeFile( + path.join(tmpRepoDir, 'package.json'), + JSON.stringify({ name: 'test-project', description: 'Test project description' }), + 'utf-8', + ); + + callLLMMock.mockReset(); + callLLMMock.mockResolvedValue({ + content: '## Overview\n\nGenerated documentation content.', + }); + getIntraModuleCallEdgesMock.mockResolvedValue([]); + getProcessesForFilesMock.mockResolvedValue([]); + getInterModuleEdgesForOverviewMock.mockResolvedValue([]); + getAllProcessesMock.mockResolvedValue([]); + }); + + afterEach(async () => { + vi.restoreAllMocks(); + await fs.rm(tmpRepoDir, { recursive: true, force: true }); + }); + + function createGenerator(): WikiGenerator { + return new WikiGenerator(tmpRepoDir, tmpStorageDir, '/dummy/lbug', { + apiKey: 'test-key', + baseUrl: 'https://test.local', + model: 'test-model', + maxTokens: 1000, + temperature: 0, + provider: 'openai', + }); + } + + it('generateParentPage passes each child module real slug (.md file) in the prompt context', async () => { + const generator = createGenerator(); + + const child1Slug = 'pkg-a-launch'; + const child2Slug = 'pkg-a-composition-database'; + + await fs.writeFile( + path.join(tmpWikiDir, `${child1Slug}.md`), + '# pkg_a — launch\n\nLaunch sub-module handles startup.\n### Architecture\nStartup details...', + 'utf-8', + ); + await fs.writeFile( + path.join(tmpWikiDir, `${child2Slug}.md`), + '# pkg_a — composition/database\n\nDatabase sub-module handles pooling.\n### Architecture\nPool details...', + 'utf-8', + ); + + const parentNode: ModuleTreeNode = { + name: 'pkg_a — Launch & Database', + slug: 'pkg-a-launch-database', + files: [], + children: [ + { + name: 'pkg_a — launch', + slug: child1Slug, + files: ['packages/a/launch.ts'], + }, + { + name: 'pkg_a — composition/database', + slug: child2Slug, + files: ['packages/a/db.ts'], + }, + ], + }; + + await (generator as any).generateParentPage(parentNode); + + expect(callLLMMock).toHaveBeenCalledTimes(1); + const capturedPrompt = callLLMMock.mock.calls[0][0] as string; + + // Both real file targets must appear in the prompt so the LLM does not guess slugs + expect(capturedPrompt).toContain(`${child1Slug}.md`); + expect(capturedPrompt).toContain(`${child2Slug}.md`); + }); + + it('generateParentPage passes child slug even when child doc is not yet generated', async () => { + const generator = createGenerator(); + + const childSlug = 'pkg-b-use-cases-1-4'; + const parentNode: ModuleTreeNode = { + name: 'pkg_b — Use Cases', + slug: 'pkg-b-use-cases', + files: [], + children: [ + { + name: 'pkg_b — use_cases (1/4)', + slug: childSlug, + files: ['packages/b/uc1.ts'], + }, + ], + }; + + await (generator as any).generateParentPage(parentNode); + + expect(callLLMMock).toHaveBeenCalledTimes(1); + const capturedPrompt = callLLMMock.mock.calls[0][0] as string; + + expect(capturedPrompt).toContain(`${childSlug}.md`); + }); + + it('generateOverview passes each module real slug (.md file) in the prompt context', async () => { + const generator = createGenerator(); + + const mod1Slug = 'pkg-a-launch-database'; + const mod2Slug = 'pkg-c'; + + await fs.writeFile( + path.join(tmpWikiDir, `${mod1Slug}.md`), + '# pkg_a — Launch & Database\n\nParent module documentation.\n### Architecture\nDetails...', + 'utf-8', + ); + await fs.writeFile( + path.join(tmpWikiDir, `${mod2Slug}.md`), + '# pkg_c\n\nModule C documentation.\n### Architecture\nDetails...', + 'utf-8', + ); + + const moduleTree: ModuleTreeNode[] = [ + { + name: 'pkg_a — Launch & Database', + slug: mod1Slug, + files: [], + children: [ + { + name: 'pkg_a — launch', + slug: 'pkg-a-launch', + files: ['packages/a/launch.ts'], + }, + ], + }, + { + name: 'pkg_c', + slug: mod2Slug, + files: ['packages/c/index.ts'], + }, + ]; + + await (generator as any).generateOverview(moduleTree); + + expect(callLLMMock).toHaveBeenCalledTimes(1); + const capturedPrompt = callLLMMock.mock.calls[0][0] as string; + + // Both real file targets must appear in the prompt so the LLM does not guess slugs + expect(capturedPrompt).toContain(`${mod1Slug}.md`); + expect(capturedPrompt).toContain(`${mod2Slug}.md`); + }); + + it('generateOverview passes module slug even when module doc is pending', async () => { + const generator = createGenerator(); + + const modSlug = 'pkg-c-pending'; + const moduleTree: ModuleTreeNode[] = [ + { + name: 'pkg_c pending module', + slug: modSlug, + files: ['packages/c/pending.ts'], + }, + ]; + + await (generator as any).generateOverview(moduleTree); + + expect(callLLMMock).toHaveBeenCalledTimes(1); + const capturedPrompt = callLLMMock.mock.calls[0][0] as string; + + expect(capturedPrompt).toContain(`${modSlug}.md`); + }); +}); diff --git a/gitnexus/test/unit/wiki-mermaid-sanitizer-parse.test.ts b/gitnexus/test/unit/wiki-mermaid-sanitizer-parse.test.ts new file mode 100644 index 0000000000..f84c5642c3 --- /dev/null +++ b/gitnexus/test/unit/wiki-mermaid-sanitizer-parse.test.ts @@ -0,0 +1,348 @@ +// @vitest-environment jsdom +import { readFileSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { runInThisContext } from 'node:vm'; +import { describe, expect, it } from 'vitest'; + +import { sanitizeMermaidDiagram } from '../../src/core/wiki/mermaid-sanitizer.js'; + +// The official tiny browser bundle includes the same flowchart parser as the +// viewer's Mermaid 11, without installing the full renderer dependency tree. +// It is a script, not an importable module; execute it as a browser script in +// this test fork's jsdom environment. Nothing here ships with the CLI. +const require = createRequire(import.meta.url); +runInThisContext(readFileSync(require.resolve('@mermaid-js/tiny'), 'utf8')); +const mermaid = ( + globalThis as unknown as { + mermaid: { + initialize(config: { startOnLoad: boolean }): void; + mermaidAPI: { getDiagramFromText(text: string): Promise<{ db: unknown }> }; + }; + } +).mermaid; + +type Graph = { + nodes: string[]; + edges: string[]; + labels: Array<{ text: string; type: string }>; + links: Array<{ text: string; type: string; stroke: string }>; +}; + +async function parseFlowchart(diagram: string): Promise { + const parsed = await mermaid.mermaidAPI.getDiagramFromText(diagram); + const db = parsed.db as { + getVertices(): Map; + getEdges(): Array<{ start: string; end: string; text: string; type: string; stroke: string }>; + }; + return { + nodes: [...db.getVertices().keys()], + edges: db.getEdges().map((edge) => `${edge.start}->${edge.end}`), + labels: [...db.getVertices().values()].map(({ text, type }) => ({ text, type })), + links: db.getEdges().map(({ text, type, stroke }) => ({ text, type, stroke })), + }; +} + +describe('sanitizeMermaidDiagram, checked with the Mermaid parser', () => { + mermaid.initialize({ startOnLoad: false }); + + it('keeps the three diagrams from the report unchanged and valid', async () => { + const diagrams = [ + 'flowchart TD\n A["value.when(...)"] -->|data| B["data"]', + 'flowchart TD\n G["x = compute(...).result"] --> H["done"]', + 'flowchart LR\n N -- ref.invalidate --> A', + ]; + + for (const diagram of diagrams) { + expect(sanitizeMermaidDiagram(diagram)).toBe(diagram); + await expect(parseFlowchart(diagram)).resolves.toBeTruthy(); + } + }); + + it('leaves rounded, circular and other shaped nodes alone at both ends of a link', async () => { + const diagrams = [ + 'flowchart LR\n A(Start) --> B', + 'flowchart LR\n X --> Y(Done)', + 'flowchart LR\n A((Start)) --> B(End)', + 'flowchart LR\n A[(db)] --> B{Choice} --> C>flag]', + 'flowchart LR\n A([Stadium]) -->|yes| B[[Sub]]', + ]; + + for (const diagram of diagrams) { + const sanitized = sanitizeMermaidDiagram(diagram); + expect(sanitized).toBe(diagram); + expect(await parseFlowchart(sanitized)).toEqual(await parseFlowchart(diagram)); + } + }); + + it('aliases every reference of a node in a chained link, plain and thick', async () => { + const plain = ['flowchart LR', ' A --- file.ts --- B', ' file.ts --> C'].join('\n'); + const thick = ['flowchart LR', ' A === file.ts === B', ' file.ts ==> C'].join('\n'); + + for (const diagram of [plain, thick]) { + const original = await parseFlowchart(diagram); + const graph = await parseFlowchart(sanitizeMermaidDiagram(diagram)); + // One node, under one id, with the same links as before. + expect(graph.nodes).toEqual(['A', 'file_ts', 'B', 'C']); + expect(graph.edges).toEqual(['A->file_ts', 'file_ts->B', 'file_ts->C']); + expect(graph.edges).toHaveLength(original.edges.length); + } + }); + + it('keeps labelled links written without spaces, and links with a cross or circle head', async () => { + const spaced = 'flowchart LR\n A --text--> B\n B ==text==> C\n C -.text.-> D'; + expect(sanitizeMermaidDiagram(spaced)).toBe(spaced); + expect((await parseFlowchart(spaced)).edges).toEqual(['A->B', 'B->C', 'C->D']); + + const heads = 'flowchart LR\n A --x B --> C\n C --o D\n D x--x E'; + expect(sanitizeMermaidDiagram(heads)).toBe(heads); + expect((await parseFlowchart(heads)).edges).toEqual(['A->B', 'B->C', 'C->D', 'D->E']); + }); + + it('reads a compact cross or circle link as a link, so the node after it is aliased too', async () => { + const cross = ['flowchart LR', ' A --xfile.ts --> B', ' file.ts --> C'].join('\n'); + const circle = ['flowchart LR', ' A --ofile.ts --> B', ' file.ts --> C'].join('\n'); + + for (const diagram of [cross, circle]) { + const graph = await parseFlowchart(sanitizeMermaidDiagram(diagram)); + expect(graph.nodes).toEqual(['A', 'file_ts', 'B', 'C']); + expect(graph.edges).toEqual(['A->file_ts', 'file_ts->B', 'file_ts->C']); + } + }); + + it('still repairs a call-shaped node id', async () => { + const sanitized = sanitizeMermaidDiagram('flowchart LR\n doc() --> B'); + + expect(sanitized).toBe('flowchart LR\n doc["doc()"] --> B'); + expect((await parseFlowchart(sanitized)).edges).toEqual(['doc->B']); + }); + + it('repairs a qualified call-shaped id as one node, at either end of a link', async () => { + const diagram = ['flowchart LR', ' foo().bar --> B', ' A --> foo().bar'].join('\n'); + + const sanitized = sanitizeMermaidDiagram(diagram); + const graph = await parseFlowchart(sanitized); + + expect(sanitized).toContain('foo___bar["foo().bar"] --> B'); + expect(sanitized).toContain('A --> foo___bar["foo().bar"]'); + expect(graph.nodes).toEqual(['foo___bar', 'B', 'A']); + expect(graph.edges).toEqual(['foo___bar->B', 'A->foo___bar']); + }); + + it('keeps the text of a labelled link and the graph around it', async () => { + const diagram = ['flowchart LR', ' cache.ts -- ref.invalidate --> store.ts'].join('\n'); + + const graph = await parseFlowchart(sanitizeMermaidDiagram(diagram)); + + expect(graph.nodes).toEqual(['cache_ts', 'store_ts']); + expect(graph.edges).toEqual(['cache_ts->store_ts']); + }); + + it('does not read pipes inside a node label as an edge label', async () => { + const diagram = 'flowchart LR\nA["a|doc()|b"] --> B'; + const sanitized = sanitizeMermaidDiagram(diagram); + expect(sanitized).toBe(diagram); + expect(await parseFlowchart(sanitized)).toEqual(await parseFlowchart(diagram)); + }); + + it('repairs an edge label even when the preceding node label contains a pipe', async () => { + const sanitized = sanitizeMermaidDiagram('flowchart LR\nA["a | b"] -->|doc()| B'); + expect(sanitized).toBe('flowchart LR\nA["a | b"] -->|"doc()"| B'); + expect((await parseFlowchart(sanitized)).edges).toEqual(['A->B']); + }); + + it.each([ + 'A & file.ts --> B\nfile.ts --> C', + 'file.ts & A --> B\nfile.ts --> C', + 'A --> B & file.ts\nfile.ts --> C', + 'A --> file.ts; file.ts --> C', + ])('preserves shared node identities in fan-out and statements: %s', async (body) => { + const original = await parseFlowchart('flowchart LR\n' + body); + const sanitized = sanitizeMermaidDiagram('flowchart LR\n' + body); + const graph = await parseFlowchart(sanitized); + expect(graph.nodes).toEqual(original.nodes.map((id) => id.replaceAll('.', '_'))); + expect(graph.edges).toEqual(original.edges.map((edge) => edge.replaceAll('.', '_'))); + expect(sanitizeMermaidDiagram(sanitized)).toBe(sanitized); + }); + + it.each(['A --> file.ts\nfile_ts --> B', 'file_ts --> B\nA --> file.ts'])( + 'does not merge an alias with an existing node: %s', + async (body) => { + const graph = await parseFlowchart(sanitizeMermaidDiagram('flowchart LR\n' + body)); + expect(graph.nodes).toHaveLength(4); + expect(graph.edges).toContain('file_ts->B'); + expect(graph.edges).toContain('A->file_ts_2'); + }, + ); + + it.each([ + '["value.when(...) | call() | a & b; c --> d"]', + '("value.when(...) | call() | a & b; c --> d")', + '(["value.when(...) | call() | a & b; c --> d"])', + '[["value.when(...) | call() | a & b; c --> d"]]', + '[("value.when(...) | call() | a & b; c --> d")]', + '(("value.when(...) | call() | a & b; c --> d"))', + '>"value.when(...) | call() | a & b; c --> d"]', + '{"value.when(...) | call() | a & b; c --> d"}', + '{{"value.when(...) | call() | a & b; c --> d"}}', + '[/"value.when(...) | call() | a & b; c --> d"/]', + '((("value.when(...) | call() | a & b; c --> d")))', + ])('preserves node shape and label contents: %s', async (shape) => { + const diagram = `flowchart LR\nA${shape} --> B${shape}`; + const original = await parseFlowchart(diagram); + const sanitized = sanitizeMermaidDiagram(diagram); + expect(sanitized).toBe(diagram); + expect(await parseFlowchart(sanitized)).toEqual(original); + }); + + it.each([ + '-->', + '---', + '<-->', + '==>', + '===', + '-.->', + '-..-', + '--x', + '--o', + 'x--x', + 'o--o', + '-- text -->', + '== text ==>', + '-. text .->', + '-->|"doc()"|', + ])('preserves link style and text: %s', async (link) => { + const diagram = `flowchart LR\nA ${link} B`; + expect(await parseFlowchart(sanitizeMermaidDiagram(diagram))).toEqual( + await parseFlowchart(diagram), + ); + }); + + it('leaves sequence diagram syntax to its own parser', async () => { + const diagram = 'sequenceDiagram\nclient.ts-->>server.ts: done'; + await expect(mermaid.mermaidAPI.getDiagramFromText(diagram)).resolves.toBeTruthy(); + expect(sanitizeMermaidDiagram(diagram)).toBe(diagram); + }); + + it('quotes edge labels using Mermaid entities rather than JavaScript escapes', async () => { + const sanitized = sanitizeMermaidDiagram('flowchart LR\nA -->|doc("C:\\tmp")| B'); + expect(sanitized).toBe('flowchart LR\nA -->|"doc(#quot;C:\\tmp#quot;)"| B'); + expect((await parseFlowchart(sanitized)).edges).toEqual(['A->B']); + }); + + it('keeps an asymmetric shape and its link-like label text', async () => { + const diagram = 'flowchart LR\nfile.ts>value --> other.ts & x] --> B'; + const graph = await parseFlowchart(sanitizeMermaidDiagram(diagram)); + expect(graph.nodes).toEqual(['file_ts', 'B']); + expect(graph.edges).toEqual(['file_ts->B']); + expect(graph.labels).toEqual((await parseFlowchart(diagram)).labels); + }); + + it.each(['file.ts["File"]\nA --> file.ts', 'A --> file.ts\nfile.ts["File"]'])( + 'preserves an explicit label across bare references: %s', + async (body) => { + const original = await parseFlowchart('flowchart LR\n' + body); + const graph = await parseFlowchart(sanitizeMermaidDiagram('flowchart LR\n' + body)); + expect(graph.labels).toEqual(original.labels); + }, + ); + + it('keeps style and class references attached to the aliased node', async () => { + const diagram = 'flowchart LR\nA --> file.ts\nstyle file.ts fill:red\nclass file.ts active'; + const sanitized = sanitizeMermaidDiagram(diagram); + const parsed = await mermaid.mermaidAPI.getDiagramFromText(sanitized); + const vertices = ( + parsed.db as { getVertices(): Map } + ).getVertices(); + expect([...vertices.keys()]).toEqual(['A', 'file_ts']); + expect(vertices.get('file_ts')?.styles).toContain('fill:red'); + expect(vertices.get('file_ts')?.classes).toContain('active'); + }); + + it('reserves subgraph identifiers before allocating node aliases', async () => { + const diagram = 'flowchart LR\nsubgraph file_ts\nA --> file.ts\nend'; + expect((await parseFlowchart(sanitizeMermaidDiagram(diagram))).edges).toEqual(['A->file_ts_2']); + }); + + it.each([ + ['style.css', 'style_css'], + ['direction.ts', 'direction_ts'], + ['click-handler.ts', 'node_click-handler_ts'], + ['class-loader.ts', 'node_class-loader_ts'], + ])('does not mistake the filename %s for a directive', async (id, alias) => { + const sanitized = sanitizeMermaidDiagram(`flowchart LR\n${id} --> B\nA --> ${id}`); + expect((await parseFlowchart(sanitized)).edges).toEqual([`${alias}->B`, `A->${alias}`]); + expect(sanitizeMermaidDiagram(sanitized)).toBe(sanitized); + }); + + it('preserves frontmatter while repairing the diagram below it', async () => { + const frontmatter = + '---\ntitle: "file.ts --> doc()"\nconfig:\n flowchart:\n curve: linear\n---\n'; + const sanitized = sanitizeMermaidDiagram( + frontmatter + '%% flow\nflowchart LR\ndoc() -->|doc()| B', + ); + expect(sanitized.startsWith(frontmatter)).toBe(true); + expect((await parseFlowchart(sanitized)).edges).toEqual(['doc->B']); + expect(sanitizeMermaidDiagram(sanitized)).toBe(sanitized); + }); + + it('preserves multiline initialization directives', async () => { + const prelude = '%%{init: {\n "theme": "dark"\n}}%%\n'; + const sanitized = sanitizeMermaidDiagram(prelude + 'flowchart LR\ndoc() --> B'); + expect(sanitized.startsWith(prelude)).toBe(true); + expect((await parseFlowchart(sanitized)).edges).toEqual(['doc->B']); + }); + + it('aliases nodes following a header on the same line', async () => { + const sanitized = sanitizeMermaidDiagram('flowchart LR; A --> file.ts\nfile.ts --> B'); + expect((await parseFlowchart(sanitized)).edges).toEqual(['A->file_ts', 'file_ts->B']); + }); + + it.each(['-->|returns List|', '-- returns Map -->'])( + 'keeps generic types in link text separate from the target: %s', + async (link) => { + const diagram = `flowchart LR\nA ${link} loader.ts[Loader]\nloader.ts --> C`; + const sanitized = sanitizeMermaidDiagram(diagram); + const graph = await parseFlowchart(sanitized); + expect(graph.nodes).toEqual(['A', 'loader_ts', 'C']); + expect(graph.edges).toEqual(['A->loader_ts', 'loader_ts->C']); + expect(graph.labels).toEqual((await parseFlowchart(diagram)).labels); + expect(sanitizeMermaidDiagram(sanitized)).toBe(sanitized); + }, + ); + + it.each(['shape: rect', 'shape: rect, label: "File"', 'label: "File", shape: rect'])( + 'preserves the label of a node with metadata: %s', + async (metadata) => { + const diagram = `flowchart LR\nfile.ts@{ ${metadata} }\nfile.ts --> B`; + const graph = await parseFlowchart(sanitizeMermaidDiagram(diagram)); + expect(graph.nodes).toEqual(['file_ts', 'B']); + expect(graph.labels).toEqual((await parseFlowchart(diagram)).labels); + }, + ); + + it('preserves multiline quoted labels containing diagram syntax', async () => { + const diagram = 'flowchart LR\nA["first\nfile.ts --> done & x; y"] --> file.ts\nfile.ts --> B'; + const sanitized = sanitizeMermaidDiagram(diagram); + const graph = await parseFlowchart(sanitized); + expect(graph.nodes).toEqual(['A', 'file_ts', 'B']); + const original = await parseFlowchart(diagram); + expect(graph.labels.map(({ text }) => text)).toEqual(original.labels.map(({ text }) => text)); + expect(graph.labels[0]).toEqual(original.labels[0]); + expect(sanitizeMermaidDiagram(sanitized)).toBe(sanitized); + }); + + it.each(['A:::hot --> B', 'A --> file.ts:::hot\nfile.ts --> B'])( + 'preserves class shorthand: %s', + async (body) => { + const parsed = await mermaid.mermaidAPI.getDiagramFromText( + sanitizeMermaidDiagram('flowchart LR\n' + body), + ); + const vertices = ( + parsed.db as { getVertices(): Map } + ).getVertices(); + const id = body.startsWith('A:::') ? 'A' : 'file_ts'; + expect(vertices.get(id)?.classes).toContain('hot'); + expect(vertices.size).toBe(body.startsWith('A:::') ? 2 : 3); + }, + ); +}); diff --git a/gitnexus/test/unit/wiki-mermaid-sanitizer.test.ts b/gitnexus/test/unit/wiki-mermaid-sanitizer.test.ts index e8c74c8cbb..d967755a4b 100644 --- a/gitnexus/test/unit/wiki-mermaid-sanitizer.test.ts +++ b/gitnexus/test/unit/wiki-mermaid-sanitizer.test.ts @@ -34,12 +34,12 @@ describe('sanitizeMermaidMarkdown', () => { expect(sanitized).toContain('Client -->|HTTP params| Script'); }); - it('escapes backslashes and quotes in quoted edge labels', () => { + it('encodes quotes and preserves backslashes in quoted edge labels', () => { const diagram = ['graph LR', ' Script -->|doc("C:\\\\tmp")| Target'].join('\n'); const sanitized = sanitizeMermaidDiagram(diagram); - expect(sanitized).toContain('Script -->|"doc(\\"C:\\\\\\\\tmp\\")"| Target'); + expect(sanitized).toContain('Script -->|"doc(#quot;C:\\\\tmp#quot;)"| Target'); }); it('aliases bare node IDs that contain dots and keeps display labels', () => { @@ -74,6 +74,51 @@ describe('sanitizeMermaidMarkdown', () => { expect(sanitized).toContain('file_name_ts[(eXist-db XML)] --> target_node["Target node"]'); }); + it('leaves an ellipsis or a dotted name inside a label alone', () => { + // #3705: these three diagrams are valid; sanitizing must not change them. + const diagrams = [ + 'flowchart TD\n A["value.when(...)"] -->|data| B["data"]', + 'flowchart TD\n G["x = compute(...).result"] --> H["done"]', + 'flowchart LR\n N -- ref.invalidate --> A', + ]; + + for (const diagram of diagrams) { + expect(sanitizeMermaidDiagram(diagram)).toBe(diagram); + } + }); + + it('reads dots as a link only in the dotted link syntax', () => { + const diagram = [ + 'flowchart LR', + ' A -.-> B', + ' B -. later .-> C', + ' C -..- D', + ' file.ts -.-> E["x..y"]', + ].join('\n'); + + const sanitized = sanitizeMermaidDiagram(diagram); + + expect(sanitized).toContain('A -.-> B'); + expect(sanitized).toContain('B -. later .-> C'); + expect(sanitized).toContain('C -..- D'); + expect(sanitized).toContain('file_ts["file.ts"] -.-> E["x..y"]'); + }); + + it('keeps the text of a labelled link while still aliasing the nodes around it', () => { + const diagram = [ + 'flowchart LR', + ' cache.ts -- ref.invalidate --> store.ts', + ' store.ts == on.save ==> db[(db)]', + ' a.b -- plain --> c[c --> d]', + ].join('\n'); + + const sanitized = sanitizeMermaidDiagram(diagram); + + expect(sanitized).toContain('cache_ts["cache.ts"] -- ref.invalidate --> store_ts["store.ts"]'); + expect(sanitized).toContain('store_ts["store.ts"] == on.save ==> db[(db)]'); + expect(sanitized).toContain('a_b["a.b"] -- plain --> c[c --> d]'); + }); + it('only rewrites fenced Mermaid blocks in markdown', () => { const markdown = [ 'Regular text with doc() and file.name.ts.', diff --git a/gitnexus/vendor/lbug-vector/LICENSE b/gitnexus/vendor/lbug-vector/LICENSE new file mode 100644 index 0000000000..9bb12b2468 --- /dev/null +++ b/gitnexus/vendor/lbug-vector/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2022-2025 Kùzu Inc. +Copyright (c) 2025-2026 Ladybug Memory Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/gitnexus/vendor/lbug-vector/README.md b/gitnexus/vendor/lbug-vector/README.md new file mode 100644 index 0000000000..ea5e9e8621 --- /dev/null +++ b/gitnexus/vendor/lbug-vector/README.md @@ -0,0 +1,32 @@ +# LadybugDB VECTOR artifacts + +These unmodified binaries come from the official LadybugDB +[v0.21.1 build](https://github.com/LadybugDB/ladybug/actions/runs/36647903773), +at core commit `17a70e51c31b50d30231da32154d9ff4bef0d95f` and extensions +commit `bf74ab654af6bd40a0e3208ac4e8bcf5cb45a7a0`. + +`manifest.json` records each GitHub artifact ID, the archive digest supplied by +GitHub, and the extracted binary's SHA-256. Every archive was checked against +that digest before extracting `vector/libvector.lbug_extension`. + +The core's `0.21.0` CDN compatibility path can serve a VECTOR binary built +against incompatible core symbols. Load the matching packaged artifact first +so vector indexes work without a network install or a mutable home-cache copy. +The existing `never` policy still disables the extension; missing artifacts +retain the normal named-load and install fallback. + +To refresh, select an official build matching the exact `@ladybugdb/core` pin, +download its platform artifacts, verify their GitHub archive digests, and +update the binaries and manifest together. Validate Linux, macOS, and Windows +native tests before changing the pin. Do not substitute a nightly binary. + +For example, the Linux x64 archive is available with: + +```sh +gh api repos/LadybugDB/ladybug/actions/artifacts/11069747578/zip > vector-linux.zip +``` + +GitHub Actions artifacts expire; the committed binaries and checksums preserve +the verified build. `test/unit/vector-artifact-coverage.test.ts` checks the core +pin, platform coverage, and binary digests. The upstream MIT license is included +in `LICENSE`. diff --git a/gitnexus/vendor/lbug-vector/manifest.json b/gitnexus/vendor/lbug-vector/manifest.json new file mode 100644 index 0000000000..a0a75ee0cc --- /dev/null +++ b/gitnexus/vendor/lbug-vector/manifest.json @@ -0,0 +1,46 @@ +{ + "coreVersion": "0.21.1", + "filename": "libvector.lbug_extension", + "upstreamRepository": "https://github.com/LadybugDB/ladybug", + "upstreamTag": "v0.21.1", + "upstreamCommit": "17a70e51c31b50d30231da32154d9ff4bef0d95f", + "extensionsCommit": "bf74ab654af6bd40a0e3208ac4e8bcf5cb45a7a0", + "workflowRun": "https://github.com/LadybugDB/ladybug/actions/runs/36647903773", + "artifacts": [ + { + "tuple": "linux-x64", + "artifactId": 11069747578, + "artifactName": "lbug-extensions-linux-x86_64", + "archiveSha256": "377be87f6cf0e56a38230a536e768a0914f273163f112b8101f69894a088777b", + "sha256": "571726cc2ea0d202df1909ae5a3b0528c9dea3ea8d40be6c16b310ec14aa8821" + }, + { + "tuple": "linux-arm64", + "artifactId": 11069462823, + "artifactName": "lbug-extensions-linux-aarch64", + "archiveSha256": "bec0b8c5eb7f75b1f448b1a10360dbbd82c4553e3514418e90a37065468cb4cd", + "sha256": "583101f5bf2d0e5d40de2ee8966018a3bdf0fb8ad8951ef51ef46cd59169445f" + }, + { + "tuple": "darwin-x64", + "artifactId": 11069679640, + "artifactName": "lbug-extensions-osx-x86_64", + "archiveSha256": "2ddd47cd3afb5a2bcdae37e928125a81a1aa73775bb2e5e9448033f51eb02c18", + "sha256": "7c0cea65d68c341453ce567e0d12897d0691b5f9ff01cff0fdf0db5756ab7851" + }, + { + "tuple": "darwin-arm64", + "artifactId": 11069049174, + "artifactName": "lbug-extensions-osx-arm64", + "archiveSha256": "5d004e4bb9e3dd6f6da7248135eba64998adca283390c88e95f17d46224bbf5c", + "sha256": "6f878f3c0a2320a34967ff568fcf6bbe9065666e95035f0eddfe28bbc73b53f4" + }, + { + "tuple": "win32-x64", + "artifactId": 11070343650, + "artifactName": "lbug-extensions-win-x86_64", + "archiveSha256": "cef691c45f28be517b703bfdfafdd66a7d30b7da236f96c4e57297f5e67cf9f2", + "sha256": "6a8878eb2c93400222187460f8fc20ffc9cda4fc2c382fcbdf88f72a350d5746" + } + ] +} diff --git a/gitnexus/vendor/lbug-vector/prebuilds/darwin-arm64/libvector.lbug_extension b/gitnexus/vendor/lbug-vector/prebuilds/darwin-arm64/libvector.lbug_extension new file mode 100644 index 0000000000..09df253e51 Binary files /dev/null and b/gitnexus/vendor/lbug-vector/prebuilds/darwin-arm64/libvector.lbug_extension differ diff --git a/gitnexus/vendor/lbug-vector/prebuilds/darwin-x64/libvector.lbug_extension b/gitnexus/vendor/lbug-vector/prebuilds/darwin-x64/libvector.lbug_extension new file mode 100644 index 0000000000..37c59b8126 Binary files /dev/null and b/gitnexus/vendor/lbug-vector/prebuilds/darwin-x64/libvector.lbug_extension differ diff --git a/gitnexus/vendor/lbug-vector/prebuilds/linux-arm64/libvector.lbug_extension b/gitnexus/vendor/lbug-vector/prebuilds/linux-arm64/libvector.lbug_extension new file mode 100644 index 0000000000..940de9cfa4 Binary files /dev/null and b/gitnexus/vendor/lbug-vector/prebuilds/linux-arm64/libvector.lbug_extension differ diff --git a/gitnexus/vendor/lbug-vector/prebuilds/linux-x64/libvector.lbug_extension b/gitnexus/vendor/lbug-vector/prebuilds/linux-x64/libvector.lbug_extension new file mode 100644 index 0000000000..8f627b5031 Binary files /dev/null and b/gitnexus/vendor/lbug-vector/prebuilds/linux-x64/libvector.lbug_extension differ diff --git a/gitnexus/vendor/lbug-vector/prebuilds/win32-x64/libvector.lbug_extension b/gitnexus/vendor/lbug-vector/prebuilds/win32-x64/libvector.lbug_extension new file mode 100644 index 0000000000..1fa3e01b9a Binary files /dev/null and b/gitnexus/vendor/lbug-vector/prebuilds/win32-x64/libvector.lbug_extension differ