kodingo-cli 1.4.1 → 1.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,162 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ /** Invented local fixtures; fake fetch never contacts a server. */
7
+ const strict_1 = __importDefault(require("node:assert/strict"));
8
+ const node_fs_1 = __importDefault(require("node:fs"));
9
+ const node_path_1 = __importDefault(require("node:path"));
10
+ const node_child_process_1 = require("node:child_process");
11
+ const node_test_1 = require("node:test");
12
+ const cloud_persistence_1 = require("../adapters/cloud-adapter/cloud-persistence");
13
+ const query_memory_1 = require("../commands/query-memory");
14
+ function fixture(run) {
15
+ const root = node_fs_1.default.mkdtempSync(node_path_1.default.join(process.cwd(), ".repo-filter-fixture-"));
16
+ const home = node_path_1.default.join(root, "home");
17
+ const repo = node_path_1.default.join(root, "Business-Unit");
18
+ try {
19
+ node_fs_1.default.mkdirSync(home);
20
+ node_fs_1.default.mkdirSync(repo);
21
+ (0, node_child_process_1.execFileSync)("git", ["-C", repo, "init", "-q"]);
22
+ node_fs_1.default.mkdirSync(node_path_1.default.join(home, ".kodingo"), { mode: 0o700 });
23
+ node_fs_1.default.writeFileSync(node_path_1.default.join(home, ".kodingo", "config.json"), JSON.stringify({ mode: "cloud", apiUrl: "https://example.invalid", workspaces: { [repo]: { mode: "cloud", apiUrl: "https://example.invalid", token: "fixture-token" } } }), { mode: 0o600 });
24
+ return run(repo, home);
25
+ }
26
+ finally {
27
+ node_fs_1.default.rmSync(root, { recursive: true, force: true });
28
+ }
29
+ }
30
+ async function fixtureAsync(run) {
31
+ const root = node_fs_1.default.mkdtempSync(node_path_1.default.join(process.cwd(), ".repo-filter-fixture-"));
32
+ const home = node_path_1.default.join(root, "home");
33
+ const repo = node_path_1.default.join(root, "Business-Unit");
34
+ try {
35
+ node_fs_1.default.mkdirSync(home);
36
+ node_fs_1.default.mkdirSync(repo);
37
+ (0, node_child_process_1.execFileSync)("git", ["-C", repo, "init", "-q"]);
38
+ node_fs_1.default.mkdirSync(node_path_1.default.join(home, ".kodingo"), { mode: 0o700 });
39
+ node_fs_1.default.writeFileSync(node_path_1.default.join(home, ".kodingo", "config.json"), JSON.stringify({ mode: "cloud", apiUrl: "https://example.invalid", workspaces: { [repo]: { mode: "cloud", apiUrl: "https://example.invalid", token: "fixture-token" } } }), { mode: 0o600 });
40
+ return await run(repo, home);
41
+ }
42
+ finally {
43
+ node_fs_1.default.rmSync(root, { recursive: true, force: true });
44
+ }
45
+ }
46
+ function record(id) {
47
+ return { id, projectId: "fixture-project", repo: "Business-Unit", type: "note", title: `QuickBooks ${id}`, content: `fixture ${id}`, tags: [], status: "affirmed", confidence: 0.8, createdAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z" };
48
+ }
49
+ function command(repo, home, options, body, module = "query-memory", expression) {
50
+ const modulePath = node_path_1.default.resolve(`dist/commands/${module}.js`);
51
+ const call = expression ?? `require(${JSON.stringify(modulePath)}).queryMemoryCommand("QuickBooks",${JSON.stringify(options)})`;
52
+ const script = `global.fetch=async(url)=>{console.log('FETCH_URL='+url);return {ok:true,status:200,json:async()=>(${JSON.stringify(body)})}};${call}.catch(e=>{console.error(e.message);process.exitCode=1})`;
53
+ const result = (0, node_child_process_1.spawnSync)(process.execPath, ["-e", script], { cwd: repo, env: { ...process.env, HOME: home }, encoding: "utf8" });
54
+ strict_1.default.equal(result.status, 0, result.stderr);
55
+ const url = result.stdout.split("\n").find(line => line.startsWith("FETCH_URL="))?.slice(10) ?? "";
56
+ return { url: new URL(url), output: result.stdout };
57
+ }
58
+ function withCloud(run) {
59
+ const originalFetch = global.fetch;
60
+ const oldUrl = process.env.KODINGO_API_URL;
61
+ const oldToken = process.env.KODINGO_API_TOKEN;
62
+ const urls = [];
63
+ process.env.KODINGO_API_URL = "https://example.invalid";
64
+ process.env.KODINGO_API_TOKEN = "fixture-token";
65
+ global.fetch = (async (input) => { urls.push(new URL(input)); return { ok: true, status: 200, json: async () => ({ data: [] }) }; });
66
+ return run(urls).finally(() => {
67
+ global.fetch = originalFetch;
68
+ if (oldUrl === undefined)
69
+ delete process.env.KODINGO_API_URL;
70
+ else
71
+ process.env.KODINGO_API_URL = oldUrl;
72
+ if (oldToken === undefined)
73
+ delete process.env.KODINGO_API_TOKEN;
74
+ else
75
+ process.env.KODINGO_API_TOKEN = oldToken;
76
+ });
77
+ }
78
+ (0, node_test_1.describe)("query-memory repo filter", () => {
79
+ (0, node_test_1.it)("defaults to q and limit without repo", () => fixture((repo, home) => {
80
+ const { url } = command(repo, home, { limit: 10 }, { data: [] });
81
+ strict_1.default.equal(url.searchParams.get("q"), "QuickBooks");
82
+ strict_1.default.equal(url.searchParams.get("limit"), "10");
83
+ strict_1.default.equal(url.searchParams.has("repo"), false);
84
+ }));
85
+ (0, node_test_1.it)("sends a bare repository name unchanged", () => fixture((repo, home) => {
86
+ const { url } = command(repo, home, { limit: 10, repo: "Business-Unit" }, { data: [] });
87
+ strict_1.default.equal(url.searchParams.get("repo"), "Business-Unit");
88
+ }));
89
+ (0, node_test_1.it)("uses the final segment of a path with a trailing slash", () => fixture((repo, home) => {
90
+ const { url } = command(repo, home, { limit: 10, repo: `${repo}/` }, { data: [] });
91
+ strict_1.default.equal(url.searchParams.get("repo"), "Business-Unit");
92
+ }));
93
+ (0, node_test_1.it)("uses the final segment of a Windows-style path", () => fixture((repo, home) => {
94
+ const { url } = command(repo, home, { limit: 10, repo: "C:\\Example\\Business-Unit\\" }, { data: [] });
95
+ strict_1.default.equal(url.searchParams.get("repo"), "Business-Unit");
96
+ }));
97
+ (0, node_test_1.it)("global overrides an explicit repo", () => fixture((repo, home) => {
98
+ const { url } = command(repo, home, { limit: 10, repo: "Business-Unit", global: true }, { data: [] });
99
+ strict_1.default.equal(url.searchParams.has("repo"), false);
100
+ }));
101
+ (0, node_test_1.it)("prints both items from the current data envelope", () => fixture((repo, home) => {
102
+ const { output } = command(repo, home, { limit: 10 }, { data: [record("one"), record("two")], limit: 10, offset: 0 });
103
+ strict_1.default.match(output, /QuickBooks one/);
104
+ strict_1.default.match(output, /QuickBooks two/);
105
+ }));
106
+ (0, node_test_1.it)("prints both items from an older array response", () => fixture((repo, home) => {
107
+ const { output } = command(repo, home, { limit: 10 }, [record("one"), record("two")]);
108
+ strict_1.default.match(output, /QuickBooks one/);
109
+ strict_1.default.match(output, /QuickBooks two/);
110
+ }));
111
+ (0, node_test_1.it)("scope helper leaves default unfiltered", () => fixture(() => strict_1.default.equal((0, query_memory_1.resolveRepoScope)({}), undefined)));
112
+ });
113
+ (0, node_test_1.describe)("other cloud memory reads", () => {
114
+ (0, node_test_1.it)("normalizes text query repo filters from event ports", async () => fixtureAsync(async (repo) => withCloud(async (urls) => {
115
+ await (0, cloud_persistence_1.queryMemory)("", 10, repo);
116
+ strict_1.default.equal(urls[0].searchParams.get("repo"), "Business-Unit");
117
+ })));
118
+ (0, node_test_1.it)("normalizes symbol query repo filters", async () => fixtureAsync(async (repo) => withCloud(async (urls) => {
119
+ await (0, cloud_persistence_1.queryMemoryBySymbol)({ symbol: "Fixture", repoPath: repo });
120
+ strict_1.default.equal(urls[0].searchParams.get("repo"), "Business-Unit");
121
+ })));
122
+ (0, node_test_1.it)("normalizes external-ID lookup repo filters", async () => fixtureAsync(async (repo) => withCloud(async (urls) => {
123
+ await (0, cloud_persistence_1.getMemoryByExternalId)("fixture-id", repo);
124
+ strict_1.default.equal(urls[0].searchParams.get("repo"), "Business-Unit");
125
+ })));
126
+ (0, node_test_1.it)("normalizes proposed and ignored lookup repo filters", async () => fixtureAsync(async (repo) => withCloud(async (urls) => {
127
+ await (0, cloud_persistence_1.getProposedOrIgnoredRecordBySymbol)({ symbol: "Fixture", repoPath: repo });
128
+ strict_1.default.equal(urls.length, 2);
129
+ strict_1.default.ok(urls.every(url => url.searchParams.get("repo") === "Business-Unit"));
130
+ })));
131
+ (0, node_test_1.it)("normalizes the sibling suppression scope", async () => fixtureAsync(async (repo) => {
132
+ const originalFetch = global.fetch;
133
+ const oldUrl = process.env.KODINGO_API_URL;
134
+ const oldToken = process.env.KODINGO_API_TOKEN;
135
+ let sent;
136
+ process.env.KODINGO_API_URL = "https://example.invalid";
137
+ process.env.KODINGO_API_TOKEN = "fixture-token";
138
+ global.fetch = (async (_input, init) => { sent = JSON.parse(String(init?.body)); return { ok: true, status: 200, json: async () => ({ suppressed: 1 }) }; });
139
+ try {
140
+ strict_1.default.equal(await (0, cloud_persistence_1.suppressProposedSiblings)({ symbol: "Fixture", repoPath: repo, excludeId: "fixture-id" }), 1);
141
+ strict_1.default.equal(sent.repo, "Business-Unit");
142
+ }
143
+ finally {
144
+ global.fetch = originalFetch;
145
+ if (oldUrl === undefined)
146
+ delete process.env.KODINGO_API_URL;
147
+ else
148
+ process.env.KODINGO_API_URL = oldUrl;
149
+ if (oldToken === undefined)
150
+ delete process.env.KODINGO_API_TOKEN;
151
+ else
152
+ process.env.KODINGO_API_TOKEN = oldToken;
153
+ }
154
+ }));
155
+ (0, node_test_1.it)("context sends the bare repository name", () => fixture((repo, home) => {
156
+ const modulePath = node_path_1.default.resolve("dist/commands/context.js");
157
+ const expression = `require(${JSON.stringify(modulePath)}).contextCommand("source.ts",{limit:5})`;
158
+ const { url, output } = command(repo, home, {}, { data: [record("one")], total: 1 }, "context", expression);
159
+ strict_1.default.equal(url.searchParams.get("repo"), "Business-Unit");
160
+ strict_1.default.match(output, /QuickBooks one/);
161
+ }));
162
+ });
@@ -52,7 +52,13 @@ exports.deleteMemoryById = deleteMemoryById;
52
52
  exports.queryMemory = queryMemory;
53
53
  exports.queryMemoryBySymbol = queryMemoryBySymbol;
54
54
  const os = __importStar(require("os"));
55
+ const path = __importStar(require("node:path"));
55
56
  const persistence_config_1 = require("../../utils/persistence-config");
57
+ /** The API's memory.repo field uses repository names, not local folder paths. */
58
+ function repoFilterName(value) {
59
+ const normalized = value.replace(/\\/g, "/").replace(/\/+$/, "");
60
+ return normalized.includes("/") ? path.posix.basename(normalized) : normalized;
61
+ }
56
62
  function getConfig() {
57
63
  const apiUrl = process.env.KODINGO_API_URL;
58
64
  const token = process.env.KODINGO_API_TOKEN;
@@ -239,7 +245,7 @@ async function suppressProposedSiblings(params) {
239
245
  excludeId: params.excludeId,
240
246
  };
241
247
  if (params.repoPath)
242
- body.repo = params.repoPath;
248
+ body.repo = repoFilterName(params.repoPath);
243
249
  const res = await apiFetch("/memory/suppress-siblings", {
244
250
  method: "POST",
245
251
  body: JSON.stringify(body),
@@ -250,7 +256,7 @@ async function suppressProposedSiblings(params) {
250
256
  * Look up a memory record by externalId, scoped to a repo.
251
257
  */
252
258
  async function getMemoryByExternalId(externalId, repoPath) {
253
- const params = new URLSearchParams({ externalId, repo: repoPath });
259
+ const params = new URLSearchParams({ externalId, repo: repoFilterName(repoPath) });
254
260
  const res = await apiFetch(`/memory?${params.toString()}`);
255
261
  const record = res.data?.[0];
256
262
  if (!record)
@@ -263,7 +269,7 @@ async function getMemoryByExternalId(externalId, repoPath) {
263
269
  async function getProposedOrIgnoredRecordBySymbol(params) {
264
270
  const qs = new URLSearchParams({
265
271
  symbol: params.symbol,
266
- repo: params.repoPath,
272
+ repo: repoFilterName(params.repoPath),
267
273
  });
268
274
  const [proposed, ignored] = await Promise.all([
269
275
  apiFetch(`/memory?${qs}&status=proposed&limit=1`),
@@ -292,15 +298,15 @@ async function deleteMemoryById(id) {
292
298
  async function queryMemory(text, limit = 10, repoPath, opts = {}) {
293
299
  const qs = new URLSearchParams({ limit: String(limit) });
294
300
  if (repoPath)
295
- qs.set("repo", repoPath);
296
- if (!opts.includeNonCanonical)
297
- qs.set("status", "proposed");
301
+ qs.set("repo", repoFilterName(repoPath));
298
302
  // Use server-side FTS when text is provided
299
303
  const term = text.trim();
300
304
  if (term)
301
305
  qs.set("q", term);
302
306
  const res = await apiFetch(`/memory?${qs.toString()}`);
303
- let records = (res.data ?? []).map(mapApiRecord);
307
+ let records = (Array.isArray(res) ? res : res.data ?? []).map(mapApiRecord);
308
+ if (!opts.includeNonCanonical)
309
+ records = records.filter(r => r.status !== "denied");
304
310
  if (opts.dedupeBySymbol) {
305
311
  const seen = new Set();
306
312
  records = records.filter((r) => {
@@ -322,7 +328,7 @@ async function queryMemoryBySymbol(params) {
322
328
  limit: String(params.limit ?? 10),
323
329
  });
324
330
  if (params.repoPath)
325
- qs.set("repo", params.repoPath);
331
+ qs.set("repo", repoFilterName(params.repoPath));
326
332
  if (params.onlyCanonical)
327
333
  qs.set("status", "affirmed");
328
334
  const res = await apiFetch(`/memory?${qs.toString()}`);
package/dist/cli.js CHANGED
@@ -126,7 +126,7 @@ program
126
126
  .argument("<text>", "text to search")
127
127
  .option("--limit <number>", "max results", "10")
128
128
  .option("--global", "search across all repos (ignore repo scope)")
129
- .option("--repo <path>", "explicit repo path to scope results")
129
+ .option("--repo <name>", "filter results by repository name (a path uses its final folder name)")
130
130
  .option("--dedupe-by-symbol", "return only the best record per symbol")
131
131
  .option("--include-non-canonical", "include denied records in results")
132
132
  .action(async (text, options) => {
@@ -3,18 +3,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.checkRulesCommand = checkRulesCommand;
4
4
  const child_process_1 = require("child_process");
5
5
  const persistence_config_1 = require("../utils/persistence-config");
6
- const API_BASE_DEFAULT = "https://kodingo-api.onrender.com";
7
- function normalizePath(p) {
8
- return p.replace(/\\/g, "/").toLowerCase();
9
- }
10
- function getCredentials() {
11
- const config = (0, persistence_config_1.readConfig)();
12
- const cwd = normalizePath(process.cwd());
13
- const ws = (0, persistence_config_1.readWorkspaceConfig)(cwd);
14
- const token = ws?.token ?? config.token ?? "";
15
- const apiUrl = ws?.apiUrl ?? config.apiUrl ?? API_BASE_DEFAULT;
16
- return { token, apiUrl };
17
- }
18
6
  function getStagedDiff() {
19
7
  try {
20
8
  return (0, child_process_1.execSync)("git diff --cached", { encoding: "utf-8", timeout: 10000 });
@@ -24,15 +12,13 @@ function getStagedDiff() {
24
12
  }
25
13
  }
26
14
  function getProjectId(token, apiUrl) {
27
- return fetch(`${apiUrl}/org/projects/by-token`, {
28
- headers: { "X-Kodingo-Token": token },
29
- })
15
+ return fetch(`${apiUrl}/org/projects/by-token`, { headers: { "X-Kodingo-Token": token } })
30
16
  .then(r => r.ok ? r.json() : null)
31
17
  .then((d) => d?.project?.id ?? null)
32
18
  .catch(() => null);
33
19
  }
34
20
  async function checkRulesCommand() {
35
- const { token, apiUrl } = getCredentials();
21
+ const { token, apiUrl } = (0, persistence_config_1.getCredentials)(process.cwd());
36
22
  if (!token)
37
23
  return; // No token — silent pass, never block
38
24
  const diff = getStagedDiff();
@@ -43,36 +43,25 @@ exports.contextCommand = contextCommand;
43
43
  */
44
44
  const path = __importStar(require("path"));
45
45
  const persistence_config_1 = require("../utils/persistence-config");
46
- const API_BASE_DEFAULT = "https://kodingo-api.onrender.com";
47
- function normalizePath(p) {
48
- return p.replace(/\\\\/g, "/").toLowerCase();
49
- }
50
- function getCredentials() {
51
- const config = (0, persistence_config_1.readConfig)();
52
- const cwd = normalizePath(process.cwd());
53
- const ws = (0, persistence_config_1.readWorkspaceConfig)(cwd);
54
- const token = ws?.token ?? config.token ?? "";
55
- const apiUrl = ws?.apiUrl ?? config.apiUrl ?? API_BASE_DEFAULT;
56
- return { token, apiUrl };
57
- }
46
+ const repo_scope_1 = require("../utils/repo-scope");
58
47
  async function contextCommand(filePath, options) {
59
- const { token, apiUrl } = getCredentials();
48
+ const { token, apiUrl } = (0, persistence_config_1.getCredentials)(process.cwd());
60
49
  if (!token) {
61
50
  console.error("No token found. Run `kodingo init` first.");
62
51
  process.exit(1);
63
52
  }
64
53
  const limit = options.limit ?? 20;
65
- const repoName = path.basename(process.cwd());
54
+ const repoName = path.basename((0, repo_scope_1.resolveRepoScope)() ?? process.cwd());
66
55
  const relFile = path.relative(process.cwd(), path.resolve(filePath));
67
56
  try {
68
- // Fetch memories for this file (by repo path)
69
- const res = await fetch(`${apiUrl}/memory?repo=${encodeURIComponent(relFile)}&status=affirmed&limit=${limit}`, { headers: { "X-Kodingo-Token": token } });
57
+ // The API stores repository names in memory.repo, not file paths.
58
+ const res = await fetch(`${apiUrl}/memory?repo=${encodeURIComponent(repoName)}&status=affirmed&limit=${limit}`, { headers: { "X-Kodingo-Token": token } });
70
59
  if (!res.ok) {
71
60
  console.error(`API error: ${res.status}`);
72
61
  process.exit(1);
73
62
  }
74
63
  const data = await res.json();
75
- const memories = data.memories ?? [];
64
+ const memories = data.data ?? data.memories ?? [];
76
65
  // Send metadata signal for each memory — agent queried it, that is weak evidence of relevance
77
66
  for (const m of memories) {
78
67
  if (m.id) {
@@ -37,6 +37,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
39
  exports.resolveGitMetadata = resolveGitMetadata;
40
+ exports.isDirtyCheckout = isDirtyCheckout;
40
41
  exports.resolveDefaultBranch = resolveDefaultBranch;
41
42
  exports.normalizeRemote = normalizeRemote;
42
43
  exports.deriveBareRepoName = deriveBareRepoName;
@@ -47,6 +48,9 @@ exports.buildUploadSummary = buildUploadSummary;
47
48
  exports.buildLocalReadSummary = buildLocalReadSummary;
48
49
  exports.decideBranchSettlement = decideBranchSettlement;
49
50
  exports.shouldSkipIncrementalScan = shouldSkipIncrementalScan;
51
+ exports.checkCheckoutFreshness = checkCheckoutFreshness;
52
+ exports.decideFreshnessAction = decideFreshnessAction;
53
+ exports.enforceCheckoutFreshness = enforceCheckoutFreshness;
50
54
  exports.settleTrackedBranch = settleTrackedBranch;
51
55
  exports.pollRun = pollRun;
52
56
  exports.printFinalOutcome = printFinalOutcome;
@@ -150,11 +154,38 @@ function resolveGitMetadata(start) {
150
154
  catch {
151
155
  return null;
152
156
  } })();
153
- const dirty = git(root, ["status", "--porcelain"]).length > 0;
157
+ const dirty = isDirtyCheckout(root);
154
158
  const remote = git(root, ["remote", "get-url", "origin"]);
155
159
  const shallow = git(root, ["rev-parse", "--is-shallow-repository"]) === "true";
156
160
  return { root, commitSha, branch, detachedHead: branch === null, dirty, remote, repository: normalizeRemote(remote), shallow };
157
161
  }
162
+ function isDirtyCheckout(root) {
163
+ const status = (0, node_child_process_1.execFileSync)("git", ["-C", root, "status", "--porcelain", "--untracked-files=all"], { encoding: "utf8" }).replace(/\n$/, "");
164
+ if (!status)
165
+ return false;
166
+ const allowedIgnoreChange = (cached) => {
167
+ const diff = git(root, ["diff", ...(cached ? ["--cached"] : []), "--no-ext-diff", "--", ".gitignore"]);
168
+ const changes = diff.split("\n").filter(line => /^[+-]/.test(line) && !/^(---|\+\+\+)/.test(line));
169
+ return changes.length > 0 && changes.every(line => line === "+# Kortex" || line === "+.kortex/");
170
+ };
171
+ for (const line of status.split("\n")) {
172
+ const code = line.slice(0, 2);
173
+ const name = line.slice(3);
174
+ if (name === ".kortex" || name.startsWith(".kortex/"))
175
+ continue;
176
+ if (name === ".gitignore") {
177
+ if (code === "??") {
178
+ const lines = node_fs_1.default.readFileSync(node_path_1.default.join(root, name), "utf8").trim().split(/\r?\n/);
179
+ if (lines.every(value => value === "# Kortex" || value === ".kortex/"))
180
+ continue;
181
+ }
182
+ else if ((!code[0].trim() || allowedIgnoreChange(true)) && (!code[1].trim() || allowedIgnoreChange(false)))
183
+ continue;
184
+ }
185
+ return true;
186
+ }
187
+ return false;
188
+ }
158
189
  /** The remote's default branch. Tries the fast, local, offline read first
159
190
  * (refs/remotes/origin/HEAD — only set once something has told the local
160
191
  * clone what the remote's HEAD is, e.g. `git clone` or `git remote set-head`;
@@ -254,17 +285,29 @@ function describeApiError(body, status) {
254
285
  * applied) scan to a plain-English sentence and the exact next step. */
255
286
  function describeApplyReason(reason) {
256
287
  if (!reason)
257
- return { sentence: "The scan was held for an unknown reason.", nextStep: "Run `kodingo deep-scan-status` for more detail." };
288
+ return { sentence: "The server is still processing this scan.", nextStep: "Run `kodingo deep-scan-status` in a minute." };
258
289
  if (reason === "clean_tracked_branch")
259
290
  return { sentence: "Applied.", nextStep: "" };
260
291
  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." };
292
+ return { sentence: "Your working tree has uncommitted changes.", nextStep: "Commit or stash them, then run kodingo deep-scan again." };
293
+ if (reason === "unverifiable_commit")
294
+ return { sentence: "The server could not confirm this commit in the repository it has on file.", nextStep: "Check that the repository is registered under the right owner and that the Kodingo GitHub app can see it." };
295
+ if (reason === "behind")
296
+ return { sentence: "This checkout is behind the tracked branch.", nextStep: "Pull, then run kodingo deep-scan again." };
297
+ if (reason === "ahead")
298
+ return { sentence: "This checkout is ahead of the tracked branch.", nextStep: "Push, then run kodingo deep-scan again." };
299
+ if (reason === "diverged")
300
+ return { sentence: "This checkout has diverged from the tracked branch.", nextStep: "Reconcile the branch, then run kodingo deep-scan again." };
301
+ if (reason === "branch_not_tracked" || reason === "branch_untracked")
302
+ return { sentence: "This branch is not tracked.", nextStep: "Run kodingo init to record a tracked branch." };
262
303
  if (reason === "detached_head")
263
304
  return { sentence: "This checkout is in detached HEAD state.", nextStep: "Check out a branch, then scan again." };
264
305
  if (reason === "branch_unknown")
265
306
  return { sentence: "The CLI could not determine the current branch.", nextStep: "Check out a named branch, then scan again." };
266
307
  if (reason === "stale_full_tree")
267
308
  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." };
309
+ if (reason === "unknown_commit")
310
+ return { sentence: "This scan's commit isn't on GitHub.", nextStep: "Push it and run `kodingo init --force`." };
268
311
  const mismatch = /^branch_mismatch:([^:]*):(.*)$/.exec(reason);
269
312
  if (mismatch) {
270
313
  const [, scanned, tracked] = mismatch;
@@ -272,8 +315,23 @@ function describeApplyReason(reason) {
272
315
  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
316
  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
317
  }
275
- return { sentence: `The scan was held (${reason}).`, nextStep: "Run `kodingo deep-scan-status` for more detail." };
318
+ const staleCommit = /^stale_commit:(\d+)$/.exec(reason);
319
+ if (staleCommit) {
320
+ const behind = staleCommit[1];
321
+ return { sentence: `This scan is ${behind} commit${behind === "1" ? "" : "s"} behind GitHub.`, nextStep: "Pull and run `kodingo init --force`." };
322
+ }
323
+ const deleteCapExceeded = /^delete_cap_exceeded:(\d+):([\d.]+)$/.exec(reason);
324
+ if (deleteCapExceeded) {
325
+ const entities = deleteCapExceeded[1];
326
+ const sharePct = Math.round(Number(deleteCapExceeded[2]) * 100);
327
+ return {
328
+ sentence: `This full-tree scan would have deleted ${entities} entities (${sharePct}% of what's stored), so it was held as a safety precaution.`,
329
+ nextStep: "An org admin must approve it; re-scanning won't resolve it.",
330
+ };
331
+ }
332
+ return { sentence: `The scan was held (${reason}).`, nextStep: "Run kodingo deep-scan-status for details." };
276
333
  }
334
+ function scanReason(value) { return value?.reason ?? value?.applyReason ?? value?.apply_reason ?? null; }
277
335
  /** Pure so the "accurate" wording regression (165 read vs N uploaded vs M
278
336
  * already known) can be unit-tested without a network call. */
279
337
  function buildUploadSummary(readLocally, willUpload, alreadyKnown, evidenceSummary) {
@@ -359,6 +417,98 @@ async function askYesNo(question) {
359
417
  rl.close();
360
418
  }
361
419
  }
420
+ /** Same shape as askYesNo, but defaults to "no" on an empty answer — used
421
+ * where silently guessing "yes" would risk reading a checkout Kortex can't
422
+ * actually verify is current. */
423
+ async function askYesNoDefaultNo(question) {
424
+ if (!process.stdin.isTTY)
425
+ return false;
426
+ const rl = promises_1.default.createInterface({ input: node_process_1.stdin, output: node_process_1.stdout });
427
+ try {
428
+ const answer = (await rl.question(question)).trim();
429
+ return /^y(?:es)?$/i.test(answer);
430
+ }
431
+ finally {
432
+ rl.close();
433
+ }
434
+ }
435
+ function describeFreshnessFetchFailure(err) {
436
+ if (err && (err.killed || err.signal))
437
+ return "git fetch timed out after 15s";
438
+ const raw = (err?.stderr ? err.stderr.toString() : "") || (err?.message ? String(err.message) : "");
439
+ const firstLine = raw.split(/\r?\n/).map((line) => line.trim()).find((line) => line.length > 0);
440
+ return firstLine || "git fetch failed";
441
+ }
442
+ /** Fetches origin/<branch> fresh (quiet, no tags, bounded to 15s so a dead
443
+ * remote never hangs a scan) and compares HEAD against it. Never guesses —
444
+ * any failure (no origin, offline, auth, an unparseable result) comes back
445
+ * as "unknown" with the reason, for the caller to decide how to handle. */
446
+ function checkCheckoutFreshness(root, branch) {
447
+ try {
448
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "fetch", "--quiet", "--no-tags", "origin", branch], { timeout: 15000, stdio: ["ignore", "pipe", "pipe"] });
449
+ }
450
+ catch (err) {
451
+ return { outcome: "unknown", reason: describeFreshnessFetchFailure(err) };
452
+ }
453
+ let counts;
454
+ try {
455
+ counts = git(root, ["rev-list", "--left-right", "--count", `HEAD...origin/${branch}`]);
456
+ }
457
+ catch (err) {
458
+ return { outcome: "unknown", reason: describeFreshnessFetchFailure(err) };
459
+ }
460
+ const match = counts.match(/^(\d+)\s+(\d+)$/);
461
+ if (!match)
462
+ return { outcome: "unknown", reason: `unexpected git output comparing against origin/${branch}` };
463
+ const ahead = Number(match[1]);
464
+ const behind = Number(match[2]);
465
+ if (ahead === 0 && behind === 0)
466
+ return { outcome: "up-to-date", shortSha: git(root, ["rev-parse", "--short", "HEAD"]) };
467
+ if (ahead === 0)
468
+ return { outcome: "behind", behind };
469
+ if (behind === 0)
470
+ return { outcome: "ahead", ahead };
471
+ return { outcome: "diverged", ahead, behind };
472
+ }
473
+ /** The pure "what to do about a stale checkout" decision — separated from
474
+ * the fetch/compare and the interactive prompt so every rule (refuse full
475
+ * scans of outdated code, warn-only for --dry-run since it uploads nothing,
476
+ * never guess on an undetermined result) is directly unit-testable. */
477
+ function decideFreshnessAction(params) {
478
+ const { check, branch, dryRun, yes, promptAnswerYes } = params;
479
+ if (check.outcome === "up-to-date") {
480
+ return { action: "proceed", note: `Reading ${branch} at ${check.shortSha}, up to date with origin/${branch}.` };
481
+ }
482
+ if (check.outcome === "unknown") {
483
+ const base = `Couldn't check whether this checkout is up to date (${check.reason}).`;
484
+ if (dryRun)
485
+ return { action: "warn", message: base };
486
+ if (yes)
487
+ return { action: "refuse", message: `${base} Refusing to guess under --yes.` };
488
+ if (promptAnswerYes)
489
+ return { action: "proceed" };
490
+ return { action: "refuse", message: base };
491
+ }
492
+ const message = check.outcome === "behind"
493
+ ? `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.`
494
+ : check.outcome === "ahead"
495
+ ? `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.`
496
+ : `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.`;
497
+ return dryRun ? { action: "warn", message } : { action: "refuse", message };
498
+ }
499
+ /** Full-tree scans only (init's first scan, and `kodingo deep-scan` without
500
+ * --changed) — never the commit hook, which always invokes --changed on
501
+ * normal, possibly-unpushed local commits. Runs a real `git fetch` against
502
+ * origin before anything is read, so a checkout behind origin never gets a
503
+ * chance to replace newer stored data with older code. */
504
+ async function enforceCheckoutFreshness(opts) {
505
+ const check = checkCheckoutFreshness(opts.root, opts.branch);
506
+ let promptAnswerYes;
507
+ if (check.outcome === "unknown" && !opts.dryRun && !opts.yes) {
508
+ promptAnswerYes = await askYesNoDefaultNo(`Couldn't check whether this checkout is up to date (${check.reason}). Continue anyway? [y/N] `);
509
+ }
510
+ return decideFreshnessAction({ check, branch: opts.branch, dryRun: opts.dryRun, yes: opts.yes, promptAnswerYes });
511
+ }
362
512
  /** Settles the project's tracked development branch against the current
363
513
  * checkout via POST /deep-scan/branch/settle, before anything is uploaded —
364
514
  * so a first scan can apply instead of landing held with no explanation. */
@@ -403,7 +553,12 @@ function printFinalOutcome(run, yes) {
403
553
  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
554
  return;
405
555
  }
406
- const { sentence, nextStep } = describeApplyReason(run.apply_reason ?? run.reason ?? null);
556
+ const reason = scanReason(run);
557
+ if (!reason) {
558
+ console.log("The server is still processing this scan. Run `kodingo deep-scan-status` in a minute.");
559
+ return;
560
+ }
561
+ const { sentence, nextStep } = describeApplyReason(reason);
407
562
  console.log(`Deep scan held: ${sentence}${nextStep ? ` ${nextStep}` : ""}`);
408
563
  if (yes)
409
564
  process.exitCode = 1;
@@ -610,8 +765,9 @@ function renderScanStatus(status) {
610
765
  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
766
  }
612
767
  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}` : ""}`);
768
+ const reason = scanReason(cli);
769
+ const { sentence, nextStep } = describeApplyReason(reason);
770
+ lines.push(`Last local scan: commit ${String(cli.commitSha).slice(0, 12)} at ${when} — ${reason ? "held" : "processing"} (${cli.entityCount} entities). ${sentence}${nextStep ? ` ${nextStep}` : ""}`);
615
771
  }
616
772
  }
617
773
  else {
@@ -634,6 +790,8 @@ function renderScanStatus(status) {
634
790
  function describeLastUploadStatus(state) {
635
791
  if (!state || state.applied !== false)
636
792
  return null;
793
+ if (!state.reason)
794
+ return "Your last commit upload is still processing. Run `kodingo deep-scan-status` in a minute.";
637
795
  const { sentence } = describeApplyReason(state.reason);
638
796
  return `Your last commit upload was held: ${sentence}`;
639
797
  }
@@ -690,6 +848,21 @@ async function deepScanCommand(options = {}) {
690
848
  const token = envToken || credentials.token;
691
849
  if (!token)
692
850
  throw new Error("No project token found. Run `kodingo init` once, or set KODINGO_TOKEN for CI.");
851
+ // Kortex must never read, scan, or upload a checkout whose HEAD is stale
852
+ // relative to origin — a clean checkout behind origin would otherwise
853
+ // apply and could silently replace newer stored data with older code.
854
+ // Full-tree scans only (never --changed, which the hook always passes for
855
+ // normal, possibly-unpushed local commits); detached HEAD has no branch to
856
+ // compare against origin and is already never applied regardless.
857
+ if (!options.changed && meta.branch && !meta.detachedHead) {
858
+ const freshness = await enforceCheckoutFreshness({ root: meta.root, branch: meta.branch, dryRun: Boolean(options.dryRun), yes: Boolean(options.yes) });
859
+ if (freshness.action === "refuse")
860
+ throw new Error(freshness.message);
861
+ if (freshness.action === "warn")
862
+ console.warn(`⚠ ${freshness.message}`);
863
+ if (freshness.action === "proceed" && freshness.note)
864
+ console.log(freshness.note);
865
+ }
693
866
  // The commit hook invokes `deep-scan --changed` unconditionally, on every
694
867
  // commit, regardless of branch — upload only for a commit on the tracked
695
868
  // branch, per a confirmed mismatch (never on "none": there's nothing to
@@ -873,6 +1046,6 @@ async function deepScanCommand(options = {}) {
873
1046
  // otherwise-silent (stdout redirected to /dev/null) held upload surface
874
1047
  // via `kodingo deep-scan-status` instead of vanishing with no visible
875
1048
  // 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");
1049
+ 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: scanReason(run) }, null, 2), "utf8");
877
1050
  printFinalOutcome(run, options.yes);
878
1051
  }