kodingo-cli 1.4.0 → 1.4.2

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,32 @@ 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.checkCheckoutFreshness = checkCheckoutFreshness;
51
+ exports.decideFreshnessAction = decideFreshnessAction;
52
+ exports.enforceCheckoutFreshness = enforceCheckoutFreshness;
53
+ exports.settleTrackedBranch = settleTrackedBranch;
54
+ exports.pollRun = pollRun;
55
+ exports.printFinalOutcome = printFinalOutcome;
56
+ exports.settleAndReconcile = settleAndReconcile;
57
+ exports.isFixedByTrackedBranchRecording = isFixedByTrackedBranchRecording;
58
+ exports.isHeldScanFixable = isHeldScanFixable;
59
+ exports.describeHeldScanDebugInfo = describeHeldScanDebugInfo;
60
+ exports.reconcileStaleHeldScan = reconcileStaleHeldScan;
61
+ exports.describeCoverageCompleteOutcome = describeCoverageCompleteOutcome;
62
+ exports.settleAlreadyCompleteProject = settleAlreadyCompleteProject;
63
+ exports.renderScanStatus = renderScanStatus;
64
+ exports.describeLastUploadStatus = describeLastUploadStatus;
65
+ exports.describeTrackedBranchNotRecorded = describeTrackedBranchNotRecorded;
42
66
  exports.deepScanStatusCommand = deepScanStatusCommand;
43
67
  exports.deepScanCommand = deepScanCommand;
44
68
  const node_child_process_1 = require("node:child_process");
@@ -52,8 +76,17 @@ const persistence_config_1 = require("../utils/persistence-config");
52
76
  const format_1 = require("kodingo-core/dist/src/entity-extractor/format");
53
77
  const sourcePolicy_1 = require("kodingo-core/dist/src/entity-extractor/sourcePolicy");
54
78
  const vendoredCodeDetector_1 = require("../utils/vendoredCodeDetector");
79
+ // Structural-language files that core's declarative extractFile pipeline
80
+ // doesn't own (they feed a separate, server-side structural pass) but that
81
+ // the CLI has always tracked. Kept as a residual, additive allow-list on top
82
+ // of kodingo-core's own supportsExtraction() so fixing the declarative-file
83
+ // gap (JSON/YAML/SQL/GraphQL/Dockerfile/etc, missing from here before) never
84
+ // drops coverage for these.
85
+ const RESIDUAL_SUPPORTED = new Set([".py", ".rb", ".java", ".go", ".rs"]);
86
+ function isEligibleForManifest(relative) {
87
+ return (0, sourcePolicy_1.supportsExtraction)(relative) || RESIDUAL_SUPPORTED.has(node_path_1.default.extname(relative).toLowerCase());
88
+ }
55
89
  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
90
  const STATE_NAME = node_path_1.default.join(".kortex", "deep-scan-state.json");
58
91
  const FACT_CACHE_DIR = node_path_1.default.join(".kortex", "entity-cache");
