kodingo-cli 1.3.5 → 1.4.1

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,878 @@
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.resolveDefaultBranch = resolveDefaultBranch;
41
+ exports.normalizeRemote = normalizeRemote;
42
+ exports.deriveBareRepoName = deriveBareRepoName;
43
+ exports.listTrackedFiles = listTrackedFiles;
44
+ exports.describeApiError = describeApiError;
45
+ exports.describeApplyReason = describeApplyReason;
46
+ exports.buildUploadSummary = buildUploadSummary;
47
+ exports.buildLocalReadSummary = buildLocalReadSummary;
48
+ exports.decideBranchSettlement = decideBranchSettlement;
49
+ exports.shouldSkipIncrementalScan = shouldSkipIncrementalScan;
50
+ exports.settleTrackedBranch = settleTrackedBranch;
51
+ exports.pollRun = pollRun;
52
+ exports.printFinalOutcome = printFinalOutcome;
53
+ exports.settleAndReconcile = settleAndReconcile;
54
+ exports.isFixedByTrackedBranchRecording = isFixedByTrackedBranchRecording;
55
+ exports.isHeldScanFixable = isHeldScanFixable;
56
+ exports.describeHeldScanDebugInfo = describeHeldScanDebugInfo;
57
+ exports.reconcileStaleHeldScan = reconcileStaleHeldScan;
58
+ exports.describeCoverageCompleteOutcome = describeCoverageCompleteOutcome;
59
+ exports.settleAlreadyCompleteProject = settleAlreadyCompleteProject;
60
+ exports.renderScanStatus = renderScanStatus;
61
+ exports.describeLastUploadStatus = describeLastUploadStatus;
62
+ exports.describeTrackedBranchNotRecorded = describeTrackedBranchNotRecorded;
63
+ exports.deepScanStatusCommand = deepScanStatusCommand;
64
+ exports.deepScanCommand = deepScanCommand;
65
+ const node_child_process_1 = require("node:child_process");
66
+ const node_fs_1 = __importDefault(require("node:fs"));
67
+ const node_os_1 = __importDefault(require("node:os"));
68
+ const node_path_1 = __importDefault(require("node:path"));
69
+ const promises_1 = __importDefault(require("node:readline/promises"));
70
+ const node_process_1 = require("node:process");
71
+ const node_worker_threads_1 = require("node:worker_threads");
72
+ const persistence_config_1 = require("../utils/persistence-config");
73
+ const format_1 = require("kodingo-core/dist/src/entity-extractor/format");
74
+ const sourcePolicy_1 = require("kodingo-core/dist/src/entity-extractor/sourcePolicy");
75
+ const vendoredCodeDetector_1 = require("../utils/vendoredCodeDetector");
76
+ // Structural-language files that core's declarative extractFile pipeline
77
+ // doesn't own (they feed a separate, server-side structural pass) but that
78
+ // the CLI has always tracked. Kept as a residual, additive allow-list on top
79
+ // of kodingo-core's own supportsExtraction() so fixing the declarative-file
80
+ // gap (JSON/YAML/SQL/GraphQL/Dockerfile/etc, missing from here before) never
81
+ // drops coverage for these.
82
+ const RESIDUAL_SUPPORTED = new Set([".py", ".rb", ".java", ".go", ".rs"]);
83
+ function isEligibleForManifest(relative) {
84
+ return (0, sourcePolicy_1.supportsExtraction)(relative) || RESIDUAL_SUPPORTED.has(node_path_1.default.extname(relative).toLowerCase());
85
+ }
86
+ const { version: CLI_VERSION } = require("../../package.json");
87
+ const STATE_NAME = node_path_1.default.join(".kortex", "deep-scan-state.json");
88
+ const FACT_CACHE_DIR = node_path_1.default.join(".kortex", "entity-cache");
89
+ function planForPath(plan, filePath) {
90
+ return {
91
+ attributeUpdates: plan.attributeUpdates.filter((item) => item.entity.path === filePath),
92
+ parentUpdates: plan.parentUpdates.filter((item) => item.entity.path === filePath),
93
+ derivedEntities: plan.derivedEntities.filter((item) => item.path === filePath),
94
+ derivedEdges: plan.derivedEdges.filter((item) => item.from.path === filePath),
95
+ replaceDerivedKinds: plan.replaceDerivedKinds,
96
+ };
97
+ }
98
+ class ExtractorWorker {
99
+ constructor() {
100
+ this.worker = this.createWorker();
101
+ this.sequence = 0;
102
+ this.filesSinceReset = 0;
103
+ this.maxFiles = Math.max(1, Number(process.env.KODINGO_EXTRACTOR_WORKER_MAX_FILES ?? 10));
104
+ this.peakRss = process.memoryUsage().rss;
105
+ }
106
+ createWorker() {
107
+ const maxOldGenerationSizeMb = Math.max(64, Number(process.env.KODINGO_EXTRACTOR_WORKER_HEAP_MB ?? 192));
108
+ return new node_worker_threads_1.Worker(node_path_1.default.join(__dirname, "deep-scan-worker.js"), { resourceLimits: { maxOldGenerationSizeMb, maxYoungGenerationSizeMb: 16 } });
109
+ }
110
+ get shouldReset() { return this.filesSinceReset >= this.maxFiles; }
111
+ async reset() { await this.worker.terminate(); this.worker = this.createWorker(); this.filesSinceReset = 0; }
112
+ async extract(absolutePath, filePath, blobSha, includeExcerpts) {
113
+ const id = ++this.sequence;
114
+ return new Promise((resolve, reject) => {
115
+ const onMessage = (message) => {
116
+ if (message.id !== id)
117
+ return;
118
+ this.worker.off("message", onMessage);
119
+ this.peakRss = Math.max(this.peakRss, process.memoryUsage().rss, Number(message.processRss ?? 0));
120
+ this.filesSinceReset++;
121
+ message.error ? reject(new Error(message.error)) : resolve(message.result ?? null);
122
+ };
123
+ this.worker.on("message", onMessage);
124
+ this.worker.postMessage({ id, absolutePath, filePath, blobSha, includeExcerpts });
125
+ });
126
+ }
127
+ async close() { await this.worker.terminate(); }
128
+ }
129
+ function parserFamily(filePath) {
130
+ const extension = node_path_1.default.extname(filePath).toLowerCase();
131
+ if ([".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs"].includes(extension))
132
+ return "js";
133
+ if (extension === ".php")
134
+ return "php";
135
+ if (extension === ".cs")
136
+ return "csharp";
137
+ if ([".cshtml", ".aspx", ".ascx", ".master", ".xaml", ".xml"].includes(extension))
138
+ return "template";
139
+ return "declarative";
140
+ }
141
+ function git(root, args) {
142
+ return (0, node_child_process_1.execFileSync)("git", ["-C", root, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
143
+ }
144
+ function resolveGitMetadata(start) {
145
+ const root = git(start, ["rev-parse", "--show-toplevel"]);
146
+ const commitSha = git(root, ["rev-parse", "HEAD"]);
147
+ const branch = (() => { try {
148
+ return git(root, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
149
+ }
150
+ catch {
151
+ return null;
152
+ } })();
153
+ const dirty = git(root, ["status", "--porcelain"]).length > 0;
154
+ const remote = git(root, ["remote", "get-url", "origin"]);
155
+ const shallow = git(root, ["rev-parse", "--is-shallow-repository"]) === "true";
156
+ return { root, commitSha, branch, detachedHead: branch === null, dirty, remote, repository: normalizeRemote(remote), shallow };
157
+ }
158
+ /** The remote's default branch. Tries the fast, local, offline read first
159
+ * (refs/remotes/origin/HEAD — only set once something has told the local
160
+ * clone what the remote's HEAD is, e.g. `git clone` or `git remote set-head`;
161
+ * not guaranteed, especially on a shallow or partial clone), then falls back
162
+ * to asking the remote directly via `git remote show origin` (which does
163
+ * contact the remote). Returns null rather than guessing when neither
164
+ * determines it. */
165
+ async function resolveDefaultBranch(root) {
166
+ try {
167
+ const ref = git(root, ["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"]);
168
+ const name = ref.split("/").pop();
169
+ if (name)
170
+ return name;
171
+ }
172
+ catch { /* fall through to the remote-show fallback */ }
173
+ try {
174
+ const output = git(root, ["remote", "show", "origin"]);
175
+ const match = output.match(/HEAD branch:\s*(\S+)/);
176
+ if (match?.[1] && match[1] !== "(unknown)")
177
+ return match[1];
178
+ }
179
+ catch { /* no origin remote, or the remote couldn't be reached */ }
180
+ return null;
181
+ }
182
+ function gitUserAttribution(root) {
183
+ const name = (() => { try {
184
+ return git(root, ["config", "user.name"]);
185
+ }
186
+ catch {
187
+ return "";
188
+ } })();
189
+ const email = (() => { try {
190
+ return git(root, ["config", "user.email"]);
191
+ }
192
+ catch {
193
+ return "";
194
+ } })();
195
+ if (name && email)
196
+ return `${name} <${email}>`;
197
+ return email || name || "A CLI user";
198
+ }
199
+ function normalizeRemote(remote) {
200
+ const cleaned = remote.replace(/^git@[^:]+:/, "").replace(/^https?:\/\/[^/]+\//, "").replace(/\.git$/, "");
201
+ return cleaned.replace(/^\/+/, "");
202
+ }
203
+ /** The bare repo name (no owner), derived from the already-normalized owner/name form. */
204
+ function deriveBareRepoName(normalizedRepository) {
205
+ const segments = normalizedRepository.split("/").filter(Boolean);
206
+ return segments[segments.length - 1] ?? normalizedRepository;
207
+ }
208
+ function globRegex(pattern) {
209
+ const normalized = pattern.trim().replace(/^\//, "");
210
+ const escaped = normalized.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "§§").replace(/\*/g, "[^/]*").replace(/§§/g, ".*").replace(/\?/g, ".");
211
+ return new RegExp(`^(?:${escaped}|.*/${escaped})(?:/.*)?$`);
212
+ }
213
+ function readKodingoIgnore(root) {
214
+ const file = node_path_1.default.join(root, ".kodingoignore");
215
+ if (!node_fs_1.default.existsSync(file))
216
+ return [];
217
+ return node_fs_1.default.readFileSync(file, "utf8").split(/\r?\n/).map((line) => line.trim()).filter((line) => line && !line.startsWith("#")).map(globRegex);
218
+ }
219
+ function listTrackedFiles(root, changedOnly = false) {
220
+ 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);
221
+ const changed = changedOnly ? new Set(git(root, ["diff-tree", "--no-commit-id", "--name-only", "-r", "HEAD"]).split(/\r?\n/).filter(Boolean)) : null;
222
+ const ignored = readKodingoIgnore(root);
223
+ const files = [];
224
+ for (const record of records) {
225
+ const match = record.match(/^\d+ ([a-f0-9]{40,64}) \d+\t(.+)$/);
226
+ if (!match)
227
+ continue;
228
+ const relative = match[2].replace(/\\/g, "/");
229
+ if (changed && !changed.has(relative))
230
+ continue;
231
+ if ((0, sourcePolicy_1.isNeverReadPath)(relative) || !isEligibleForManifest(relative) || ignored.some((pattern) => pattern.test(relative)) || (0, vendoredCodeDetector_1.isVendoredPath)(relative).vendored)
232
+ continue;
233
+ const absolute = node_path_1.default.join(root, relative);
234
+ if (!node_fs_1.default.existsSync(absolute) || !node_fs_1.default.statSync(absolute).isFile())
235
+ continue;
236
+ files.push({ path: relative, blobSha: match[1], size: node_fs_1.default.statSync(absolute).size });
237
+ }
238
+ return files.sort((a, b) => a.path.localeCompare(b.path));
239
+ }
240
+ function describeApiError(body, status) {
241
+ const message = body.error ?? `HTTP ${status}`;
242
+ const details = [];
243
+ if (body.sentLabel)
244
+ details.push(`sent: "${body.sentLabel}"`);
245
+ if (body.sentBareName)
246
+ details.push(`bare name: "${body.sentBareName}"`);
247
+ if (Array.isArray(body.registeredRepos))
248
+ details.push(`registered: ${body.registeredRepos.map((r) => `"${r}"`).join(", ") || "none"}`);
249
+ if (Array.isArray(body.matchingRegisteredRepos))
250
+ details.push(`matches: ${body.matchingRegisteredRepos.map((r) => `"${r}"`).join(", ")}`);
251
+ return details.length ? `${message} (${details.join("; ")})` : message;
252
+ }
253
+ /** Maps every apply_reason code the server can produce for a held (or
254
+ * applied) scan to a plain-English sentence and the exact next step. */
255
+ function describeApplyReason(reason) {
256
+ if (!reason)
257
+ return { sentence: "The scan was held for an unknown reason.", nextStep: "Run `kodingo deep-scan-status` for more detail." };
258
+ if (reason === "clean_tracked_branch")
259
+ return { sentence: "Applied.", nextStep: "" };
260
+ if (reason === "dirty_checkout")
261
+ return { sentence: "Your working tree has uncommitted changes.", nextStep: "Commit or stash your changes, then run `kodingo init` (or `kodingo deep-scan`) again." };
262
+ if (reason === "detached_head")
263
+ return { sentence: "This checkout is in detached HEAD state.", nextStep: "Check out a branch, then scan again." };
264
+ if (reason === "branch_unknown")
265
+ return { sentence: "The CLI could not determine the current branch.", nextStep: "Check out a named branch, then scan again." };
266
+ if (reason === "stale_full_tree")
267
+ return { sentence: "This was a full-repository scan at a commit that's no longer the tracked branch's current head — re-applying it could incorrectly remove data for files changed since.", nextStep: "Run `kodingo deep-scan` (or `kodingo init --force`) to scan the current commit." };
268
+ const mismatch = /^branch_mismatch:([^:]*):(.*)$/.exec(reason);
269
+ if (mismatch) {
270
+ const [, scanned, tracked] = mismatch;
271
+ if (tracked === "unregistered")
272
+ return { sentence: `No tracked branch is recorded for this repository (this scan ran on "${scanned}").`, nextStep: "Run `kodingo init` again to record a tracked branch." };
273
+ return { sentence: `The tracked branch is "${tracked}", but this scan ran on "${scanned}".`, nextStep: `Switch to "${tracked}", or ask an org admin to change the tracked branch.` };
274
+ }
275
+ return { sentence: `The scan was held (${reason}).`, nextStep: "Run `kodingo deep-scan-status` for more detail." };
276
+ }
277
+ /** Pure so the "accurate" wording regression (165 read vs N uploaded vs M
278
+ * already known) can be unit-tested without a network call. */
279
+ function buildUploadSummary(readLocally, willUpload, alreadyKnown, evidenceSummary) {
280
+ return `${readLocally} files read locally (${evidenceSummary}); ${willUpload} will upload, ${alreadyKnown} already known to Kortex. Whole source files are not uploaded; .env files were not read.`;
281
+ }
282
+ /** The pre-consent summary — built from local data only. No upload session
283
+ * exists yet (that's what sends the file manifest — every path, size, and
284
+ * blob SHA — to the server), so there's no real upload/already-known split
285
+ * to report yet; that requires the server's held-blob-SHA list, which only
286
+ * exists once a session is created, and a session is only ever created
287
+ * after this consent is granted. */
288
+ function buildLocalReadSummary(readLocally, evidenceSummary) {
289
+ return `${readLocally} files read locally; they will be checked against what Kortex already holds (${evidenceSummary}). Whole source files are not uploaded; .env files were not read.`;
290
+ }
291
+ function decideBranchSettlement(params) {
292
+ const { outcome, trackedBranch, branch, repository, yes, promptAnswerYes, defaultBranch } = params;
293
+ const scanPending = params.scanPending !== false;
294
+ if (outcome === "match")
295
+ return { action: "proceed" };
296
+ if (outcome === "mismatch") {
297
+ return {
298
+ action: "proceed-held",
299
+ message: scanPending
300
+ ? `Tracked branch for ${repository} is "${trackedBranch}"; this checkout is on "${branch}". This scan will be held. Switch to "${trackedBranch}", or ask an org admin to change the tracked branch.`
301
+ : `This project tracks "${trackedBranch}"; commits on "${branch}" will not update Kortex. Switch branches or ask an org admin to change the tracked branch.`,
302
+ };
303
+ }
304
+ // outcome === "none"
305
+ if (yes) {
306
+ if (defaultBranch && defaultBranch === branch)
307
+ return { action: "record" };
308
+ return {
309
+ action: "refuse",
310
+ message: defaultBranch
311
+ ? `No tracked branch is recorded for ${repository}, and this checkout ("${branch}") does not match the remote's default branch ("${defaultBranch}"). Refusing to guess under --yes — record a tracked branch first (run \`kodingo init\` interactively, or ask an org admin), or check out "${defaultBranch}".`
312
+ : `No tracked branch is recorded for ${repository}, and the remote's default branch could not be determined. Refusing to guess under --yes — record a tracked branch first (run \`kodingo init\` interactively, or ask an org admin).`,
313
+ };
314
+ }
315
+ if (promptAnswerYes)
316
+ return { action: "record" };
317
+ return {
318
+ action: "proceed-held",
319
+ message: scanPending
320
+ ? `No tracked branch is recorded for ${repository}. This scan will be held. Run \`kodingo init\` again and accept tracking "${branch}" to apply it.`
321
+ : `No tracked branch is recorded for ${repository}. Commits will not update Kortex until one is tracked. Run \`kodingo init\` again and accept tracking "${branch}" to enable it.`,
322
+ };
323
+ }
324
+ /** The commit hook must never upload for a commit it can positively confirm
325
+ * is NOT on the tracked branch. "none" (nothing tracked yet) and "match"
326
+ * both proceed — only a confirmed "mismatch" skips. */
327
+ function shouldSkipIncrementalScan(outcome) {
328
+ return outcome === "mismatch";
329
+ }
330
+ async function apiRequest(apiUrl, token, route, init = {}) {
331
+ const response = await fetch(`${apiUrl.replace(/\/$/, "")}${route}`, { ...init, headers: { "content-type": "application/json", "X-Kodingo-Token": token, ...(init.headers ?? {}) } });
332
+ const body = await response.json().catch(() => ({}));
333
+ if (!response.ok)
334
+ throw new Error(describeApiError(body, response.status));
335
+ return body;
336
+ }
337
+ async function permission(options, summary) {
338
+ if (options.yes)
339
+ return true;
340
+ if (!process.stdin.isTTY)
341
+ return false;
342
+ const rl = promises_1.default.createInterface({ input: node_process_1.stdin, output: node_process_1.stdout });
343
+ try {
344
+ return /^y(?:es)?$/i.test((await rl.question(`${summary}\nUpload this structural summary? [y/N] `)).trim());
345
+ }
346
+ finally {
347
+ rl.close();
348
+ }
349
+ }
350
+ async function askYesNo(question) {
351
+ if (!process.stdin.isTTY)
352
+ return false;
353
+ const rl = promises_1.default.createInterface({ input: node_process_1.stdin, output: node_process_1.stdout });
354
+ try {
355
+ const answer = (await rl.question(question)).trim();
356
+ return answer === "" || /^y(?:es)?$/i.test(answer);
357
+ }
358
+ finally {
359
+ rl.close();
360
+ }
361
+ }
362
+ /** Settles the project's tracked development branch against the current
363
+ * checkout via POST /deep-scan/branch/settle, before anything is uploaded —
364
+ * so a first scan can apply instead of landing held with no explanation. */
365
+ async function settleTrackedBranch(opts) {
366
+ const check = await apiRequest(opts.apiUrl, opts.token, "/deep-scan/branch/settle", { method: "POST", body: JSON.stringify({ repository: opts.repository, repositoryName: opts.repositoryName, branch: opts.branch, record: false }) });
367
+ let promptAnswerYes;
368
+ if (check.outcome === "none" && !opts.yes) {
369
+ promptAnswerYes = await askYesNo(`No tracked branch is recorded for ${opts.repository}. Track "${opts.branch}"? [Y/n] `);
370
+ }
371
+ const defaultBranch = check.outcome === "none" && opts.yes ? await resolveDefaultBranch(opts.root) : null;
372
+ const decision = decideBranchSettlement({ outcome: check.outcome, trackedBranch: check.trackedBranch, branch: opts.branch, repository: opts.repository, yes: opts.yes, promptAnswerYes, defaultBranch, scanPending: opts.scanPending });
373
+ if (decision.action === "refuse")
374
+ throw new Error(decision.message);
375
+ if (decision.action === "proceed-held") {
376
+ console.log(decision.message);
377
+ return { recorded: false, held: true, trackedBranch: check.trackedBranch };
378
+ }
379
+ if (decision.action === "record") {
380
+ const attributedBy = gitUserAttribution(opts.root);
381
+ await apiRequest(opts.apiUrl, opts.token, "/deep-scan/branch/settle", { method: "POST", body: JSON.stringify({ repository: opts.repository, repositoryName: opts.repositoryName, branch: opts.branch, record: true, attributedBy }) });
382
+ console.log(`✔ Tracked branch for ${opts.repository} set to "${opts.branch}".`);
383
+ return { recorded: true, held: false, trackedBranch: opts.branch };
384
+ }
385
+ return { recorded: false, held: false, trackedBranch: check.trackedBranch }; // match — proceed silently
386
+ }
387
+ async function pollRun(apiUrl, token, runId, timeoutMs = 60000) {
388
+ const start = Date.now();
389
+ let delay = 500;
390
+ for (;;) {
391
+ const run = await apiRequest(apiUrl, token, `/deep-scan/runs/${runId}`);
392
+ if (run.state === "held" || run.state === "completed" || run.state === "failed")
393
+ return run;
394
+ if (Date.now() - start > timeoutMs)
395
+ return run;
396
+ await new Promise((resolve) => setTimeout(resolve, delay));
397
+ delay = Math.min(delay * 2, 5000);
398
+ }
399
+ }
400
+ /** Prints the one real outcome of a scan — never "accepted" when held. */
401
+ function printFinalOutcome(run, yes) {
402
+ if (run.applied) {
403
+ console.log(`Deep scan applied: ${run.entity_count ?? 0} entities, ${run.edge_count ?? 0} edges, ${run.file_count ?? run.filesDone ?? 0} files. Use \`kodingo deep-scan-status\` to see coverage.`);
404
+ return;
405
+ }
406
+ const { sentence, nextStep } = describeApplyReason(run.apply_reason ?? run.reason ?? null);
407
+ console.log(`Deep scan held: ${sentence}${nextStep ? ` ${nextStep}` : ""}`);
408
+ if (yes)
409
+ process.exitCode = 1;
410
+ }
411
+ /** Runs tracked-branch settlement and, if a branch was just recorded and a
412
+ * held scan already exists for this exact commit, re-evaluates it without a
413
+ * new upload. Returns handled:true when that reconciliation fully covers
414
+ * this commit, so the caller can skip the normal upload flow. */
415
+ async function settleAndReconcile(opts) {
416
+ const meta = resolveGitMetadata(opts.root);
417
+ if (meta.detachedHead || !meta.branch)
418
+ return { handled: false };
419
+ const settlement = await settleTrackedBranch({
420
+ apiUrl: opts.apiUrl, token: opts.token, root: opts.root,
421
+ repository: meta.repository, repositoryName: deriveBareRepoName(meta.repository),
422
+ branch: meta.branch, yes: opts.yes,
423
+ });
424
+ if (!settlement.recorded)
425
+ return { handled: false };
426
+ const status = await apiRequest(opts.apiUrl, opts.token, "/deep-scan/status");
427
+ const lastScan = status.lastScan;
428
+ if (!lastScan || lastScan.commitSha !== meta.commitSha || lastScan.applied)
429
+ return { handled: false };
430
+ const result = await apiRequest(opts.apiUrl, opts.token, `/deep-scan/scans/${lastScan.id}/reapply`, { method: "POST", body: "{}" });
431
+ printFinalOutcome({ applied: result.applied, apply_reason: result.reason, entity_count: result.entityCount, edge_count: result.edgeCount, file_count: result.fileCount }, opts.yes);
432
+ return { handled: true };
433
+ }
434
+ /** A held scan's reason is one a CURRENT tracked branch could plausibly
435
+ * have fixed — "branch_unknown" (the server couldn't tell what branch a
436
+ * session was even on) or a mismatch against an explicitly "unregistered"
437
+ * tracked branch (there was none recorded at the time it was uploaded).
438
+ * Any other hold reason (dirty_checkout, detached_head, or a mismatch
439
+ * against a real, different tracked branch) is NOT fixed by this —
440
+ * reapplying it would just report the exact same hold again.
441
+ *
442
+ * This is a STATIC fallback only — it reads the reason string embedded at
443
+ * upload time, so it can't tell that e.g. "branch_mismatch:main:develop"
444
+ * (tracked was "develop" back then) has since become fixable because the
445
+ * tracked branch is now "main". Prefer isHeldScanFixable, which uses the
446
+ * server's own fresh re-evaluation when available. */
447
+ function isFixedByTrackedBranchRecording(reason) {
448
+ if (!reason)
449
+ return false;
450
+ if (reason === "branch_unknown")
451
+ return true;
452
+ return /^branch_mismatch:[^:]*:unregistered$/.test(reason);
453
+ }
454
+ /** Whether a held CLI scan would actually apply if re-applied right now —
455
+ * authoritative when the server reports it (fixableByTrackedBranch, added
456
+ * additively to lastCliScan: the server re-derives this from the scan's
457
+ * own stored session flags against whatever the tracked branch IS right
458
+ * now, not from parsing a reason string), falling back to the static
459
+ * reason-string check for an older server that doesn't send it yet. */
460
+ function isHeldScanFixable(lastCliScan) {
461
+ if (typeof lastCliScan.fixableByTrackedBranch === "boolean")
462
+ return lastCliScan.fixableByTrackedBranch;
463
+ return isFixedByTrackedBranchRecording(lastCliScan.reason ?? null);
464
+ }
465
+ /** Pure so --verbose/KODINGO_DEBUG's "print the inputs behind the
466
+ * decision" requirement is directly unit-testable. */
467
+ function describeHeldScanDebugInfo(params) {
468
+ const scanInfo = params.lastCliScan
469
+ ? `held scan id=${params.lastCliScan.id} commit=${params.lastCliScan.commitSha.slice(0, 12)} reason=${params.lastCliScan.reason ?? "none"}`
470
+ : "no held CLI scan";
471
+ const fixabilitySource = params.lastCliScan && typeof params.lastCliScan.fixableByTrackedBranch === "boolean" ? "server" : "reason-string fallback";
472
+ const fixableText = params.fixable === null ? "n/a" : `${params.fixable} (${fixabilitySource})`;
473
+ return `[debug] tracked branch=${params.trackedBranch ?? "none"}; ${scanInfo}; fixable=${fixableText}`;
474
+ }
475
+ /** Re-applies the project's most recent HELD **CLI** scan — from
476
+ * lastCliScan, never lastScan (the project's overall most recent scan of
477
+ * ANY source — a project with GitHub coverage can have an hourly
478
+ * github_light_backup row, source:'github', applied:true, as its most
479
+ * recent scan while a real held CLI scan sits untouched in lastCliScan;
480
+ * reading lastScan here silently skips reconciling it entirely, which is
481
+ * exactly the bug this fixes) — AT ANY COMMIT, not just the current
482
+ * checkout's, and regardless of whether a tracked branch was JUST recorded
483
+ * THIS run, recorded in an earlier run, or set by someone else entirely —
484
+ * if its hold reason is one the CURRENT tracked branch fixes (see
485
+ * isHeldScanFixable). Unlike settleAndReconcile's exact-commit reapply
486
+ * (used when a fresh scan is about to run regardless, so reconciling an
487
+ * older held scan would be moot), this is for the "coverage is already
488
+ * complete, no new scan is happening" path — reconciling whatever's held
489
+ * is the ONLY way it ever gets applied there.
490
+ *
491
+ * Reports every outcome in plain words, with no silent path: applied
492
+ * (with counts, via the existing printFinalOutcome), nothing held, a held
493
+ * scan that isn't fixed by the tracked branch (its reason and next step),
494
+ * the held scan's session having expired (a distinct, actionable message),
495
+ * any other still-held reason (via describeApplyReason, which also covers
496
+ * the server's stale-full-tree refusal), or a server/network error. Never
497
+ * throws — a failure here must not abort the whole "coverage already
498
+ * complete" flow, which has already told the user their project is read
499
+ * and recorded their tracked branch. */
500
+ async function reconcileStaleHeldScan(opts) {
501
+ let status;
502
+ try {
503
+ status = await apiRequest(opts.apiUrl, opts.token, "/deep-scan/status");
504
+ }
505
+ catch (err) {
506
+ console.log(`Could not check for a held scan to re-apply: ${err.message}`);
507
+ if (opts.yes)
508
+ process.exitCode = 1;
509
+ return { outcome: "error", message: err.message };
510
+ }
511
+ const lastCliScan = status.lastCliScan;
512
+ const isHeld = Boolean(lastCliScan) && !lastCliScan.applied;
513
+ const fixable = isHeld ? isHeldScanFixable(lastCliScan) : null;
514
+ if (opts.verbose)
515
+ console.log(describeHeldScanDebugInfo({ trackedBranch: opts.trackedBranch ?? null, lastCliScan: isHeld ? lastCliScan : null, fixable }));
516
+ if (!isHeld) {
517
+ console.log("No CLI scan is currently held.");
518
+ return { outcome: "none-to-reconcile" };
519
+ }
520
+ if (!fixable) {
521
+ const { sentence, nextStep } = describeApplyReason(lastCliScan.reason);
522
+ console.log(`A held scan exists, but the tracked branch doesn't fix it: ${sentence}${nextStep ? ` ${nextStep}` : ""}`);
523
+ return { outcome: "none-to-reconcile" };
524
+ }
525
+ try {
526
+ const result = await apiRequest(opts.apiUrl, opts.token, `/deep-scan/scans/${lastCliScan.id}/reapply`, { method: "POST", body: "{}" });
527
+ if (result.applied) {
528
+ printFinalOutcome({ applied: true, entity_count: result.entityCount, edge_count: result.edgeCount, file_count: result.fileCount }, opts.yes);
529
+ return { outcome: "applied" };
530
+ }
531
+ if (result.sessionExpired) {
532
+ console.log("The held scan can no longer be applied (its upload session expired). Run `kodingo init --force` to scan again.");
533
+ if (opts.yes)
534
+ process.exitCode = 1;
535
+ return { outcome: "still-held", reason: "session_expired" };
536
+ }
537
+ printFinalOutcome({ applied: false, apply_reason: result.reason }, opts.yes);
538
+ return { outcome: "still-held", reason: result.reason ?? null };
539
+ }
540
+ catch (err) {
541
+ console.log(`Could not re-apply the held scan: ${err.message}`);
542
+ if (opts.yes)
543
+ process.exitCode = 1;
544
+ return { outcome: "error", message: err.message };
545
+ }
546
+ }
547
+ /** Pure so "the closing message is only the confident one when the branch
548
+ * matches" is directly unit-testable. */
549
+ function describeCoverageCompleteOutcome(held) {
550
+ return held
551
+ ? "Kortex already has a complete read of this project."
552
+ : "Kortex already has a complete read of this project. Your commits will keep it up to date.";
553
+ }
554
+ /** The "coverage is already complete, skip the local scan" path still needs
555
+ * the tracked branch settled — skipping the scan must never also silently
556
+ * skip recording a tracked branch, or a project with complete coverage but
557
+ * no tracked branch would hold every future commit (including the hook's)
558
+ * forever with no visible error. Uses the exact same settleTrackedBranch
559
+ * rules as the first-scan flow (record only when none exists and, under
560
+ * --yes, only on the remote's default branch; never overwrite an existing
561
+ * one), just with scanPending:false so the wording reflects that no scan
562
+ * is actually about to run. Reconciliation runs whenever a tracked branch
563
+ * CURRENTLY exists — recorded just now, recorded in an earlier run, or set
564
+ * by someone else entirely; never gated on whether THIS call is what
565
+ * recorded it (that was the bug: an already-recorded tracked branch, e.g.
566
+ * from a prior `kodingo init`, left a held scan sitting unreconciled
567
+ * forever, since recording never happened on any later run either). If a
568
+ * held scan is fixed by it (see isHeldScanFixable), it's reapplied — and
569
+ * the confident closing line only ever prints once the held-scan state has
570
+ * been reported, one way or another: nothing held, applied, or a clear
571
+ * reason it still isn't (not fixable, expired, stale, or any other), never
572
+ * silently skipped. */
573
+ async function settleAlreadyCompleteProject(opts) {
574
+ if (opts.detachedHead || !opts.branch) {
575
+ console.log(describeCoverageCompleteOutcome(true));
576
+ console.log("This checkout is in detached HEAD state — tracked-branch settlement was skipped. Commits here will not update Kortex until you check out a named branch.");
577
+ console.log("Held scan state was not checked (no named branch to settle against).");
578
+ return;
579
+ }
580
+ const settlement = await settleTrackedBranch({
581
+ apiUrl: opts.apiUrl, token: opts.token, root: opts.root,
582
+ repository: opts.repository, repositoryName: opts.repositoryName,
583
+ branch: opts.branch, yes: opts.yes, scanPending: false,
584
+ });
585
+ let reconciliation = { outcome: "none-to-reconcile" };
586
+ if (settlement.trackedBranch !== null) {
587
+ reconciliation = await reconcileStaleHeldScan({ apiUrl: opts.apiUrl, token: opts.token, yes: opts.yes, trackedBranch: settlement.trackedBranch, verbose: opts.verbose });
588
+ }
589
+ else {
590
+ console.log("No tracked branch exists yet, so no held scan was checked.");
591
+ }
592
+ const stillUnresolved = reconciliation.outcome === "still-held" || reconciliation.outcome === "error";
593
+ console.log(describeCoverageCompleteOutcome(settlement.held || stillUnresolved));
594
+ }
595
+ /** Pure so the wording — and the "never call a GitHub backup record a CLI
596
+ * scan" fix — is directly unit-testable without a network call. A project
597
+ * can have both a local-scan history and a GitHub-read history at once
598
+ * (or either alone, or neither); each is reported from its own
599
+ * source-scoped field, never from whichever scan merely happened most
600
+ * recently. */
601
+ function renderScanStatus(status) {
602
+ const lines = [];
603
+ const coveragePct = `${Math.round((status.coverage ?? 0) * 100)}%`;
604
+ const sourceDescriptor = status.source === "github" ? "read through GitHub" : status.source === "cli" ? "local scan" : "no scan yet";
605
+ lines.push(`Coverage: ${coveragePct} (${sourceDescriptor})`);
606
+ const cli = status.lastCliScan;
607
+ if (cli) {
608
+ const when = cli.completedAt ?? "unknown time";
609
+ if (cli.applied) {
610
+ lines.push(`Last local scan: commit ${String(cli.commitSha).slice(0, 12)} at ${when} — applied (${cli.entityCount} entities, ${cli.edgeCount} edges, ${cli.fileCount} files).`);
611
+ }
612
+ else {
613
+ const { sentence, nextStep } = describeApplyReason(cli.reason);
614
+ lines.push(`Last local scan: commit ${String(cli.commitSha).slice(0, 12)} at ${when} — held. ${sentence}${nextStep ? ` ${nextStep}` : ""}`);
615
+ }
616
+ }
617
+ else {
618
+ lines.push("No local scan yet.");
619
+ }
620
+ const github = status.lastGithubScan;
621
+ if (github) {
622
+ const when = github.completedAt ?? "unknown time";
623
+ lines.push(`Last GitHub read: commit ${String(github.commitSha).slice(0, 12)} at ${when}.`);
624
+ }
625
+ return lines;
626
+ }
627
+ /** Pure so "the hook's held-reason file feeds the status" is directly
628
+ * unit-testable without touching the filesystem or network. `state` is
629
+ * whatever's currently in .kortex/deep-scan-state.json — `applied` is only
630
+ * ever present once a run has actually been polled to completion (see
631
+ * deepScanCommand), so its absence (still mid-upload, or the process never
632
+ * got that far) is deliberately treated the same as "nothing to report",
633
+ * not as "held". */
634
+ function describeLastUploadStatus(state) {
635
+ if (!state || state.applied !== false)
636
+ return null;
637
+ const { sentence } = describeApplyReason(state.reason);
638
+ return `Your last commit upload was held: ${sentence}`;
639
+ }
640
+ /** Pure so "say so on its own line and give the one command to fix it" is
641
+ * directly unit-testable. Only "none" needs its own line here — "match" has
642
+ * nothing to add, and "mismatch" is already covered by the held-scan
643
+ * reason surfaced elsewhere in status (describeApplyReason's own
644
+ * branch_mismatch wording). */
645
+ function describeTrackedBranchNotRecorded(outcome, repository) {
646
+ if (outcome !== "none")
647
+ return null;
648
+ return `No tracked branch is recorded for ${repository}. Run \`kodingo init\` to record one.`;
649
+ }
650
+ async function deepScanStatusCommand(options = {}) {
651
+ const meta = resolveGitMetadata(node_path_1.default.resolve(options.repo ?? process.cwd()));
652
+ const credentials = (0, persistence_config_1.getCredentials)(meta.root);
653
+ if (!credentials.token)
654
+ throw new Error("No project token found. Run `kodingo init` in this project first.");
655
+ const status = await apiRequest(credentials.apiUrl, credentials.token, "/deep-scan/status");
656
+ for (const line of renderScanStatus(status))
657
+ console.log(line);
658
+ // Whether a tracked branch is recorded at all isn't in /deep-scan/status —
659
+ // reuse the same read-only (record:false) branch/settle check the first-
660
+ // scan and complete-project paths already make, rather than guessing from
661
+ // scan history alone (a project can be fully read via GitHub with no CLI
662
+ // scan history at all, and still have no tracked branch recorded).
663
+ if (meta.branch && !meta.detachedHead) {
664
+ try {
665
+ const check = await apiRequest(credentials.apiUrl, credentials.token, "/deep-scan/branch/settle", { method: "POST", body: JSON.stringify({ repository: meta.repository, repositoryName: deriveBareRepoName(meta.repository), branch: meta.branch, record: false }) });
666
+ const line = describeTrackedBranchNotRecorded(check.outcome, meta.repository);
667
+ if (line)
668
+ console.log(line);
669
+ }
670
+ catch { /* status must never fail just because this extra check couldn't run */ }
671
+ }
672
+ try {
673
+ const state = JSON.parse(node_fs_1.default.readFileSync(node_path_1.default.join(meta.root, STATE_NAME), "utf8"));
674
+ const line = describeLastUploadStatus(state);
675
+ if (line)
676
+ console.log(line);
677
+ }
678
+ catch { /* no local state file yet — nothing to report */ }
679
+ console.log(JSON.stringify({ repository: meta.repository, branch: meta.branch, ...status }, null, 2));
680
+ }
681
+ async function deepScanCommand(options = {}) {
682
+ const started = Date.now();
683
+ const meta = resolveGitMetadata(node_path_1.default.resolve(options.repo ?? process.cwd()));
684
+ if (meta.detachedHead)
685
+ console.warn("Detached HEAD detected: this scan will be uploaded for review but not applied.");
686
+ if (meta.shallow)
687
+ console.warn("Shallow clone detected: the current tracked snapshot can be scanned, but earlier history is unavailable.");
688
+ const credentials = (0, persistence_config_1.getCredentials)(meta.root);
689
+ const envToken = process.env.KODINGO_TOKEN?.trim();
690
+ const token = envToken || credentials.token;
691
+ if (!token)
692
+ throw new Error("No project token found. Run `kodingo init` once, or set KODINGO_TOKEN for CI.");
693
+ // The commit hook invokes `deep-scan --changed` unconditionally, on every
694
+ // commit, regardless of branch — upload only for a commit on the tracked
695
+ // branch, per a confirmed mismatch (never on "none": there's nothing to
696
+ // mismatch against yet, and the server already holds that case cleanly).
697
+ // Read-only (record:false) and fails open on any error — a network
698
+ // hiccup here must never block, delay, or fail the commit; it just means
699
+ // this one incremental scan proceeds exactly as it did before this check
700
+ // existed, and the server's own apply-time branch check still applies.
701
+ if (options.changed && !options.dryRun && meta.branch && !meta.detachedHead) {
702
+ try {
703
+ const check = await apiRequest(credentials.apiUrl, token, "/deep-scan/branch/settle", { method: "POST", body: JSON.stringify({ repository: meta.repository, repositoryName: deriveBareRepoName(meta.repository), branch: meta.branch, record: false }) });
704
+ if (shouldSkipIncrementalScan(check.outcome)) {
705
+ console.log(`Skipping incremental scan: tracked branch for ${meta.repository} is "${check.trackedBranch}"; this commit is on "${meta.branch}".`);
706
+ return;
707
+ }
708
+ }
709
+ catch { /* fail open — scan proceeds exactly as it did before this check */ }
710
+ }
711
+ const policy = options.dryRun
712
+ ? { excerptsEnabled: true }
713
+ : await apiRequest(credentials.apiUrl, token, "/deep-scan/policy");
714
+ const files = listTrackedFiles(meta.root, options.changed === true);
715
+ if (!files.length) {
716
+ console.log("No supported tracked files need scanning.");
717
+ return;
718
+ }
719
+ const manifest = { repository: meta.repository, repositoryName: deriveBareRepoName(meta.repository), remote: meta.remote, 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 } };
720
+ const spoolDir = node_fs_1.default.mkdtempSync(node_path_1.default.join(node_os_1.default.tmpdir(), "kodingo-deep-scan-"));
721
+ const spoolPath = node_path_1.default.join(spoolDir, `deep-scan-${meta.commitSha}.jsonl`);
722
+ node_fs_1.default.writeFileSync(spoolPath, "", { mode: 0o600 });
723
+ let processed = 0;
724
+ let extractedCount = 0;
725
+ let evidenceCount = 0;
726
+ let peakRss = process.memoryUsage().rss;
727
+ let extractionPeakRss = peakRss;
728
+ const cacheDir = node_path_1.default.join(meta.root, FACT_CACHE_DIR);
729
+ node_fs_1.default.mkdirSync(cacheDir, { recursive: true });
730
+ const extractor = new ExtractorWorker();
731
+ const scanFiles = [...files].sort((left, right) => parserFamily(left.path).localeCompare(parserFamily(right.path)) || left.path.localeCompare(right.path));
732
+ let activeFamily;
733
+ try {
734
+ for (const file of scanFiles) {
735
+ const family = parserFamily(file.path);
736
+ if (activeFamily !== undefined && (family !== activeFamily || extractor.shouldReset))
737
+ await extractor.reset();
738
+ activeFamily = family;
739
+ const cachePath = node_path_1.default.join(cacheDir, `${file.blobSha}.json`);
740
+ let extracted = null;
741
+ try {
742
+ extracted = JSON.parse(node_fs_1.default.readFileSync(cachePath, "utf8"));
743
+ }
744
+ catch {
745
+ extracted = await extractor.extract(node_path_1.default.join(meta.root, file.path), file.path, file.blobSha, policy.excerptsEnabled);
746
+ if (extracted)
747
+ node_fs_1.default.writeFileSync(cachePath, JSON.stringify(extracted), { mode: 0o600 });
748
+ }
749
+ if (extracted) {
750
+ node_fs_1.default.appendFileSync(spoolPath, `${JSON.stringify(extracted)}\n`, "utf8");
751
+ extractedCount++;
752
+ evidenceCount += extracted.observations.length;
753
+ }
754
+ peakRss = Math.max(peakRss, process.memoryUsage().rss, extractor.peakRss);
755
+ extractionPeakRss = Math.max(extractionPeakRss, peakRss);
756
+ processed++;
757
+ if (process.stdout.isTTY)
758
+ process.stdout.write(`\rExtracted ${processed}/${files.length} files`);
759
+ if (processed % Math.max(1, node_os_1.default.cpus().length) === 0)
760
+ await new Promise((resolve) => setImmediate(resolve));
761
+ }
762
+ }
763
+ finally {
764
+ await extractor.close();
765
+ }
766
+ // Keep extraction output on the spool until the parser worker (and its WASM
767
+ // heaps) has exited. This avoids overlapping parser memory with the full
768
+ // in-memory project link set on large polyglot repositories.
769
+ const linkFiles = [];
770
+ const { toLinkFile, linkProject } = await Promise.resolve().then(() => __importStar(require("kodingo-core/dist/src/entity-extractor/linker")));
771
+ const linkLines = promises_1.default.createInterface({ input: node_fs_1.default.createReadStream(spoolPath, { encoding: "utf8" }), crlfDelay: Infinity });
772
+ for await (const line of linkLines)
773
+ if (line)
774
+ linkFiles.push(toLinkFile(JSON.parse(line)));
775
+ peakRss = Math.max(peakRss, process.memoryUsage().rss);
776
+ const linked = linkProject(linkFiles);
777
+ peakRss = Math.max(peakRss, process.memoryUsage().rss);
778
+ const linkPeakRss = process.memoryUsage().rss;
779
+ const linksByPath = new Map();
780
+ for (const reference of linked.references) {
781
+ const list = linksByPath.get(reference.sourcePath) ?? [];
782
+ list.push(reference);
783
+ linksByPath.set(reference.sourcePath, list);
784
+ }
785
+ if (process.stdout.isTTY)
786
+ process.stdout.write("\n");
787
+ if (options.dryRun) {
788
+ const outputPath = node_path_1.default.resolve(options.dryRun);
789
+ const outputFd = node_fs_1.default.openSync(outputPath, "w", 0o600);
790
+ try {
791
+ node_fs_1.default.writeSync(outputFd, `{"manifest":${JSON.stringify(manifest)},"files":[`);
792
+ let first = true;
793
+ const lines = promises_1.default.createInterface({ input: node_fs_1.default.createReadStream(spoolPath, { encoding: "utf8" }), crlfDelay: Infinity });
794
+ for await (const line of lines) {
795
+ if (!line)
796
+ continue;
797
+ const file = JSON.parse(line);
798
+ file.linkedReferences = linksByPath.get(file.path) ?? [];
799
+ file.linkPlan = planForPath(linked.plan, file.path);
800
+ node_fs_1.default.writeSync(outputFd, `${first ? "" : ","}${JSON.stringify(file)}`);
801
+ first = false;
802
+ }
803
+ node_fs_1.default.writeSync(outputFd, "]}");
804
+ }
805
+ finally {
806
+ node_fs_1.default.closeSync(outputFd);
807
+ node_fs_1.default.rmSync(spoolDir, { recursive: true, force: true });
808
+ }
809
+ 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.`);
810
+ return;
811
+ }
812
+ // Consent is asked from LOCAL data only — nothing about this checkout has
813
+ // reached the server yet (the policy fetch above carries no repo/file
814
+ // data, just an org-level excerpt setting). The real upload/already-known
815
+ // split needs the server's held-blob-SHA list, which only exists once a
816
+ // session is created — so that, and everything else server-side, happens
817
+ // only after this consent is granted, never before.
818
+ const evidenceSummary = policy.excerptsEnabled ? `${evidenceCount} short evidence excerpts, each capped at 200 characters` : "no source excerpts (disabled by your organisation)";
819
+ const approved = await permission(options, buildLocalReadSummary(extractedCount, evidenceSummary));
820
+ if (!approved) {
821
+ node_fs_1.default.rmSync(spoolDir, { recursive: true, force: true });
822
+ console.log("Upload cancelled.");
823
+ return;
824
+ }
825
+ manifest.consent.confirmedAt = new Date().toISOString();
826
+ const session = await apiRequest(credentials.apiUrl, token, "/deep-scan/sessions", { method: "POST", body: JSON.stringify(manifest) });
827
+ const held = new Set(session.heldBlobShas ?? []);
828
+ let willUpload = 0, alreadyKnown = 0;
829
+ {
830
+ const countLines = promises_1.default.createInterface({ input: node_fs_1.default.createReadStream(spoolPath, { encoding: "utf8" }), crlfDelay: Infinity });
831
+ for await (const line of countLines) {
832
+ if (!line)
833
+ continue;
834
+ const file = JSON.parse(line);
835
+ if (held.has(file.blobSha))
836
+ alreadyKnown++;
837
+ else
838
+ willUpload++;
839
+ }
840
+ }
841
+ console.log(buildUploadSummary(extractedCount, willUpload, alreadyKnown, evidenceSummary));
842
+ const statePath = node_path_1.default.join(meta.root, STATE_NAME);
843
+ node_fs_1.default.mkdirSync(node_path_1.default.dirname(statePath), { recursive: true });
844
+ let prior = null;
845
+ try {
846
+ prior = JSON.parse(node_fs_1.default.readFileSync(statePath, "utf8"));
847
+ }
848
+ catch { }
849
+ const batchSize = Math.max(1, Math.min(Number(session.limits?.filesPerBatch ?? 200), 200));
850
+ let batch = [];
851
+ let uploaded = 0;
852
+ const lines = promises_1.default.createInterface({ input: node_fs_1.default.createReadStream(spoolPath, { encoding: "utf8" }), crlfDelay: Infinity });
853
+ const flush = async () => { if (!batch.length)
854
+ 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"); };
855
+ for await (const line of lines) {
856
+ if (!line)
857
+ continue;
858
+ const file = JSON.parse(line);
859
+ if (held.has(file.blobSha))
860
+ continue;
861
+ file.linkedReferences = linksByPath.get(file.path) ?? [];
862
+ file.linkPlan = planForPath(linked.plan, file.path);
863
+ batch.push(file);
864
+ if (batch.length >= batchSize)
865
+ await flush();
866
+ }
867
+ await flush();
868
+ node_fs_1.default.rmSync(spoolDir, { recursive: true, force: true });
869
+ const finalized = await apiRequest(credentials.apiUrl, token, `/deep-scan/sessions/${session.sessionId}/finalize`, { method: "POST", body: "{}" });
870
+ node_fs_1.default.writeFileSync(statePath, JSON.stringify({ sessionId: session.sessionId, runId: finalized.runId, commitSha: meta.commitSha, completedAt: new Date().toISOString() }, null, 2), "utf8");
871
+ const run = await pollRun(credentials.apiUrl, token, finalized.runId);
872
+ // Record the real outcome locally — this is what lets the commit hook's
873
+ // otherwise-silent (stdout redirected to /dev/null) held upload surface
874
+ // via `kodingo deep-scan-status` instead of vanishing with no visible
875
+ // error on the engineer's own machine.
876
+ node_fs_1.default.writeFileSync(statePath, JSON.stringify({ sessionId: session.sessionId, runId: finalized.runId, commitSha: meta.commitSha, completedAt: new Date().toISOString(), applied: Boolean(run.applied), reason: run.apply_reason ?? run.reason ?? null }, null, 2), "utf8");
877
+ printFinalOutcome(run, options.yes);
878
+ }