kodingo-cli 1.4.0 → 1.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,136 @@
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
+ /** Validation fixtures only; no production or customer identifiers.
7
+ * The post-commit hook invokes `deep-scan --changed --yes` unconditionally,
8
+ * on every commit, regardless of branch. This covers the gate that keeps it
9
+ * from uploading a commit it can positively confirm isn't on the tracked
10
+ * branch — and proves a failure in that check never fails the commit (it
11
+ * fails open and the scan proceeds exactly as before this gate existed).
12
+ */
13
+ const strict_1 = __importDefault(require("node:assert/strict"));
14
+ const node_fs_1 = __importDefault(require("node:fs"));
15
+ const node_os_1 = __importDefault(require("node:os"));
16
+ const node_path_1 = __importDefault(require("node:path"));
17
+ const node_child_process_1 = require("node:child_process");
18
+ const node_test_1 = require("node:test");
19
+ const deep_scan_1 = require("../commands/deep-scan");
20
+ function fakeFetch(responses) {
21
+ const calls = [];
22
+ const fn = async (url, init) => {
23
+ calls.push({ url, init });
24
+ const next = responses.shift();
25
+ if (!next)
26
+ throw new Error(`deepScanHookBranchGate test: no mock response left for ${url}`);
27
+ return { ok: (next.status ?? 200) < 300, status: next.status ?? 200, json: async () => next.body };
28
+ };
29
+ return { fn, calls };
30
+ }
31
+ function withFetch(responses, run) {
32
+ const original = global.fetch;
33
+ const { fn, calls } = fakeFetch(responses);
34
+ global.fetch = fn;
35
+ return run(calls).finally(() => { global.fetch = original; });
36
+ }
37
+ function makeRepo() {
38
+ const root = node_fs_1.default.mkdtempSync(node_path_1.default.join(node_os_1.default.tmpdir(), "kodingo-hook-gate-"));
39
+ (0, node_child_process_1.execFileSync)("git", ["init", "-q", "-b", "feature/x", root]);
40
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "config", "user.email", "test@example.invalid"]);
41
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "config", "user.name", "Validation Test"]);
42
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "remote", "add", "origin", "git@github.com:validation/repository.git"]);
43
+ node_fs_1.default.writeFileSync(node_path_1.default.join(root, "page.ts"), "export function Page() { return 1; }");
44
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "add", "."]);
45
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "commit", "-qm", "first commit — a root commit has no diff-tree parent to scope --changed against"]);
46
+ node_fs_1.default.writeFileSync(node_path_1.default.join(root, "page.ts"), "export function Page() { return 2; }");
47
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "add", "."]);
48
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "commit", "-qm", "the commit the hook actually runs against"]);
49
+ return root;
50
+ }
51
+ function withConsoleLog(run) {
52
+ const logs = [];
53
+ const original = console.log;
54
+ console.log = (...args) => { logs.push(args.join(" ")); };
55
+ return run(logs).finally(() => { console.log = original; });
56
+ }
57
+ (0, node_test_1.describe)("deep-scan --changed (the hook's exact invocation) — upload only on the tracked branch", () => {
58
+ (0, node_test_1.it)("a confirmed mismatch skips the scan entirely: no further request is made, and the commit is never failed", async () => {
59
+ const root = makeRepo();
60
+ const oldToken = process.env.KODINGO_TOKEN;
61
+ process.env.KODINGO_TOKEN = "validation-token";
62
+ try {
63
+ await withConsoleLog((logs) => withFetch([{ body: { outcome: "mismatch", trackedBranch: "main" } }], async (calls) => {
64
+ await strict_1.default.doesNotReject(() => (0, deep_scan_1.deepScanCommand)({ repo: root, changed: true, yes: true }));
65
+ strict_1.default.equal(calls.length, 1, `expected only the branch-settle check, got: ${JSON.stringify(calls.map((c) => c.url))}`);
66
+ strict_1.default.match(calls[0].url, /\/deep-scan\/branch\/settle$/);
67
+ strict_1.default.ok(logs.some((l) => /Skipping incremental scan/.test(l)), `expected a skip log, got: ${JSON.stringify(logs)}`);
68
+ }));
69
+ }
70
+ finally {
71
+ if (oldToken === undefined)
72
+ delete process.env.KODINGO_TOKEN;
73
+ else
74
+ process.env.KODINGO_TOKEN = oldToken;
75
+ }
76
+ });
77
+ (0, node_test_1.it)("a match proceeds with the normal incremental scan and upload", async () => {
78
+ const root = makeRepo();
79
+ const oldToken = process.env.KODINGO_TOKEN;
80
+ process.env.KODINGO_TOKEN = "validation-token";
81
+ try {
82
+ await withFetch([
83
+ { body: { outcome: "match", trackedBranch: "feature/x" } }, // POST /deep-scan/branch/settle
84
+ { body: { excerptsEnabled: true } }, // GET /deep-scan/policy
85
+ { body: { sessionId: "sess-1", heldBlobShas: [], limits: { filesPerBatch: 200 } } }, // POST /deep-scan/sessions
86
+ { body: { accepted: 1 } }, // POST /deep-scan/sessions/:id/files
87
+ { body: { runId: "run-1" } }, // POST /deep-scan/sessions/:id/finalize
88
+ { body: { state: "completed", applied: true, entity_count: 1, edge_count: 0, file_count: 1 } }, // GET /deep-scan/runs/:id
89
+ ], async (calls) => {
90
+ await strict_1.default.doesNotReject(() => (0, deep_scan_1.deepScanCommand)({ repo: root, changed: true, yes: true }));
91
+ strict_1.default.equal(calls.length, 6, `expected all 6 calls to happen, got: ${JSON.stringify(calls.map((c) => c.url))}`);
92
+ });
93
+ }
94
+ finally {
95
+ if (oldToken === undefined)
96
+ delete process.env.KODINGO_TOKEN;
97
+ else
98
+ process.env.KODINGO_TOKEN = oldToken;
99
+ }
100
+ });
101
+ (0, node_test_1.it)("never fails the commit when the branch-settle check itself errors — fails open and scans anyway", async () => {
102
+ const root = makeRepo();
103
+ const oldToken = process.env.KODINGO_TOKEN;
104
+ process.env.KODINGO_TOKEN = "validation-token";
105
+ const calls = [];
106
+ const original = global.fetch;
107
+ global.fetch = async (url, init) => {
108
+ calls.push(url);
109
+ if (url.endsWith("/deep-scan/branch/settle"))
110
+ throw new Error("network down");
111
+ if (url.endsWith("/deep-scan/policy"))
112
+ return { ok: true, status: 200, json: async () => ({ excerptsEnabled: true }) };
113
+ if (url.endsWith("/deep-scan/sessions"))
114
+ return { ok: true, status: 201, json: async () => ({ sessionId: "sess-1", heldBlobShas: [], limits: { filesPerBatch: 200 } }) };
115
+ if (url.includes("/deep-scan/sessions/sess-1/files"))
116
+ return { ok: true, status: 200, json: async () => ({ accepted: 1 }) };
117
+ if (url.endsWith("/finalize"))
118
+ return { ok: true, status: 202, json: async () => ({ runId: "run-1" }) };
119
+ if (url.endsWith("/deep-scan/runs/run-1"))
120
+ return { ok: true, status: 200, json: async () => ({ state: "completed", applied: true, entity_count: 1, edge_count: 0, file_count: 1 }) };
121
+ throw new Error(`unexpected url: ${url}`);
122
+ };
123
+ try {
124
+ await strict_1.default.doesNotReject(() => (0, deep_scan_1.deepScanCommand)({ repo: root, changed: true, yes: true }));
125
+ strict_1.default.ok(calls.some((u) => u.endsWith("/deep-scan/branch/settle")));
126
+ strict_1.default.ok(calls.some((u) => u.endsWith("/deep-scan/sessions")), "the scan must still proceed after the gate check fails");
127
+ }
128
+ finally {
129
+ global.fetch = original;
130
+ if (oldToken === undefined)
131
+ delete process.env.KODINGO_TOKEN;
132
+ else
133
+ process.env.KODINGO_TOKEN = oldToken;
134
+ }
135
+ });
136
+ });
@@ -20,6 +20,60 @@ const deep_scan_1 = require("../commands/deep-scan");
20
20
  strict_1.default.equal((0, local_deep_scan_extractor_1.privacySafeExcerpt)(` first();\nsecond();`).trim(), "first()");
