kodingo-cli 1.4.2 → 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.
@@ -272,7 +272,7 @@ const repository = "validation-org/validation-repo";
272
272
  lastCliScan: { commitSha: "c".repeat(40), applied: false, reason: "dirty_checkout", entityCount: 0, edgeCount: 0, fileCount: 0, completedAt: "2026-11-03T02:00:00.000Z" },
273
273
  lastGithubScan: null,
274
274
  });
275
- strict_1.default.match(lines[1], /^Last local scan: commit c{12} at 2026-11-03T02:00:00\.000Z — held\. Your working tree has uncommitted changes\./);
275
+ strict_1.default.match(lines[1], /^Last local scan: commit c{12} at 2026-11-03T02:00:00\.000Z — held \(0 entities\)\. Your working tree has uncommitted changes\./);
276
276
  });
277
277
  });
278
278
  (0, node_test_1.describe)("shouldSkipIncrementalScan", () => {
@@ -0,0 +1,243 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ /** Invented, local fixtures for CLI configuration and scan outcomes. */
40
+ const strict_1 = __importDefault(require("node:assert/strict"));
41
+ const node_fs_1 = __importDefault(require("node:fs"));
42
+ const node_path_1 = __importDefault(require("node:path"));
43
+ const node_child_process_1 = require("node:child_process");
44
+ const node_test_1 = require("node:test");
45
+ const persistence_config_1 = require("../utils/persistence-config");
46
+ function fixture(run) {
47
+ const root = node_fs_1.default.mkdtempSync(node_path_1.default.join(process.cwd(), ".cli-fixture-"));
48
+ try {
49
+ run(root);
50
+ }
51
+ finally {
52
+ node_fs_1.default.rmSync(root, { recursive: true, force: true });
53
+ }
54
+ }
55
+ function config(workspaces) {
56
+ return { mode: "cloud", apiUrl: "https://example.invalid", workspaces };
57
+ }
58
+ function git(root, ...args) {
59
+ return (0, node_child_process_1.execFileSync)("git", ["-C", root, ...args], { encoding: "utf8" }).trim();
60
+ }
61
+ function repo(run) {
62
+ fixture(root => {
63
+ git(root, "init", "-q");
64
+ git(root, "config", "user.name", "Fixture");
65
+ git(root, "config", "user.email", "fixture@example.invalid");
66
+ node_fs_1.default.writeFileSync(node_path_1.default.join(root, "source.ts"), "export const value = 1;\n");
67
+ git(root, "add", "source.ts");
68
+ git(root, "commit", "-qm", "fixture");
69
+ run(root);
70
+ });
71
+ }
72
+ (0, node_test_1.describe)("nearest workspace lookup", () => {
73
+ const cases = [
74
+ ["capitalized path", "Project", "Project"],
75
+ ["case folded path", "Project", "project"],
76
+ ["trailing slash", "Project/", "Project"],
77
+ ["backslash key", "Project\\Nested", "Project/Nested"],
78
+ ["parent directory", "Project", "Project/Nested"],
79
+ ["deep parent directory", "Project", "Project/Nested/Deep"],
80
+ ["nested entry", "Project/Nested", "Project/Nested/Deep"],
81
+ ["case folded nested", "PROJECT/NESTED", "Project/Nested/Deep"],
82
+ ["trailing slash nested", "Project/Nested/", "Project/Nested/Deep"],
83
+ ["mixed slash and case", "PROJECT\\NESTED\\", "Project/Nested/Deep"],
84
+ ];
85
+ for (const [label, key, cwd] of cases)
86
+ (0, node_test_1.it)(label, () => fixture(root => {
87
+ const keyPath = node_path_1.default.join(root, key);
88
+ const ws = config({ [keyPath]: { mode: "cloud", token: "fixture-token" } });
89
+ strict_1.default.equal((0, persistence_config_1.findWorkspaceEntry)(node_path_1.default.join(root, cwd), ws)?.token, "fixture-token");
90
+ strict_1.default.deepEqual(Object.keys(ws.workspaces), [keyPath]);
91
+ }));
92
+ (0, node_test_1.it)("nearest entry wins", () => fixture(root => {
93
+ const ws = config({ [node_path_1.default.join(root, "Project")]: { mode: "cloud", token: "parent" }, [node_path_1.default.join(root, "Project/Nested")]: { mode: "cloud", token: "nested" } });
94
+ strict_1.default.equal((0, persistence_config_1.findWorkspaceEntry)(node_path_1.default.join(root, "Project/Nested/Deep"), ws)?.token, "nested");
95
+ }));
96
+ (0, node_test_1.it)("no match returns null", () => fixture(root => {
97
+ strict_1.default.equal((0, persistence_config_1.findWorkspaceEntry)(node_path_1.default.join(root, "Other"), config({ [node_path_1.default.join(root, "Project")]: { mode: "cloud", token: "fixture" } })), null);
98
+ }));
99
+ (0, node_test_1.it)("symlink resolves to registered path", () => fixture(root => {
100
+ const target = node_path_1.default.join(root, "Target");
101
+ node_fs_1.default.mkdirSync(target);
102
+ node_fs_1.default.symlinkSync(target, node_path_1.default.join(root, "Alias"));
103
+ strict_1.default.equal((0, persistence_config_1.findWorkspaceEntry)(node_path_1.default.join(root, "Alias"), config({ [target]: { mode: "cloud", token: "fixture" } }))?.token, "fixture");
104
+ }));
105
+ (0, node_test_1.it)("registered symlink resolves to actual path", () => fixture(root => {
106
+ const target = node_path_1.default.join(root, "Target");
107
+ node_fs_1.default.mkdirSync(target);
108
+ const alias = node_path_1.default.join(root, "Alias");
109
+ node_fs_1.default.symlinkSync(target, alias);
110
+ strict_1.default.equal((0, persistence_config_1.findWorkspaceEntry)(target, config({ [alias]: { mode: "cloud", token: "fixture" } }))?.token, "fixture");
111
+ }));
112
+ });
113
+ (0, node_test_1.describe)("configuration file safety", () => {
114
+ (0, node_test_1.it)("writes a private directory and file atomically", { skip: process.platform === "win32" }, () => fixture(root => {
115
+ const script = `const c=require(${JSON.stringify(node_path_1.default.resolve("dist/utils/persistence-config.js"))}); c.writeConfig({mode:"cloud",apiUrl:"https://example.invalid"});`;
116
+ (0, node_child_process_1.execFileSync)(process.execPath, ["-e", script], { env: { ...process.env, HOME: root } });
117
+ const dir = node_path_1.default.join(root, ".kodingo");
118
+ strict_1.default.equal(node_fs_1.default.statSync(dir).mode & 0o077, 0);
119
+ strict_1.default.equal(node_fs_1.default.statSync(node_path_1.default.join(dir, "config.json")).mode & 0o077, 0);
120
+ strict_1.default.deepEqual(node_fs_1.default.readdirSync(dir), ["config.json"]);
121
+ }));
122
+ (0, node_test_1.it)("tightens old permissions and warns once", { skip: process.platform === "win32" }, () => fixture(root => {
123
+ const dir = node_path_1.default.join(root, ".kodingo");
124
+ node_fs_1.default.mkdirSync(dir, { mode: 0o755 });
125
+ node_fs_1.default.writeFileSync(node_path_1.default.join(dir, "config.json"), '{"mode":"cloud"}', { mode: 0o644 });
126
+ const script = `const c=require(${JSON.stringify(node_path_1.default.resolve("dist/utils/persistence-config.js"))}); c.readConfig(); c.readConfig();`;
127
+ const { spawnSync } = require("node:child_process");
128
+ const result = spawnSync(process.execPath, ["-e", script], { env: { ...process.env, HOME: root }, encoding: "utf8" });
129
+ strict_1.default.equal(result.status, 0);
130
+ strict_1.default.equal(result.stderr.trim().split("\n").length, 1);
131
+ strict_1.default.equal(node_fs_1.default.statSync(dir).mode & 0o077, 0);
132
+ strict_1.default.equal(node_fs_1.default.statSync(node_path_1.default.join(dir, "config.json")).mode & 0o077, 0);
133
+ }));
134
+ });
135
+ (0, node_test_1.describe)("cloud text query", () => {
136
+ (0, node_test_1.it)("sends q and repo without a proposed-only filter", async () => {
137
+ const original = global.fetch;
138
+ const token = process.env.KODINGO_API_TOKEN;
139
+ const url = process.env.KODINGO_API_URL;
140
+ process.env.KODINGO_API_TOKEN = "fixture-token";
141
+ process.env.KODINGO_API_URL = "https://example.invalid";
142
+ let requested = "";
143
+ global.fetch = (async (input) => { requested = input; return { ok: true, status: 200, json: async () => ({ data: [] }) }; });
144
+ try {
145
+ const cloud = await Promise.resolve().then(() => __importStar(require("../adapters/cloud-adapter/cloud-persistence")));
146
+ strict_1.default.deepEqual(await cloud.queryMemory("invoice", 10, "/Fixture/Repo"), []);
147
+ strict_1.default.match(requested, /q=invoice/);
148
+ strict_1.default.match(requested, /repo=Repo/);
149
+ strict_1.default.doesNotMatch(requested, /status=proposed/);
150
+ }
151
+ finally {
152
+ global.fetch = original;
153
+ if (token === undefined)
154
+ delete process.env.KODINGO_API_TOKEN;
155
+ else
156
+ process.env.KODINGO_API_TOKEN = token;
157
+ if (url === undefined)
158
+ delete process.env.KODINGO_API_URL;
159
+ else
160
+ process.env.KODINGO_API_URL = url;
161
+ }
162
+ });
163
+ (0, node_test_1.it)("propagates authentication errors", async () => {
164
+ const original = global.fetch;
165
+ const token = process.env.KODINGO_API_TOKEN;
166
+ const url = process.env.KODINGO_API_URL;
167
+ process.env.KODINGO_API_TOKEN = "fixture-token";
168
+ process.env.KODINGO_API_URL = "https://example.invalid";
169
+ global.fetch = (async () => ({ ok: false, status: 401, text: async () => "Unauthorized" }));
170
+ try {
171
+ const cloud = await Promise.resolve().then(() => __importStar(require("../adapters/cloud-adapter/cloud-persistence")));
172
+ await strict_1.default.rejects(cloud.queryMemory("invoice"), /401.*Unauthorized/);
173
+ }
174
+ finally {
175
+ global.fetch = original;
176
+ if (token === undefined)
177
+ delete process.env.KODINGO_API_TOKEN;
178
+ else
179
+ process.env.KODINGO_API_TOKEN = token;
180
+ if (url === undefined)
181
+ delete process.env.KODINGO_API_URL;
182
+ else
183
+ process.env.KODINGO_API_URL = url;
184
+ }
185
+ });
186
+ });
187
+ (0, node_test_1.describe)("query-memory command output", () => {
188
+ for (const [label, response, expected] of [
189
+ ["empty successful search", "{ok:true,status:200,json:async()=>({data:[]})}", 'No results for "invoice" in this project.'],
190
+ ["authentication failure", "{ok:false,status:401,text:async()=>\"Unauthorized\"}", "kodingo-api error 401: Unauthorized"],
191
+ ])
192
+ (0, node_test_1.it)(label, () => fixture(root => {
193
+ const { spawnSync } = require("node:child_process");
194
+ const cfg = node_path_1.default.join(root, ".kodingo");
195
+ node_fs_1.default.mkdirSync(cfg, { mode: 0o700 });
196
+ node_fs_1.default.writeFileSync(node_path_1.default.join(cfg, "config.json"), JSON.stringify({ mode: "cloud", apiUrl: "https://example.invalid", token: "fixture-token" }), { mode: 0o600 });
197
+ const script = `global.fetch=async()=>(${response});require(${JSON.stringify(node_path_1.default.resolve("dist/commands/query-memory.js"))}).queryMemoryCommand("invoice",{limit:10}).catch(e=>{console.error(e.message);process.exitCode=1})`;
198
+ const result = spawnSync(process.execPath, ["-e", script], { cwd: root, env: { ...process.env, HOME: root }, encoding: "utf8" });
199
+ strict_1.default.match(result.stdout + result.stderr, new RegExp(expected.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")));
200
+ strict_1.default.equal(result.status, label === "authentication failure" ? 1 : 0);
201
+ }));
202
+ });
203
+ (0, node_test_1.describe)("doctor workspace credentials", () => {
204
+ for (const hasWorkspace of [false, true])
205
+ (0, node_test_1.it)(hasWorkspace ? "validates the folder token" : "reports a missing folder token", () => fixture(root => {
206
+ const { spawnSync } = require("node:child_process");
207
+ const project = node_path_1.default.join(root, "Project");
208
+ node_fs_1.default.mkdirSync(project);
209
+ const cfg = node_path_1.default.join(root, ".kodingo");
210
+ node_fs_1.default.mkdirSync(cfg, { mode: 0o700 });
211
+ const workspaces = hasWorkspace ? { [project]: { mode: "cloud", apiUrl: "https://example.invalid", token: "folder-token" } } : {};
212
+ node_fs_1.default.writeFileSync(node_path_1.default.join(cfg, "config.json"), JSON.stringify({ mode: "cloud", apiUrl: "https://example.invalid", workspaces }), { mode: 0o600 });
213
+ const script = `global.fetch=async(url,init)=>{if(url.endsWith('/health'))return {ok:true,status:200};if(url.includes('/memory')){if(init?.method==='POST')return {ok:true,status:200,json:async()=>({id:'fixture-id'})};if(init?.method==='DELETE')return {ok:true,status:204};return {ok:true,status:200,json:async()=>({data:[{id:'fixture-id',createdAt:'2026-01-01',updatedAt:'2026-01-01',status:'proposed',confidence:0.5}]})}}throw Error(url)};require(${JSON.stringify(node_path_1.default.resolve("dist/commands/doctor.js"))}).doctorCommand().catch(e=>{console.error(e.message);process.exitCode=1})`;
214
+ const result = spawnSync(process.execPath, ["-e", script], { cwd: project, env: { ...process.env, HOME: root }, encoding: "utf8" });
215
+ if (hasWorkspace) {
216
+ strict_1.default.match(result.stdout, /OK: KODINGO_API_TOKEN is configured/);
217
+ strict_1.default.match(result.stdout, /OK: kodingo-api token valid/);
218
+ }
219
+ else
220
+ strict_1.default.match(result.stdout, /No project token for this folder\. Run kodingo init here\./);
221
+ }));
222
+ });
223
+ (0, node_test_1.describe)("credential fallback", () => {
224
+ for (const globalToken of [undefined, "legacy-token"])
225
+ (0, node_test_1.it)(globalToken ? "uses top-level token if no workspace matches" : "returns no token if nothing matches", () => fixture(root => {
226
+ const { spawnSync } = require("node:child_process");
227
+ const cfg = node_path_1.default.join(root, ".kodingo");
228
+ node_fs_1.default.mkdirSync(cfg, { mode: 0o700 });
229
+ node_fs_1.default.writeFileSync(node_path_1.default.join(cfg, "config.json"), JSON.stringify({ mode: "cloud", apiUrl: "https://example.invalid", token: globalToken, workspaces: { [node_path_1.default.join(root, "Other")]: { mode: "cloud", token: "other" } } }), { mode: 0o600 });
230
+ const script = `console.log(JSON.stringify(require(${JSON.stringify(node_path_1.default.resolve("dist/utils/persistence-config.js"))}).getCredentials(process.cwd())))`;
231
+ const result = spawnSync(process.execPath, ["-e", script], { cwd: root, env: { ...process.env, HOME: root }, encoding: "utf8" });
232
+ strict_1.default.equal(result.status, 0);
233
+ strict_1.default.equal(JSON.parse(result.stdout).token, globalToken ?? "");
234
+ }));
235
+ (0, node_test_1.it)("writeWorkspaceConfig preserves the original key", () => fixture(root => {
236
+ const { spawnSync } = require("node:child_process");
237
+ const key = node_path_1.default.join(root, "Project");
238
+ const script = `const c=require(${JSON.stringify(node_path_1.default.resolve("dist/utils/persistence-config.js"))});c.writeWorkspaceConfig(${JSON.stringify(key)},{mode:"cloud",token:"fixture"});console.log(JSON.stringify(Object.keys(c.readConfig().workspaces)))`;
239
+ const result = spawnSync(process.execPath, ["-e", script], { cwd: root, env: { ...process.env, HOME: root }, encoding: "utf8" });
240
+ strict_1.default.equal(result.status, 0);
241
+ strict_1.default.deepEqual(JSON.parse(result.stdout), [key]);
242
+ }));
243
+ });
@@ -0,0 +1,117 @@
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 for scan and checkout behavior. */
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 deep_scan_1 = require("../commands/deep-scan");
13
+ const init_1 = require("../commands/init");
14
+ function fixture(run) {
15
+ const root = node_fs_1.default.mkdtempSync(node_path_1.default.join(process.cwd(), ".cli-fixture-"));
16
+ try {
17
+ run(root);
18
+ }
19
+ finally {
20
+ node_fs_1.default.rmSync(root, { recursive: true, force: true });
21
+ }
22
+ }
23
+ function git(root, ...args) {
24
+ return (0, node_child_process_1.execFileSync)("git", ["-C", root, ...args], { encoding: "utf8" }).trim();
25
+ }
26
+ function repo(run) {
27
+ fixture(root => {
28
+ git(root, "init", "-q");
29
+ git(root, "config", "user.name", "Fixture");
30
+ git(root, "config", "user.email", "fixture@example.invalid");
31
+ node_fs_1.default.writeFileSync(node_path_1.default.join(root, "source.ts"), "export const value = 1;\n");
32
+ git(root, "add", "source.ts");
33
+ git(root, "commit", "-qm", "fixture");
34
+ run(root);
35
+ });
36
+ }
37
+ (0, node_test_1.describe)("apply reason wording", () => {
38
+ for (const [reason, fragment] of [
39
+ ["dirty_checkout", "Commit or stash them"],
40
+ ["unverifiable_commit", "right owner"],
41
+ ["behind", "Pull"],
42
+ ["ahead", "Push"],
43
+ ["diverged", "Reconcile"],
44
+ ["branch_not_tracked", "kodingo init"],
45
+ ["branch_untracked", "kodingo init"],
46
+ ["detached_head", "Check out a branch"],
47
+ ["custom_code", "custom_code"],
48
+ ])
49
+ (0, node_test_1.it)(reason, () => {
50
+ const result = (0, deep_scan_1.describeApplyReason)(reason);
51
+ strict_1.default.match(result.sentence + result.nextStep, new RegExp(fragment));
52
+ strict_1.default.doesNotMatch(result.sentence, /unknown reason/);
53
+ });
54
+ (0, node_test_1.it)("missing reason means processing", () => {
55
+ strict_1.default.match((0, deep_scan_1.describeApplyReason)(null).sentence, /still processing/);
56
+ });
57
+ for (const field of ["reason", "applyReason", "apply_reason"])
58
+ (0, node_test_1.it)(`outcome uses ${field}`, () => {
59
+ const lines = [];
60
+ const old = console.log;
61
+ const exit = process.exitCode;
62
+ console.log = (...parts) => lines.push(parts.join(" "));
63
+ try {
64
+ (0, deep_scan_1.printFinalOutcome)({ applied: false, [field]: "dirty_checkout" }, false);
65
+ }
66
+ finally {
67
+ console.log = old;
68
+ process.exitCode = exit;
69
+ }
70
+ strict_1.default.match(lines.join(" "), /uncommitted changes/);
71
+ });
72
+ (0, node_test_1.it)("outcome without reason says processing", () => {
73
+ const lines = [];
74
+ const old = console.log;
75
+ const exit = process.exitCode;
76
+ console.log = (...parts) => lines.push(parts.join(" "));
77
+ try {
78
+ (0, deep_scan_1.printFinalOutcome)({ applied: false, state: "processing" }, true);
79
+ }
80
+ finally {
81
+ console.log = old;
82
+ process.exitCode = exit;
83
+ }
84
+ strict_1.default.match(lines.join(" "), /still processing/);
85
+ });
86
+ (0, node_test_1.it)("status includes processing, commit and count", () => {
87
+ const lines = (0, deep_scan_1.renderScanStatus)({ lastCliScan: { commitSha: "a".repeat(40), applied: false, reason: null, entityCount: 7, edgeCount: 0, fileCount: 0, completedAt: null } });
88
+ strict_1.default.match(lines.join(" "), /processing \(7 entities\)/);
89
+ strict_1.default.match(lines.join(" "), /aaaaaaaaaaaa/);
90
+ });
91
+ });
92
+ (0, node_test_1.describe)("local checkout hygiene", () => {
93
+ (0, node_test_1.it)("local exclude leaves worktree and index clean", () => repo(root => {
94
+ (0, init_1.ensureLocalExclude)(root, ".kortex/");
95
+ strict_1.default.equal(git(root, "status", "--porcelain"), "");
96
+ strict_1.default.match(node_fs_1.default.readFileSync(node_path_1.default.join(root, ".git/info/exclude"), "utf8"), /\.kortex\//);
97
+ }));
98
+ (0, node_test_1.it)("local exclude is idempotent", () => repo(root => {
99
+ (0, init_1.ensureLocalExclude)(root, ".kortex/");
100
+ (0, init_1.ensureLocalExclude)(root, ".kortex/");
101
+ strict_1.default.equal(node_fs_1.default.readFileSync(node_path_1.default.join(root, ".git/info/exclude"), "utf8").split(".kortex/").length, 2);
102
+ }));
103
+ (0, node_test_1.it)("staged Kortex ignore lines are clean", () => repo(root => {
104
+ node_fs_1.default.writeFileSync(node_path_1.default.join(root, ".gitignore"), "# Kortex\n.kortex/\n");
105
+ git(root, "add", ".gitignore");
106
+ strict_1.default.equal((0, deep_scan_1.isDirtyCheckout)(root), false);
107
+ }));
108
+ (0, node_test_1.it)("real source modification is dirty", () => repo(root => {
109
+ node_fs_1.default.writeFileSync(node_path_1.default.join(root, "source.ts"), "export const value = 2;\n");
110
+ strict_1.default.equal((0, deep_scan_1.isDirtyCheckout)(root), true);
111
+ }));
112
+ (0, node_test_1.it)("untracked generated folder is clean", () => repo(root => {
113
+ node_fs_1.default.mkdirSync(node_path_1.default.join(root, ".kortex"));
114
+ node_fs_1.default.writeFileSync(node_path_1.default.join(root, ".kortex/state.json"), "{}");
115
+ strict_1.default.equal((0, deep_scan_1.isDirtyCheckout)(root), false);
116
+ }));
117
+ });
@@ -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;
@@ -153,11 +154,38 @@ function resolveGitMetadata(start) {
153
154
  catch {
154
155
  return null;
155
156
  } })();
156
- const dirty = git(root, ["status", "--porcelain"]).length > 0;
157
+ const dirty = isDirtyCheckout(root);
157
158
  const remote = git(root, ["remote", "get-url", "origin"]);
158
159
  const shallow = git(root, ["rev-parse", "--is-shallow-repository"]) === "true";
159
160
  return { root, commitSha, branch, detachedHead: branch === null, dirty, remote, repository: normalizeRemote(remote), shallow };
160
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
+ }
161
189
  /** The remote's default branch. Tries the fast, local, offline read first
162
190
  * (refs/remotes/origin/HEAD — only set once something has told the local
163
191
  * clone what the remote's HEAD is, e.g. `git clone` or `git remote set-head`;
@@ -257,11 +285,21 @@ function describeApiError(body, status) {
257
285
  * applied) scan to a plain-English sentence and the exact next step. */
258
286
  function describeApplyReason(reason) {
259
287
  if (!reason)
260
- 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." };
261
289
  if (reason === "clean_tracked_branch")
262
290
  return { sentence: "Applied.", nextStep: "" };
263
291
  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." };
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." };
265
303
  if (reason === "detached_head")
266
304
  return { sentence: "This checkout is in detached HEAD state.", nextStep: "Check out a branch, then scan again." };
267
305
  if (reason === "branch_unknown")
@@ -291,8 +329,9 @@ function describeApplyReason(reason) {
291
329
  nextStep: "An org admin must approve it; re-scanning won't resolve it.",
292
330
  };
293
331
  }
294
- return { sentence: `The scan was held (${reason}).`, nextStep: "Run `kodingo deep-scan-status` for more detail." };
332
+ return { sentence: `The scan was held (${reason}).`, nextStep: "Run kodingo deep-scan-status for details." };
295
333
  }
334
+ function scanReason(value) { return value?.reason ?? value?.applyReason ?? value?.apply_reason ?? null; }
296
335
  /** Pure so the "accurate" wording regression (165 read vs N uploaded vs M
297
336
  * already known) can be unit-tested without a network call. */
298
337
  function buildUploadSummary(readLocally, willUpload, alreadyKnown, evidenceSummary) {
@@ -514,7 +553,12 @@ function printFinalOutcome(run, yes) {
514
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.`);
515
554
  return;
516
555
  }
517
- 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);
518
562
  console.log(`Deep scan held: ${sentence}${nextStep ? ` ${nextStep}` : ""}`);
519
563
  if (yes)
520
564
  process.exitCode = 1;
@@ -721,8 +765,9 @@ function renderScanStatus(status) {
721
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).`);
722
766
  }
723
767
  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}` : ""}`);
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}` : ""}`);
726
771
  }
