kodingo-cli 1.3.5 → 1.4.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.
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const strict_1 = __importDefault(require("node:assert/strict"));
7
+ const node_fs_1 = __importDefault(require("node:fs"));
8
+ const node_os_1 = __importDefault(require("node:os"));
9
+ const node_path_1 = __importDefault(require("node:path"));
10
+ const node_child_process_1 = require("node:child_process");
11
+ const node_test_1 = require("node:test");
12
+ const local_deep_scan_extractor_1 = require("../utils/local-deep-scan-extractor");
13
+ const deep_scan_1 = require("../commands/deep-scan");
14
+ (0, node_test_1.describe)("local deep scan privacy", () => {
15
+ (0, node_test_1.it)("never reads env paths and redacts secrets from excerpts", () => {
16
+ strict_1.default.equal((0, local_deep_scan_extractor_1.isNeverReadPath)("apps/web/.env.production"), true);
17
+ strict_1.default.equal((0, local_deep_scan_extractor_1.privacySafeExcerpt)('const token = "ghp_abcdefghijklmnopqrstuvwxyz012345";'), "const [REDACTED]");
18
+ });
19
+ (0, node_test_1.it)("caps evidence to one short statement", () => {
20
+ strict_1.default.equal((0, local_deep_scan_extractor_1.privacySafeExcerpt)(` first();\nsecond();`).trim(), "first()");
21
+ strict_1.default.ok((0, local_deep_scan_extractor_1.privacySafeExcerpt)("x".repeat(500)).length <= 200);
22
+ });
23
+ (0, node_test_1.it)("honors git tracking, .kodingoignore, and env exclusion", () => {
24
+ const root = node_fs_1.default.mkdtempSync(node_path_1.default.join(node_os_1.default.tmpdir(), "kodingo-deep-scan-"));
25
+ (0, node_child_process_1.execFileSync)("git", ["init", "-q", root]);
26
+ node_fs_1.default.mkdirSync(node_path_1.default.join(root, "src"));
27
+ node_fs_1.default.writeFileSync(node_path_1.default.join(root, "src", "keep.ts"), "export function keep() { return 1; }");
28
+ node_fs_1.default.writeFileSync(node_path_1.default.join(root, "src", "skip.ts"), "export function skip() { return 1; }");
29
+ node_fs_1.default.writeFileSync(node_path_1.default.join(root, ".env"), "SECRET=value");
30
+ node_fs_1.default.writeFileSync(node_path_1.default.join(root, ".kodingoignore"), "src/skip.ts\n");
31
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "add", "."]);
32
+ const files = (0, deep_scan_1.listTrackedFiles)(root);
33
+ strict_1.default.deepEqual(files.map((file) => file.path), ["src/keep.ts"]);
34
+ });
35
+ (0, node_test_1.it)("extracts structure without uploading a function body", async () => {
36
+ const source = Buffer.from("export function hello() {\n return <main>Hello</main>;\n}\n");
37
+ const result = await (0, local_deep_scan_extractor_1.extractLocalFile)("src/hello.tsx", "a".repeat(40), source);
38
+ strict_1.default.equal(result?.observations[0].name, "hello");
39
+ strict_1.default.ok((result?.observations[0].excerpt.length ?? 0) <= 200);
40
+ strict_1.default.equal(JSON.stringify(result).includes(source.toString("utf8")), false);
41
+ });
42
+ (0, node_test_1.it)("records real UTF-8 byte spans rather than excerpt-relative placeholders", async () => {
43
+ const source = Buffer.from("// café 🚀\nexport function hello() {\n return <main>Hello</main>;\n}\n");
44
+ const result = await (0, local_deep_scan_extractor_1.extractLocalFile)("src/hello.tsx", "a".repeat(40), source);
45
+ const observation = result?.observations.find((item) => item.name === "hello");
46
+ strict_1.default.equal(observation?.startByte, Buffer.byteLength("// café 🚀\n"));
47
+ strict_1.default.ok((observation?.endByte ?? 0) > (observation?.startByte ?? 0));
48
+ strict_1.default.equal(source.subarray(observation?.startByte, observation?.endByte).toString("utf8").startsWith("export function hello"), true);
49
+ });
50
+ (0, node_test_1.it)("normalizes SSH and HTTPS remotes", () => {
51
+ strict_1.default.equal((0, deep_scan_1.normalizeRemote)("git@github.com:owner/repo.git"), "owner/repo");
52
+ strict_1.default.equal((0, deep_scan_1.normalizeRemote)("https://github.com/owner/repo.git"), "owner/repo");
53
+ });
54
+ (0, node_test_1.it)("writes an inspectable dry-run payload without contacting the server", async () => {
55
+ const root = node_fs_1.default.mkdtempSync(node_path_1.default.join(node_os_1.default.tmpdir(), "kodingo-dry-run-"));
56
+ (0, node_child_process_1.execFileSync)("git", ["init", "-q", root]);
57
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "config", "user.email", "test@example.invalid"]);
58
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "config", "user.name", "Validation Test"]);
59
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "remote", "add", "origin", "git@github.com:validation/repository.git"]);
60
+ node_fs_1.default.writeFileSync(node_path_1.default.join(root, "page.ts"), "export function Page() { return 1; }");
61
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "add", "."]);
62
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "commit", "-qm", "fixture"]);
63
+ const output = node_path_1.default.join(root, "payload.json");
64
+ const oldToken = process.env.KODINGO_TOKEN;
65
+ process.env.KODINGO_TOKEN = "validation-token";
66
+ try {
67
+ await (0, deep_scan_1.deepScanCommand)({ repo: root, dryRun: output });
68
+ }
69
+ finally {
70
+ if (oldToken === undefined)
71
+ delete process.env.KODINGO_TOKEN;
72
+ else
73
+ process.env.KODINGO_TOKEN = oldToken;
74
+ }
75
+ const payload = JSON.parse(node_fs_1.default.readFileSync(output, "utf8"));
76
+ strict_1.default.equal(payload.manifest.repository, "validation/repository");
77
+ strict_1.default.equal(payload.files[0].path, "page.ts");
78
+ strict_1.default.ok(Array.isArray(payload.files[0].linkPlan.attributeUpdates));
79
+ strict_1.default.ok(Array.isArray(payload.files[0].linkPlan.derivedEntities));
80
+ strict_1.default.equal(JSON.stringify(payload).includes("return 1"), false);
81
+ });
82
+ });
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const strict_1 = __importDefault(require("node:assert/strict"));
7
+ const node_test_1 = require("node:test");
8
+ const version_policy_1 = require("../utils/version-policy");
9
+ (0, node_test_1.it)("compares CLI policy versions numerically", () => {
10
+ strict_1.default.equal((0, version_policy_1.compareVersions)("1.10.0", "1.9.9"), 1);
11
+ strict_1.default.equal((0, version_policy_1.compareVersions)("1.3.5", "1.3.5"), 0);
12
+ strict_1.default.equal((0, version_policy_1.compareVersions)("1.3.4", "1.3.5"), -1);
13
+ });
@@ -0,0 +1,74 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
+ if (k2 === undefined) k2 = k;
5
+ var desc = Object.getOwnPropertyDescriptor(m, k);
6
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
+ desc = { enumerable: true, get: function() { return m[k]; } };
8
+ }
9
+ Object.defineProperty(o, k2, desc);
10
+ }) : (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ o[k2] = m[k];
13
+ }));
14
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
16
+ }) : function(o, v) {
17
+ o["default"] = v;
18
+ });
19
+ var __importStar = (this && this.__importStar) || (function () {
20
+ var ownKeys = function(o) {
21
+ ownKeys = Object.getOwnPropertyNames || function (o) {
22
+ var ar = [];
23
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
24
+ return ar;
25
+ };
26
+ return ownKeys(o);
27
+ };
28
+ return function (mod) {
29
+ if (mod && mod.__esModule) return mod;
30
+ var result = {};
31
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
32
+ __setModuleDefault(result, mod);
33
+ return result;
34
+ };
35
+ })();
36
+ Object.defineProperty(exports, "__esModule", { value: true });
37
+ const commander_1 = require("commander");
38
+ async function runLocalScanCommand(commandName) {
39
+ if (!["init", "deep-scan", "deep-scan-status"].includes(commandName))
40
+ return false;
41
+ const program = new commander_1.Command();
42
+ const { version } = require("../package.json");
43
+ program.name("kodingo").description("Kodingo CLI").version(version);
44
+ const { enforceVersionPolicy } = await Promise.resolve().then(() => __importStar(require("./utils/version-policy")));
45
+ program.hook("preAction", async () => enforceVersionPolicy());
46
+ if (commandName === "init") {
47
+ const { registerInitCommand } = await Promise.resolve().then(() => __importStar(require("./commands/init")));
48
+ registerInitCommand(program);
49
+ }
50
+ else {
51
+ const { deepScanCommand, deepScanStatusCommand } = await Promise.resolve().then(() => __importStar(require("./commands/deep-scan")));
52
+ program.command("deep-scan")
53
+ .description("Read this tracked checkout locally and upload a privacy-safe structural summary")
54
+ .option("--repo <path>", "repo path (defaults to the current repo)")
55
+ .option("--yes", "non-interactive consent (token may come from KODINGO_TOKEN)")
56
+ .option("--dry-run <file>", "write the exact payload for review without uploading file summaries")
57
+ .option("--changed", "scan files changed by the current commit only")
58
+ .option("--no-update", "do not auto-update (used by hooks and CI)")
59
+ .action(async (options) => deepScanCommand(options));
60
+ program.command("deep-scan-status")
61
+ .description("Show local deep-scan coverage for this project")
62
+ .option("--repo <path>", "repo path (defaults to the current repo)")
63
+ .action(async (options) => deepScanStatusCommand(options));
64
+ }
65
+ await program.parseAsync(process.argv);
66
+ return true;
67
+ }
68
+ void runLocalScanCommand(process.argv[2] ?? "").then(async (handled) => {
69
+ if (!handled)
70
+ await Promise.resolve().then(() => __importStar(require("./cli")));
71
+ }).catch((error) => {
72
+ console.error(error instanceof Error ? error.message : String(error));
73
+ process.exitCode = 1;
74
+ });
package/dist/cli.js CHANGED
@@ -13,7 +13,6 @@ const ignore_1 = require("./commands/ignore");
13
13
  const deny_1 = require("./commands/deny");