21
21
  strict_1.default.ok((0, local_deep_scan_extractor_1.privacySafeExcerpt)("x".repeat(500)).length <= 200);
22
22
  });
23
+ (0, node_test_1.it)("the commit hook's --changed scope is bounded by the commit diff, not by whether the local entity cache is populated — never a full-project extraction", () => {
24
+ const root = node_fs_1.default.mkdtempSync(node_path_1.default.join(node_os_1.default.tmpdir(), "kodingo-deep-scan-"));
25
+ (0, node_child_process_1.execFileSync)("git", ["init", "-q", root]);
26
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "config", "user.email", "test@example.invalid"]);
27
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "config", "user.name", "Validation Test"]);
28
+ node_fs_1.default.mkdirSync(node_path_1.default.join(root, "src"));
29
+ node_fs_1.default.writeFileSync(node_path_1.default.join(root, "src", "a.ts"), "export function a() { return 1; }");
30
+ node_fs_1.default.writeFileSync(node_path_1.default.join(root, "src", "b.ts"), "export function b() { return 2; }");
31
+ node_fs_1.default.writeFileSync(node_path_1.default.join(root, "src", "c.ts"), "export function c() { return 3; }");
32
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "add", "."]);
33
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "commit", "-qm", "first commit — a new engineer's empty-cache clone starts here"]);
34
+ // A new engineer's clone has no .kortex/entity-cache at all yet — confirm
35
+ // that's genuinely true for this fixture before trusting the assertion.
36
+ strict_1.default.equal(node_fs_1.default.existsSync(node_path_1.default.join(root, ".kortex", "entity-cache")), false);
37
+ // Only one file changes in the NEXT commit — this is what the post-commit
38
+ // hook's `deep-scan --changed` runs against.
39
+ node_fs_1.default.writeFileSync(node_path_1.default.join(root, "src", "b.ts"), "export function b() { return 22; }");
40
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "add", "."]);
41
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "commit", "-qm", "second commit — only b.ts changes"]);
42
+ const full = (0, deep_scan_1.listTrackedFiles)(root, false);
43
+ strict_1.default.deepEqual(full.map((f) => f.path).sort(), ["src/a.ts", "src/b.ts", "src/c.ts"]);
44
+ const changedOnly = (0, deep_scan_1.listTrackedFiles)(root, true);
45
+ strict_1.default.deepEqual(changedOnly.map((f) => f.path), ["src/b.ts"], "the hook's file set must be exactly the commit diff, never the whole tracked tree, regardless of cache state");
46
+ });
47
+ (0, node_test_1.it)("tracks declarative files (package manifests, lockfiles, deployment/compose files, plain YAML) — the production incident's root cause: these were silently excluded by a stale, hand-maintained extension list, so a fullTree apply deleted every entity ever produced for them, project-wide", () => {
48
+ const root = node_fs_1.default.mkdtempSync(node_path_1.default.join(node_os_1.default.tmpdir(), "kodingo-deep-scan-"));
49
+ (0, node_child_process_1.execFileSync)("git", ["init", "-q", root]);
50
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "config", "user.email", "test@example.invalid"]);
51
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "config", "user.name", "Validation Test"]);
52
+ node_fs_1.default.mkdirSync(node_path_1.default.join(root, "k8s"));
53
+ node_fs_1.default.writeFileSync(node_path_1.default.join(root, "package.json"), JSON.stringify({ name: "my-app", dependencies: { react: "^18.2.0" } }));
54
+ node_fs_1.default.writeFileSync(node_path_1.default.join(root, "package-lock.json"), JSON.stringify({ name: "my-app", lockfileVersion: 1 }));
55
+ node_fs_1.default.writeFileSync(node_path_1.default.join(root, "docker-compose.yml"), "services:\n web:\n image: my-app:latest\n");
56
+ node_fs_1.default.writeFileSync(node_path_1.default.join(root, "Dockerfile"), "FROM node:20\n");
57
+ node_fs_1.default.writeFileSync(node_path_1.default.join(root, "k8s", "deployment.yaml"), "apiVersion: apps/v1\nkind: Deployment\n");
58
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "add", "."]);
59
+ const files = (0, deep_scan_1.listTrackedFiles)(root).map((file) => file.path).sort();
60
+ strict_1.default.deepEqual(files, [
61
+ "Dockerfile",
62
+ "docker-compose.yml",
63
+ "k8s/deployment.yaml",
64
+ "package-lock.json",
65
+ "package.json",
66
+ ].sort());
67
+ });
68
+ (0, node_test_1.it)("tracks a committed .env.example template but never a real .env file", () => {
69
+ const root = node_fs_1.default.mkdtempSync(node_path_1.default.join(node_os_1.default.tmpdir(), "kodingo-deep-scan-"));
70
+ (0, node_child_process_1.execFileSync)("git", ["init", "-q", root]);
71
+ node_fs_1.default.writeFileSync(node_path_1.default.join(root, ".env.example"), "DATABASE_URL=postgres://localhost/app\n");
72
+ node_fs_1.default.writeFileSync(node_path_1.default.join(root, ".env"), "SECRET=value\n");
73
+ node_fs_1.default.writeFileSync(node_path_1.default.join(root, ".env.production"), "SECRET=value\n");
74
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "add", "-f", "."]);
75
+ strict_1.default.deepEqual((0, deep_scan_1.listTrackedFiles)(root).map((file) => file.path), [".env.example"]);
76
+ });
23
77
  (0, node_test_1.it)("honors git tracking, .kodingoignore, and env exclusion", () => {
24
78
  const root = node_fs_1.default.mkdtempSync(node_path_1.default.join(node_os_1.default.tmpdir(), "kodingo-deep-scan-"));
25
79
  (0, node_child_process_1.execFileSync)("git", ["init", "-q", root]);
@@ -51,6 +105,15 @@ const deep_scan_1 = require("../commands/deep-scan");
51
105
  strict_1.default.equal((0, deep_scan_1.normalizeRemote)("git@github.com:owner/repo.git"), "owner/repo");
52
106
  strict_1.default.equal((0, deep_scan_1.normalizeRemote)("https://github.com/owner/repo.git"), "owner/repo");
53
107
  });
