code-intelligence 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,41 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here. Format based on [Keep a Changelog](https://keepachangelog.com/), versioning follows [SemVer](https://semver.org/).
4
+
5
+ ## [Unreleased]
6
+
7
+ ## [0.1.0]
8
+
9
+ ### Added
10
+
11
+ - `scan` with gitleaks (secrets), semgrep (SAST), osv-scanner with trivy fallback (dependencies) and ast-grep (architecture rules from the project's `sgconfig.yml`); `changed`, `staged`, `since` and `all` scopes; `quick` and `deep` profiles.
12
+ - Normalized findings with stable fingerprints, severity, location and remediation; text, JSON (`schemaVersion` 1) and SARIF 2.1.0 output.
13
+ - Exit code 3 for incomplete scans: missing engines, timeouts and crashes are never reported as a pass.
14
+ - `baseline` and `--new-only`; changed-line filtering for SAST with an explicit "hidden" count.
15
+ - `impact` (CodeGraph transitive, labelled heuristic fallback) and `mutate` (StrykerJS, scoped to changed lines).
16
+ - `doctor`, `init`, structured logging, JSON Schemas for config and report.
17
+ - Exact-match result cache for engines whose output is a pure function of file contents.
18
+
19
+ ### Security
20
+
21
+ Found by scanning this repository with itself and by an independent review that reproduced each issue; all fixed with regression tests before release:
22
+
23
+ - Glob matching is now linear-time with no regular expressions (an earlier capped-regex version was still exploitable).
24
+ - The changed-line diff parser can no longer be fooled by added lines that look like file headers.
25
+ - Cache, baseline and `init` writes never follow symlinks; baseline cannot target `.git`; a symlinked config or baseline is refused without echoing its contents.
26
+ - Files reached through a symlinked parent directory are not scanned; `git` runs with textconv and external diff disabled.
27
+ - Repository-supplied configuration that weakens a scan is always disclosed; `--ignore-repo-config` discards it.
28
+ - Cache entries are validated and keyed by config and rule-file contents (previously, editing a rule or `.gitleaks.toml` did not invalidate cached results).
29
+ - Secrets-category semgrep findings use a fixed message; text output escapes control and invisible (bidirectional, zero-width) characters; identical lines get distinct fingerprints; `impact` no longer has a quadratic regex.
30
+ - A second independent pass found the first fixes only partly effective; corrected before release:
31
+ - `--ignore-repo-config` now truly ignores the repository's gitleaks config and ignore file (previously a staged `.gitleaks.toml` was still auto-discovered while the report claimed it was ignored); inline `gitleaks:allow` / `nosemgrep` comments and `.semgrepignore` are counted and disclosed.
32
+ - The result cache moved **out of the repository** into the user's cache directory (`CODE_INTEL_CACHE_DIR` overrides it): a cache inside a scanned repository cannot be trusted.
33
+ - Exclude globs are bounded in count, expansion and total matching work.
34
+ - Git clean filters from a hostile `.git/config` are neutralized (not only textconv).
35
+ - Protected baseline paths are normalized and case-folded; baseline reads refuse symlinked parents and never echo parser messages.
36
+ - CI binary downloads use SHA-256 hashes pinned in the repository; the release job installs no third-party tools and requires the tag on `main` and a green CI run for the commit.
37
+
38
+ ### Fixed
39
+
40
+ - A repository's own `.gitleaksignore` entries now take effect (gitleaks is run from the staging directory so its fingerprints are repo-relative, as in a manual run).
41
+ - Engine error details report the real exception line (not a Python traceback header) with absolute paths scrubbed.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 micio86dev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,155 @@
1
- # Temporary Holding Version
1
+ # code-intelligence
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A small CLI, `code-intel`, that gives AI coding agents (and humans) the one thing LLM review cannot: **deterministic evidence**. It runs mature open-source scanners on _what you changed_, normalizes their output into one stable format, and reports only what matters.
4
+
5
+ It works with any agent that can run a shell command (Claude Code, Codex, OpenCode, Pi, Gentle Shell, ...). It has no dependency on any of them.
6
+
7
+ ```console
8
+ $ code-intel scan
9
+ code-intelligence 0.1.0 | profile quick | changed | 4 file(s), 0 excluded | 3.17s
10
+
11
+ Engines
12
+ [FOUND ] gitleaks 8.30.1 1 finding(s), 0.02s
13
+ [FOUND ] semgrep 1.186.0 1 finding(s), 2.20s
14
+ [FOUND ] osv-scanner 2.7.1 5 finding(s), 0.75s
15
+
16
+ Findings (6)
17
+ HIGH creds.txt:1 [gitleaks +semgrep] aws-access-token
18
+ Identified a pattern that may indicate AWS credentials, risking unauthorized cloud resource access and data breaches on AWS platforms.
19
+ fix: Revoke and rotate this credential now, remove it from the code and git history, and load it from a secret manager or environment variable.
20
+ HIGH package-lock.json [osv-scanner] GHSA-35jh-r3h4-6jhm
21
+ lodash@4.17.15 (npm) is affected by GHSA-35jh-r3h4-6jhm (CVE-2021-23337): Command Injection in lodash
22
+ fix: Upgrade lodash to 4.17.21 or later.
23
+ ...4 more findings omitted here...
24
+
25
+ Summary: 4 high, 2 medium
26
+ Result: FAIL (exit 1): findings at or above 'high'.
27
+ ```
28
+
29
+ (Captured output of a scan of a throwaway project containing a fake AWS key and a lockfile pinning lodash 4.17.15. Four of the six findings are omitted for length, which the `...` line marks; nothing shown was edited. Note `[gitleaks +semgrep]`: both engines found the same key and it is reported once.)
30
+
31
+ ## The problem
32
+
33
+ Agent workflows today verify code with _another LLM_. That is useful, but it cannot tell you "this lockfile pins a package with a published CVE", "this string is a live AWS key", or "your tests would not notice if `>=` became `>`". Those are facts, and tools already exist to establish them. They are just slow to run everywhere, noisy, and each has its own output format.
34
+
35
+ `code-intel` makes them cheap and uniform:
36
+
37
+ | Question | Command | Engine (not bundled) |
38
+ | ---------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------- |
39
+ | Did I just commit a secret? | `scan` | [gitleaks](https://github.com/gitleaks/gitleaks) |
40
+ | Did I introduce an injection or unsafe call? | `scan` | [semgrep](https://semgrep.dev) |
41
+ | Do my dependencies have known vulnerabilities? | `scan` | [osv-scanner](https://github.com/google/osv-scanner), fallback [trivy](https://trivy.dev) |
42
+ | Did I break a layer boundary (domain → infra)? | `scan -p deep` | [ast-grep](https://ast-grep.github.io) with _your_ rules |
43
+ | Which tests does this change affect? | `impact` | [codegraph](https://github.com/colbymchenry/codegraph) (transitive), labelled heuristic otherwise |
44
+ | Would my tests notice a behavior change? | `mutate` | [StrykerJS](https://stryker-mutator.io) (JS/TS) |
45
+
46
+ ## What it deliberately does not do
47
+
48
+ - **No LLM, no API key, no network service of its own.** Interpretation is the agent's job; this tool only supplies evidence.
49
+ - **No daemon, no MCP server, no hooks, no background process.** It runs, prints, exits.
50
+ - **No automatic full scans.** Nothing runs unless you (or your agent) call it. Default scope is the files you changed.
51
+ - **No orchestration, memory, skills, model selection or LLM code review.** Those are solved by your agent framework; see below.
52
+ - **No bundled scanners.** It drives the ones you install, and tells you precisely what is missing instead of pretending a check passed.
53
+ - **No rules of its own for architecture.** You write the ast-grep rules; we only run them.
54
+
55
+ ## How it differs from agent frameworks
56
+
57
+ Gentle AI / Gentle Shell, Claude Code, Codex and friends decide _what to do and when_. `code-intel` answers _"what does the code actually contain?"_ with a command that has a stable interface and exit codes. It does not replace [Gentle AI or Gentle Shell](https://github.com/Gentleman-Programming): it plugs into them. For example, Gentle AI's `review-risk` lens asks for "concrete exploit or scanner evidence" but has no tool to get any; `code-intel scan --format json` is exactly that evidence. The companion repo [code-intelligence-skills](https://github.com/micio86dev/code-intelligence-skills) ships the skill that teaches each agent when to call it.
58
+
59
+ Likewise it does not duplicate [CodeGraph](https://github.com/colbymchenry/codegraph): `impact` calls `codegraph affected` rather than building its own graph.
60
+
61
+ ## Install
62
+
63
+ Requires Node.js 22 or newer.
64
+
65
+ ```bash
66
+ # From a GitHub release (prebuilt, no build step):
67
+ npm install -g https://github.com/micio86dev/code-intelligence/releases/download/v0.1.0/code-intelligence-0.1.0.tgz
68
+
69
+ # Or straight from the repository (builds on install):
70
+ npm install -g github:micio86dev/code-intelligence
71
+ ```
72
+
73
+ (npm registry publishing is not set up yet; see [ROADMAP](ROADMAP.md).)
74
+
75
+ Then install the engines you want. `code-intel doctor` prints what is present and the exact command for what is missing:
76
+
77
+ ```bash
78
+ brew install gitleaks semgrep osv-scanner ast-grep # macOS / Linuxbrew
79
+ code-intel doctor
80
+ ```
81
+
82
+ Nothing is installed automatically.
83
+
84
+ ## Quick start
85
+
86
+ ```bash
87
+ cd your-repo
88
+ code-intel doctor # which engines are available?
89
+ code-intel scan # changed files, quick profile
90
+ code-intel scan --staged # only what is staged (pre-commit)
91
+ code-intel scan --since main # everything on this branch
92
+ code-intel scan --all -p deep # whole repo, adds architecture rules
93
+ code-intel scan --format json # for agents and CI
94
+ code-intel scan --format sarif > results.sarif # GitHub code scanning
95
+
96
+ code-intel impact # which tests does my change affect?
97
+ code-intel mutate # are my tests strong enough? (slow, JS/TS)
98
+
99
+ code-intel init # optional: write .code-intel.json
100
+ code-intel baseline # accept today's findings...
101
+ code-intel scan --new-only # ...and only fail on new ones
102
+ ```
103
+
104
+ ### Exit codes
105
+
106
+ | Code | Meaning |
107
+ | ---- | ------------------------------------------------------------------------------------------------- |
108
+ | 0 | Complete scan, nothing at or above `--fail-on` (default `high`) |
109
+ | 1 | Findings at or above `--fail-on` |
110
+ | 2 | Usage or configuration error |
111
+ | 3 | **Incomplete**: no blocking findings, but an engine timed out, crashed or is missing. Not a pass. |
112
+
113
+ A missing scanner is reported as `unavailable` and yields exit 3. A check is never silently skipped and counted as success. Pass `--allow-missing` if you really want it downgraded.
114
+
115
+ ## Using it from several agents
116
+
117
+ The CLI is the same everywhere; only the one-time wiring differs. [code-intelligence-skills](https://github.com/micio86dev/code-intelligence-skills) provides a single canonical skill and installers for Gentle Shell, Claude Code, Codex, OpenCode and Pi. Any other agent that can run shell commands can use the CLI directly with `--format json`.
118
+
119
+ ## Profiles
120
+
121
+ | | `quick` (default) | `deep` |
122
+ | --------------------- | ------------------- | -------------- |
123
+ | Categories | secrets, sast, deps | + architecture |
124
+ | Time limit per engine | 60 s | 10 min |
125
+ | Typical scope | changed files | `--all` |
126
+
127
+ `mutate` is a separate command because it is minutes, not seconds.
128
+
129
+ ## Honest limitations
130
+
131
+ - `impact` is only transitive with a CodeGraph index (`codegraph init`). Without one it lists direct importers and name matches and _says so_.
132
+ - `mutate` supports JavaScript/TypeScript (StrykerJS). Other languages are listed as skipped, not ignored. See [ROADMAP](ROADMAP.md).
133
+ - SAST findings on lines you did not touch are hidden in changed-file scans (and the count is printed). Use `--all` to see them.
134
+ - `osv-scanner` and `semgrep` registry rulesets need network access. See [docs/security.md](docs/security.md) for exactly what leaves your machine.
135
+ - Result caching only applies to engines whose output is a pure function of file contents (gitleaks; semgrep with local rules). With default settings the gain is small. See [docs/performance.md](docs/performance.md).
136
+ - Changed-file scans do not descend into git **submodules** (a nested repository carries its own configuration, which would be executable surface); scan the submodule's own repository.
137
+ - A repository can configure a scan to find less. Every report lists what the repository supplied (`config.inEffect`), and `--ignore-repo-config` discards it. Inline `gitleaks:allow` / `nosemgrep` comments cannot be disabled; they are counted and disclosed.
138
+
139
+ ## Disable or remove
140
+
141
+ ```bash
142
+ npm uninstall -g code-intelligence
143
+ rm -rf .code-intel .code-intel.json # per-project config and baseline (optional)
144
+ rm -rf "$(code-intel doctor --json | jq -r .cacheDir | sed "s#^~#$HOME#")" # this repository's result cache (optional)
145
+ ```
146
+
147
+ It writes only your optional `.code-intel.json` and `.code-intel/baseline.json` (if you run `init` / `baseline`) inside a repository, a result cache in your user cache directory (`code-intel doctor` prints the path; safe to delete), and temporary directories that are removed after each run.
148
+
149
+ ## Documentation
150
+
151
+ [Architecture](docs/architecture.md) · [CLI reference](docs/cli.md) · [Configuration](docs/configuration.md) · [Security model](docs/security.md) · [Performance](docs/performance.md) · [Benchmarks](docs/benchmarks.md) · [Troubleshooting](docs/troubleshooting.md) · [Contributing](CONTRIBUTING.md) · [Changelog](CHANGELOG.md) · [Roadmap](ROADMAP.md) · [Third-party notices](THIRD_PARTY.md)
152
+
153
+ ## License
154
+
155
+ MIT. The scanners it drives keep their own licenses; see [THIRD_PARTY.md](THIRD_PARTY.md).
package/THIRD_PARTY.md ADDED
@@ -0,0 +1,17 @@
1
+ # Third-party notices
2
+
3
+ `code-intelligence` bundles **no** third-party code at runtime (zero runtime dependencies). It _invokes_ the following tools if you install them; each remains under its own license and is not redistributed here. Versions are those the project was developed and tested against.
4
+
5
+ | Tool | Used for | License | Project |
6
+ | --------------------- | ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | --------------------------------------------- |
7
+ | gitleaks 8.30.1 | secrets | MIT | https://github.com/gitleaks/gitleaks |
8
+ | Semgrep 1.186.0 (CLI) | SAST | LGPL-2.1 (engine); rulesets carry their own licenses (the Semgrep registry rules are under the Semgrep Rules License) | https://github.com/semgrep/semgrep |
9
+ | OSV-Scanner 2.7.1 | dependency vulnerabilities | Apache-2.0 | https://github.com/google/osv-scanner |
10
+ | Trivy 0.76.1 | dependency vulnerabilities (fallback) | Apache-2.0 | https://github.com/aquasecurity/trivy |
11
+ | ast-grep 0.51.3 | architecture rules | MIT | https://github.com/ast-grep/ast-grep |
12
+ | CodeGraph 1.2.0 | test impact (optional) | MIT | https://github.com/colbymchenry/codegraph |
13
+ | StrykerJS 10.1.1 | mutation testing (project dev dependency) | Apache-2.0 | https://github.com/stryker-mutator/stryker-js |
14
+
15
+ Development-only dependencies: TypeScript (Apache-2.0), `@types/node` (MIT), Biome (MIT/Apache-2.0).
16
+
17
+ License identifiers above are as published by each project at the time of writing; check the upstream repositories for the authoritative text.
package/dist/cli.js ADDED
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ import { main } from "./main.js";
3
+ process.exitCode = await main(process.argv.slice(2), {
4
+ cwd: process.cwd(),
5
+ stdout: (s) => process.stdout.write(s),
6
+ stderr: (s) => process.stderr.write(`${s}\n`),
7
+ });
@@ -0,0 +1,80 @@
1
+ import { existsSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { defaultCacheDir } from "../core/cache.js";
5
+ import { CONFIG_FILE, loadConfig } from "../core/config.js";
6
+ import { UsageError } from "../core/errors.js";
7
+ import { findBinary } from "../core/exec.js";
8
+ import { findGitRoot } from "../core/targets.js";
9
+ import { ENGINES } from "../engines/registry.js";
10
+ import { TOOL_NAME, VERSION } from "../version.js";
11
+ export async function runDoctor(cwd, engines = ENGINES) {
12
+ const gitRoot = await findGitRoot(cwd).catch(() => null);
13
+ const root = gitRoot ?? cwd;
14
+ const cfg = {
15
+ file: CONFIG_FILE,
16
+ present: existsSync(join(root, CONFIG_FILE)),
17
+ valid: true,
18
+ errors: [],
19
+ };
20
+ try {
21
+ loadConfig(root, engines.map((e) => e.name));
22
+ }
23
+ catch (e) {
24
+ if (e instanceof UsageError) {
25
+ cfg.valid = false;
26
+ cfg.errors = [e.message, ...e.details];
27
+ }
28
+ else
29
+ throw e;
30
+ }
31
+ const detections = await Promise.all(engines.map((e) => e.detect()));
32
+ const report = {
33
+ tool: { name: TOOL_NAME, version: VERSION },
34
+ node: process.version,
35
+ git: findBinary("git") !== null,
36
+ repository: gitRoot !== null,
37
+ config: cfg,
38
+ engines: engines.map((e, i) => {
39
+ const d = detections[i];
40
+ return {
41
+ name: e.name,
42
+ category: e.category,
43
+ available: d?.available ?? false,
44
+ version: d?.version ?? null,
45
+ hint: d?.available ? null : e.installHint,
46
+ };
47
+ }),
48
+ optional: [
49
+ {
50
+ name: "codegraph",
51
+ available: findBinary("codegraph") !== null,
52
+ note: "used by `code-intel impact` for import-graph test selection",
53
+ },
54
+ ],
55
+ cacheDir: defaultCacheDir(root).replace(homedir(), "~"),
56
+ ok: false,
57
+ };
58
+ report.ok = report.git && cfg.valid && report.engines.every((e) => e.available);
59
+ return report;
60
+ }
61
+ export function renderDoctor(r) {
62
+ const L = [`${r.tool.name} ${r.tool.version} | node ${r.node}`, ""];
63
+ L.push(`git: ${r.git ? "found" : "MISSING (needed for changed-file scans)"}`);
64
+ L.push(`repository: ${r.repository ? "git repository" : "not a git repository (only --all scans work)"}`);
65
+ L.push(`config: ${r.config.present ? (r.config.valid ? `${r.config.file} valid` : `${r.config.file} INVALID`) : `no ${r.config.file} (defaults in use)`}`);
66
+ for (const e of r.config.errors)
67
+ L.push(` - ${e}`);
68
+ L.push("", "Engines");
69
+ for (const e of r.engines) {
70
+ L.push(` [${e.available ? "ok" : "MISSING"}] ${e.name.padEnd(14)} ${e.category.padEnd(8)} ${e.available ? (e.version ?? "") : (e.hint ?? "")}`);
71
+ }
72
+ L.push("", `Result cache: ${r.cacheDir} (outside the repository; safe to delete)`);
73
+ L.push("", "Optional");
74
+ for (const o of r.optional)
75
+ L.push(` [${o.available ? "ok" : "absent"}] ${o.name.padEnd(14)} ${o.note}`);
76
+ L.push("", r.ok
77
+ ? "Ready."
78
+ : "Some engines are missing: scans that need them report 'unavailable' (exit 3) instead of passing.");
79
+ return `${L.join("\n")}\n`;
80
+ }
@@ -0,0 +1,148 @@
1
+ import { existsSync, readFileSync, statSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { loadConfig } from "../core/config.js";
4
+ import { exec, findBinary } from "../core/exec.js";
5
+ import { resolveTarget } from "../core/targets.js";
6
+ import { ENGINES } from "../engines/registry.js";
7
+ import { TOOL_NAME, VERSION } from "../version.js";
8
+ const TEST_RE = [
9
+ /(^|\/)(__tests__|tests?|specs?)\//i,
10
+ /\.(test|spec)\.[cm]?[jt]sx?$/,
11
+ /(^|\/)test_[^/]+\.py$/,
12
+ /_test\.(py|go|rs)$/,
13
+ /(Test|Tests|IT)\.(java|kt|cs)$/,
14
+ ];
15
+ export const isTestFile = (p) => TEST_RE.some((re) => re.test(p));
16
+ const SOURCE_RE = /\.(?:[cm]?[jt]sx?|py|go|rs|java|kt|cs|rb|php|swift)$/;
17
+ const stem = (p) => {
18
+ const base = p.slice(p.lastIndexOf("/") + 1).replace(/\.[^.]+$/, "");
19
+ if (base === "index" || base === "__init__" || base === "mod") {
20
+ const parts = p.split("/");
21
+ return parts[parts.length - 2] ?? base;
22
+ }
23
+ return base;
24
+ };
25
+ // Horizontal whitespace only: `\s*` on a file of many blank lines is quadratic (verified: 400 KB took 65 s).
26
+ const IMPORT_RE = /(?:from|require\(|import\()[ \t]*['"]([^'"]+)['"]|^[ \t]*(?:from|import)[ \t]+([\w.]+)/gm;
27
+ const MAX_SCAN_BYTES = 1_000_000;
28
+ /** Direct importers + name matches. Honest but shallow: it cannot see transitive dependents. */
29
+ function heuristic(root, changed, allFiles) {
30
+ const stems = new Set(changed.filter((f) => !isTestFile(f)).map(stem));
31
+ const hits = new Set();
32
+ for (const t of allFiles.filter((f) => isTestFile(f) && SOURCE_RE.test(f))) {
33
+ const tStem = t
34
+ .slice(t.lastIndexOf("/") + 1)
35
+ .replace(/\.(test|spec)(?=\.)/, "")
36
+ .replace(/^test_|_test(?=\.)/, "")
37
+ .replace(/\.[^.]+$/, "");
38
+ if (stems.has(tStem)) {
39
+ hits.add(t);
40
+ continue;
41
+ }
42
+ let src;
43
+ try {
44
+ if (statSync(join(root, t)).size > MAX_SCAN_BYTES)
45
+ continue;
46
+ src = readFileSync(join(root, t), "utf8");
47
+ }
48
+ catch {
49
+ continue;
50
+ }
51
+ for (const m of src.matchAll(IMPORT_RE)) {
52
+ const spec = (m[1] ?? m[2] ?? "").replace(/\.[cm]?[jt]sx?$/, "");
53
+ const last = spec.split(/[/.]/).filter(Boolean).pop() ?? "";
54
+ if (stems.has(last)) {
55
+ hits.add(t);
56
+ break;
57
+ }
58
+ }
59
+ }
60
+ return [...hits];
61
+ }
62
+ export async function runImpact(opts) {
63
+ const mode = opts.mode ?? "changed";
64
+ const probe = await resolveTarget({ cwd: opts.cwd, mode, ref: opts.ref, exclude: [] });
65
+ const config = loadConfig(probe.root, ENGINES.map((e) => e.name));
66
+ const target = await resolveTarget({
67
+ cwd: opts.cwd,
68
+ mode,
69
+ ref: opts.ref,
70
+ exclude: config.exclude,
71
+ });
72
+ const changed = target.files;
73
+ const notes = [];
74
+ const changedTests = changed.filter(isTestFile);
75
+ const changedSource = changed.filter((f) => !isTestFile(f) && SOURCE_RE.test(f));
76
+ const cg = findBinary("codegraph");
77
+ const hasIndex = existsSync(join(target.root, ".codegraph"));
78
+ let method = "heuristic";
79
+ let affected = new Set(changedTests);
80
+ if (cg && hasIndex) {
81
+ // Bring the index up to date first; a stale index would silently under-report.
82
+ const sync = await exec(cg, ["sync", "--quiet", target.root], {
83
+ cwd: target.root,
84
+ timeoutMs: 60_000,
85
+ });
86
+ const r = sync.code === 0
87
+ ? await exec(cg, ["affected", "--stdin", "--json", "--path", target.root], {
88
+ cwd: target.root,
89
+ timeoutMs: 60_000,
90
+ input: `${changedSource.join("\n")}\n`,
91
+ })
92
+ : null;
93
+ try {
94
+ if (!r || r.code !== 0)
95
+ throw new Error(sync.code === 0 ? "codegraph affected failed" : "codegraph sync failed");
96
+ const parsed = JSON.parse(r.stdout);
97
+ for (const t of parsed.affectedTests ?? [])
98
+ affected.add(t);
99
+ method = "codegraph";
100
+ }
101
+ catch (e) {
102
+ notes.push(`codegraph was unavailable (${e.message}); fell back to the heuristic`);
103
+ affected = new Set(changedTests);
104
+ }
105
+ }
106
+ else if (cg && !hasIndex) {
107
+ notes.push("No .codegraph index in this repository. Run `codegraph init` for transitive, import-graph-accurate results.");
108
+ }
109
+ else {
110
+ notes.push("codegraph is not installed. Install it and run `codegraph init` for transitive results.");
111
+ }
112
+ if (method === "heuristic") {
113
+ const all = await resolveTarget({
114
+ cwd: opts.cwd,
115
+ mode: "all",
116
+ ref: null,
117
+ exclude: config.exclude,
118
+ });
119
+ for (const t of heuristic(target.root, changed, all.files))
120
+ affected.add(t);
121
+ notes.push("Heuristic: only tests that directly import a changed module or share its name are listed. Transitive dependents are NOT detected.");
122
+ }
123
+ if (changedSource.length === 0 && changedTests.length === 0)
124
+ notes.push("No source or test files changed in scope.");
125
+ return {
126
+ schemaVersion: 1,
127
+ tool: { name: TOOL_NAME, version: VERSION },
128
+ method,
129
+ target: { mode: target.mode, ref: target.ref, fileCount: changed.length },
130
+ changedFiles: changed,
131
+ affectedTests: [...affected].sort(),
132
+ notes,
133
+ };
134
+ }
135
+ export function renderImpact(r) {
136
+ const L = [
137
+ `${r.tool.name} ${r.tool.version} | impact | method: ${r.method} | ${r.changedFiles.length} changed file(s)`,
138
+ "",
139
+ ];
140
+ L.push(`Tests to run (${r.affectedTests.length})`);
141
+ for (const t of r.affectedTests)
142
+ L.push(` ${t}`);
143
+ if (r.affectedTests.length === 0)
144
+ L.push(" none found");
145
+ for (const n of r.notes)
146
+ L.push("", `Note: ${n}`);
147
+ return `${L.join("\n")}\n`;
148
+ }
@@ -0,0 +1,27 @@
1
+ import { join } from "node:path";
2
+ import { CONFIG_FILE } from "../core/config.js";
3
+ import { UsageError } from "../core/errors.js";
4
+ import { lexists, safeWrite, UnsafePathError } from "../core/safefs.js";
5
+ import { findGitRoot } from "../core/targets.js";
6
+ const TEMPLATE = {
7
+ $schema: "https://raw.githubusercontent.com/micio86dev/code-intelligence/main/schema/config.schema.json",
8
+ failOn: "high",
9
+ exclude: [],
10
+ };
11
+ /** Create .code-intel.json. Never overwrites anything and never follows a link. */
12
+ export async function runInit(cwd) {
13
+ const root = (await findGitRoot(cwd)) ?? cwd;
14
+ // lstat-based: a dangling symlink named .code-intel.json counts as "exists" (existsSync would say no).
15
+ if (lexists(join(root, CONFIG_FILE))) {
16
+ throw new UsageError(`${CONFIG_FILE} already exists; leaving it untouched`);
17
+ }
18
+ try {
19
+ safeWrite(root, CONFIG_FILE, `${JSON.stringify(TEMPLATE, null, 2)}\n`);
20
+ return { created: [CONFIG_FILE] };
21
+ }
22
+ catch (e) {
23
+ if (e instanceof UnsafePathError)
24
+ throw new UsageError(`init: ${e.message}`);
25
+ throw e;
26
+ }
27
+ }