59
92
  function planForPath(plan, filePath) {
@@ -125,10 +158,56 @@ function resolveGitMetadata(start) {
125
158
  const shallow = git(root, ["rev-parse", "--is-shallow-repository"]) === "true";
126
159
  return { root, commitSha, branch, detachedHead: branch === null, dirty, remote, repository: normalizeRemote(remote), shallow };
127
160
  }
161
+ /** The remote's default branch. Tries the fast, local, offline read first
162
+ * (refs/remotes/origin/HEAD — only set once something has told the local
163
+ * clone what the remote's HEAD is, e.g. `git clone` or `git remote set-head`;
164
+ * not guaranteed, especially on a shallow or partial clone), then falls back
165
+ * to asking the remote directly via `git remote show origin` (which does
166
+ * contact the remote). Returns null rather than guessing when neither
167
+ * determines it. */
168
+ async function resolveDefaultBranch(root) {
169
+ try {
170
+ const ref = git(root, ["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"]);
171
+ const name = ref.split("/").pop();
172
+ if (name)
173
+ return name;
174
+ }
175
+ catch { /* fall through to the remote-show fallback */ }
176
+ try {
177
+ const output = git(root, ["remote", "show", "origin"]);
178
+ const match = output.match(/HEAD branch:\s*(\S+)/);
179
+ if (match?.[1] && match[1] !== "(unknown)")
180
+ return match[1];
181
+ }
182
+ catch { /* no origin remote, or the remote couldn't be reached */ }
183
+ return null;
184
+ }
185
+ function gitUserAttribution(root) {
186
+ const name = (() => { try {
187
+ return git(root, ["config", "user.name"]);
188
+ }
189
+ catch {
190
+ return "";
191
+ } })();
192
+ const email = (() => { try {
193
+ return git(root, ["config", "user.email"]);
194
+ }
195
+ catch {
196
+ return "";
197
+ } })();
198
+ if (name && email)
199
+ return `${name} <${email}>`;
200
+ return email || name || "A CLI user";
201
+ }
128
202
  function normalizeRemote(remote) {
129
203
  const cleaned = remote.replace(/^git@[^:]+:/, "").replace(/^https?:\/\/[^/]+\//, "").replace(/\.git$/, "");
130
204
  return cleaned.replace(/^\/+/, "");
131
205
  }
206
+ /** The bare repo name (no owner), derived from the already-normalized owner/name form. */
207
+ function deriveBareRepoName(normalizedRepository) {
208
+ const segments = normalizedRepository.split("/").filter(Boolean);
209
+ return segments[segments.length - 1] ?? normalizedRepository;
210
+ }
132
211
  function globRegex(pattern) {
133
212
  const normalized = pattern.trim().replace(/^\//, "");
134
213
  const escaped = normalized.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "§§").replace(/\*/g, "[^/]*").replace(/§§/g, ".*").replace(/\?/g, ".");
@@ -152,7 +231,7 @@ function listTrackedFiles(root, changedOnly = false) {
152
231
  const relative = match[2].replace(/\\/g, "/");
153
232
  if (changed && !changed.has(relative))
154
233
  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)
234
+ if ((0, sourcePolicy_1.isNeverReadPath)(relative) || !isEligibleForManifest(relative) || ignored.some((pattern) => pattern.test(relative)) || (0, vendoredCodeDetector_1.isVendoredPath)(relative).vendored)
156
235
  continue;
157
236
  const absolute = node_path_1.default.join(root, relative);
158
237
  if (!node_fs_1.default.existsSync(absolute) || !node_fs_1.default.statSync(absolute).isFile())
@@ -161,11 +240,117 @@ function listTrackedFiles(root, changedOnly = false) {
161
240
  }
162
241
  return files.sort((a, b) => a.path.localeCompare(b.path));
163
242
  }
243
+ function describeApiError(body, status) {
244
+ const message = body.error ?? `HTTP ${status}`;
245
+ const details = [];
246
+ if (body.sentLabel)
247
+ details.push(`sent: "${body.sentLabel}"`);
248
+ if (body.sentBareName)
249
+ details.push(`bare name: "${body.sentBareName}"`);
250
+ if (Array.isArray(body.registeredRepos))
251
+ details.push(`registered: ${body.registeredRepos.map((r) => `"${r}"`).join(", ") || "none"}`);
252
+ if (Array.isArray(body.matchingRegisteredRepos))
253
+ details.push(`matches: ${body.matchingRegisteredRepos.map((r) => `"${r}"`).join(", ")}`);
254
+ return details.length ? `${message} (${details.join("; ")})` : message;
255
+ }
256
+ /** Maps every apply_reason code the server can produce for a held (or
257
+ * applied) scan to a plain-English sentence and the exact next step. */
258
+ function describeApplyReason(reason) {
259
+ if (!reason)
260
+ return { sentence: "The scan was held for an unknown reason.", nextStep: "Run `kodingo deep-scan-status` for more detail." };
261
+ if (reason === "clean_tracked_branch")
262
+ return { sentence: "Applied.", nextStep: "" };
263
+ if (reason === "dirty_checkout")
264
+ return { sentence: "Your working tree has uncommitted changes.", nextStep: "Commit or stash your changes, then run `kodingo init` (or `kodingo deep-scan`) again." };
265
+ if (reason === "detached_head")
266
+ return { sentence: "This checkout is in detached HEAD state.", nextStep: "Check out a branch, then scan again." };
267
+ if (reason === "branch_unknown")
268
+ return { sentence: "The CLI could not determine the current branch.", nextStep: "Check out a named branch, then scan again." };
269
+ if (reason === "stale_full_tree")
270
+ 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." };
271
+ if (reason === "unknown_commit")
272
+ return { sentence: "This scan's commit isn't on GitHub.", nextStep: "Push it and run `kodingo init --force`." };
273
+ const mismatch = /^branch_mismatch:([^:]*):(.*)$/.exec(reason);
274
+ if (mismatch) {
275
+ const [, scanned, tracked] = mismatch;
276
+ if (tracked === "unregistered")
277
+ 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." };
278
+ 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.` };
279
+ }
280
+ const staleCommit = /^stale_commit:(\d+)$/.exec(reason);
281
+ if (staleCommit) {
282
+ const behind = staleCommit[1];
283
+ return { sentence: `This scan is ${behind} commit${behind === "1" ? "" : "s"} behind GitHub.`, nextStep: "Pull and run `kodingo init --force`." };
284
+ }
285
+ const deleteCapExceeded = /^delete_cap_exceeded:(\d+):([\d.]+)$/.exec(reason);
286
+ if (deleteCapExceeded) {
287
+ const entities = deleteCapExceeded[1];
288
+ const sharePct = Math.round(Number(deleteCapExceeded[2]) * 100);
289
+ return {
290
+ sentence: `This full-tree scan would have deleted ${entities} entities (${sharePct}% of what's stored), so it was held as a safety precaution.`,
291
+ nextStep: "An org admin must approve it; re-scanning won't resolve it.",
292
+ };
293
+ }
294
+ return { sentence: `The scan was held (${reason}).`, nextStep: "Run `kodingo deep-scan-status` for more detail." };
295
+ }
296
+ /** Pure so the "accurate" wording regression (165 read vs N uploaded vs M
297
+ * already known) can be unit-tested without a network call. */
298
+ function buildUploadSummary(readLocally, willUpload, alreadyKnown, evidenceSummary) {
299
+ 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.`;
300
+ }
301
+ /** The pre-consent summary — built from local data only. No upload session
302
+ * exists yet (that's what sends the file manifest — every path, size, and
303
+ * blob SHA — to the server), so there's no real upload/already-known split
304
+ * to report yet; that requires the server's held-blob-SHA list, which only
305
+ * exists once a session is created, and a session is only ever created
306
+ * after this consent is granted. */
307
+ function buildLocalReadSummary(readLocally, evidenceSummary) {
308
+ 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.`;
309
+ }
310
+ function decideBranchSettlement(params) {
311
+ const { outcome, trackedBranch, branch, repository, yes, promptAnswerYes, defaultBranch } = params;
312
+ const scanPending = params.scanPending !== false;
313
+ if (outcome === "match")
314
+ return { action: "proceed" };
315
+ if (outcome === "mismatch") {
316
+ return {
317
+ action: "proceed-held",
318
+ message: scanPending
319
+ ? `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.`
320
+ : `This project tracks "${trackedBranch}"; commits on "${branch}" will not update Kortex. Switch branches or ask an org admin to change the tracked branch.`,
321
+ };
322
+ }
323
+ // outcome === "none"
324
+ if (yes) {
325
+ if (defaultBranch && defaultBranch === branch)
326
+ return { action: "record" };
327
+ return {
328
+ action: "refuse",
329
+ message: defaultBranch
330
+ ? `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}".`
331
+ : `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).`,
332
+ };
333
+ }
334
+ if (promptAnswerYes)
335
+ return { action: "record" };
336
+ return {
337
+ action: "proceed-held",
338
+ message: scanPending
339
+ ? `No tracked branch is recorded for ${repository}. This scan will be held. Run \`kodingo init\` again and accept tracking "${branch}" to apply it.`
340
+ : `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.`,
341
+ };
342
+ }
343
+ /** The commit hook must never upload for a commit it can positively confirm
344
+ * is NOT on the tracked branch. "none" (nothing tracked yet) and "match"
345
+ * both proceed — only a confirmed "mismatch" skips. */
346
+ function shouldSkipIncrementalScan(outcome) {
347
+ return outcome === "mismatch";
348
+ }
164
349
  async function apiRequest(apiUrl, token, route, init = {}) {
165
350
  const response = await fetch(`${apiUrl.replace(/\/$/, "")}${route}`, { ...init, headers: { "content-type": "application/json", "X-Kodingo-Token": token, ...(init.headers ?? {}) } });
166
351
  const body = await response.json().catch(() => ({}));
167
352
  if (!response.ok)
168
- throw new Error(body.error ?? `HTTP ${response.status}`);
353
+ throw new Error(describeApiError(body, response.status));
169
354
  return body;
170
355
  }
171
356
  async function permission(options, summary) {
@@ -181,12 +366,427 @@ async function permission(options, summary) {
181
366
  rl.close();
182
367
  }
183
368
  }
369
+ async function askYesNo(question) {
370
+ if (!process.stdin.isTTY)
371
+ return false;
372
+ const rl = promises_1.default.createInterface({ input: node_process_1.stdin, output: node_process_1.stdout });
373
+ try {
374
+ const answer = (await rl.question(question)).trim();
375
+ return answer === "" || /^y(?:es)?$/i.test(answer);
376
+ }
377
+ finally {
378
+ rl.close();
379
+ }
380
+ }
381
+ /** Same shape as askYesNo, but defaults to "no" on an empty answer — used
382
+ * where silently guessing "yes" would risk reading a checkout Kortex can't
383
+ * actually verify is current. */
384
+ async function askYesNoDefaultNo(question) {
385
+ if (!process.stdin.isTTY)
386
+ return false;
387
+ const rl = promises_1.default.createInterface({ input: node_process_1.stdin, output: node_process_1.stdout });
388
+ try {
389
+ const answer = (await rl.question(question)).trim();
390
+ return /^y(?:es)?$/i.test(answer);
391
+ }
392
+ finally {
393
+ rl.close();
394
+ }
395
+ }
396
+ function describeFreshnessFetchFailure(err) {
397
+ if (err && (err.killed || err.signal))
398
+ return "git fetch timed out after 15s";
399
+ const raw = (err?.stderr ? err.stderr.toString() : "") || (err?.message ? String(err.message) : "");
400
+ const firstLine = raw.split(/\r?\n/).map((line) => line.trim()).find((line) => line.length > 0);
401
+ return firstLine || "git fetch failed";
402
+ }
403
+ /** Fetches origin/<branch> fresh (quiet, no tags, bounded to 15s so a dead
404
+ * remote never hangs a scan) and compares HEAD against it. Never guesses —
405
+ * any failure (no origin, offline, auth, an unparseable result) comes back
406
+ * as "unknown" with the reason, for the caller to decide how to handle. */
407
+ function checkCheckoutFreshness(root, branch) {
408
+ try {
409
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "fetch", "--quiet", "--no-tags", "origin", branch], { timeout: 15000, stdio: ["ignore", "pipe", "pipe"] });
410
+ }
411
+ catch (err) {
412
+ return { outcome: "unknown", reason: describeFreshnessFetchFailure(err) };
413
+ }
414
+ let counts;
415
+ try {
416
+ counts = git(root, ["rev-list", "--left-right", "--count", `HEAD...origin/${branch}`]);
417
+ }
418
+ catch (err) {
419
+ return { outcome: "unknown", reason: describeFreshnessFetchFailure(err) };
420
+ }
421
+ const match = counts.match(/^(\d+)\s+(\d+)$/);
422
+ if (!match)
423
+ return { outcome: "unknown", reason: `unexpected git output comparing against origin/${branch}` };
424
+ const ahead = Number(match[1]);
425
+ const behind = Number(match[2]);
426
+ if (ahead === 0 && behind === 0)
427
+ return { outcome: "up-to-date", shortSha: git(root, ["rev-parse", "--short", "HEAD"]) };
428
+ if (ahead === 0)
429
+ return { outcome: "behind", behind };
430
+ if (behind === 0)
431
+ return { outcome: "ahead", ahead };
432
+ return { outcome: "diverged", ahead, behind };
433
+ }
434
+ /** The pure "what to do about a stale checkout" decision — separated from
435
+ * the fetch/compare and the interactive prompt so every rule (refuse full
436
+ * scans of outdated code, warn-only for --dry-run since it uploads nothing,
437
+ * never guess on an undetermined result) is directly unit-testable. */
438
+ function decideFreshnessAction(params) {
439
+ const { check, branch, dryRun, yes, promptAnswerYes } = params;
440
+ if (check.outcome === "up-to-date") {
441
+ return { action: "proceed", note: `Reading ${branch} at ${check.shortSha}, up to date with origin/${branch}.` };
442
+ }
443
+ if (check.outcome === "unknown") {
444
+ const base = `Couldn't check whether this checkout is up to date (${check.reason}).`;
445
+ if (dryRun)
446
+ return { action: "warn", message: base };
447
+ if (yes)
448
+ return { action: "refuse", message: `${base} Refusing to guess under --yes.` };
449
+ if (promptAnswerYes)
450
+ return { action: "proceed" };
451
+ return { action: "refuse", message: base };
452
+ }
453
+ const message = check.outcome === "behind"
454
+ ? `Your checkout of ${branch} is ${check.behind} commit${check.behind === 1 ? "" : "s"} behind origin/${branch}, so Kortex would read outdated code. Run \`git pull\` and try again.`
455
+ : check.outcome === "ahead"
456
+ ? `Your checkout of ${branch} has ${check.ahead} commit${check.ahead === 1 ? "" : "s"} that ${check.ahead === 1 ? "is" : "are"} not pushed. Push first so Kortex reads the same code GitHub has.`
457
+ : `Your checkout of ${branch} has diverged from origin/${branch}: ${check.ahead} commit${check.ahead === 1 ? "" : "s"} not pushed and ${check.behind} commit${check.behind === 1 ? "" : "s"} behind. Reconcile the branches, then try again.`;
458
+ return dryRun ? { action: "warn", message } : { action: "refuse", message };
459
+ }
460
+ /** Full-tree scans only (init's first scan, and `kodingo deep-scan` without
461
+ * --changed) — never the commit hook, which always invokes --changed on
462
+ * normal, possibly-unpushed local commits. Runs a real `git fetch` against
463
+ * origin before anything is read, so a checkout behind origin never gets a
464
+ * chance to replace newer stored data with older code. */
465
+ async function enforceCheckoutFreshness(opts) {
466
+ const check = checkCheckoutFreshness(opts.root, opts.branch);
467
+ let promptAnswerYes;
468
+ if (check.outcome === "unknown" && !opts.dryRun && !opts.yes) {
469
+ promptAnswerYes = await askYesNoDefaultNo(`Couldn't check whether this checkout is up to date (${check.reason}). Continue anyway? [y/N] `);
470
+ }
471
+ return decideFreshnessAction({ check, branch: opts.branch, dryRun: opts.dryRun, yes: opts.yes, promptAnswerYes });
472
+ }
473
+ /** Settles the project's tracked development branch against the current
474
+ * checkout via POST /deep-scan/branch/settle, before anything is uploaded —
475
+ * so a first scan can apply instead of landing held with no explanation. */
476
+ async function settleTrackedBranch(opts) {
477
+ 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 }) });
478
+ let promptAnswerYes;
479
+ if (check.outcome === "none" && !opts.yes) {
480
+ promptAnswerYes = await askYesNo(`No tracked branch is recorded for ${opts.repository}. Track "${opts.branch}"? [Y/n] `);
481
+ }
482
+ const defaultBranch = check.outcome === "none" && opts.yes ? await resolveDefaultBranch(opts.root) : null;
483
+ const decision = decideBranchSettlement({ outcome: check.outcome, trackedBranch: check.trackedBranch, branch: opts.branch, repository: opts.repository, yes: opts.yes, promptAnswerYes, defaultBranch, scanPending: opts.scanPending });
484
+ if (decision.action === "refuse")
485
+ throw new Error(decision.message);
486
+ if (decision.action === "proceed-held") {
487
+ console.log(decision.message);
488
+ return { recorded: false, held: true, trackedBranch: check.trackedBranch };
489
+ }
490
+ if (decision.action === "record") {
491
+ const attributedBy = gitUserAttribution(opts.root);
492
+ 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 }) });
493
+ console.log(`✔ Tracked branch for ${opts.repository} set to "${opts.branch}".`);
494
+ return { recorded: true, held: false, trackedBranch: opts.branch };
495
+ }
496
+ return { recorded: false, held: false, trackedBranch: check.trackedBranch }; // match — proceed silently
497
+ }
498
+ async function pollRun(apiUrl, token, runId, timeoutMs = 60000) {
499
+ const start = Date.now();
500
+ let delay = 500;
501
+ for (;;) {
502
+ const run = await apiRequest(apiUrl, token, `/deep-scan/runs/${runId}`);
503
+ if (run.state === "held" || run.state === "completed" || run.state === "failed")
504
+ return run;
505
+ if (Date.now() - start > timeoutMs)
506
+ return run;
507
+ await new Promise((resolve) => setTimeout(resolve, delay));
508
+ delay = Math.min(delay * 2, 5000);
509
+ }
510
+ }
511
+ /** Prints the one real outcome of a scan — never "accepted" when held. */
512
+ function printFinalOutcome(run, yes) {
513
+ if (run.applied) {
514
+ 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.`);
515
+ return;
516
+ }
517
+ const { sentence, nextStep } = describeApplyReason(run.apply_reason ?? run.reason ?? null);
518
+ console.log(`Deep scan held: ${sentence}${nextStep ? ` ${nextStep}` : ""}`);
519
+ if (yes)
520
+ process.exitCode = 1;
521
+ }
522
+ /** Runs tracked-branch settlement and, if a branch was just recorded and a
523
+ * held scan already exists for this exact commit, re-evaluates it without a
524
+ * new upload. Returns handled:true when that reconciliation fully covers
525
+ * this commit, so the caller can skip the normal upload flow. */
526
+ async function settleAndReconcile(opts) {
527
+ const meta = resolveGitMetadata(opts.root);
528
+ if (meta.detachedHead || !meta.branch)
529
+ return { handled: false };
530
+ const settlement = await settleTrackedBranch({
531
+ apiUrl: opts.apiUrl, token: opts.token, root: opts.root,
532
+ repository: meta.repository, repositoryName: deriveBareRepoName(meta.repository),
533
+ branch: meta.branch, yes: opts.yes,
534
+ });
535
+ if (!settlement.recorded)
536
+ return { handled: false };
537
+ const status = await apiRequest(opts.apiUrl, opts.token, "/deep-scan/status");
538
+ const lastScan = status.lastScan;
539
+ if (!lastScan || lastScan.commitSha !== meta.commitSha || lastScan.applied)
540
+ return { handled: false };
541
+ const result = await apiRequest(opts.apiUrl, opts.token, `/deep-scan/scans/${lastScan.id}/reapply`, { method: "POST", body: "{}" });
542
+ printFinalOutcome({ applied: result.applied, apply_reason: result.reason, entity_count: result.entityCount, edge_count: result.edgeCount, file_count: result.fileCount }, opts.yes);
543
+ return { handled: true };
544
+ }
545
+ /** A held scan's reason is one a CURRENT tracked branch could plausibly
546
+ * have fixed — "branch_unknown" (the server couldn't tell what branch a
547
+ * session was even on) or a mismatch against an explicitly "unregistered"
548
+ * tracked branch (there was none recorded at the time it was uploaded).
549
+ * Any other hold reason (dirty_checkout, detached_head, or a mismatch
550
+ * against a real, different tracked branch) is NOT fixed by this —
551
+ * reapplying it would just report the exact same hold again.
552
+ *
553
+ * This is a STATIC fallback only — it reads the reason string embedded at
554
+ * upload time, so it can't tell that e.g. "branch_mismatch:main:develop"
555
+ * (tracked was "develop" back then) has since become fixable because the
556
+ * tracked branch is now "main". Prefer isHeldScanFixable, which uses the
557
+ * server's own fresh re-evaluation when available. */
558
+ function isFixedByTrackedBranchRecording(reason) {
559
+ if (!reason)
560
+ return false;
561
+ if (reason === "branch_unknown")
562
+ return true;
563
+ return /^branch_mismatch:[^:]*:unregistered$/.test(reason);
564
+ }
565
+ /** Whether a held CLI scan would actually apply if re-applied right now —
566
+ * authoritative when the server reports it (fixableByTrackedBranch, added
567
+ * additively to lastCliScan: the server re-derives this from the scan's
568
+ * own stored session flags against whatever the tracked branch IS right
569
+ * now, not from parsing a reason string), falling back to the static
570
+ * reason-string check for an older server that doesn't send it yet. */
571
+ function isHeldScanFixable(lastCliScan) {
572
+ if (typeof lastCliScan.fixableByTrackedBranch === "boolean")
573
+ return lastCliScan.fixableByTrackedBranch;
574
+ return isFixedByTrackedBranchRecording(lastCliScan.reason ?? null);
575
+ }
576
+ /** Pure so --verbose/KODINGO_DEBUG's "print the inputs behind the
577
+ * decision" requirement is directly unit-testable. */
578
+ function describeHeldScanDebugInfo(params) {
579
+ const scanInfo = params.lastCliScan
580
+ ? `held scan id=${params.lastCliScan.id} commit=${params.lastCliScan.commitSha.slice(0, 12)} reason=${params.lastCliScan.reason ?? "none"}`
581
+ : "no held CLI scan";
582
+ const fixabilitySource = params.lastCliScan && typeof params.lastCliScan.fixableByTrackedBranch === "boolean" ? "server" : "reason-string fallback";
583
+ const fixableText = params.fixable === null ? "n/a" : `${params.fixable} (${fixabilitySource})`;
584
+ return `[debug] tracked branch=${params.trackedBranch ?? "none"}; ${scanInfo}; fixable=${fixableText}`;
585
+ }
586
+ /** Re-applies the project's most recent HELD **CLI** scan — from
587
+ * lastCliScan, never lastScan (the project's overall most recent scan of
588
+ * ANY source — a project with GitHub coverage can have an hourly
589
+ * github_light_backup row, source:'github', applied:true, as its most
590
+ * recent scan while a real held CLI scan sits untouched in lastCliScan;
591
+ * reading lastScan here silently skips reconciling it entirely, which is
592
+ * exactly the bug this fixes) — AT ANY COMMIT, not just the current
593
+ * checkout's, and regardless of whether a tracked branch was JUST recorded
594
+ * THIS run, recorded in an earlier run, or set by someone else entirely —
595
+ * if its hold reason is one the CURRENT tracked branch fixes (see
596
+ * isHeldScanFixable). Unlike settleAndReconcile's exact-commit reapply
597
+ * (used when a fresh scan is about to run regardless, so reconciling an
598
+ * older held scan would be moot), this is for the "coverage is already
599
+ * complete, no new scan is happening" path — reconciling whatever's held
600
+ * is the ONLY way it ever gets applied there.
601
+ *
602
+ * Reports every outcome in plain words, with no silent path: applied
603
+ * (with counts, via the existing printFinalOutcome), nothing held, a held
604
+ * scan that isn't fixed by the tracked branch (its reason and next step),
605
+ * the held scan's session having expired (a distinct, actionable message),
606
+ * any other still-held reason (via describeApplyReason, which also covers
607
+ * the server's stale-full-tree refusal), or a server/network error. Never
608
+ * throws — a failure here must not abort the whole "coverage already
609
+ * complete" flow, which has already told the user their project is read
610
+ * and recorded their tracked branch. */
611
+ async function reconcileStaleHeldScan(opts) {
612
+ let status;
613
+ try {
614
+ status = await apiRequest(opts.apiUrl, opts.token, "/deep-scan/status");
615
+ }
616
+ catch (err) {
617
+ console.log(`Could not check for a held scan to re-apply: ${err.message}`);
618
+ if (opts.yes)
619
+ process.exitCode = 1;
620
+ return { outcome: "error", message: err.message };
621
+ }
622
+ const lastCliScan = status.lastCliScan;
623
+ const isHeld = Boolean(lastCliScan) && !lastCliScan.applied;
624
+ const fixable = isHeld ? isHeldScanFixable(lastCliScan) : null;
625
+ if (opts.verbose)
626
+ console.log(describeHeldScanDebugInfo({ trackedBranch: opts.trackedBranch ?? null, lastCliScan: isHeld ? lastCliScan : null, fixable }));
627
+ if (!isHeld) {
628
+ console.log("No CLI scan is currently held.");
629
+ return { outcome: "none-to-reconcile" };
630
+ }
631
+ if (!fixable) {
632
+ const { sentence, nextStep } = describeApplyReason(lastCliScan.reason);
633
+ console.log(`A held scan exists, but the tracked branch doesn't fix it: ${sentence}${nextStep ? ` ${nextStep}` : ""}`);
634
+ return { outcome: "none-to-reconcile" };
635
+ }
636
+ try {
637
+ const result = await apiRequest(opts.apiUrl, opts.token, `/deep-scan/scans/${lastCliScan.id}/reapply`, { method: "POST", body: "{}" });
638
+ if (result.applied) {
639
+ printFinalOutcome({ applied: true, entity_count: result.entityCount, edge_count: result.edgeCount, file_count: result.fileCount }, opts.yes);
640
+ return { outcome: "applied" };
641
+ }
642
+ if (result.sessionExpired) {
643
+ console.log("The held scan can no longer be applied (its upload session expired). Run `kodingo init --force` to scan again.");
644
+ if (opts.yes)
645
+ process.exitCode = 1;
646
+ return { outcome: "still-held", reason: "session_expired" };
647
+ }
648
+ printFinalOutcome({ applied: false, apply_reason: result.reason }, opts.yes);
649
+ return { outcome: "still-held", reason: result.reason ?? null };
650
+ }
651
+ catch (err) {
652
+ console.log(`Could not re-apply the held scan: ${err.message}`);
653
+ if (opts.yes)
654
+ process.exitCode = 1;
655
+ return { outcome: "error", message: err.message };
656
+ }
657
+ }
658
+ /** Pure so "the closing message is only the confident one when the branch
659
+ * matches" is directly unit-testable. */
660
+ function describeCoverageCompleteOutcome(held) {
661
+ return held
662
+ ? "Kortex already has a complete read of this project."
663
+ : "Kortex already has a complete read of this project. Your commits will keep it up to date.";
664
+ }
665
+ /** The "coverage is already complete, skip the local scan" path still needs
666
+ * the tracked branch settled — skipping the scan must never also silently
667
+ * skip recording a tracked branch, or a project with complete coverage but
668
+ * no tracked branch would hold every future commit (including the hook's)
669
+ * forever with no visible error. Uses the exact same settleTrackedBranch
670
+ * rules as the first-scan flow (record only when none exists and, under
671
+ * --yes, only on the remote's default branch; never overwrite an existing
672
+ * one), just with scanPending:false so the wording reflects that no scan
673
+ * is actually about to run. Reconciliation runs whenever a tracked branch
674
+ * CURRENTLY exists — recorded just now, recorded in an earlier run, or set
675
+ * by someone else entirely; never gated on whether THIS call is what
676
+ * recorded it (that was the bug: an already-recorded tracked branch, e.g.
677
+ * from a prior `kodingo init`, left a held scan sitting unreconciled
678
+ * forever, since recording never happened on any later run either). If a
679
+ * held scan is fixed by it (see isHeldScanFixable), it's reapplied — and
680
+ * the confident closing line only ever prints once the held-scan state has
681
+ * been reported, one way or another: nothing held, applied, or a clear
682
+ * reason it still isn't (not fixable, expired, stale, or any other), never
683
+ * silently skipped. */
684
+ async function settleAlreadyCompleteProject(opts) {
685
+ if (opts.detachedHead || !opts.branch) {
686
+ console.log(describeCoverageCompleteOutcome(true));
687
+ 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.");
688
+ console.log("Held scan state was not checked (no named branch to settle against).");
689
+ return;
690
+ }
691
+ const settlement = await settleTrackedBranch({
692
+ apiUrl: opts.apiUrl, token: opts.token, root: opts.root,
693
+ repository: opts.repository, repositoryName: opts.repositoryName,
694
+ branch: opts.branch, yes: opts.yes, scanPending: false,
695
+ });
696
+ let reconciliation = { outcome: "none-to-reconcile" };
697
+ if (settlement.trackedBranch !== null) {
698
+ reconciliation = await reconcileStaleHeldScan({ apiUrl: opts.apiUrl, token: opts.token, yes: opts.yes, trackedBranch: settlement.trackedBranch, verbose: opts.verbose });
699
+ }
700
+ else {
701
+ console.log("No tracked branch exists yet, so no held scan was checked.");
702
+ }
703
+ const stillUnresolved = reconciliation.outcome === "still-held" || reconciliation.outcome === "error";
704
+ console.log(describeCoverageCompleteOutcome(settlement.held || stillUnresolved));
705
+ }
706
+ /** Pure so the wording — and the "never call a GitHub backup record a CLI
707
+ * scan" fix — is directly unit-testable without a network call. A project
708
+ * can have both a local-scan history and a GitHub-read history at once
709
+ * (or either alone, or neither); each is reported from its own
710
+ * source-scoped field, never from whichever scan merely happened most
711
+ * recently. */
712
+ function renderScanStatus(status) {
713
+ const lines = [];
714
+ const coveragePct = `${Math.round((status.coverage ?? 0) * 100)}%`;
715
+ const sourceDescriptor = status.source === "github" ? "read through GitHub" : status.source === "cli" ? "local scan" : "no scan yet";
716
+ lines.push(`Coverage: ${coveragePct} (${sourceDescriptor})`);
717
+ const cli = status.lastCliScan;
718
+ if (cli) {
719
+ const when = cli.completedAt ?? "unknown time";
720
+ if (cli.applied) {
721
+ lines.push(`Last local scan: commit ${String(cli.commitSha).slice(0, 12)} at ${when} — applied (${cli.entityCount} entities, ${cli.edgeCount} edges, ${cli.fileCount} files).`);
722
+ }
723
+ else {
724
+ const { sentence, nextStep } = describeApplyReason(cli.reason);
725
+ lines.push(`Last local scan: commit ${String(cli.commitSha).slice(0, 12)} at ${when} — held. ${sentence}${nextStep ? ` ${nextStep}` : ""}`);
726
+ }
727
+ }
728
+ else {
729
+ lines.push("No local scan yet.");
730
+ }
731
+ const github = status.lastGithubScan;
732
+ if (github) {
733
+ const when = github.completedAt ?? "unknown time";
734
+ lines.push(`Last GitHub read: commit ${String(github.commitSha).slice(0, 12)} at ${when}.`);
735
+ }
736
+ return lines;
737
+ }
738
+ /** Pure so "the hook's held-reason file feeds the status" is directly
739
+ * unit-testable without touching the filesystem or network. `state` is
740
+ * whatever's currently in .kortex/deep-scan-state.json — `applied` is only
741
+ * ever present once a run has actually been polled to completion (see
742
+ * deepScanCommand), so its absence (still mid-upload, or the process never
743
+ * got that far) is deliberately treated the same as "nothing to report",
744
+ * not as "held". */
745
+ function describeLastUploadStatus(state) {
746
+ if (!state || state.applied !== false)
747
+ return null;
748
+ const { sentence } = describeApplyReason(state.reason);
749
+ return `Your last commit upload was held: ${sentence}`;
750
+ }
751
+ /** Pure so "say so on its own line and give the one command to fix it" is
752
+ * directly unit-testable. Only "none" needs its own line here — "match" has
753
+ * nothing to add, and "mismatch" is already covered by the held-scan
754
+ * reason surfaced elsewhere in status (describeApplyReason's own
755
+ * branch_mismatch wording). */
756
+ function describeTrackedBranchNotRecorded(outcome, repository) {
757
+ if (outcome !== "none")
758
+ return null;
759
+ return `No tracked branch is recorded for ${repository}. Run \`kodingo init\` to record one.`;
760
+ }
184
761
  async function deepScanStatusCommand(options = {}) {
185
762
  const meta = resolveGitMetadata(node_path_1.default.resolve(options.repo ?? process.cwd()));
186
763
  const credentials = (0, persistence_config_1.getCredentials)(meta.root);
187
764
  if (!credentials.token)
188
765
  throw new Error("No project token found. Run `kodingo init` in this project first.");
189
766
  const status = await apiRequest(credentials.apiUrl, credentials.token, "/deep-scan/status");
767
+ for (const line of renderScanStatus(status))
768
+ console.log(line);
769
+ // Whether a tracked branch is recorded at all isn't in /deep-scan/status —
770
+ // reuse the same read-only (record:false) branch/settle check the first-
771
+ // scan and complete-project paths already make, rather than guessing from
772
+ // scan history alone (a project can be fully read via GitHub with no CLI
773
+ // scan history at all, and still have no tracked branch recorded).
774
+ if (meta.branch && !meta.detachedHead) {
775
+ try {
776
+ 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 }) });
777
+ const line = describeTrackedBranchNotRecorded(check.outcome, meta.repository);
778
+ if (line)
779
+ console.log(line);
780
+ }
781
+ catch { /* status must never fail just because this extra check couldn't run */ }
782
+ }
783
+ try {
784
+ const state = JSON.parse(node_fs_1.default.readFileSync(node_path_1.default.join(meta.root, STATE_NAME), "utf8"));
785
+ const line = describeLastUploadStatus(state);
786
+ if (line)
787
+ console.log(line);
788
+ }
789
+ catch { /* no local state file yet — nothing to report */ }
190
790
  console.log(JSON.stringify({ repository: meta.repository, branch: meta.branch, ...status }, null, 2));