108
+ (0, node_test_1.it)("derives the bare repo name from the normalized owner/name form", () => {
109
+ strict_1.default.equal((0, deep_scan_1.deriveBareRepoName)("Dragnet-Solutions/checkin-tracker"), "checkin-tracker");
110
+ strict_1.default.equal((0, deep_scan_1.deriveBareRepoName)("checkin-tracker"), "checkin-tracker");
111
+ });
112
+ (0, node_test_1.it)("builds an actionable error message from a server mismatch response, without mutating a plain message", () => {
113
+ strict_1.default.equal((0, deep_scan_1.describeApiError)({ error: "boom" }, 500), "boom");
114
+ strict_1.default.equal((0, deep_scan_1.describeApiError)({ error: "repository is not registered to this project", sentLabel: "Dragnet-Solutions/checkin-tracker", registeredRepos: ["checkin-tracker"] }, 403), 'repository is not registered to this project (sent: "Dragnet-Solutions/checkin-tracker"; registered: "checkin-tracker")');
115
+ strict_1.default.equal((0, deep_scan_1.describeApiError)({ error: "repository label \"foo\" matches more than one registered repository and cannot be resolved automatically", sentLabel: "foo", registeredRepos: ["OrgA/foo", "OrgB/foo"], matchingRegisteredRepos: ["OrgA/foo", "OrgB/foo"] }, 409), 'repository label "foo" matches more than one registered repository and cannot be resolved automatically (sent: "foo"; registered: "OrgA/foo", "OrgB/foo"; matches: "OrgA/foo", "OrgB/foo")');
116
+ });
54
117
  (0, node_test_1.it)("writes an inspectable dry-run payload without contacting the server", async () => {
55
118
  const root = node_fs_1.default.mkdtempSync(node_path_1.default.join(node_os_1.default.tmpdir(), "kodingo-dry-run-"));
56
119
  (0, node_child_process_1.execFileSync)("git", ["init", "-q", root]);
@@ -74,6 +137,8 @@ const deep_scan_1 = require("../commands/deep-scan");
74
137
  }
75
138
  const payload = JSON.parse(node_fs_1.default.readFileSync(output, "utf8"));
76
139
  strict_1.default.equal(payload.manifest.repository, "validation/repository");
140
+ strict_1.default.equal(payload.manifest.repositoryName, "repository");
141
+ strict_1.default.equal(payload.manifest.remote, "git@github.com:validation/repository.git");
77
142
  strict_1.default.equal(payload.files[0].path, "page.ts");
78
143
  strict_1.default.ok(Array.isArray(payload.files[0].linkPlan.attributeUpdates));
79
144
  strict_1.default.ok(Array.isArray(payload.files[0].linkPlan.derivedEntities));
@@ -0,0 +1,154 @@
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
+ /** Validation fixtures only; no production or customer identifiers.
7
+ * Exercises the network-facing branch-settlement/poll/reconcile flow with a
8
+ * hand-rolled fetch stub (no real HTTP, no database) — matching this repo's
9
+ * own dry-run test's pattern of using a real temporary git repo for git
10
+ * plumbing while keeping every network call mocked.
11
+ */
12
+ const strict_1 = __importDefault(require("node:assert/strict"));
13
+ const node_fs_1 = __importDefault(require("node:fs"));
14
+ const node_os_1 = __importDefault(require("node:os"));
15
+ const node_path_1 = __importDefault(require("node:path"));
16
+ const node_child_process_1 = require("node:child_process");
17
+ const node_test_1 = require("node:test");
18
+ const deep_scan_1 = require("../commands/deep-scan");
19
+ function fakeFetch(responses) {
20
+ const calls = [];
21
+ const fn = async (url, init) => {
22
+ calls.push({ url, init });
23
+ const next = responses.shift();
24
+ if (!next)
25
+ throw new Error(`deepScanNetworkFlows test: no mock response left for ${url}`);
26
+ return { ok: (next.status ?? 200) < 300, status: next.status ?? 200, json: async () => next.body };
27
+ };
28
+ return { fn, calls };
29
+ }
30
+ function withFetch(responses, run) {
31
+ const original = global.fetch;
32
+ const { fn, calls } = fakeFetch(responses);
33
+ global.fetch = fn;
34
+ return run(calls).finally(() => { global.fetch = original; });
35
+ }
36
+ function makeRepo(branch = "main") {
37
+ const root = node_fs_1.default.mkdtempSync(node_path_1.default.join(node_os_1.default.tmpdir(), "kodingo-branch-settle-"));
38
+ (0, node_child_process_1.execFileSync)("git", ["init", "-q", "-b", branch, root]);
39
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "config", "user.email", "test@example.invalid"]);
40
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "config", "user.name", "Validation Test"]);
41
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "remote", "add", "origin", "git@github.com:org/repo.git"]);
42
+ node_fs_1.default.writeFileSync(node_path_1.default.join(root, "a.ts"), "export const a = 1;\n");
43
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "add", "."]);
44
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "commit", "-qm", "fixture"]);
45
+ return root;
46
+ }
47
+ (0, node_test_1.describe)("settleTrackedBranch", () => {
48
+ (0, node_test_1.it)("proceeds silently on a match, making only the one check call", async () => {
49
+ const root = makeRepo("main");
50
+ const result = await withFetch([{ body: { outcome: "match", trackedBranch: "main" } }], async (calls) => {
51
+ const r = await (0, deep_scan_1.settleTrackedBranch)({ apiUrl: "https://api.test", token: "tok", root, repository: "org/repo", repositoryName: "repo", branch: "main", yes: false });
52
+ strict_1.default.equal(calls.length, 1);
53
+ return r;
54
+ });
55
+ strict_1.default.deepEqual(result, { recorded: false, held: false, trackedBranch: "main" });
56
+ });
57
+ (0, node_test_1.it)("reports a mismatch as held, without ever attempting to record over it", async () => {
58
+ const root = makeRepo("feature/x");
59
+ const result = await withFetch([{ body: { outcome: "mismatch", trackedBranch: "main" } }], (calls) => (0, deep_scan_1.settleTrackedBranch)({ apiUrl: "https://api.test", token: "tok", root, repository: "org/repo", repositoryName: "repo", branch: "feature/x", yes: false }).then((r) => { strict_1.default.equal(calls.length, 1); return r; }));
60
+ strict_1.default.deepEqual(result, { recorded: false, held: true, trackedBranch: "main" });
61
+ });
62
+ (0, node_test_1.it)("holds with a plain message when none is tracked and non-interactive input declines the prompt", async () => {
63
+ const root = makeRepo("main");
64
+ const result = await withFetch([{ body: { outcome: "none", trackedBranch: null } }], (calls) => (0, deep_scan_1.settleTrackedBranch)({ apiUrl: "https://api.test", token: "tok", root, repository: "org/repo", repositoryName: "repo", branch: "main", yes: false }).then((r) => { strict_1.default.equal(calls.length, 1); return r; }));
65
+ strict_1.default.deepEqual(result, { recorded: false, held: true, trackedBranch: null });
66
+ });
67
+ (0, node_test_1.it)("--yes records a branch when none is tracked and the checkout matches the remote's default branch", async () => {
68
+ const root = makeRepo("main");
69
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main"]);
70
+ const result = await withFetch([{ body: { outcome: "none", trackedBranch: null } }, { body: { outcome: "recorded", trackedBranch: "main" } }], (calls) => (0, deep_scan_1.settleTrackedBranch)({ apiUrl: "https://api.test", token: "tok", root, repository: "org/repo", repositoryName: "repo", branch: "main", yes: true }).then((r) => {
71
+ strict_1.default.equal(calls.length, 2);
72
+ const secondBody = JSON.parse(calls[1].init.body);
73
+ strict_1.default.equal(secondBody.record, true);
74
+ strict_1.default.ok(typeof secondBody.attributedBy === "string" && secondBody.attributedBy.length > 0);
75
+ return r;
76
+ }));
77
+ strict_1.default.deepEqual(result, { recorded: true, held: false, trackedBranch: "main" });
78
+ });
79
+ (0, node_test_1.it)("--yes refuses with a non-zero-exit-causing error when the default branch cannot be determined", async () => {
80
+ const root = makeRepo("main");
81
+ // Point origin at a path that doesn't exist, locally — resolveDefaultBranch's
82
+ // `git remote show origin` fallback then fails fast, offline, rather than
83
+ // attempting a real network connection to the fake git@github.com remote.
84
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "remote", "set-url", "origin", "/nonexistent/kodingo-test-remote"]);
85
+ await withFetch([{ body: { outcome: "none", trackedBranch: null } }], async () => {
86
+ await strict_1.default.rejects(() => (0, deep_scan_1.settleTrackedBranch)({ apiUrl: "https://api.test", token: "tok", root, repository: "org/repo", repositoryName: "repo", branch: "main", yes: true }), /could not be determined/);
87
+ });
88
+ });
89
+ (0, node_test_1.it)("--yes refuses when the checkout does not match the remote's default branch", async () => {
90
+ const root = makeRepo("feature/x");
91
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main"]);
92
+ await withFetch([{ body: { outcome: "none", trackedBranch: null } }], async () => {
93
+ await strict_1.default.rejects(() => (0, deep_scan_1.settleTrackedBranch)({ apiUrl: "https://api.test", token: "tok", root, repository: "org/repo", repositoryName: "repo", branch: "feature/x", yes: true }), /does not match the remote's default branch/);
94
+ });
95
+ });
96
+ });
97
+ (0, node_test_1.describe)("resolveDefaultBranch", () => {
98
+ (0, node_test_1.it)("returns null when neither the local ref nor the remote-show fallback can determine it", async () => {
99
+ const root = makeRepo("main");
100
+ // A local path that doesn't exist — `git remote show origin` fails fast,
101
+ // offline, exactly like a genuinely unreachable remote would, without this
102
+ // test ever attempting a real network connection.
103
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "remote", "set-url", "origin", "/nonexistent/kodingo-test-remote"]);
104
+ strict_1.default.equal(await (0, deep_scan_1.resolveDefaultBranch)(root), null);
105
+ });
106
+ (0, node_test_1.it)("reads the branch name from refs/remotes/origin/HEAD when present", async () => {
107
+ const root = makeRepo("main");
108
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main"]);
109
+ strict_1.default.equal(await (0, deep_scan_1.resolveDefaultBranch)(root), "main");
110
+ });
111
+ (0, node_test_1.it)("falls back to `git remote show origin` when refs/remotes/origin/HEAD isn't set", async () => {
112
+ // A real, local (no network) git repo standing in for the remote — this
113
+ // exercises the actual `git remote show origin` fallback path, not a stub.
114
+ const remoteRoot = node_fs_1.default.mkdtempSync(node_path_1.default.join(node_os_1.default.tmpdir(), "kodingo-fake-remote-"));
115
+ (0, node_child_process_1.execFileSync)("git", ["init", "-q", "-b", "trunk", remoteRoot]);
116
+ (0, node_child_process_1.execFileSync)("git", ["-C", remoteRoot, "config", "user.email", "test@example.invalid"]);
117
+ (0, node_child_process_1.execFileSync)("git", ["-C", remoteRoot, "config", "user.name", "Validation Test"]);
118
+ node_fs_1.default.writeFileSync(node_path_1.default.join(remoteRoot, "f.txt"), "hi\n");
119
+ (0, node_child_process_1.execFileSync)("git", ["-C", remoteRoot, "add", "."]);
120
+ (0, node_child_process_1.execFileSync)("git", ["-C", remoteRoot, "commit", "-qm", "fixture"]);
121
+ const root = makeRepo("main");
122
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "remote", "set-url", "origin", remoteRoot]);
123
+ // No refs/remotes/origin/HEAD set — the first strategy has nothing to read.
124
+ strict_1.default.equal(await (0, deep_scan_1.resolveDefaultBranch)(root), "trunk");
125
+ });
126
+ });
127
+ (0, node_test_1.describe)("settleAndReconcile — the held-then-applied path", () => {
128
+ (0, node_test_1.it)("records the tracked branch and automatically reapplies a held scan at the same commit, without a new upload", async () => {
129
+ const root = makeRepo("main");
130
+ (0, node_child_process_1.execFileSync)("git", ["-C", root, "symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main"]);
131
+ const commitSha = (0, node_child_process_1.execFileSync)("git", ["-C", root, "rev-parse", "HEAD"], { encoding: "utf8" }).trim();
132
+ const logs = [];
133
+ const originalLog = console.log;
134
+ console.log = (...args) => { logs.push(args.join(" ")); };
135
+ try {
136
+ const result = await withFetch([
137
+ { body: { outcome: "none", trackedBranch: null } },
138
+ { body: { outcome: "recorded", trackedBranch: "main" } },
139
+ { body: { lastScan: { id: "scan-1", commitSha, applied: false, reason: "branch_mismatch:main:unregistered", entityCount: 0, edgeCount: 0, fileCount: 0 } } },
140
+ { body: { scanId: "scan-1", applied: true, reason: "clean_tracked_branch", entityCount: 2, evidenceCount: 3, edgeCount: 1, fileCount: 1 } },
141
+ ], (calls) => (0, deep_scan_1.settleAndReconcile)({ apiUrl: "https://api.test", token: "tok", root, yes: true }).then((r) => { strict_1.default.equal(calls.length, 4); return r; }));
142
+ strict_1.default.deepEqual(result, { handled: true });
143
+ strict_1.default.ok(logs.some((line) => /Deep scan applied: 2 entities, 1 edges, 1 files/.test(line)), `expected an applied summary line, got: ${JSON.stringify(logs)}`);
144
+ }
145
+ finally {
146
+ console.log = originalLog;
147
+ }
148
+ });
149
+ (0, node_test_1.it)("does not attempt reconciliation when the branch was already tracked (match — nothing recorded)", async () => {
150
+ const root = makeRepo("main");
151
+ const result = await withFetch([{ body: { outcome: "match", trackedBranch: "main" } }], (calls) => (0, deep_scan_1.settleAndReconcile)({ apiUrl: "https://api.test", token: "tok", root, yes: false }).then((r) => { strict_1.default.equal(calls.length, 1); return r; }));
152
+ strict_1.default.deepEqual(result, { handled: false });
153
+ });
154
+ });
@@ -0,0 +1,54 @@
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
+ /** Validation fixtures only; no production or customer identifiers.
7
+ * Covers the product rule: a project whose read is complete (from any
8
+ * source, any commit) does not need another local scan — and --force
9
+ * always overrides that shortcut.
10
+ */
11
+ const strict_1 = __importDefault(require("node:assert/strict"));
12
+ const node_test_1 = require("node:test");
13
+ const init_1 = require("../commands/init");
14
+ function withFetch(impl, run) {
15
+ const original = global.fetch;
16
+ global.fetch = impl;
17
+ return run().finally(() => { global.fetch = original; });
18
+ }
19
+ (0, node_test_1.describe)("checkoutCoverageComplete", () => {
20
+ (0, node_test_1.it)("fires for a complete project regardless of which commit or source produced that completeness", async () => {
21
+ const result = await withFetch(async () => ({ ok: true, json: async () => ({ state: "complete", coverage: 1, lastCommit: "some-other-commit-entirely", source: "github" }) }), () => (0, init_1.checkoutCoverageComplete)("https://api.test", "tok", true));
22
+ strict_1.default.equal(result, true);
23
+ });
24
+ (0, node_test_1.it)("does not fire for an incomplete project", async () => {
25
+ const result = await withFetch(async () => ({ ok: true, json: async () => ({ state: "partial", coverage: 0.4, source: "github" }) }), () => (0, init_1.checkoutCoverageComplete)("https://api.test", "tok", true));
26
+ strict_1.default.equal(result, false);
27
+ });
28
+ (0, node_test_1.it)("does not fire when this checkout's repo wasn't already a registered repo of the project — even if the project reports complete", async () => {
29
+ let called = false;
30
+ const result = await withFetch(async () => { called = true; return { ok: true, json: async () => ({ state: "complete" }) }; }, () => (0, init_1.checkoutCoverageComplete)("https://api.test", "tok", false));
31
+ strict_1.default.equal(result, false);
32
+ strict_1.default.equal(called, false, "must not even ask the server when this checkout's repo isn't confirmed registered");
33
+ });
34
+ (0, node_test_1.it)("fails open to false on a server error or network failure", async () => {
35
+ const errored = await withFetch(async () => ({ ok: false, json: async () => ({}) }), () => (0, init_1.checkoutCoverageComplete)("https://api.test", "tok", true));
36
+ strict_1.default.equal(errored, false);
37
+ const offline = await withFetch(async () => { throw new Error("network down"); }, () => (0, init_1.checkoutCoverageComplete)("https://api.test", "tok", true));
38
+ strict_1.default.equal(offline, false);
39
+ });
40
+ });
41
+ (0, node_test_1.describe)("shouldSkipLocalScan", () => {
42
+ (0, node_test_1.it)("skips when coverage is complete and neither --force nor --dry-run is set", () => {
43
+ strict_1.default.equal((0, init_1.shouldSkipLocalScan)(undefined, undefined, true), true);
44
+ });
45
+ (0, node_test_1.it)("--force always runs the full flow, even on a complete project", () => {
46
+ strict_1.default.equal((0, init_1.shouldSkipLocalScan)(true, undefined, true), false);
47
+ });
48
+ (0, node_test_1.it)("--dry-run always runs the full flow (dry-run stays fully local, never short-circuited)", () => {
49
+ strict_1.default.equal((0, init_1.shouldSkipLocalScan)(undefined, "/tmp/payload.json", true), false);
50
+ });
51
+ (0, node_test_1.it)("never skips when coverage is not complete", () => {
52
+ strict_1.default.equal((0, init_1.shouldSkipLocalScan)(undefined, undefined, false), false);
53
+ });
54
+ });
@@ -0,0 +1,62 @@
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
+ /** Validation fixtures only; no production or customer identifiers. */
7
+ const strict_1 = __importDefault(require("node:assert/strict"));
8
+ const node_fs_1 = __importDefault(require("node:fs"));
9
+ const node_os_1 = __importDefault(require("node:os"));
10
+ const node_path_1 = __importDefault(require("node:path"));
11
+ const node_child_process_1 = require("node:child_process");
12
+ const node_test_1 = require("node:test");
13
+ const install_hook_1 = require("../commands/install-hook");
14
+ function makeRepo() {
15
+ const root = node_fs_1.default.mkdtempSync(node_path_1.default.join(node_os_1.default.tmpdir(), "kodingo-install-hook-"));
16
+ (0, node_child_process_1.execFileSync)("git", ["init", "-q", root]);
17
+ return root;
18
+ }
19
+ (0, node_test_1.describe)("installHookCommand", () => {
20
+ (0, node_test_1.it)("installs once, reports installed:true, and never installs a second hook block on a repeat call", async () => {
21
+ const root = makeRepo();
22
+ const first = await (0, install_hook_1.installHookCommand)({ repo: root });
23
+ strict_1.default.equal(first, true);
24
+ const hookPath = node_path_1.default.join(root, ".git", "hooks", "post-commit");
25
+ const afterFirst = node_fs_1.default.readFileSync(hookPath, "utf-8");
26
+ strict_1.default.equal((afterFirst.match(/# <kodingo>/g) ?? []).length, 1);
27
+ const second = await (0, install_hook_1.installHookCommand)({ repo: root });
28
+ strict_1.default.equal(second, false, "a repeat install must report installed:false, so the caller prints exactly one accurate line");
29
+ const afterSecond = node_fs_1.default.readFileSync(hookPath, "utf-8");
30
+ strict_1.default.equal(afterSecond, afterFirst, "the hook file must be byte-identical — no duplicate kodingo block appended");
31
+ strict_1.default.equal((afterSecond.match(/# <kodingo>/g) ?? []).length, 1);
32
+ });
33
+ (0, node_test_1.it)("the deep-scan line is backgrounded end-to-end, under a portable (non-GNU-timeout-dependent) watchdog, with its output silenced", async () => {
34
+ const root = makeRepo();
35
+ await (0, install_hook_1.installHookCommand)({ repo: root });
36
+ const hook = node_fs_1.default.readFileSync(node_path_1.default.join(root, ".git", "hooks", "post-commit"), "utf-8");
37
+ // The whole deep-scan block is one backgrounded subshell...
38
+ strict_1.default.match(hook, /\(\n\s*".*" deep-scan .* --changed --yes --no-update >\/dev\/null 2>&1 &\n/);
39
+ strict_1.default.match(hook, /\) &\s*\n# <\/kodingo>/);
40
+ // ...with a sleep+kill watchdog that doesn't depend on the GNU `timeout`
41
+ // binary being installed (unlike a plain `command -v timeout` check).
42
+ strict_1.default.match(hook, /sleep 120.*kill -9/);
43
+ strict_1.default.doesNotMatch(hook, /command -v timeout/);
44
+ // scan-git and sync-dependencies are also silenced, so an uncaught
45
+ // exception in either never prints a stack trace to the user's terminal.
46
+ strict_1.default.match(hook, /scan-git --repo "\$\(git rev-parse --show-toplevel\)" >\/dev\/null 2>&1 &/);
47
+ strict_1.default.match(hook, /sync-dependencies --repo "\$\(git rev-parse --show-toplevel\)" >\/dev\/null 2>&1 &/);
48
+ });
49
+ (0, node_test_1.it)("never prompts: deep-scan always runs with --yes", async () => {
50
+ const root = makeRepo();
51
+ await (0, install_hook_1.installHookCommand)({ repo: root });
52
+ const hook = node_fs_1.default.readFileSync(node_path_1.default.join(root, ".git", "hooks", "post-commit"), "utf-8");
53
+ strict_1.default.match(hook, /--yes/);
54
+ });
55
+ (0, node_test_1.it)("is chmod +x so git will actually execute it, and is a post-commit hook (never blocks or fails the commit by construction)", async () => {
56
+ const root = makeRepo();
57
+ await (0, install_hook_1.installHookCommand)({ repo: root });
58
+ const hookPath = node_path_1.default.join(root, ".git", "hooks", "post-commit");
59
+ const mode = node_fs_1.default.statSync(hookPath).mode & 0o777;
60
+ strict_1.default.equal(mode, 0o755);
61
+ });
62
+ });
@@ -0,0 +1,89 @@
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
+ /** Validation fixtures only; no production or customer identifiers. */
7
+ const strict_1 = __importDefault(require("node:assert/strict"));
8
+ const node_test_1 = require("node:test");
9
+ const deep_scan_1 = require("../commands/deep-scan");
10
+ function withCapturedLog(run) {
11
+ const logs = [];
12
+ const original = console.log;
13
+ console.log = (...args) => { logs.push(args.join(" ")); };
14
+ try {
15
+ run();
16
+ }
17
+ finally {
18
+ console.log = original;
19
+ }
20
+ return logs;
21
+ }
22
+ (0, node_test_1.describe)("printFinalOutcome", () => {
23
+ (0, node_test_1.it)("prints an applied summary with entities/edges/files, and never sets a non-zero exit code", () => {
24
+ const originalExitCode = process.exitCode;
25
+ process.exitCode = undefined;
26
+ try {
27
+ const logs = withCapturedLog(() => (0, deep_scan_1.printFinalOutcome)({ applied: true, entity_count: 5, edge_count: 2, file_count: 3 }, true));
28
+ strict_1.default.ok(logs.some((line) => /Deep scan applied: 5 entities, 2 edges, 3 files/.test(line)));
29
+ strict_1.default.notEqual(process.exitCode, 1);
30
+ }
31
+ finally {
32
+ process.exitCode = originalExitCode;
33
+ }
34
+ });
35
+ (0, node_test_1.it)("never prints 'accepted' and, under --yes, exits non-zero when held", () => {
36
+ const originalExitCode = process.exitCode;
37
+ process.exitCode = undefined;
38
+ try {
39
+ const logs = withCapturedLog(() => (0, deep_scan_1.printFinalOutcome)({ applied: false, apply_reason: "dirty_checkout" }, true));
40
+ strict_1.default.ok(logs.some((line) => /^Deep scan held:/.test(line)));
41
+ strict_1.default.ok(!logs.some((line) => /accepted/i.test(line)));
42
+ strict_1.default.equal(process.exitCode, 1);
43
+ }
44
+ finally {
45
+ process.exitCode = originalExitCode;
46
+ }
47
+ });
48
+ (0, node_test_1.it)("does not force a non-zero exit when held outside --yes", () => {
49
+ const originalExitCode = process.exitCode;
50
+ process.exitCode = undefined;
51
+ try {
52
+ withCapturedLog(() => (0, deep_scan_1.printFinalOutcome)({ applied: false, apply_reason: "dirty_checkout" }, false));
53
+ strict_1.default.notEqual(process.exitCode, 1);
54
+ }
55
+ finally {
56
+ process.exitCode = originalExitCode;
57
+ }
58
+ });
59
+ });
60
+ (0, node_test_1.describe)("pollRun", () => {
61
+ (0, node_test_1.it)("returns as soon as the run reaches a terminal state, backing off between polls", async () => {
62
+ const original = global.fetch;
63
+ let calls = 0;
64
+ global.fetch = async () => {
65
+ calls += 1;
66
+ const state = calls < 2 ? "running" : "completed";
67
+ return { ok: true, status: 200, json: async () => ({ state }) };
68
+ };
69
+ try {
70
+ const run = await (0, deep_scan_1.pollRun)("https://api.test", "tok", "run-1", 5000);
71
+ strict_1.default.equal(run.state, "completed");
72
+ strict_1.default.equal(calls, 2);
73
+ }
74
+ finally {
75
+ global.fetch = original;
76
+ }
77
+ });
78
+ (0, node_test_1.it)("gives up and returns the last known state once the timeout elapses", async () => {
79
+ const original = global.fetch;
80
+ global.fetch = async () => ({ ok: true, status: 200, json: async () => ({ state: "running" }) });
81
+ try {
82
+ const run = await (0, deep_scan_1.pollRun)("https://api.test", "tok", "run-1", 1);
83
+ strict_1.default.equal(run.state, "running");
84
+ }
85
+ finally {
86
+ global.fetch = original;
87
+ }
88
+ });
89
+ });
@@ -118,3 +118,35 @@ function makeTempDir() {
118
118
  strict_1.default.equal(result, "fot");
119
119
  });
120
120
  });
121
+ (0, node_test_1.describe)("resolveRepoRegistration — the gate the complete-coverage shortcut needs", () => {
122
+ let dir;
123
+ const originalFetch = globalThis.fetch;
124
+ (0, node_test_1.beforeEach)(() => {
125
+ dir = makeTempDir();
126
+ (0, node_child_process_1.execSync)("git init -q", { cwd: dir });
127
+ (0, node_child_process_1.execSync)("git remote add origin https://github.com/abokidev/fot.git", { cwd: dir });
128
+ });
129
+ (0, node_test_1.afterEach)(() => {
130
+ node_fs_1.default.rmSync(dir, { recursive: true, force: true });
131
+ globalThis.fetch = originalFetch;
132
+ });
133
+ for (const matched of ["single-registered", "multi-matched"]) {
134
+ (0, node_test_1.it)(`alreadyRegistered:true when the server reports "${matched}" — a repo that pre-existed this call`, async () => {
135
+ globalThis.fetch = (async () => new Response(JSON.stringify({ repoName: "fot", registered: false, matched }), { status: 200 }));
136
+ const result = await (0, repo_identity_1.resolveRepoRegistration)({ repoRoot: dir, apiUrl: "https://example.invalid", token: "t" });
137
+ strict_1.default.deepEqual(result, { repoName: "fot", alreadyRegistered: true });
138
+ });
139
+ }
140
+ for (const matched of ["first-registration", "multi-new"]) {
141
+ (0, node_test_1.it)(`alreadyRegistered:false when the server reports "${matched}" — this call just registered it for the first time`, async () => {
142
+ globalThis.fetch = (async () => new Response(JSON.stringify({ repoName: "fot", registered: true, matched }), { status: 200 }));
143
+ const result = await (0, repo_identity_1.resolveRepoRegistration)({ repoRoot: dir, apiUrl: "https://example.invalid", token: "t" });
144
+ strict_1.default.deepEqual(result, { repoName: "fot", alreadyRegistered: false });
145
+ });
146
+ }
147
+ (0, node_test_1.it)("alreadyRegistered:false when the server is unreachable — never trust a merely-local fallback as a registered match", async () => {
148
+ globalThis.fetch = (async () => { throw new Error("network down"); });
149
+ const result = await (0, repo_identity_1.resolveRepoRegistration)({ repoRoot: dir, apiUrl: "https://example.invalid", token: "t" });
150
+ strict_1.default.deepEqual(result, { repoName: "fot", alreadyRegistered: false });
151
+ });
152
+ });