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.
@@ -42,6 +42,8 @@ var __importStar = (this && this.__importStar) || (function () {
42
42
  };
43
43
  })();
44
44
  Object.defineProperty(exports, "__esModule", { value: true });
45
+ exports.checkoutCoverageComplete = checkoutCoverageComplete;
46
+ exports.shouldSkipLocalScan = shouldSkipLocalScan;
45
47
  exports.registerInitCommand = registerInitCommand;
46
48
  const readline = __importStar(require("node:readline"));
47
49
  const fs = __importStar(require("fs"));
@@ -179,22 +181,43 @@ async function createProject(authToken, name, orgId) {
179
181
  throw new Error(data.error ?? "Failed to create project");
180
182
  return data;
181
183
  }
182
- async function checkoutAlreadyFullyRead(repoRoot, apiUrl, token) {
184
+ /**
185
+ * The product rule: a project whose read is complete — from ANY source,
186
+ * GitHub or a local scan — does not need another local scan. Completeness
187
+ * is the test, not the commit or the source: this used to also require
188
+ * `status.lastCommit === metadata.commitSha`, which meant the shortcut only
189
+ * ever fired for the EXACT commit a prior scan (of either source) happened
190
+ * to run against — in practice almost never true for a new engineer's
191
+ * checkout, since a GitHub-sourced "complete" project updates its recorded
192
+ * commit on its own schedule (see utils/entityScanScheduler.ts's hourly
193
+ * github_light_backup rows), not this engineer's.
194
+ *
195
+ * `alreadyRegistered` guards the one real risk of dropping the commit
196
+ * check: a multi-repo project where /deep-scan/status's completeness is a
197
+ * PROJECT-wide aggregate, not scoped to any one repo. Only when this
198
+ * checkout's repo was already a genuinely registered repo of the project
199
+ * (not one this very call is registering for the first time) does that
200
+ * aggregate completeness legitimately describe THIS checkout.
201
+ */
202
+ async function checkoutCoverageComplete(apiUrl, token, alreadyRegistered) {
203
+ if (!alreadyRegistered)
204
+ return false;
183
205
  try {
184
- const { resolveGitMetadata } = await Promise.resolve().then(() => __importStar(require("./deep-scan")));
185
- const metadata = resolveGitMetadata(repoRoot);
186
- if (metadata.dirty || metadata.detachedHead)
187
- return false;
188
206
  const response = await fetch(`${apiUrl.replace(/\/$/, "")}/deep-scan/status`, { headers: { "X-Kodingo-Token": token } });
189
207
  if (!response.ok)
190
208
  return false;
191
209
  const status = await response.json();
192
- return status.state === "complete" && status.lastCommit === metadata.commitSha;
210
+ return status.state === "complete";
193
211
  }
194
212
  catch {
195
213
  return false;
196
214
  }
197
215
  }
216
+ /** Pure so --force's override of an otherwise-complete project is directly
217
+ * unit-testable without driving the whole interactive/CI init flow. */
218
+ function shouldSkipLocalScan(force, dryRun, coverageComplete) {
219
+ return !force && !dryRun && coverageComplete;
220
+ }
198
221
  // ── Command ───────────────────────────────────────────────────────────────────
199
222
  function registerInitCommand(program) {
200
223
  program
@@ -203,8 +226,11 @@ function registerInitCommand(program) {
203
226
  .option("--logout", "Log out and clear saved credentials")
204
227
  .option("--yes", "non-interactive consent (use KODINGO_TOKEN in CI)")
205
228
  .option("--dry-run <file>", "write the exact deep-scan payload without uploading")
229
+ .option("--force", "run the full local scan even if Kortex already has complete coverage of this project")
230
+ .option("--verbose", "print the inputs behind each held-scan reconciliation decision (same as KODINGO_DEBUG=1)")
206
231
  .action(async (opts) => {
207
232
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
233
+ const verbose = Boolean(opts.verbose) || process.env.KODINGO_DEBUG === "1";
208
234
  try {
209
235
  // ── Logout ──────────────────────────────────────────────────────────
210
236
  if (opts.logout) {
@@ -223,9 +249,24 @@ function registerInitCommand(program) {
223
249
  (0, persistence_config_1.writeConfig)({ ...existingConfig, mode: "cloud", apiUrl, machineId: getMachineId() });
224
250
  (0, persistence_config_1.writeWorkspaceConfig)(repoRoot, { mode: "cloud", apiUrl, token: environmentToken });
225
251
  ensureGitignoreEntry(repoRoot, ".kortex/");
226
- await (0, repo_identity_1.resolveCanonicalRepoName)({ repoRoot, apiUrl, token: environmentToken });
227
- const { deepScanCommand } = await Promise.resolve().then(() => __importStar(require("./deep-scan")));
228
- await deepScanCommand({ repo: repoRoot, yes: true, dryRun: opts.dryRun, noUpdate: true });
252
+ const registration = await (0, repo_identity_1.resolveRepoRegistration)({ repoRoot, apiUrl, token: environmentToken });
253
+ const coverageComplete = (!opts.force && !opts.dryRun) ? await checkoutCoverageComplete(apiUrl, environmentToken, registration.alreadyRegistered) : false;
254
+ const alreadyComplete = shouldSkipLocalScan(opts.force, opts.dryRun, coverageComplete);
255
+ const { deepScanCommand, settleAndReconcile, settleAlreadyCompleteProject, resolveGitMetadata, deriveBareRepoName } = await Promise.resolve().then(() => __importStar(require("./deep-scan")));
256
+ if (alreadyComplete) {
257
+ const meta = resolveGitMetadata(repoRoot);
258
+ await settleAlreadyCompleteProject({
259
+ apiUrl, token: environmentToken, root: repoRoot, branch: meta.branch, detachedHead: meta.detachedHead,
260
+ repository: meta.repository, repositoryName: deriveBareRepoName(meta.repository), yes: true, verbose,
261
+ });
262
+ }
263
+ else {
264
+ const handled = opts.dryRun
265
+ ? false
266
+ : (await settleAndReconcile({ apiUrl, token: environmentToken, root: repoRoot, yes: true })).handled;
267
+ if (!handled)
268
+ await deepScanCommand({ repo: repoRoot, yes: true, dryRun: opts.dryRun, noUpdate: true });
269
+ }
229
270
  return;
230
271
  }
231
272
  // ── Check if already logged in ───────────────────────────────────────
@@ -310,9 +351,13 @@ function registerInitCommand(program) {
310
351
  // contamination — resolved from the git remote (stable across
311
352
  // machines and folder names), not the local folder name itself,
312
353
  // so the registration this creates is trustworthy for every future
313
- // scan to resolve against.
354
+ // scan to resolve against. Its result also tells us whether this
355
+ // checkout's repo was ALREADY registered — the gate the
356
+ // complete-coverage shortcut below needs (see
357
+ // checkoutCoverageComplete's own comment for why).
358
+ let registration = { repoName: "", alreadyRegistered: false };
314
359
  try {
315
- await (0, repo_identity_1.resolveCanonicalRepoName)({
360
+ registration = await (0, repo_identity_1.resolveRepoRegistration)({
316
361
  repoRoot,
317
362
  apiUrl,
318
363
  token: selectedProject.token,
@@ -320,26 +365,45 @@ function registerInitCommand(program) {
320
365
  }
321
366
  catch { }
322
367
  console.log(`✔ Connected. Token saved to ${persistence_config_1.CONFIG_PATH}`);
323
- const alreadyRead = await checkoutAlreadyFullyRead(repoRoot, apiUrl, selectedProject.token);
324
- if (alreadyRead)
325
- console.log("\n✔ This clean checkout already has a complete deep scan at the current commit; no upload is needed.");
326
- else
368
+ const coverageComplete = (!opts.force && !opts.dryRun) ? await checkoutCoverageComplete(apiUrl, selectedProject.token, registration.alreadyRegistered) : false;
369
+ const alreadyComplete = shouldSkipLocalScan(opts.force, opts.dryRun, coverageComplete);
370
+ if (!alreadyComplete)
327
371
  console.log("\nKortex will now read this checkout locally. Review the upload summary before consenting.");
328
372
  // The local deep scan is the one first-read path. The retired
329
373
  // scan-repo capture is deliberately not run here.
330
- try {
331
- const { deepScanCommand } = await Promise.resolve().then(() => __importStar(require("./deep-scan")));
332
- if (!alreadyRead)
333
- await deepScanCommand({ repo: repoRoot, yes: Boolean(opts.yes), dryRun: opts.dryRun });
374
+ const { deepScanCommand, settleAndReconcile, settleAlreadyCompleteProject, resolveGitMetadata, deriveBareRepoName } = await Promise.resolve().then(() => __importStar(require("./deep-scan")));
375
+ if (alreadyComplete) {
376
+ try {
377
+ const meta = resolveGitMetadata(repoRoot);
378
+ await settleAlreadyCompleteProject({
379
+ apiUrl, token: selectedProject.token, root: repoRoot, branch: meta.branch, detachedHead: meta.detachedHead,
380
+ repository: meta.repository, repositoryName: deriveBareRepoName(meta.repository), yes: Boolean(opts.yes), verbose,
381
+ });
382
+ }
383
+ catch (err) {
384
+ throw new Error(`Tracked-branch settlement failed: ${err.message}`);
385
+ }
334
386
  }
335
- catch (err) {
336
- throw new Error(`Initial deep scan failed: ${err.message}`);
387
+ else {
388
+ try {
389
+ // Settle the tracked branch — and reconcile any already-held scan
390
+ // for this exact commit — before uploading anything, so a first
391
+ // scan can apply instead of silently landing held.
392
+ const handled = opts.dryRun
393
+ ? false
394
+ : (await settleAndReconcile({ apiUrl, token: selectedProject.token, root: repoRoot, yes: Boolean(opts.yes) })).handled;
395
+ if (!handled)
396
+ await deepScanCommand({ repo: repoRoot, yes: Boolean(opts.yes), dryRun: opts.dryRun });
397
+ }
398
+ catch (err) {
399
+ throw new Error(`Initial deep scan failed: ${err.message}`);
400
+ }
337
401
  }
338
402
  // Install only after the user has reviewed/accepted the first scan.
339
403
  try {
340
404
  const { installHookCommand } = await Promise.resolve().then(() => __importStar(require("./install-hook")));
341
- await installHookCommand({ repo: repoRoot });
342
- console.log("✔ Incremental commit hook installed.\n");
405
+ const installed = await installHookCommand({ repo: repoRoot });
406
+ console.log(installed ? "✔ Incremental commit hook installed.\n" : "✔ Incremental commit hook already installed.\n");
343
407
  }
344
408
  catch (err) {
345
409
  console.log(`⚠ Could not install the hook (${err.message}). Run \`kodingo install-hook\` later.\n`);
@@ -6,6 +6,12 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.installHookCommand = installHookCommand;
7
7
  const fs_1 = __importDefault(require("fs"));
8
8
  const path_1 = __importDefault(require("path"));
9
+ /** Returns true when a hook block was newly installed, false when one was
10
+ * already present (nothing written). Callers decide what to print — this
11
+ * used to print its own "Hook already installed"/"Kodingo hook installed"
12
+ * line unconditionally, which `kodingo init` then followed with its own
13
+ * "Incremental commit hook installed" regardless of which case this was,
14
+ * producing a contradictory pair of lines on a repeat `init`. */
9
15
  async function installHookCommand(options) {
10
16
  const repoRoot = resolveRepoRoot(options);
11
17
  const hooksDir = path_1.default.join(repoRoot, ".git", "hooks");
@@ -16,12 +22,22 @@ async function installHookCommand(options) {
16
22
  const hookPath = path_1.default.join(hooksDir, "post-commit");
17
23
  const hookBlock = [
18
24
  "# <kodingo>",
19
- "# Kodingo: auto-infer decision memory from git commits",
20
- `"${kodingoBin}" scan-git --repo "$(git rev-parse --show-toplevel)" &`,
25
+ "# Kodingo: auto-infer decision memory from git commits — backgrounded and",
26
+ "# silenced so a failure here is never visible on (or blocks) the commit.",
27
+ `"${kodingoBin}" scan-git --repo "$(git rev-parse --show-toplevel)" >/dev/null 2>&1 &`,
21
28
  "# Kodingo Security: keep dependency data current for vulnerability scanning",
22
- `"${kodingoBin}" sync-dependencies --repo "$(git rev-parse --show-toplevel)" &`,
23
- "# Kortex Deep Scan: extract only the committed files locally; never block the commit",
24
- `(command -v timeout >/dev/null 2>&1 && timeout 120 "${kodingoBin}" deep-scan --repo "$(git rev-parse --show-toplevel)" --changed --yes --no-update >/dev/null 2>&1 || "${kodingoBin}" deep-scan --repo "$(git rev-parse --show-toplevel)" --changed --yes --no-update >/dev/null 2>&1) &`,
29
+ `"${kodingoBin}" sync-dependencies --repo "$(git rev-parse --show-toplevel)" >/dev/null 2>&1 &`,
30
+ "# Kortex Deep Scan: extract only the committed files locally; never block the",
31
+ "# commit. A portable watchdog (sleep+kill) enforces the timeout regardless of",
32
+ "# whether the GNU `timeout` binary is installed on this machine.",
33
+ "(",
34
+ ` "${kodingoBin}" deep-scan --repo "$(git rev-parse --show-toplevel)" --changed --yes --no-update >/dev/null 2>&1 &`,
35
+ " kodingo_scan_pid=$!",
36
+ " ( sleep 120; kill -9 \"$kodingo_scan_pid\" ) >/dev/null 2>&1 &",
37
+ " kodingo_watchdog_pid=$!",
38
+ " wait \"$kodingo_scan_pid\" >/dev/null 2>&1",
39
+ " kill \"$kodingo_watchdog_pid\" >/dev/null 2>&1",
40
+ ") &",
25
41
  "# </kodingo>",
26
42
  ].join("\n");
27
43
  // Pre-commit hook — runs synchronously to enforce guardrails
@@ -49,8 +65,7 @@ async function installHookCommand(options) {
49
65
  if (fs_1.default.existsSync(hookPath)) {
50
66
  const existing = fs_1.default.readFileSync(hookPath, "utf-8");
51
67
  if (existing.includes("# <kodingo>")) {
52
- console.log("Hook already installed");
53
- return;
68
+ return false;
54
69
  }
55
70
  // Append to existing hook
56
71
  const updated = existing.endsWith("\n")
@@ -64,7 +79,7 @@ async function installHookCommand(options) {
64
79
  fs_1.default.writeFileSync(hookPath, content, "utf-8");
65
80
  }
66
81
  fs_1.default.chmodSync(hookPath, 0o755);
67
- console.log(`Kodingo hook installed for repo: ${repoRoot}`);
82
+ return true;
68
83
  }
69
84
  function resolveRepoRoot(options) {
70
85
  if (options.repo && options.repo.trim()) {
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.parseRepoNameFromRemote = parseRepoNameFromRemote;
7
7
  exports.getRemoteUrl = getRemoteUrl;
8
8
  exports.deriveCandidateRepoName = deriveCandidateRepoName;
9
+ exports.resolveRepoRegistration = resolveRepoRegistration;
9
10
  exports.resolveCanonicalRepoName = resolveCanonicalRepoName;
10
11
  /**
11
12
  * Resolves the canonical `repo` identity sent to the server, instead of
@@ -56,13 +57,14 @@ async function deriveCandidateRepoName(repoRoot) {
56
57
  return { candidateName: path_1.default.basename(repoRoot), hasRemote: false };
57
58
  }
58
59
  /**
59
- * Returns the canonical repo label to send with this scan. Fails open to
60
- * the locally derived candidate if the server is unreachable — a scan
61
- * should never be blocked by this resolution, and the git-remote-derived
62
- * candidate is already more stable than the old folder-basename behaviour
63
- * even without a round-trip to the server.
60
+ * Returns the canonical repo label to send with this scan, AND whether that
61
+ * label was already a registered repo for this project before this call
62
+ * (as opposed to one this call just registered, or one resolved only by
63
+ * local fallback because the server was unreachable). Fails open to the
64
+ * locally derived candidate (alreadyRegistered:false) if the server is
65
+ * unreachable — a scan should never be blocked by this resolution.
64
66
  */
65
- async function resolveCanonicalRepoName(params) {
67
+ async function resolveRepoRegistration(params) {
66
68
  const { candidateName, hasRemote } = await deriveCandidateRepoName(params.repoRoot);
67
69
  try {
68
70
  const res = await fetch(`${params.apiUrl}/cli/repo/resolve`, {
@@ -72,12 +74,24 @@ async function resolveCanonicalRepoName(params) {
72
74
  });
73
75
  if (res.ok) {
74
76
  const data = (await res.json());
75
- if (data.repoName)
76
- return data.repoName;
77
+ if (data.repoName) {
78
+ const alreadyRegistered = data.matched === "single-registered" || data.matched === "multi-matched";
79
+ return { repoName: data.repoName, alreadyRegistered };
80
+ }
77
81
  }
78
82
  }
79
83
  catch {
80
84
  // offline / server unreachable — fail open below
81
85
  }
82
- return candidateName;
86
+ return { repoName: candidateName, alreadyRegistered: false };
87
+ }
88
+ /**
89
+ * Returns the canonical repo label to send with this scan. Fails open to
90
+ * the locally derived candidate if the server is unreachable — a scan
91
+ * should never be blocked by this resolution, and the git-remote-derived
92
+ * candidate is already more stable than the old folder-basename behaviour
93
+ * even without a round-trip to the server.
94
+ */
95
+ async function resolveCanonicalRepoName(params) {
96
+ return (await resolveRepoRegistration(params)).repoName;
83
97
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kodingo-cli",
3
- "version": "1.4.0",
3
+ "version": "1.4.2",
4
4
  "description": "Kodingo CLI",
5
5
  "license": "MIT",
6
6
  "private": false,
@@ -26,7 +26,7 @@
26
26
  "@typescript-eslint/typescript-estree": "^8.61.1",
27
27
  "commander": "^12.1.0",
28
28
  "kodingo-agent": "^0.2.0",
29
- "kodingo-core": "^0.3.6",
29
+ "kodingo-core": "^0.3.7",
30
30
  "open": "^11.0.0",
31
31
  "simple-git": "^3.30.0",
32
32
  "tree-sitter-wasms": "^0.1.13",