kodingo-cli 1.4.0 → 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.
@@ -37,8 +37,29 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
39
  exports.resolveGitMetadata = resolveGitMetadata;
40
+ exports.resolveDefaultBranch = resolveDefaultBranch;
40
41
  exports.normalizeRemote = normalizeRemote;
42
+ exports.deriveBareRepoName = deriveBareRepoName;
41
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;
42
63
  exports.deepScanStatusCommand = deepScanStatusCommand;
43
64
  exports.deepScanCommand = deepScanCommand;
44
65
  const node_child_process_1 = require("node:child_process");
@@ -52,8 +73,17 @@ const persistence_config_1 = require("../utils/persistence-config");
52
73
  const format_1 = require("kodingo-core/dist/src/entity-extractor/format");
53
74
  const sourcePolicy_1 = require("kodingo-core/dist/src/entity-extractor/sourcePolicy");
54
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
+ }
55
86
  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
87
  const STATE_NAME = node_path_1.default.join(".kortex", "deep-scan-state.json");
58
88
  const FACT_CACHE_DIR = node_path_1.default.join(".kortex", "entity-cache");
59
89
  function planForPath(plan, filePath) {
@@ -125,10 +155,56 @@ function resolveGitMetadata(start) {
125
155
  const shallow = git(root, ["rev-parse", "--is-shallow-repository"]) === "true";
126
156
  return { root, commitSha, branch, detachedHead: branch === null, dirty, remote, repository: normalizeRemote(remote), shallow };
127
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
+ }
128
199
  function normalizeRemote(remote) {
129
200
  const cleaned = remote.replace(/^git@[^:]+:/, "").replace(/^https?:\/\/[^/]+\//, "").replace(/\.git$/, "");
130
201
  return cleaned.replace(/^\/+/, "");
131
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
+ }
132
208
  function globRegex(pattern) {
133
209
  const normalized = pattern.trim().replace(/^\//, "");
134
210
  const escaped = normalized.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "§§").replace(/\*/g, "[^/]*").replace(/§§/g, ".*").replace(/\?/g, ".");
@@ -152,7 +228,7 @@ function listTrackedFiles(root, changedOnly = false) {
152
228
  const relative = match[2].replace(/\\/g, "/");
153
229
  if (changed && !changed.has(relative))
154
230
  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)
231
+ if ((0, sourcePolicy_1.isNeverReadPath)(relative) || !isEligibleForManifest(relative) || ignored.some((pattern) => pattern.test(relative)) || (0, vendoredCodeDetector_1.isVendoredPath)(relative).vendored)
156
232
  continue;
157
233
  const absolute = node_path_1.default.join(root, relative);
158
234
  if (!node_fs_1.default.existsSync(absolute) || !node_fs_1.default.statSync(absolute).isFile())
@@ -161,11 +237,101 @@ function listTrackedFiles(root, changedOnly = false) {
161
237
  }
162
238
  return files.sort((a, b) => a.path.localeCompare(b.path));
163
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
+ }
164
330
  async function apiRequest(apiUrl, token, route, init = {}) {
165
331
  const response = await fetch(`${apiUrl.replace(/\/$/, "")}${route}`, { ...init, headers: { "content-type": "application/json", "X-Kodingo-Token": token, ...(init.headers ?? {}) } });
166
332
  const body = await response.json().catch(() => ({}));
167
333
  if (!response.ok)
168
- throw new Error(body.error ?? `HTTP ${response.status}`);
334
+ throw new Error(describeApiError(body, response.status));
169
335
  return body;
170
336
  }
171
337
  async function permission(options, summary) {
@@ -181,12 +347,335 @@ async function permission(options, summary) {
181
347
  rl.close();
182
348
  }
183
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
+ }
184
650
  async function deepScanStatusCommand(options = {}) {
185
651
  const meta = resolveGitMetadata(node_path_1.default.resolve(options.repo ?? process.cwd()));
186
652
  const credentials = (0, persistence_config_1.getCredentials)(meta.root);
187
653
  if (!credentials.token)
188
654
  throw new Error("No project token found. Run `kodingo init` in this project first.");
189
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 */ }
190
679
  console.log(JSON.stringify({ repository: meta.repository, branch: meta.branch, ...status }, null, 2));
191
680
  }
192
681
  async function deepScanCommand(options = {}) {
@@ -201,6 +690,24 @@ async function deepScanCommand(options = {}) {
201
690
  const token = envToken || credentials.token;
202
691
  if (!token)
203
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
+ }
204
711
  const policy = options.dryRun
205
712
  ? { excerptsEnabled: true }
206
713
  : await apiRequest(credentials.apiUrl, token, "/deep-scan/policy");
@@ -209,7 +716,7 @@ async function deepScanCommand(options = {}) {
209
716
  console.log("No supported tracked files need scanning.");
210
717
  return;
211
718
  }
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 } };
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 } };
213
720
  const spoolDir = node_fs_1.default.mkdtempSync(node_path_1.default.join(node_os_1.default.tmpdir(), "kodingo-deep-scan-"));
214
721
  const spoolPath = node_path_1.default.join(spoolDir, `deep-scan-${meta.commitSha}.jsonl`);
215
722
  node_fs_1.default.writeFileSync(spoolPath, "", { mode: 0o600 });
@@ -302,13 +809,36 @@ async function deepScanCommand(options = {}) {
302
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.`);
303
810
  return;
304
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.
305
818
  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.`);
819
+ const approved = await permission(options, buildLocalReadSummary(extractedCount, evidenceSummary));
307
820
  if (!approved) {
308
821
  node_fs_1.default.rmSync(spoolDir, { recursive: true, force: true });
309
822
  console.log("Upload cancelled.");
310
823
  return;
311
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));
312
842
  const statePath = node_path_1.default.join(meta.root, STATE_NAME);
313
843
  node_fs_1.default.mkdirSync(node_path_1.default.dirname(statePath), { recursive: true });
314
844
  let prior = null;
@@ -316,8 +846,6 @@ async function deepScanCommand(options = {}) {
316
846
  prior = JSON.parse(node_fs_1.default.readFileSync(statePath, "utf8"));
317
847
  }
318
848
  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
849
  const batchSize = Math.max(1, Math.min(Number(session.limits?.filesPerBatch ?? 200), 200));
322
850
  let batch = [];
323
851
  let uploaded = 0;
@@ -340,5 +868,11 @@ async function deepScanCommand(options = {}) {
340
868
  node_fs_1.default.rmSync(spoolDir, { recursive: true, force: true });
341
869
  const finalized = await apiRequest(credentials.apiUrl, token, `/deep-scan/sessions/${session.sessionId}/finalize`, { method: "POST", body: "{}" });
342
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");
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.`);
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);
344
878
  }