14
14
  const scan_git_1 = require("./commands/scan-git");
15
15
  const scan_claude_1 = require("./commands/scan-claude");
16
- const scan_repo_1 = require("./commands/scan-repo");
17
16
  const sync_graph_1 = require("./commands/sync-graph");
18
17
  const sync_dependencies_1 = require("./commands/sync-dependencies");
19
18
  const security_scan_1 = require("./commands/security-scan");
@@ -28,11 +27,28 @@ const guardrails_1 = require("./commands/guardrails");
28
27
  const session_brief_1 = require("./commands/session-brief");
29
28
  const check_rules_1 = require("./commands/check-rules");
30
29
  const aging_1 = require("./commands/aging");
30
+ const deep_scan_1 = require("./commands/deep-scan");
31
+ const version_policy_1 = require("./utils/version-policy");
31
32
  const program = new commander_1.Command();
33
+ program.hook("preAction", async () => (0, version_policy_1.enforceVersionPolicy)());
32
34
  const { version } = require("../package.json");
33
35
  program.name("kodingo").description("Kodingo CLI").version(version);
34
36
  // ── init ──────────────────────────────────────────────────────────────────────
35
37
  (0, init_1.registerInitCommand)(program);
38
+ program
39
+ .command("deep-scan")
40
+ .description("Read this tracked checkout locally and upload a privacy-safe structural summary")
41
+ .option("--repo <path>", "repo path (defaults to the current repo)")
42
+ .option("--yes", "non-interactive consent (token may come from KODINGO_TOKEN)")
43
+ .option("--dry-run <file>", "write the exact payload for review without uploading file summaries")
44
+ .option("--changed", "scan files changed by the current commit only")
45
+ .option("--no-update", "do not auto-update (used by hooks and CI)")
46
+ .action(async (options) => (0, deep_scan_1.deepScanCommand)(options));
47
+ program
48
+ .command("deep-scan-status")
49
+ .description("Show local deep-scan coverage for this project")
50
+ .option("--repo <path>", "repo path (defaults to the current repo)")
51
+ .action(async (options) => (0, deep_scan_1.deepScanStatusCommand)(options));
36
52
  // ── build ─────────────────────────────────────────────────────────────────────
37
53
  program
38
54
  .command("build")
@@ -261,13 +277,11 @@ program
261
277
  // ── scan-repo ─────────────────────────────────────────────────────────────────
262
278
  program
263
279
  .command("scan-repo")
264
- .description("Bulk scan existing codebase and capture memory for functions not yet in Kortex")
280
+ .description("Deprecated alias for the local deep scan")
265
281
  .option("--repo <path>", "repo path to scan")
266
282
  .action(async (options) => {
267
- const payload = {};
268
- if (options.repo)
269
- payload.repo = String(options.repo);
270
- await (0, scan_repo_1.scanRepoCommand)(payload);
283
+ console.warn("`kodingo scan-repo` is deprecated; use `npx kodingo-cli init` for first setup or `kodingo deep-scan` for a later rescan.");
284
+ await (0, deep_scan_1.deepScanCommand)(options.repo ? { repo: String(options.repo) } : {});
271
285
  });
272
286
  program