191
791
  }
192
792
  async function deepScanCommand(options = {}) {
@@ -201,6 +801,39 @@ async function deepScanCommand(options = {}) {
201
801
  const token = envToken || credentials.token;
202
802
  if (!token)
203
803
  throw new Error("No project token found. Run `kodingo init` once, or set KODINGO_TOKEN for CI.");
804
+ // Kortex must never read, scan, or upload a checkout whose HEAD is stale
805
+ // relative to origin — a clean checkout behind origin would otherwise
806
+ // apply and could silently replace newer stored data with older code.
807
+ // Full-tree scans only (never --changed, which the hook always passes for
808
+ // normal, possibly-unpushed local commits); detached HEAD has no branch to
809
+ // compare against origin and is already never applied regardless.
810
+ if (!options.changed && meta.branch && !meta.detachedHead) {
811
+ const freshness = await enforceCheckoutFreshness({ root: meta.root, branch: meta.branch, dryRun: Boolean(options.dryRun), yes: Boolean(options.yes) });
812
+ if (freshness.action === "refuse")
813
+ throw new Error(freshness.message);
814
+ if (freshness.action === "warn")
815
+ console.warn(`⚠ ${freshness.message}`);
816
+ if (freshness.action === "proceed" && freshness.note)
817
+ console.log(freshness.note);
818
+ }
819
+ // The commit hook invokes `deep-scan --changed` unconditionally, on every
820
+ // commit, regardless of branch — upload only for a commit on the tracked
821
+ // branch, per a confirmed mismatch (never on "none": there's nothing to
822
+ // mismatch against yet, and the server already holds that case cleanly).
823
+ // Read-only (record:false) and fails open on any error — a network
824
+ // hiccup here must never block, delay, or fail the commit; it just means
825
+ // this one incremental scan proceeds exactly as it did before this check
826
+ // existed, and the server's own apply-time branch check still applies.
827
+ if (options.changed && !options.dryRun && meta.branch && !meta.detachedHead) {
828
+ try {
829
+ 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 }) });
830
+ if (shouldSkipIncrementalScan(check.outcome)) {
831
+ console.log(`Skipping incremental scan: tracked branch for ${meta.repository} is "${check.trackedBranch}"; this commit is on "${meta.branch}".`);
832
+ return;
833
+ }
834
+ }
835
+ catch { /* fail open — scan proceeds exactly as it did before this check */ }
836
+ }
204
837
  const policy = options.dryRun
