kodingo-cli 1.3.4 → 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.
- package/dist/__tests__/deepScanLocal.test.js +82 -0
- package/dist/__tests__/inference.test.js +78 -0
- package/dist/__tests__/versionPolicy.test.js +13 -0
- package/dist/adapters/ai/inference.js +5 -2
- package/dist/bootstrap.js +74 -0
- package/dist/cli.js +20 -6
- package/dist/commands/deep-scan-process.js +22 -0
- package/dist/commands/deep-scan-worker.js +19 -0
- package/dist/commands/deep-scan.js +344 -0
- package/dist/commands/init.js +51 -23
- package/dist/commands/install-hook.js +2 -0
- package/dist/commands/scan-git.js +2 -17
- package/dist/commands/update.js +18 -6
- package/dist/ports/cloud-event-port.js +4 -0
- package/dist/ports/db-event-port.js +4 -0
- package/dist/utils/local-deep-scan-extractor.js +21 -0
- package/dist/utils/persistence-config.js +27 -0
- package/dist/utils/vendoredCodeDetector.js +16 -143
- package/dist/utils/version-policy.js +44 -0
- package/package.json +3 -3
- package/dist/test-buildgraph-debug.js +0 -10
- package/dist/test-calls-debug.js +0 -16
|
@@ -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
|
+
}
|
package/dist/commands/init.js
CHANGED
|
@@ -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
|
|
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
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
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 {
|
|
296
|
-
|
|
297
|
-
|
|
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
|
-
|
|
336
|
+
throw new Error(`Initial deep scan failed: ${err.message}`);
|
|
301
337
|
}
|
|
302
|
-
//
|
|
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 {
|
|
306
|
-
await
|
|
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
|
-
|
|
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
|
|
@@ -15,23 +15,8 @@ const db_event_port_1 = require("../ports/db-event-port");
|
|
|
15
15
|
const cloud_event_port_1 = require("../ports/cloud-event-port");
|
|
16
16
|
const persistence_config_2 = require("../utils/persistence-config");
|
|
17
17
|
const repo_identity_1 = require("../utils/repo-identity");
|
|
18
|
-
const API_BASE_DEFAULT = "https://kodingo-api.onrender.com";
|
|
19
|
-
function getCredentials(repoRoot) {
|
|
20
|
-
const config = (0, persistence_config_1.readConfig)();
|
|
21
|
-
const normRoot = repoRoot.replace(/\/+$/, "");
|
|
22
|
-
let wsEntry = config.workspaces?.[normRoot] ?? config.workspaces?.[normRoot + "/"];
|
|
23
|
-
// Walk parent directories
|
|
24
|
-
let current = normRoot;
|
|
25
|
-
while (!wsEntry && current !== path_1.default.dirname(current)) {
|
|
26
|
-
current = path_1.default.dirname(current);
|
|
27
|
-
wsEntry = config.workspaces?.[current] ?? config.workspaces?.[current + "/"];
|
|
28
|
-
}
|
|
29
|
-
const token = wsEntry?.token ?? "";
|
|
30
|
-
const apiUrl = wsEntry?.apiUrl ?? config.apiUrl ?? API_BASE_DEFAULT;
|
|
31
|
-
return { token, apiUrl };
|
|
32
|
-
}
|
|
33
18
|
async function detectContextDecay(repoRoot, changedFiles, repoName) {
|
|
34
|
-
const { token, apiUrl } = getCredentials(repoRoot);
|
|
19
|
+
const { token, apiUrl } = (0, persistence_config_1.getCredentials)(repoRoot);
|
|
35
20
|
if (!token)
|
|
36
21
|
return;
|
|
37
22
|
for (const filePath of changedFiles) {
|
|
@@ -106,7 +91,7 @@ async function scanGitCommand(options) {
|
|
|
106
91
|
console.log(`Git scan complete (latest commit) for repo: ${repoRoot} commit: ${commitHash.slice(0, 8)}`);
|
|
107
92
|
// Send code_change signals for functions touched in this commit that already have memory
|
|
108
93
|
try {
|
|
109
|
-
const { token, apiUrl } = getCredentials(repoRoot);
|
|
94
|
+
const { token, apiUrl } = (0, persistence_config_1.getCredentials)(repoRoot);
|
|
110
95
|
const diffOutput = await git.diff([`${commitHash}^`, commitHash, '--name-only']).catch(() => '');
|
|
111
96
|
const commitChangedFiles = diffOutput.split('\n').filter(Boolean).map((f) => path_1.default.join(repoRoot, f)).filter((f) => /\.(ts|tsx|js|jsx|py|go|rs|php|java|kt|rb)$/.test(f));
|
|
112
97
|
if (token && commitChangedFiles.length > 0) {
|
package/dist/commands/update.js
CHANGED
|
@@ -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.
|
|
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.
|
|
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.
|
|
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
|
-
|
|
45
|
+
throw error;
|
|
34
46
|
}
|
|
35
47
|
}
|
|
@@ -7,6 +7,7 @@ exports.CloudEventPort = void 0;
|
|
|
7
7
|
const kodingo_core_1 = require("kodingo-core");
|
|
8
8
|
const persistence_config_1 = require("../utils/persistence-config");
|
|
9
9
|
const inference_1 = require("../adapters/ai/inference");
|
|
10
|
+
const persistence_config_2 = require("../utils/persistence-config");
|
|
10
11
|
const path_1 = __importDefault(require("path"));
|
|
11
12
|
/**
|
|
12
13
|
* EventPort implementation that persists via getPersistence().
|
|
@@ -152,6 +153,7 @@ class CloudEventPort {
|
|
|
152
153
|
const filePaths = extractFilePaths(filesChanged);
|
|
153
154
|
const repoName = path_1.default.basename(this.repoPath);
|
|
154
155
|
const shortHash = String(commitHash).slice(0, 8);
|
|
156
|
+
const { token, apiUrl } = (0, persistence_config_2.getCredentials)(this.repoPath);
|
|
155
157
|
const content = await (0, inference_1.inferDecisionSummary)({
|
|
156
158
|
diff: typeof summary?.rawDiff === "string"
|
|
157
159
|
? summary.rawDiff
|
|
@@ -160,6 +162,8 @@ class CloudEventPort {
|
|
|
160
162
|
symbol: symbol ?? "unknown",
|
|
161
163
|
commitMessage: decision.rationale ?? "",
|
|
162
164
|
repoName,
|
|
165
|
+
token,
|
|
166
|
+
apiUrl,
|
|
163
167
|
});
|
|
164
168
|
const title = symbol
|
|
165
169
|
? `Decision: changes to ${symbol}`
|
|
@@ -7,6 +7,7 @@ exports.DbEventPort = void 0;
|
|
|
7
7
|
const kodingo_core_1 = require("kodingo-core");
|
|
8
8
|
const memory_persistence_1 = require("../adapters/db-adapter/memory-persistence");
|
|
9
9
|
const inference_1 = require("../adapters/ai/inference");
|
|
10
|
+
const persistence_config_1 = require("../utils/persistence-config");
|
|
10
11
|
const path_1 = __importDefault(require("path"));
|
|
11
12
|
/**
|
|
12
13
|
* Minimal EventPort implementation for the CLI.
|
|
@@ -113,6 +114,7 @@ class DbEventPort {
|
|
|
113
114
|
const filePaths = extractFilePaths(filesChanged);
|
|
114
115
|
const repoName = path_1.default.basename(this.repoPath);
|
|
115
116
|
const shortHash = String(commitHash).slice(0, 8);
|
|
117
|
+
const { token, apiUrl } = (0, persistence_config_1.getCredentials)(this.repoPath);
|
|
116
118
|
const content = await (0, inference_1.inferDecisionSummary)({
|
|
117
119
|
diff: typeof summary?.rawDiff === "string"
|
|
118
120
|
? summary.rawDiff
|
|
@@ -121,6 +123,8 @@ class DbEventPort {
|
|
|
121
123
|
symbol: symbol ?? "unknown",
|
|
122
124
|
commitMessage: decision.rationale ?? "",
|
|
123
125
|
repoName,
|
|
126
|
+
token,
|
|
127
|
+
apiUrl,
|
|
124
128
|
});
|
|
125
129
|
const title = symbol
|
|
126
130
|
? `Decision: changes to ${symbol}`
|
|
@@ -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
|
+
}
|