273
287
  .command("sync-graph")
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const node_fs_1 = __importDefault(require("node:fs"));
7
+ const node_path_1 = __importDefault(require("node:path"));
8
+ const node_worker_threads_1 = require("node:worker_threads");
9
+ const worker = new node_worker_threads_1.Worker(node_path_1.default.join(__dirname, "deep-scan-worker.js"));
10
+ process.on("message", (message) => {
11
+ try {
12
+ const bytes = node_fs_1.default.readFileSync(message.absolutePath);
13
+ const transferable = bytes.buffer instanceof ArrayBuffer && bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength ? new Uint8Array(bytes.buffer) : Uint8Array.from(bytes);
14
+ worker.postMessage({ id: message.id, filePath: message.filePath, blobSha: message.blobSha, bytes: transferable, includeExcerpts: message.includeExcerpts }, [transferable.buffer]);
15
+ }
16
+ catch (error) {
17
+ process.send?.({ id: message.id, error: error instanceof Error ? error.message : String(error) });
18
+ }
19
+ });
20
+ worker.on("message", (message) => process.send?.({ ...message, processRss: process.memoryUsage().rss }));
21
+ worker.on("error", (error) => process.send?.({ id: -1, error: error.message }));
22
+ process.on("disconnect", async () => { await worker.terminate(); process.exit(0); });
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const node_worker_threads_1 = require("node:worker_threads");
7
+ const node_fs_1 = __importDefault(require("node:fs"));
8
+ const local_deep_scan_extractor_1 = require("../utils/local-deep-scan-extractor");
9
+ node_worker_threads_1.parentPort?.on("message", async (message) => {
10
+ try {
11
+ const bytes = node_fs_1.default.readFileSync(message.absolutePath);
12
+ const extracted = await (0, local_deep_scan_extractor_1.extractLocalFile)(message.filePath, message.blobSha, bytes);
13
+ const result = extracted ? (0, local_deep_scan_extractor_1.sanitizeLocalExtraction)(extracted, message.includeExcerpts) : null;
14
+ node_worker_threads_1.parentPort?.postMessage({ id: message.id, result, processRss: process.memoryUsage().rss });
15
+ }
16
+ catch (error) {
17
+ node_worker_threads_1.parentPort?.postMessage({ id: message.id, error: error instanceof Error ? error.message : String(error) });
18
+ }
19
+ });
@@ -0,0 +1,344 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.resolveGitMetadata = resolveGitMetadata;
40
+ exports.normalizeRemote = normalizeRemote;
41
+ exports.listTrackedFiles = listTrackedFiles;
42
+ exports.deepScanStatusCommand = deepScanStatusCommand;
43
+ exports.deepScanCommand = deepScanCommand;
44
+ const node_child_process_1 = require("node:child_process");
45
+ const node_fs_1 = __importDefault(require("node:fs"));
46
+ const node_os_1 = __importDefault(require("node:os"));
47
+ const node_path_1 = __importDefault(require("node:path"));
48
+ const promises_1 = __importDefault(require("node:readline/promises"));
49
+ const node_process_1 = require("node:process");
50
+ const node_worker_threads_1 = require("node:worker_threads");
51
+ const persistence_config_1 = require("../utils/persistence-config");
52
+ const format_1 = require("kodingo-core/dist/src/entity-extractor/format");
53
+ const sourcePolicy_1 = require("kodingo-core/dist/src/entity-extractor/sourcePolicy");
54
+ const vendoredCodeDetector_1 = require("../utils/vendoredCodeDetector");
55
+ const { version: CLI_VERSION } = require("../../package.json");
56
+ const SUPPORTED = new Set([".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".php", ".cs", ".cshtml", ".aspx", ".xaml", ".xml", ".py", ".rb", ".java", ".go", ".rs"]);
57
+ const STATE_NAME = node_path_1.default.join(".kortex", "deep-scan-state.json");
58
+ const FACT_CACHE_DIR = node_path_1.default.join(".kortex", "entity-cache");
59
+ function planForPath(plan, filePath) {
60
+ return {
61
+ attributeUpdates: plan.attributeUpdates.filter((item) => item.entity.path === filePath),
62
+ parentUpdates: plan.parentUpdates.filter((item) => item.entity.path === filePath),
63
+ derivedEntities: plan.derivedEntities.filter((item) => item.path === filePath),
64
+ derivedEdges: plan.derivedEdges.filter((item) => item.from.path === filePath),
65
+ replaceDerivedKinds: plan.replaceDerivedKinds,
66
+ };
67
+ }
68
+ class ExtractorWorker {
69
+ constructor() {
70
+ this.worker = this.createWorker();
71
+ this.sequence = 0;
72
+ this.filesSinceReset = 0;
73
+ this.maxFiles = Math.max(1, Number(process.env.KODINGO_EXTRACTOR_WORKER_MAX_FILES ?? 10));
74
+ this.peakRss = process.memoryUsage().rss;
75
+ }
76
+ createWorker() {
77
+ const maxOldGenerationSizeMb = Math.max(64, Number(process.env.KODINGO_EXTRACTOR_WORKER_HEAP_MB ?? 192));
78
+ return new node_worker_threads_1.Worker(node_path_1.default.join(__dirname, "deep-scan-worker.js"), { resourceLimits: { maxOldGenerationSizeMb, maxYoungGenerationSizeMb: 16 } });
79
+ }
80
+ get shouldReset() { return this.filesSinceReset >= this.maxFiles; }
81
+ async reset() { await this.worker.terminate(); this.worker = this.createWorker(); this.filesSinceReset = 0; }
82
+ async extract(absolutePath, filePath, blobSha, includeExcerpts) {
83
+ const id = ++this.sequence;
84
+ return new Promise((resolve, reject) => {
85
+ const onMessage = (message) => {
86
+ if (message.id !== id)
87
+ return;
88
+ this.worker.off("message", onMessage);
89
+ this.peakRss = Math.max(this.peakRss, process.memoryUsage().rss, Number(message.processRss ?? 0));
90
+ this.filesSinceReset++;
91
+ message.error ? reject(new Error(message.error)) : resolve(message.result ?? null);
92
+ };
93
+ this.worker.on("message", onMessage);
94
+ this.worker.postMessage({ id, absolutePath, filePath, blobSha, includeExcerpts });
95
+ });
96
+ }
97
+ async close() { await this.worker.terminate(); }
98
+ }
99
+ function parserFamily(filePath) {
100
+ const extension = node_path_1.default.extname(filePath).toLowerCase();
101
+ if ([".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs"].includes(extension))
102
+ return "js";
103
+ if (extension === ".php")
104
+ return "php";
105
+ if (extension === ".cs")
106
+ return "csharp";
107
+ if ([".cshtml", ".aspx", ".ascx", ".master", ".xaml", ".xml"].includes(extension))
108
+ return "template";
109
+ return "declarative";
110
+ }
111
+ function git(root, args) {
112
+ return (0, node_child_process_1.execFileSync)("git", ["-C", root, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
113
+ }
114
+ function resolveGitMetadata(start) {
115
+ const root = git(start, ["rev-parse", "--show-toplevel"]);
116
+ const commitSha = git(root, ["rev-parse", "HEAD"]);
117
+ const branch = (() => { try {
118
+ return git(root, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
119
+ }
120
+ catch {
121
+ return null;
122
+ } })();
123
+ const dirty = git(root, ["status", "--porcelain"]).length > 0;
124
+ const remote = git(root, ["remote", "get-url", "origin"]);
125
+ const shallow = git(root, ["rev-parse", "--is-shallow-repository"]) === "true";
126
+ return { root, commitSha, branch, detachedHead: branch === null, dirty, remote, repository: normalizeRemote(remote), shallow };
127
+ }
128
+ function normalizeRemote(remote) {
129
+ const cleaned = remote.replace(/^git@[^:]+:/, "").replace(/^https?:\/\/[^/]+\//, "").replace(/\.git$/, "");
130
+ return cleaned.replace(/^\/+/, "");
131
+ }
132
+ function globRegex(pattern) {
133
+ const normalized = pattern.trim().replace(/^\//, "");
134
+ const escaped = normalized.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "§§").replace(/\*/g, "[^/]*").replace(/§§/g, ".*").replace(/\?/g, ".");
135
+ return new RegExp(`^(?:${escaped}|.*/${escaped})(?:/.*)?$`);
136
+ }
137
+ function readKodingoIgnore(root) {
138
+ const file = node_path_1.default.join(root, ".kodingoignore");
139
+ if (!node_fs_1.default.existsSync(file))
140
+ return [];
141
+ return node_fs_1.default.readFileSync(file, "utf8").split(/\r?\n/).map((line) => line.trim()).filter((line) => line && !line.startsWith("#")).map(globRegex);
142
+ }
143
+ function listTrackedFiles(root, changedOnly = false) {
144
+ const records = (0, node_child_process_1.execFileSync)("git", ["-C", root, "ls-files", "-s", "-z"], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 }).split("\0").filter(Boolean);
145
+ const changed = changedOnly ? new Set(git(root, ["diff-tree", "--no-commit-id", "--name-only", "-r", "HEAD"]).split(/\r?\n/).filter(Boolean)) : null;
146
+ const ignored = readKodingoIgnore(root);
147
+ const files = [];
148
+ for (const record of records) {
149
+ const match = record.match(/^\d+ ([a-f0-9]{40,64}) \d+\t(.+)$/);
150
+ if (!match)
151
+ continue;
152
+ const relative = match[2].replace(/\\/g, "/");
153
+ if (changed && !changed.has(relative))
154
+ continue;
155
+ if ((0, sourcePolicy_1.isNeverReadPath)(relative) || !SUPPORTED.has(node_path_1.default.extname(relative).toLowerCase()) || ignored.some((pattern) => pattern.test(relative)) || (0, vendoredCodeDetector_1.isVendoredPath)(relative).vendored)
156
+ continue;
157
+ const absolute = node_path_1.default.join(root, relative);
158
+ if (!node_fs_1.default.existsSync(absolute) || !node_fs_1.default.statSync(absolute).isFile())
159
+ continue;
160
+ files.push({ path: relative, blobSha: match[1], size: node_fs_1.default.statSync(absolute).size });
161
+ }
162
+ return files.sort((a, b) => a.path.localeCompare(b.path));
163
+ }
164
+ async function apiRequest(apiUrl, token, route, init = {}) {
165
+ const response = await fetch(`${apiUrl.replace(/\/$/, "")}${route}`, { ...init, headers: { "content-type": "application/json", "X-Kodingo-Token": token, ...(init.headers ?? {}) } });
166
+ const body = await response.json().catch(() => ({}));
167
+ if (!response.ok)
168
+ throw new Error(body.error ?? `HTTP ${response.status}`);
169
+ return body;
170
+ }
171
+ async function permission(options, summary) {
172
+ if (options.yes)
173
+ return true;
174
+ if (!process.stdin.isTTY)
175
+ return false;
176
+ const rl = promises_1.default.createInterface({ input: node_process_1.stdin, output: node_process_1.stdout });
177
+ try {
178
+ return /^y(?:es)?$/i.test((await rl.question(`${summary}\nUpload this structural summary? [y/N] `)).trim());
179
+ }
180
+ finally {
181
+ rl.close();
182
+ }
183
+ }
184
+ async function deepScanStatusCommand(options = {}) {
185
+ const meta = resolveGitMetadata(node_path_1.default.resolve(options.repo ?? process.cwd()));
186
+ const credentials = (0, persistence_config_1.getCredentials)(meta.root);
187
+ if (!credentials.token)
188
+ throw new Error("No project token found. Run `kodingo init` in this project first.");
189
+ const status = await apiRequest(credentials.apiUrl, credentials.token, "/deep-scan/status");
190
+ console.log(JSON.stringify({ repository: meta.repository, branch: meta.branch, ...status }, null, 2));
191
+ }
192
+ async function deepScanCommand(options = {}) {
193
+ const started = Date.now();
194
+ const meta = resolveGitMetadata(node_path_1.default.resolve(options.repo ?? process.cwd()));
195
+ if (meta.detachedHead)
196
+ console.warn("Detached HEAD detected: this scan will be uploaded for review but not applied.");
197
+ if (meta.shallow)
198
+ console.warn("Shallow clone detected: the current tracked snapshot can be scanned, but earlier history is unavailable.");
199
+ const credentials = (0, persistence_config_1.getCredentials)(meta.root);
200
+ const envToken = process.env.KODINGO_TOKEN?.trim();
201
+ const token = envToken || credentials.token;
202
+ if (!token)
203
+ throw new Error("No project token found. Run `kodingo init` once, or set KODINGO_TOKEN for CI.");
204
+ const policy = options.dryRun
205
+ ? { excerptsEnabled: true }
206
+ : await apiRequest(credentials.apiUrl, token, "/deep-scan/policy");
207
+ const files = listTrackedFiles(meta.root, options.changed === true);
208
+ if (!files.length) {
209
+ console.log("No supported tracked files need scanning.");
210
+ return;
211
+ }
212
+ const manifest = { repository: meta.repository, branch: meta.branch, commitSha: meta.commitSha, dirty: meta.dirty, detachedHead: meta.detachedHead, fullTree: !options.changed, cliVersion: CLI_VERSION, extractorFormatVersion: format_1.EXTRACTOR_FORMAT_VERSION, files, consent: { confirmed: true, confirmedAt: new Date().toISOString(), actor: node_os_1.default.userInfo().username } };
213
+ const spoolDir = node_fs_1.default.mkdtempSync(node_path_1.default.join(node_os_1.default.tmpdir(), "kodingo-deep-scan-"));
214
+ const spoolPath = node_path_1.default.join(spoolDir, `deep-scan-${meta.commitSha}.jsonl`);
215
+ node_fs_1.default.writeFileSync(spoolPath, "", { mode: 0o600 });
216
+ let processed = 0;
217
+ let extractedCount = 0;
218
+ let evidenceCount = 0;
219
+ let peakRss = process.memoryUsage().rss;
220
+ let extractionPeakRss = peakRss;
221
+ const cacheDir = node_path_1.default.join(meta.root, FACT_CACHE_DIR);
222
+ node_fs_1.default.mkdirSync(cacheDir, { recursive: true });
223
+ const extractor = new ExtractorWorker();
224
+ const scanFiles = [...files].sort((left, right) => parserFamily(left.path).localeCompare(parserFamily(right.path)) || left.path.localeCompare(right.path));
225
+ let activeFamily;
226
+ try {
227
+ for (const file of scanFiles) {
228
+ const family = parserFamily(file.path);
229
+ if (activeFamily !== undefined && (family !== activeFamily || extractor.shouldReset))
230
+ await extractor.reset();
231
+ activeFamily = family;
232
+ const cachePath = node_path_1.default.join(cacheDir, `${file.blobSha}.json`);
233
+ let extracted = null;
234
+ try {
235
+ extracted = JSON.parse(node_fs_1.default.readFileSync(cachePath, "utf8"));
236
+ }
237
+ catch {
238
+ extracted = await extractor.extract(node_path_1.default.join(meta.root, file.path), file.path, file.blobSha, policy.excerptsEnabled);
239
+ if (extracted)
240
+ node_fs_1.default.writeFileSync(cachePath, JSON.stringify(extracted), { mode: 0o600 });
241
+ }
242
+ if (extracted) {
243
+ node_fs_1.default.appendFileSync(spoolPath, `${JSON.stringify(extracted)}\n`, "utf8");
244
+ extractedCount++;
245
+ evidenceCount += extracted.observations.length;
246
+ }
247
+ peakRss = Math.max(peakRss, process.memoryUsage().rss, extractor.peakRss);
248
+ extractionPeakRss = Math.max(extractionPeakRss, peakRss);
249
+ processed++;
250
+ if (process.stdout.isTTY)
251
+ process.stdout.write(`\rExtracted ${processed}/${files.length} files`);
252
+ if (processed % Math.max(1, node_os_1.default.cpus().length) === 0)
253
+ await new Promise((resolve) => setImmediate(resolve));
254
+ }
255
+ }
256
+ finally {
257
+ await extractor.close();
258
+ }
259
+ // Keep extraction output on the spool until the parser worker (and its WASM
260
+ // heaps) has exited. This avoids overlapping parser memory with the full
261
+ // in-memory project link set on large polyglot repositories.
262
+ const linkFiles = [];
263
+ const { toLinkFile, linkProject } = await Promise.resolve().then(() => __importStar(require("kodingo-core/dist/src/entity-extractor/linker")));
264
+ const linkLines = promises_1.default.createInterface({ input: node_fs_1.default.createReadStream(spoolPath, { encoding: "utf8" }), crlfDelay: Infinity });
265
+ for await (const line of linkLines)
266
+ if (line)
267
+ linkFiles.push(toLinkFile(JSON.parse(line)));
268
+ peakRss = Math.max(peakRss, process.memoryUsage().rss);
269
+ const linked = linkProject(linkFiles);
270
+ peakRss = Math.max(peakRss, process.memoryUsage().rss);
271
+ const linkPeakRss = process.memoryUsage().rss;
272
+ const linksByPath = new Map();
273
+ for (const reference of linked.references) {
274
+ const list = linksByPath.get(reference.sourcePath) ?? [];
275
+ list.push(reference);
276
+ linksByPath.set(reference.sourcePath, list);
277
+ }
278
+ if (process.stdout.isTTY)
279
+ process.stdout.write("\n");
280
+ if (options.dryRun) {
281
+ const outputPath = node_path_1.default.resolve(options.dryRun);
282
+ const outputFd = node_fs_1.default.openSync(outputPath, "w", 0o600);
283
+ try {
284
+ node_fs_1.default.writeSync(outputFd, `{"manifest":${JSON.stringify(manifest)},"files":[`);
285
+ let first = true;
286
+ const lines = promises_1.default.createInterface({ input: node_fs_1.default.createReadStream(spoolPath, { encoding: "utf8" }), crlfDelay: Infinity });
287
+ for await (const line of lines) {
288
+ if (!line)
289
+ continue;
290
+ const file = JSON.parse(line);
291
+ file.linkedReferences = linksByPath.get(file.path) ?? [];
292
+ file.linkPlan = planForPath(linked.plan, file.path);
293
+ node_fs_1.default.writeSync(outputFd, `${first ? "" : ","}${JSON.stringify(file)}`);
294
+ first = false;
295
+ }
296
+ node_fs_1.default.writeSync(outputFd, "]}");
297
+ }
298
+ finally {
299
+ node_fs_1.default.closeSync(outputFd);
300
+ node_fs_1.default.rmSync(spoolDir, { recursive: true, force: true });
301
+ }
302
+ console.log(`Dry-run payload written to ${node_path_1.default.resolve(options.dryRun)}. Nothing was uploaded. Peak RSS ${(peakRss / 1024 / 1024).toFixed(1)} MiB (extract ${(extractionPeakRss / 1024 / 1024).toFixed(1)}, link ${(linkPeakRss / 1024 / 1024).toFixed(1)}); ${((Date.now() - started) / 1000).toFixed(1)}s.`);
303
+ return;
304
+ }
305
+ const evidenceSummary = policy.excerptsEnabled ? `${evidenceCount} short evidence excerpts, each capped at 200 characters` : "no source excerpts (disabled by your organisation)";
306
+ const approved = await permission(options, `Kortex will upload structure for ${extractedCount} changed files (${evidenceSummary}). Whole source files are not uploaded; .env files were not read.`);
307
+ if (!approved) {
308
+ node_fs_1.default.rmSync(spoolDir, { recursive: true, force: true });
309
+ console.log("Upload cancelled.");
310
+ return;
311
+ }
312
+ const statePath = node_path_1.default.join(meta.root, STATE_NAME);
313
+ node_fs_1.default.mkdirSync(node_path_1.default.dirname(statePath), { recursive: true });
314
+ let prior = null;
315
+ try {
316
+ prior = JSON.parse(node_fs_1.default.readFileSync(statePath, "utf8"));
317
+ }
318
+ catch { }
319
+ const session = await apiRequest(credentials.apiUrl, token, "/deep-scan/sessions", { method: "POST", body: JSON.stringify(manifest) });
320
+ const held = new Set(session.heldBlobShas ?? []);
321
+ const batchSize = Math.max(1, Math.min(Number(session.limits?.filesPerBatch ?? 200), 200));
322
+ let batch = [];
323
+ let uploaded = 0;
324
+ const lines = promises_1.default.createInterface({ input: node_fs_1.default.createReadStream(spoolPath, { encoding: "utf8" }), crlfDelay: Infinity });
325
+ const flush = async () => { if (!batch.length)
326
+ return; await apiRequest(credentials.apiUrl, token, `/deep-scan/sessions/${session.sessionId}/files`, { method: "POST", body: JSON.stringify({ files: batch }) }); uploaded += batch.length; batch = []; node_fs_1.default.writeFileSync(statePath, JSON.stringify({ sessionId: session.sessionId, commitSha: meta.commitSha, uploaded, total: extractedCount, priorSessionId: prior?.sessionId ?? null }, null, 2), "utf8"); };
327
+ for await (const line of lines) {
328
+ if (!line)
329
+ continue;
330
+ const file = JSON.parse(line);
331
+ if (held.has(file.blobSha))
332
+ continue;
333
+ file.linkedReferences = linksByPath.get(file.path) ?? [];
334
+ file.linkPlan = planForPath(linked.plan, file.path);
335
+ batch.push(file);
336
+ if (batch.length >= batchSize)
337
+ await flush();
338
+ }
339
+ await flush();
340
+ node_fs_1.default.rmSync(spoolDir, { recursive: true, force: true });
341
+ const finalized = await apiRequest(credentials.apiUrl, token, `/deep-scan/sessions/${session.sessionId}/finalize`, { method: "POST", body: "{}" });
342
+ node_fs_1.default.writeFileSync(statePath, JSON.stringify({ sessionId: session.sessionId, runId: finalized.runId, commitSha: meta.commitSha, completedAt: new Date().toISOString() }, null, 2), "utf8");
343
+ console.log(`Deep scan accepted in ${((Date.now() - started) / 1000).toFixed(1)}s. Run ${finalized.runId}. Use \`kodingo deep-scan-status\` to see coverage.`);
344
+ }
@@ -179,12 +179,30 @@ async function createProject(authToken, name, orgId) {
179
179
  throw new Error(data.error ?? "Failed to create project");
180
180
  return data;
181
181
  }
182
+ async function checkoutAlreadyFullyRead(repoRoot, apiUrl, token) {
183
+ try {
184
+ const { resolveGitMetadata } = await Promise.resolve().then(() => __importStar(require("./deep-scan")));
185
+ const metadata = resolveGitMetadata(repoRoot);
186
+ if (metadata.dirty || metadata.detachedHead)
187
+ return false;
188
+ const response = await fetch(`${apiUrl.replace(/\/$/, "")}/deep-scan/status`, { headers: { "X-Kodingo-Token": token } });
189
+ if (!response.ok)
190
+ return false;
191
+ const status = await response.json();
192
+ return status.state === "complete" && status.lastCommit === metadata.commitSha;
193
+ }
194
+ catch {
195
+ return false;
196
+ }
197
+ }
182
198
  // ── Command ───────────────────────────────────────────────────────────────────
183
199
  function registerInitCommand(program) {
184
200
  program
185
201
  .command("init")
186
- .description("Connect this repository to a Kodingo project")
202
+ .description("Connect this repository, run the first local deep scan, and install incremental capture")
187
203
  .option("--logout", "Log out and clear saved credentials")
204
+ .option("--yes", "non-interactive consent (use KODINGO_TOKEN in CI)")
205
+ .option("--dry-run <file>", "write the exact deep-scan payload without uploading")
188
206
  .action(async (opts) => {
189
207
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
190
208
  try {
@@ -195,6 +213,21 @@ function registerInitCommand(program) {
195
213
  console.log("✔ Logged out of Kodingo.");
196
214
  return;
197
215
  }
216
+ // CI/non-interactive first run: the project-scoped token is already
217
+ // the project match. No browser or project-name prompt is needed.
218
+ const environmentToken = process.env.KODINGO_TOKEN?.trim();
219
+ if (environmentToken) {
220
+ const repoRoot = findRepoRoot(process.cwd());
221
+ const apiUrl = process.env.KODINGO_API_URL?.trim() || API_BASE;
222
+ const existingConfig = (0, persistence_config_1.readConfig)();
223
+ (0, persistence_config_1.writeConfig)({ ...existingConfig, mode: "cloud", apiUrl, machineId: getMachineId() });
224
+ (0, persistence_config_1.writeWorkspaceConfig)(repoRoot, { mode: "cloud", apiUrl, token: environmentToken });
225
+ ensureGitignoreEntry(repoRoot, ".kortex/");
226
+ await (0, repo_identity_1.resolveCanonicalRepoName)({ repoRoot, apiUrl, token: environmentToken });
227
+ const { deepScanCommand } = await Promise.resolve().then(() => __importStar(require("./deep-scan")));
228
+ await deepScanCommand({ repo: repoRoot, yes: true, dryRun: opts.dryRun, noUpdate: true });
229
+ return;
230
+ }
198
231
  // ── Check if already logged in ───────────────────────────────────────
199
232
  let authToken = readAuthToken();
200
233
  let email = readAuthEmail();
@@ -287,35 +320,30 @@ function registerInitCommand(program) {
287
320
  }
288
321
  catch { }
289
322
  console.log(`✔ Connected. Token saved to ${persistence_config_1.CONFIG_PATH}`);
290
- console.log("\nKortex is now watching this repo.");
291
- // Install the git hook automatically — no manual step required.
292
- // This is what triggers scan-git and sync-dependencies on every future
293
- // commit, silently in the background.
323
+ const alreadyRead = await checkoutAlreadyFullyRead(repoRoot, apiUrl, selectedProject.token);
324
+ if (alreadyRead)
325
+ console.log("\n✔ This clean checkout already has a complete deep scan at the current commit; no upload is needed.");
326
+ else
327
+ console.log("\nKortex will now read this checkout locally. Review the upload summary before consenting.");
328
+ // The local deep scan is the one first-read path. The retired
329
+ // scan-repo capture is deliberately not run here.
294
330
  try {
295
- const { installHookCommand } = await Promise.resolve().then(() => __importStar(require("./install-hook")));
296
- await installHookCommand({ repo: repoRoot });
297
- console.log("✔ Git hook installed — memories and dependency data will stay current automatically on every commit.\n");
331
+ const { deepScanCommand } = await Promise.resolve().then(() => __importStar(require("./deep-scan")));
332
+ if (!alreadyRead)
333
+ await deepScanCommand({ repo: repoRoot, yes: Boolean(opts.yes), dryRun: opts.dryRun });
298
334
  }
299
335
  catch (err) {
300
- console.log(`⚠ Could not auto-install git hook (${err.message}). Run \`kodingo install-hook\` manually to enable automatic capture.\n`);
336
+ throw new Error(`Initial deep scan failed: ${err.message}`);
301
337
  }
302
- // Initial dependency sync — so security scanning has data immediately,
303
- // rather than waiting for the next commit to trigger the hook.
338
+ // Install only after the user has reviewed/accepted the first scan.
304
339
  try {
305
- const { syncDependenciesCommand } = await Promise.resolve().then(() => __importStar(require("./sync-dependencies")));
306
- await syncDependenciesCommand({ repo: repoRoot, silent: true });
340
+ const { installHookCommand } = await Promise.resolve().then(() => __importStar(require("./install-hook")));
341
+ await installHookCommand({ repo: repoRoot });
342
+ console.log("✔ Incremental commit hook installed.\n");
307
343
  }
308
- catch { }
309
- // Auto-scan existing codebase
310
- try {
311
- const { scanRepoCommand } = await Promise.resolve().then(() => __importStar(require("./scan-repo")));
312
- console.log("🔍 Scanning existing codebase for functions without memory...");
313
- const captured = await scanRepoCommand({ repo: repoRoot, silent: false });
314
- if (captured === 0) {
315
- console.log(" No existing functions found — Kortex will capture them as you write and commit code.");
316
- }
344
+ catch (err) {
345
+ console.log(`⚠ Could not install the hook (${err.message}). Run \`kodingo install-hook\` later.\n`);
317
346
  }
318
- catch { }
319
347
  }
320
348
  catch (err) {
321
349
  console.error(`\n✖ ${err.message}`);
@@ -20,6 +20,8 @@ async function installHookCommand(options) {
20
20
  `"${kodingoBin}" scan-git --repo "$(git rev-parse --show-toplevel)" &`,
21
21
  "# Kodingo Security: keep dependency data current for vulnerability scanning",
22
22
  `"${kodingoBin}" sync-dependencies --repo "$(git rev-parse --show-toplevel)" &`,
23
+ "# Kortex Deep Scan: extract only the committed files locally; never block the commit",
24
+ `(command -v timeout >/dev/null 2>&1 && timeout 120 "${kodingoBin}" deep-scan --repo "$(git rev-parse --show-toplevel)" --changed --yes --no-update >/dev/null 2>&1 || "${kodingoBin}" deep-scan --repo "$(git rev-parse --show-toplevel)" --changed --yes --no-update >/dev/null 2>&1) &`,
23
25
  "# </kodingo>",
24
26
  ].join("\n");
25
27
  // Pre-commit hook — runs synchronously to enforce guardrails
@@ -2,18 +2,18 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.updateCommand = updateCommand;
4
4
  const child_process_1 = require("child_process");
5
- async function updateCommand() {
5
+ async function updateCommand(targetVersion) {
6
6
  console.log("Checking for updates...");
7
7
  let currentVersion;
8
8
  let latestVersion;
9
9
  try {
10
- currentVersion = (0, child_process_1.execSync)("kodingo --version", { encoding: "utf-8" }).trim();
10
+ currentVersion = (0, child_process_1.execFileSync)("kodingo", ["--version"], { encoding: "utf-8" }).trim();
11
11
  }
12
12
  catch {
13
13
  currentVersion = "unknown";
14
14
  }
15
15
  try {
16
- latestVersion = (0, child_process_1.execSync)("npm view kodingo-cli version", { encoding: "utf-8" }).trim();
16
+ latestVersion = targetVersion ?? (0, child_process_1.execFileSync)("npm", ["view", "kodingo-cli", "version"], { encoding: "utf-8" }).trim();
17
17
  }
18
18
  catch {
19
19
  console.error("Could not fetch latest version. Check your internet connection.");
@@ -25,11 +25,23 @@ async function updateCommand() {
25
25
  }
26
26
  console.log(`Updating from ${currentVersion} to ${latestVersion}...`);
27
27
  try {
28
- (0, child_process_1.execSync)("npm install -g kodingo-cli@latest", { stdio: "inherit" });
28
+ const integrity = (0, child_process_1.execFileSync)("npm", ["view", `kodingo-cli@${latestVersion}`, "dist.integrity"], { encoding: "utf8" }).trim();
29
+ if (!integrity.startsWith("sha512-"))
30
+ throw new Error("registry did not provide an sha512 integrity value");
31
+ (0, child_process_1.execFileSync)("npm", ["install", "-g", `kodingo-cli@${latestVersion}`], { stdio: "inherit" });
32
+ const installed = (0, child_process_1.execFileSync)("kodingo", ["--version"], { encoding: "utf8" }).trim();
33
+ if (installed !== latestVersion)
34
+ throw new Error(`installed version ${installed} does not match ${latestVersion}`);
29
35
  console.log(`Updated to ${latestVersion} successfully.`);
30
36
  }
31
- catch {
37
+ catch (error) {
38
+ if (currentVersion !== "unknown") {
39
+ try {
40
+ (0, child_process_1.execFileSync)("npm", ["install", "-g", `kodingo-cli@${currentVersion}`], { stdio: "ignore" });
41
+ }
42
+ catch { /* best-effort rollback; exact recovery command is printed below */ }
43
+ }
32
44
  console.error("Update failed. Try running: npm install -g kodingo-cli@latest");
33
- process.exit(1);
45
+ throw error;
34
46
  }
35
47
  }
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.redactSecrets = exports.privacySafeExcerpt = exports.isNeverReadPath = exports.EVIDENCE_EXCERPT_LIMIT = exports.EXTRACTOR_FORMAT_VERSION = void 0;
4
+ exports.extractLocalFile = extractLocalFile;
5
+ exports.sanitizeLocalExtraction = sanitizeLocalExtraction;
6
+ /** Compatibility wrapper around the single shared extractor package. */
7
+ const kodingo_core_1 = require("kodingo-core");
8
+ Object.defineProperty(exports, "EXTRACTOR_FORMAT_VERSION", { enumerable: true, get: function () { return kodingo_core_1.EXTRACTOR_FORMAT_VERSION; } });
9
+ Object.defineProperty(exports, "EVIDENCE_EXCERPT_LIMIT", { enumerable: true, get: function () { return kodingo_core_1.DEFAULT_EVIDENCE_EXCERPT_LIMIT; } });
10
+ Object.defineProperty(exports, "isNeverReadPath", { enumerable: true, get: function () { return kodingo_core_1.isNeverReadPath; } });
11
+ Object.defineProperty(exports, "privacySafeExcerpt", { enumerable: true, get: function () { return kodingo_core_1.privacySafeExcerpt; } });
12
+ Object.defineProperty(exports, "redactSecrets", { enumerable: true, get: function () { return kodingo_core_1.redactSecrets; } });
13
+ async function extractLocalFile(filePath, blobSha, bytes) {
14
+ const result = await (0, kodingo_core_1.extractFile)({ path: filePath, blobSha, bytes });
15
+ if (result.skipped)
16
+ return null;
17
+ return (0, kodingo_core_1.sanitizeForUpload)(result);
18
+ }
19
+ function sanitizeLocalExtraction(result, includeExcerpts) {
20
+ return (0, kodingo_core_1.sanitizeForUpload)(result, includeExcerpts);
21
+ }
@@ -1,145 +1,18 @@
1
1
  "use strict";
2
- /**
3
- * vendoredCodeDetector.ts
4
- *
5
- * Real, general, structural detection of vendored/third-party/bundled code
6
- * — NOT a hardcoded library-name list as the primary mechanism. Build
7
- * brief: "Stop capturing vendored/third-party code as if it were the
8
- * client's own" (2026-09-22). Mirrored, identically-designed module in
9
- * kodingo-api (utils/vendoredCodeDetector.ts) and kodingo-vscode
10
- * (src/utils/vendoredCodeDetector.ts) — each repo has its own real,
11
- * separate walk/extract pipeline with no shared low-level utility package
12
- * between them (kodingo-core is explicitly scoped to decision/memory
13
- * lifecycle domain logic, not general file classification), so this is
14
- * duplicated by design, matching this codebase's own established
15
- * precedent (e.g. IGNORED_DIRS is already independently duplicated across
16
- * scan-repo.ts and security-scan.ts within this same repo). See this
17
- * brief's own final report for the full reasoning.
18
- *
19
- * Real, confirmed evidence this fixes: an admin deep scan of a real
20
- * .NET/WebForms project (TestHaven/FOTX) captured real jQuery internals
21
- * (domManip, isWindow, movePrevious) and real ASP.NET WebForms framework
22
- * internals (WebPartManager_InitiateWebPartDragDrop,
23
- * WebForm_GetElementByTagName, Zone_UpdatePosition) as if they were the
24
- * client's own business logic — diluting a real answer to "what is this
25
- * project" into near-nothing.
26
- *
27
- * Three real, independent layers, checked cheapest/most-certain first:
28
- * 1. Path/directory conventions — reliable across languages/ecosystems,
29
- * needs only the file path.
30
- * 2. File-naming conventions (.min.js/.min.css) — same, path-only.
31
- * 3. Content heuristics (minified shape, an explicit auto-generated
32
- * header) — needs real file content.
33
- * A fourth, explicitly-acknowledged-INCOMPLETE layer: a real, growing list
34
- * of specific, well-known bundled framework files. This list will NEVER be
35
- * complete — it exists because layers 1-2, by design, cannot catch every
36
- * real case: these specific files are frequently checked in un-minified,
37
- * under an ordinarily-legitimate-looking folder name (e.g. "Scripts/",
38
- * which is NOT treated as a vendored-directory convention here precisely
39
- * because plenty of real WebForms projects also put their OWN
40
- * app-specific JS there — see isVendoredPath's own reasoning below).
41
- */
42
- Object.defineProperty(exports, "__esModule", { value: true });
43
- exports.isVendoredPath = isVendoredPath;
44
- exports.isVendoredContent = isVendoredContent;
45
- exports.isVendoredCode = isVendoredCode;
46
- const NOT_VENDORED = { vendored: false, reason: null };
47
- // ── Layer 1: path/directory conventions ─────────────────────────────────────
48
- const VENDORED_DIR_SEGMENTS = [
49
- "node_modules", "vendor", "bower_components", "jspm_packages", "pods",
50
- ".venv", "venv", "site-packages",
51
- ];
52
- // "wwwroot/lib/" specifically is ASP.NET Core's real, well-known convention
53
- // for client-side libraries pulled in via LibMan/npm — directly relevant
54
- // to this exact client's real stack. "lib/" alone is NOT treated as
55
- // vendored — an extremely common real application folder name on its own.
56
- const VENDORED_PATH_PAIRS = [
57
- ["wwwroot", "lib"],
58
- ];
59
- // Classic NuGet packages/ convention: packages/<PackageName>.<Version>/...
60
- // Deliberately NOT a bare "packages/" match — that would false-positive on
61
- // the equally common JS/TS monorepo convention (Lerna/Yarn/npm workspaces)
62
- // where packages/<name>/ holds the CLIENT'S OWN first-party code.
63
- const NUGET_VERSIONED_DIR = /^[A-Za-z0-9_.-]+\.\d+\.\d+(\.\d+)?(-[A-Za-z0-9.]+)?$/;
64
- function pathSegments(filePath) {
65
- return filePath.replace(/\\/g, "/").split("/").filter(Boolean);
66
- }
67
- function isVendoredPath(filePath) {
68
- const segments = pathSegments(filePath);
69
- const lowerSegments = segments.map(s => s.toLowerCase());
70
- for (const dir of VENDORED_DIR_SEGMENTS) {
71
- if (lowerSegments.includes(dir)) {
72
- return { vendored: true, reason: `Path contains the "${dir}/" vendored-dependency directory convention.` };
73
- }
74
- }
75
- for (const [first, second] of VENDORED_PATH_PAIRS) {
76
- for (let i = 0; i < lowerSegments.length - 1; i++) {
77
- if (lowerSegments[i] === first && lowerSegments[i + 1] === second) {
78
- return { vendored: true, reason: `Path contains the "${first}/${second}/" vendored-dependency directory convention.` };
79
- }
80
- }
81
- }
82
- const packagesIdx = lowerSegments.indexOf("packages");
83
- if (packagesIdx !== -1 && packagesIdx + 1 < segments.length && NUGET_VERSIONED_DIR.test(segments[packagesIdx + 1])) {
84
- return { vendored: true, reason: `Path matches the classic NuGet "packages/<Name>.<Version>/" vendored-package convention.` };
85
- }
86
- const basename = segments[segments.length - 1] ?? "";
87
- if (/\.min\.(js|css)$/i.test(basename) || /-min\.(js|css)$/i.test(basename)) {
88
- return { vendored: true, reason: `Filename "${basename}" follows the minified-distribution naming convention (.min.js/.min.css).` };
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
89
7
  }
90
- const knownFileReason = matchKnownVendoredFile(basename);
91
- if (knownFileReason)
92
- return { vendored: true, reason: knownFileReason };
93
- return NOT_VENDORED;
94
- }
95
- // ── Layer 2: content heuristics ─────────────────────────────────────────────
96
- const MIN_CONTENT_LENGTH_FOR_MINIFICATION_CHECK = 5000;
97
- const MINIFIED_AVG_LINE_LENGTH_THRESHOLD = 500;
98
- const AUTO_GENERATED_HEADER_PATTERN = /<auto-generated|@generated\b|do not (edit|modify) this file|this file (is|was) auto-generated|machine[- ]generated/i;
99
- function isVendoredContent(content) {
100
- const header = content.slice(0, 500);
101
- if (AUTO_GENERATED_HEADER_PATTERN.test(header)) {
102
- return { vendored: true, reason: "File header contains an explicit auto-generated marker." };
103
- }
104
- if (content.length >= MIN_CONTENT_LENGTH_FOR_MINIFICATION_CHECK) {
105
- const lineCount = content.split("\n").length;
106
- const avgLineLength = content.length / Math.max(1, lineCount);
107
- if (avgLineLength > MINIFIED_AVG_LINE_LENGTH_THRESHOLD) {
108
- return {
109
- vendored: true,
110
- reason: `Unusually long average line length (${Math.round(avgLineLength)} chars/line across ${lineCount} lines) consistent with minified/bundled code, not hand-written source.`,
111
- };
112
- }
113
- }
114
- return NOT_VENDORED;
115
- }
116
- // ── Layer 3 (secondary, explicitly incomplete): known bundled framework files ──
117
- const KNOWN_VENDORED_FILENAME_PATTERNS = [
118
- /^jquery(-\d+(\.\d+){1,2})?(\.min)?\.js$/i,
119
- /^jquery-ui(-\d+(\.\d+){1,2})?(\.min)?\.js$/i,
120
- /^jquery\.validate(\.unobtrusive)?(\.min)?\.js$/i,
121
- /^jquery\.unobtrusive-ajax(\.min)?\.js$/i,
122
- /^WebUIValidation\.js$/i,
123
- /^WebForms\.js$/i,
124
- /^MicrosoftAjax(WebForms|Timer)?(\.debug)?\.js$/i,
125
- /^SmartNav\.js$/i,
126
- /^bootstrap(\.bundle)?(\.min)?\.(js|css)$/i,
127
- /^modernizr(-\d+(\.\d+){1,2})?(\.min)?\.js$/i,
128
- ];
129
- function matchKnownVendoredFile(basename) {
130
- for (const pattern of KNOWN_VENDORED_FILENAME_PATTERNS) {
131
- if (pattern.test(basename)) {
132
- return `Filename "${basename}" matches a real, known bundled/vendored framework file (secondary, explicitly-incomplete list — see this module's own file header).`;
133
- }
134
- }
135
- return null;
136
- }
137
- // ── Combined convenience ─────────────────────────────────────────────────────
138
- function isVendoredCode(filePath, content) {
139
- const pathResult = isVendoredPath(filePath);
140
- if (pathResult.vendored)
141
- return pathResult;
142
- if (content !== null)
143
- return isVendoredContent(content);
144
- return NOT_VENDORED;
145
- }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ /** Compatibility facade; canonical vendored-code policy lives in kodingo-core. */
18
+ __exportStar(require("kodingo-core/dist/src/entity-extractor/vendoredCodeDetector"), exports);
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.compareVersions = compareVersions;
4
+ exports.enforceVersionPolicy = enforceVersionPolicy;
5
+ const persistence_config_1 = require("./persistence-config");
6
+ const local_deep_scan_extractor_1 = require("./local-deep-scan-extractor");
7
+ const update_1 = require("../commands/update");
8
+ const { version: CLI_VERSION } = require("../../package.json");
9
+ function compareVersions(left, right) {
10
+ const a = left.split(".").map(Number), b = right.split(".").map(Number);
11
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
12
+ const delta = (a[i] ?? 0) - (b[i] ?? 0);
13
+ if (delta)
14
+ return delta > 0 ? 1 : -1;
15
+ }
16
+ return 0;
17
+ }
18
+ async function enforceVersionPolicy(args = process.argv.slice(2)) {
19
+ if (process.env.KODINGO_SKIP_UPDATE_CHECK === "true" || args[0] === "update")
20
+ return;
21
+ const apiUrl = ((0, persistence_config_1.readConfig)().apiUrl ?? "https://kodingo-api.onrender.com").replace(/\/$/, "");
22
+ let policy;
23
+ try {
24
+ const response = await fetch(`${apiUrl}/cli/version-policy`, { signal: AbortSignal.timeout(3000) });
25
+ if (!response.ok)
26
+ return;
27
+ policy = await response.json();
28
+ }
29
+ catch {
30
+ return;
31
+ }
32
+ if (local_deep_scan_extractor_1.EXTRACTOR_FORMAT_VERSION < policy.minimumExtractorFormat || local_deep_scan_extractor_1.EXTRACTOR_FORMAT_VERSION > policy.maximumExtractorFormat)
33
+ throw new Error(`${policy.message} Run: ${policy.updateCommand}`);
34
+ if (compareVersions(CLI_VERSION, policy.minimumCliVersion) < 0)
35
+ throw new Error(`Kodingo CLI ${CLI_VERSION} is below the required ${policy.minimumCliVersion}. Run: ${policy.updateCommand}`);
36
+ const nonInteractive = Boolean(process.env.CI) || args.includes("--no-update") || process.env.KODINGO_NO_AUTO_UPDATE === "true";
37
+ if (compareVersions(CLI_VERSION, policy.latestCliVersion) < 0) {
38
+ if (nonInteractive) {
39
+ console.warn(`Kodingo CLI ${policy.latestCliVersion} is available. Run: ${policy.updateCommand}`);
40
+ return;
41
+ }
42
+ await (0, update_1.updateCommand)(policy.latestCliVersion);
43
+ }
44
+ }
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "kodingo-cli",
3
- "version": "1.3.5",
3
+ "version": "1.4.0",
4
4
  "description": "Kodingo CLI",
5
5
  "license": "MIT",
6
6
  "private": false,
7
7
  "type": "commonjs",
8
8
  "main": "dist/cli.js",
9
9
  "bin": {
10
- "kodingo": "dist/cli.js"
10
+ "kodingo": "dist/bootstrap.js"
11
11
  },
12
12
  "files": [
13
13
  "dist"
@@ -26,7 +26,7 @@
26
26
  "@typescript-eslint/typescript-estree": "^8.61.1",
27
27
  "commander": "^12.1.0",
28
28
  "kodingo-agent": "^0.2.0",
29
- "kodingo-core": "^0.3.1",
29
+ "kodingo-core": "^0.3.6",
30
30
  "open": "^11.0.0",
31
31
  "simple-git": "^3.30.0",
32
32
  "tree-sitter-wasms": "^0.1.13",
@@ -1,10 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const graph_builder_1 = require("./utils/graph-builder");
4
- async function main() {
5
- const repoRoot = process.argv[2];
6
- const graph = await (0, graph_builder_1.buildGraph)(repoRoot);
7
- const node = Object.values(graph.nodes).find(n => n.name === "projectRoutes");
8
- console.log(node);
9
- }
10
- main();
@@ -1,16 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const fs_1 = __importDefault(require("fs"));
7
- const ast_parser_1 = require("./utils/ast-parser");
8
- async function main() {
9
- const filePath = process.argv[2];
10
- const source = fs_1.default.readFileSync(filePath, "utf-8");
11
- const symbols = await (0, ast_parser_1.parseFile)(filePath, source);
12
- for (const s of symbols) {
13
- console.log(`${s.name}: calls = [${s.calls.join(", ")}]`);
14
- }
15
- }
16
- main();