205
838
  ? { excerptsEnabled: true }
206
839
  : await apiRequest(credentials.apiUrl, token, "/deep-scan/policy");
@@ -209,7 +842,7 @@ async function deepScanCommand(options = {}) {
209
842
  console.log("No supported tracked files need scanning.");
210
843
  return;
211
844
  }
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 } };
845
+ 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
846
  const spoolDir = node_fs_1.default.mkdtempSync(node_path_1.default.join(node_os_1.default.tmpdir(), "kodingo-deep-scan-"));
214
847
  const spoolPath = node_path_1.default.join(spoolDir, `deep-scan-${meta.commitSha}.jsonl`);
215
848
  node_fs_1.default.writeFileSync(spoolPath, "", { mode: 0o600 });
@@ -302,13 +935,36 @@ async function deepScanCommand(options = {}) {
302
935
  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
936
  return;
304
937
  }
938
+ // Consent is asked from LOCAL data only — nothing about this checkout has
939
+ // reached the server yet (the policy fetch above carries no repo/file
940
+ // data, just an org-level excerpt setting). The real upload/already-known
941
+ // split needs the server's held-blob-SHA list, which only exists once a
942
+ // session is created — so that, and everything else server-side, happens
943
+ // only after this consent is granted, never before.
305
944
  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.`);
945
+ const approved = await permission(options, buildLocalReadSummary(extractedCount, evidenceSummary));
307
946
  if (!approved) {
308
947
  node_fs_1.default.rmSync(spoolDir, { recursive: true, force: true });
309
948
  console.log("Upload cancelled.");
310
949
  return;
311
950
  }
951
+ manifest.consent.confirmedAt = new Date().toISOString();
952
+ const session = await apiRequest(credentials.apiUrl, token, "/deep-scan/sessions", { method: "POST", body: JSON.stringify(manifest) });
953
+ const held = new Set(session.heldBlobShas ?? []);
954
+ let willUpload = 0, alreadyKnown = 0;
955
+ {
956
+ const countLines = promises_1.default.createInterface({ input: node_fs_1.default.createReadStream(spoolPath, { encoding: "utf8" }), crlfDelay: Infinity });
957
+ for await (const line of countLines) {
958
+ if (!line)
959
+ continue;
960
+ const file = JSON.parse(line);
961
+ if (held.has(file.blobSha))
962
+ alreadyKnown++;
963
+ else
964
+ willUpload++;
965
+ }
966
+ }
967
+ console.log(buildUploadSummary(extractedCount, willUpload, alreadyKnown, evidenceSummary));
312
968
  const statePath = node_path_1.default.join(meta.root, STATE_NAME);
313
969
  node_fs_1.default.mkdirSync(node_path_1.default.dirname(statePath), { recursive: true });
314
970
  let prior = null;
@@ -316,8 +972,6 @@ async function deepScanCommand(options = {}) {
316
972
  prior = JSON.parse(node_fs_1.default.readFileSync(statePath, "utf8"));
317
973
  }
318
974
  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
975
  const batchSize = Math.max(1, Math.min(Number(session.limits?.filesPerBatch ?? 200), 200));
322
976
  let batch = [];
323
977
  let uploaded = 0;
@@ -340,5 +994,11 @@ async function deepScanCommand(options = {}) {
340
994
  node_fs_1.default.rmSync(spoolDir, { recursive: true, force: true });
341
995
  const finalized = await apiRequest(credentials.apiUrl, token, `/deep-scan/sessions/${session.sessionId}/finalize`, { method: "POST", body: "{}" });
342
996
  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.`);
997
+ const run = await pollRun(credentials.apiUrl, token, finalized.runId);
998
+ // Record the real outcome locally — this is what lets the commit hook's
999
+ // otherwise-silent (stdout redirected to /dev/null) held upload surface
1000
+ // via `kodingo deep-scan-status` instead of vanishing with no visible
1001
+ // error on the engineer's own machine.
1002
+ 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");
1003
+ printFinalOutcome(run, options.yes);
344
1004
  }