727
772
  }
728
773
  else {
@@ -745,6 +790,8 @@ function renderScanStatus(status) {
745
790
  function describeLastUploadStatus(state) {
746
791
  if (!state || state.applied !== false)
747
792
  return null;
793
+ if (!state.reason)
794
+ return "Your last commit upload is still processing. Run `kodingo deep-scan-status` in a minute.";
748
795
  const { sentence } = describeApplyReason(state.reason);
749
796
  return `Your last commit upload was held: ${sentence}`;
750
797
  }
@@ -999,6 +1046,6 @@ async function deepScanCommand(options = {}) {
999
1046
  // otherwise-silent (stdout redirected to /dev/null) held upload surface
1000
1047
  // via `kodingo deep-scan-status` instead of vanishing with no visible
1001
1048
  // 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");
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");
1003
1050
  printFinalOutcome(run, options.yes);
1004
1051
  }
@@ -37,8 +37,13 @@ async function doctorCommand() {
37
37
  process.exitCode = 1;
38
38
  }
39
39
  async function runDoctor(results) {
40
- const { initDb, saveMemory, queryMemory } = (0, persistence_config_1.getPersistence)();
41
40
  const cloudMode = (0, persistence_config_1.isCloudMode)();
41
+ const credentials = (0, persistence_config_1.getCredentials)(process.cwd());
42
+ if (cloudMode && !credentials.token) {
43
+ results.push({ name: "Project token", ok: false, error: "No project token for this folder. Run kodingo init here." });
44
+ return null;
45
+ }
46
+ const { initDb, saveMemory, queryMemory } = (0, persistence_config_1.getPersistence)();
42
47
  // ── Mode-specific connectivity checks ──────────────────────────────────────
43
48
  if (cloudMode) {
44
49
  await runCloudChecks(results);
@@ -104,28 +109,28 @@ async function runLocalChecks(results) {
104
109
  }
105
110
  // ── Cloud mode checks ─────────────────────────────────────────────────────────
106
111
  async function runCloudChecks(results) {
107
- const config = (0, persistence_config_1.readConfig)();
112
+ const credentials = (0, persistence_config_1.getCredentials)(process.cwd());
108
113
  await runStep("KODINGO_API_URL is configured", async () => {
109
- if (!config.apiUrl) {
114
+ if (!credentials.apiUrl) {
110
115
  throw new Error("apiUrl is not set in ~/.kodingo/config.json");
111
116
  }
112
117
  }, results);
113
118
  await runStep("KODINGO_API_TOKEN is configured", async () => {
114
- if (!config.token) {
115
- throw new Error("token is not set in ~/.kodingo/config.json");
119
+ if (!credentials.token) {
120
+ throw new Error("No project token for this folder. Run kodingo init here.");
116
121
  }
117
122
  }, results);
118
123
  await runStep("kodingo-api reachable", async () => {
119
- const apiUrl = config.apiUrl.replace(/\/$/, "");
124
+ const apiUrl = credentials.apiUrl.replace(/\/$/, "");
120
125
  const res = await fetch(`${apiUrl}/health`);
121
126
  if (!res.ok) {
122
127
  throw new Error(`Health check failed: HTTP ${res.status}`);
123
128
  }
124
129
  }, results);
125
130
  await runStep("kodingo-api token valid", async () => {
126
- const apiUrl = config.apiUrl.replace(/\/$/, "");
131
+ const apiUrl = credentials.apiUrl.replace(/\/$/, "");
127
132
  const res = await fetch(`${apiUrl}/memory?limit=1`, {
128
- headers: { "X-Kodingo-Token": config.token },
133
+ headers: { "X-Kodingo-Token": credentials.token },
129
134
  });
130
135
  if (res.status === 401) {
131
136
  throw new Error("Token is invalid or expired");
@@ -2,20 +2,8 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.guardrailsCommand = guardrailsCommand;
4
4
  const persistence_config_1 = require("../utils/persistence-config");
5
- const API_BASE_DEFAULT = "https://kodingo-api.onrender.com";
6
- function normalizePath(p) {
7
- return p.replace(/\\\\/g, "/").toLowerCase();
8
- }
9
- function getCredentials() {
10
- const config = (0, persistence_config_1.readConfig)();
11
- const cwd = normalizePath(process.cwd());
12
- const ws = (0, persistence_config_1.readWorkspaceConfig)(cwd);
13
- const token = ws?.token ?? config.token ?? "";
14
- const apiUrl = ws?.apiUrl ?? config.apiUrl ?? API_BASE_DEFAULT;
15
- return { token, apiUrl };
16
- }
17
5
  async function guardrailsCommand(options) {
18
- const { token, apiUrl } = getCredentials();
6
+ const { token, apiUrl } = (0, persistence_config_1.getCredentials)(process.cwd());
19
7
  if (!token) {
20
8
  console.error("No token found. Run `kodingo init` first.");
21
9
  process.exit(1);
@@ -42,6 +42,7 @@ var __importStar = (this && this.__importStar) || (function () {
42
42
  };
43
43
  })();
44
44
  Object.defineProperty(exports, "__esModule", { value: true });
45
+ exports.ensureLocalExclude = ensureLocalExclude;
45
46
  exports.checkoutCoverageComplete = checkoutCoverageComplete;
46
47
  exports.shouldSkipLocalScan = shouldSkipLocalScan;
47
48
  exports.registerInitCommand = registerInitCommand;
@@ -49,6 +50,7 @@ const readline = __importStar(require("node:readline"));
49
50
  const fs = __importStar(require("fs"));
50
51
  const path = __importStar(require("path"));
51
52
  const os = __importStar(require("os"));
53
+ const node_child_process_1 = require("node:child_process");
52
54
  // open is imported dynamically to avoid ESM/CJS compatibility issues on Windows
53
55
  const persistence_config_1 = require("../utils/persistence-config");
54
56
  const repo_identity_1 = require("../utils/repo-identity");
@@ -112,18 +114,20 @@ function findRepoRoot(startPath) {
112
114
  current = parent;
113
115
  }
114
116
  }
115
- // ── .gitignore helper ─────────────────────────────────────────────────────────
116
- function ensureGitignoreEntry(repoRoot, entry) {
117
- const gitignorePath = path.join(repoRoot, ".gitignore");
117
+ // ── Local git exclusion; never edit the working tree or index ───────────────
118
+ function ensureLocalExclude(repoRoot, entry) {
119
+ const exclude = (0, node_child_process_1.execFileSync)("git", ["-C", repoRoot, "rev-parse", "--git-path", "info/exclude"], { encoding: "utf8" }).trim();
120
+ const gitignorePath = path.resolve(repoRoot, exclude);
118
121
  const line = entry.endsWith("\n") ? entry : `${entry}\n`;
122
+ fs.mkdirSync(path.dirname(gitignorePath), { recursive: true });
119
123
  if (fs.existsSync(gitignorePath)) {
120
124
  const contents = fs.readFileSync(gitignorePath, "utf-8");
121
125
  if (contents.split("\n").some(l => l.trim() === entry.trim()))
122
126
  return;
123
- fs.appendFileSync(gitignorePath, `\n# Kortex\n${line}`, "utf-8");
127
+ fs.appendFileSync(gitignorePath, `${contents.endsWith("\n") ? "" : "\n"}${line}`, "utf-8");
124
128
  }
125
129
  else {
126
- fs.writeFileSync(gitignorePath, `# Kortex\n${line}`, "utf-8");
130
+ fs.writeFileSync(gitignorePath, line, "utf-8");
127
131
  }
128
132
  }
129
133
  // ── Browser login flow ────────────────────────────────────────────────────────
@@ -248,7 +252,7 @@ function registerInitCommand(program) {
248
252
  const existingConfig = (0, persistence_config_1.readConfig)();
249
253
  (0, persistence_config_1.writeConfig)({ ...existingConfig, mode: "cloud", apiUrl, machineId: getMachineId() });
250
254
  (0, persistence_config_1.writeWorkspaceConfig)(repoRoot, { mode: "cloud", apiUrl, token: environmentToken });
251
- ensureGitignoreEntry(repoRoot, ".kortex/");
255
+ ensureLocalExclude(repoRoot, ".kortex/");
252
256
  const registration = await (0, repo_identity_1.resolveRepoRegistration)({ repoRoot, apiUrl, token: environmentToken });
253
257
  const coverageComplete = (!opts.force && !opts.dryRun) ? await checkoutCoverageComplete(apiUrl, environmentToken, registration.alreadyRegistered) : false;
254
258
  const alreadyComplete = shouldSkipLocalScan(opts.force, opts.dryRun, coverageComplete);
@@ -345,7 +349,7 @@ function registerInitCommand(program) {
345
349
  const machineId = getMachineId();
346
350
  (0, persistence_config_1.writeConfig)({ ...existingConfig, mode: "cloud", apiUrl, machineId });
347
351
  (0, persistence_config_1.writeWorkspaceConfig)(repoRoot, { mode: "cloud", apiUrl, token: selectedProject.token });
348
- ensureGitignoreEntry(repoRoot, ".kortex/");
352
+ ensureLocalExclude(repoRoot, ".kortex/");
349
353
  // Register this repo with the project on the API.
350
354
  // This is the authoritative binding that prevents cross-project
351
355
  // contamination — resolved from the git remote (stable across
@@ -4,7 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.queryMemoryCommand = queryMemoryCommand;
7
- const fs_1 = __importDefault(require("fs"));
7
+ exports.resolveRepoScope = resolveRepoScope;
8
8
  const path_1 = __importDefault(require("path"));
9
9
  const persistence_config_1 = require("../utils/persistence-config");
10
10
  async function queryMemoryCommand(text, options) {
@@ -17,7 +17,7 @@ async function queryMemoryCommand(text, options) {
17
17
  includeNonCanonical: options.includeNonCanonical === true,
18
18
  });
19
19
  if (results.length === 0) {
20
- console.log("No results.");
20
+ console.log(`No results for ${JSON.stringify(text)} in this project.`);
21
21
  return;
22
22
  }
23
23
  for (const r of results) {
@@ -43,19 +43,8 @@ function resolveRepoScope(options) {
43
43
  if (options.global === true)
44
44
  return undefined;
45
45
  if (options.repo && options.repo.trim()) {
46
- return path_1.default.resolve(options.repo.trim());
47
- }
48
- return findRepoRoot(process.cwd());
49
- }
50
- function findRepoRoot(startPath) {
51
- let current = startPath;
52
- while (true) {
53
- const gitPath = path_1.default.join(current, ".git");
54
- if (fs_1.default.existsSync(gitPath))
55
- return current;
56
- const parent = path_1.default.dirname(current);
57
- if (parent === current)
58
- return startPath;
59
- current = parent;
46
+ const value = options.repo.trim().replace(/\\/g, "/").replace(/\/+$/, "");
47
+ return value.includes("/") ? path_1.default.posix.basename(value) : value;
60
48
  }
49
+ return undefined;
61
50
  }
@@ -43,20 +43,8 @@ exports.sessionBriefCommand = sessionBriefCommand;
43
43
  */
44
44
  const persistence_config_1 = require("../utils/persistence-config");
45
45
  const path = __importStar(require("path"));
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
- }
58
46
  async function sessionBriefCommand(options) {
59
- const { token, apiUrl } = getCredentials();
47
+ const { token, apiUrl } = (0, persistence_config_1.getCredentials)(process.cwd());
60
48
  if (!token) {
61
49
  console.error("No token found. Run `kodingo init` first.");
62
50
  process.exit(1);
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.CONFIG_PATH = void 0;
7
+ exports.findWorkspaceEntry = findWorkspaceEntry;
7
8
  exports.readConfig = readConfig;
8
9
  exports.writeConfig = writeConfig;
9
10
  exports.writeWorkspaceConfig = writeWorkspaceConfig;
@@ -28,14 +29,55 @@ const node_fs_1 = __importDefault(require("node:fs"));
28
29
  const node_path_1 = __importDefault(require("node:path"));
29
30
  const node_os_1 = __importDefault(require("node:os"));
30
31
  exports.CONFIG_PATH = node_path_1.default.join(node_os_1.default.homedir(), ".kodingo", "config.json");
31
- function normalizePath(p) {
32
- return p.replace(/\\/g, '/').toLowerCase();
32
+ let permissionsWarningPrinted = false;
33
+ function comparablePath(value) {
34
+ const normalized = node_path_1.default.resolve(value.replace(/\\/g, "/")).replace(/\/+$/, "") || "/";
35
+ try {
36
+ return node_fs_1.default.realpathSync(normalized).replace(/\\/g, "/").replace(/\/+$/, "").toLowerCase() || "/";
37
+ }
38
+ catch {
39
+ return normalized.toLowerCase();
40
+ }
41
+ }
42
+ /** Find the nearest workspace without changing its stored key. */
43
+ function findWorkspaceEntry(cwd, config) {
44
+ const entries = Object.entries(config.workspaces ?? {}).map(([key, value]) => [comparablePath(key), value]);
45
+ let current = node_path_1.default.resolve(cwd.replace(/\\/g, "/"));
46
+ for (;;) {
47
+ const match = entries.find(([key]) => key === comparablePath(current));
48
+ if (match)
49
+ return match[1];
50
+ const parent = node_path_1.default.dirname(current);
51
+ if (parent === current)
52
+ return null;
53
+ current = parent;
54
+ }
55
+ }
56
+ function tightenPermissions() {
57
+ if (process.platform === "win32")
58
+ return;
59
+ const dir = node_path_1.default.dirname(exports.CONFIG_PATH);
60
+ let tightened = false;
61
+ for (const [target, mode] of [[dir, 0o700], [exports.CONFIG_PATH, 0o600]]) {
62
+ try {
63
+ if (node_fs_1.default.existsSync(target) && (node_fs_1.default.statSync(target).mode & 0o077)) {
64
+ node_fs_1.default.chmodSync(target, mode);
65
+ tightened = true;
66
+ }
67
+ }
68
+ catch { /* Reading config must survive permission repair failures. */ }
69
+ }
70
+ if (tightened && !permissionsWarningPrinted) {
71
+ console.error("Tightened permissions on ~/.kodingo/config.json (it holds project tokens).");
72
+ permissionsWarningPrinted = true;
73
+ }
33
74
  }
34
75
  function readConfig() {
35
76
  if (!node_fs_1.default.existsSync(exports.CONFIG_PATH)) {
36
77
  return { mode: "cloud", apiUrl: "https://kodingo-api.onrender.com" };
37
78
  }
38
79
  try {
80
+ tightenPermissions();
39
81
  const raw = node_fs_1.default.readFileSync(exports.CONFIG_PATH, "utf-8");
40
82
  const parsed = JSON.parse(raw);
41
83
  if (!parsed.mode)
@@ -49,10 +91,24 @@ function readConfig() {
49
91
  }
50
92
  function writeConfig(config) {
51
93
  const dir = node_path_1.default.dirname(exports.CONFIG_PATH);
52
- if (!node_fs_1.default.existsSync(dir)) {
53
- node_fs_1.default.mkdirSync(dir, { recursive: true });
94
+ node_fs_1.default.mkdirSync(dir, { recursive: true, mode: 0o700 });
95
+ if (process.platform !== "win32") {
96
+ try {
97
+ node_fs_1.default.chmodSync(dir, 0o700);
98
+ }
99
+ catch { }
100
+ }
101
+ const temporary = node_path_1.default.join(dir, `.config-${process.pid}-${Math.random().toString(16).slice(2)}.tmp`);
102
+ try {
103
+ node_fs_1.default.writeFileSync(temporary, JSON.stringify(config, null, 2), { encoding: "utf-8", mode: 0o600, flag: "wx" });
104
+ node_fs_1.default.renameSync(temporary, exports.CONFIG_PATH);
105
+ }
106
+ finally {
107
+ try {
108
+ node_fs_1.default.unlinkSync(temporary);
109
+ }
110
+ catch { }
54
111
  }
55
- node_fs_1.default.writeFileSync(exports.CONFIG_PATH, JSON.stringify(config, null, 2), "utf-8");
56
112
  }
57
113
  function writeWorkspaceConfig(repoPath, wsConfig) {
58
114
  const existing = readConfig();
@@ -61,8 +117,7 @@ function writeWorkspaceConfig(repoPath, wsConfig) {
61
117
  writeConfig({ ...existing, workspaces });
62
118
  }
63
119
  function readWorkspaceConfig(repoPath) {
64
- const config = readConfig();
65
- return config.workspaces?.[repoPath] ?? null;
120
+ return findWorkspaceEntry(repoPath, readConfig());
66
121
  }
67
122
  function isCloudMode() {
68
123
  return readConfig().mode === "cloud";
@@ -82,14 +137,8 @@ const API_BASE_DEFAULT = "https://kodingo-api.onrender.com";
82
137
  */
83
138
  function getCredentials(repoRoot) {
84
139
  const config = readConfig();
85
- const normRoot = repoRoot.replace(/\/+$/, "");
86
- let wsEntry = config.workspaces?.[normRoot] ?? config.workspaces?.[normRoot + "/"];
87
- let current = normRoot;
88
- while (!wsEntry && current !== node_path_1.default.dirname(current)) {
89
- current = node_path_1.default.dirname(current);
90
- wsEntry = config.workspaces?.[current] ?? config.workspaces?.[current + "/"];
91
- }
92
- const token = wsEntry?.token ?? "";
140
+ const wsEntry = findWorkspaceEntry(repoRoot, config);
141
+ const token = wsEntry?.token ?? config.token ?? "";
93
142
  const apiUrl = wsEntry?.apiUrl ?? config.apiUrl ?? API_BASE_DEFAULT;
94
143
  return { token, apiUrl };
95
144
  }
@@ -100,15 +149,16 @@ function getCredentials(repoRoot) {
100
149
  function getPersistence() {
101
150
  const config = readConfig();
102
151
  if (config.mode === "cloud") {
103
- if (!config.apiUrl)
152
+ const wsConfig = findWorkspaceEntry(process.cwd(), config);
153
+ const apiUrl = wsConfig?.apiUrl ?? config.apiUrl;
154
+ if (!apiUrl)
104
155
  throw new Error("Cloud mode requires apiUrl in ~/.kodingo/config.json");
105
156
  // Try workspace-scoped token first, fall back to global token
106
- const wsConfig = readWorkspaceConfig(normalizePath(process.cwd()));
107
157
  const token = wsConfig?.token ?? config.token ?? "";
108
158
  if (!token)
109
159
  throw new Error("No project token found. Run `kodingo init` in your project directory first.");
110
160
  // Inject into env so cloud-persistence picks them up
111
- process.env.KODINGO_API_URL = wsConfig?.apiUrl ?? config.apiUrl;
161
+ process.env.KODINGO_API_URL = apiUrl;
112
162
  process.env.KODINGO_API_TOKEN = token;
113
163
  return require("../adapters/cloud-adapter/cloud-persistence");
114
164
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kodingo-cli",
3
- "version": "1.4.2",
3
+ "version": "1.4.3",
4
4
  "description": "Kodingo CLI",
5
5
  "license": "MIT",
6
6
  "private": false,
@@ -1,22 +0,0 @@
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
- const node_fs_1 = __importDefault(require("node:fs"));
7
- const node_path_1 = __importDefault(require("node:path"));
8
- const node_worker_threads_1 = require("node:worker_threads");
9
- const worker = new node_worker_threads_1.Worker(node_path_1.default.join(__dirname, "deep-scan-worker.js"));
10
- process.on("message", (message) => {
11
- try {
12
- const bytes = node_fs_1.default.readFileSync(message.absolutePath);
13
- const transferable = bytes.buffer instanceof ArrayBuffer && bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength ? new Uint8Array(bytes.buffer) : Uint8Array.from(bytes);
14
- worker.postMessage({ id: message.id, filePath: message.filePath, blobSha: message.blobSha, bytes: transferable, includeExcerpts: message.includeExcerpts }, [transferable.buffer]);
15
- }
16
- catch (error) {
17
- process.send?.({ id: message.id, error: error instanceof Error ? error.message : String(error) });
18
- }
19
- });
20
- worker.on("message", (message) => process.send?.({ ...message, processRss: process.memoryUsage().rss }));
21
- worker.on("error", (error) => process.send?.({ id: -1, error: error.message }));
22
- process.on("disconnect", async () => { await worker.terminate(); process.exit(0); });