diff --git a/.coderabbit.yaml b/.coderabbit.yaml index a300ee5f..8e18f878 100644 --- a/.coderabbit.yaml +++ b/.coderabbit.yaml @@ -73,6 +73,6 @@ reviews: instructions: | - Ensure mocks are clean and shared correctly. - Verify that tests cover both happy paths and error conditions. - - pre_merge_checks: - linked_issue_assessment: - mode: "warning" \ No newline at end of file + pre_merge_checks: + issue_assessment: + mode: "warning" diff --git a/package-lock.json b/package-lock.json index a327cd72..b446fb3a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,6 +9,7 @@ "version": "3.1.0", "license": "AGPL-3.0-only", "dependencies": { + "@google/genai": "^1.30.0", "@kubernetes/client-node": "^1.4.0", "@vr_patel/tui": "^1.0.0", "chalk": "^6.0.0", @@ -16,17 +17,21 @@ "commander": "^15.0.0", "conf": "^16.0.0", "cosmiconfig": "^10.0.1", + "diff": "^8.0.3", "dockerode": "^5.0.0", "ink": "^8.0.0", "ink-spinner": "^5.0.0", "ink-text-input": "^6.0.0", "nodemailer": "^10.0.0", - "react": "^19.2.7" + "react": "^19.2.7", + "yaml": "^2.9.1", + "zod": "^3.25.76" }, "bin": { "kdm": "bin/kdm.js" }, "devDependencies": { + "@types/diff": "^8.0.0", "@types/dockerode": "^4.0.2", "@types/node": "^26.0.1", "@types/nodemailer": "^8.0.0", @@ -572,6 +577,30 @@ "node": ">=18" } }, + "node_modules/@google/genai": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/@google/genai/-/genai-1.52.0.tgz", + "integrity": "sha512-gwSvbpiN/17O9TbsqSsE/OzZcpv5Fo4RQjdngGgogtuB9RsyJ8ZHhX5KjHj1bp5N9snN2eK8LDGXSaWW2hof8Q==", + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "google-auth-library": "^10.3.0", + "p-retry": "^4.6.2", + "protobufjs": "^7.5.4", + "ws": "^8.18.0" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "@modelcontextprotocol/sdk": "^1.25.2" + }, + "peerDependenciesMeta": { + "@modelcontextprotocol/sdk": { + "optional": true + } + } + }, "node_modules/@grpc/grpc-js": { "version": "1.14.5", "resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.14.5.tgz", @@ -781,9 +810,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -970,9 +996,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -990,9 +1013,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1010,9 +1030,6 @@ "ppc64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1030,9 +1047,6 @@ "s390x" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1050,9 +1064,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1070,9 +1081,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1232,9 +1240,6 @@ "arm" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1249,9 +1254,6 @@ "arm" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1266,9 +1268,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1283,9 +1282,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1300,9 +1296,6 @@ "loong64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1317,9 +1310,6 @@ "loong64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1334,9 +1324,6 @@ "ppc64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1351,9 +1338,6 @@ "ppc64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1368,9 +1352,6 @@ "riscv64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1385,9 +1366,6 @@ "riscv64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1402,9 +1380,6 @@ "s390x" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1419,9 +1394,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1436,9 +1408,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1554,6 +1523,17 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/diff": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/@types/diff/-/diff-8.0.0.tgz", + "integrity": "sha512-o7jqJM04gfaYrdCecCVMbZhNdG6T1MHg/oQoRFdERLV+4d+V7FijhiEAbFu0Usww84Yijk9yH58U4Jk4HbtzZw==", + "deprecated": "This is a stub types definition. diff provides its own type definitions, so you do not need this installed.", + "dev": true, + "license": "MIT", + "dependencies": { + "diff": "*" + } + }, "node_modules/@types/docker-modem": { "version": "3.0.6", "resolved": "https://registry.npmjs.org/@types/docker-modem/-/docker-modem-3.0.6.tgz", @@ -1629,6 +1609,12 @@ "csstype": "^3.2.2" } }, + "node_modules/@types/retry": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/@types/retry/-/retry-0.12.0.tgz", + "integrity": "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==", + "license": "MIT" + }, "node_modules/@types/ssh2": { "version": "1.15.5", "resolved": "https://registry.npmjs.org/@types/ssh2/-/ssh2-1.15.5.tgz", @@ -2457,6 +2443,15 @@ "tweetnacl": "^0.14.3" } }, + "node_modules/bignumber.js": { + "version": "9.3.1", + "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.3.1.tgz", + "integrity": "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ==", + "license": "MIT", + "engines": { + "node": "*" + } + }, "node_modules/bl": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", @@ -2492,6 +2487,12 @@ "ieee754": "^1.1.13" } }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", + "license": "BSD-3-Clause" + }, "node_modules/buildcheck": { "version": "0.0.7", "resolved": "https://registry.npmjs.org/buildcheck/-/buildcheck-0.0.7.tgz", @@ -2947,6 +2948,15 @@ "devOptional": true, "license": "MIT" }, + "node_modules/data-uri-to-buffer": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz", + "integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, "node_modules/debounce-fn": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/debounce-fn/-/debounce-fn-6.0.0.tgz", @@ -2998,6 +3008,15 @@ "node": ">=8" } }, + "node_modules/diff": { + "version": "8.0.4", + "resolved": "https://registry.npmjs.org/diff/-/diff-8.0.4.tgz", + "integrity": "sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.3.1" + } + }, "node_modules/docker-modem": { "version": "5.0.7", "resolved": "https://registry.npmjs.org/docker-modem/-/docker-modem-5.0.7.tgz", @@ -3058,6 +3077,15 @@ "node": ">= 0.4" } }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, "node_modules/emoji-regex": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", @@ -3253,6 +3281,12 @@ "node": ">=12.0.0" } }, + "node_modules/extend": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", + "license": "MIT" + }, "node_modules/fast-deep-equal": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", @@ -3299,6 +3333,29 @@ } } }, + "node_modules/fetch-blob": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz", + "integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "paypal", + "url": "https://paypal.me/jimmywarting" + } + ], + "license": "MIT", + "dependencies": { + "node-domexception": "^1.0.0", + "web-streams-polyfill": "^3.0.3" + }, + "engines": { + "node": "^12.20 || >= 14.13" + } + }, "node_modules/fix-dts-default-cjs-exports": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/fix-dts-default-cjs-exports/-/fix-dts-default-cjs-exports-1.0.1.tgz", @@ -3327,6 +3384,18 @@ "node": ">= 6" } }, + "node_modules/formdata-polyfill": { + "version": "4.0.10", + "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz", + "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==", + "license": "MIT", + "dependencies": { + "fetch-blob": "^3.1.2" + }, + "engines": { + "node": ">=12.20.0" + } + }, "node_modules/fs-constants": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", @@ -3357,6 +3426,52 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/gaxios": { + "version": "7.3.1", + "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-7.3.1.tgz", + "integrity": "sha512-kB3rzJV7d9juLZh8/56QTXCwQfxyhdOMdyYk1HdQKFtF8TJTDTZQJtixWIwXdE9Jji91mC41DUNpjleo4L4eAQ==", + "license": "Apache-2.0", + "dependencies": { + "extend": "^3.0.2", + "https-proxy-agent": "^7.0.1", + "node-fetch": "^3.3.2" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/gaxios/node_modules/node-fetch": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz", + "integrity": "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==", + "license": "MIT", + "dependencies": { + "data-uri-to-buffer": "^4.0.0", + "fetch-blob": "^3.1.4", + "formdata-polyfill": "^4.0.10" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/node-fetch" + } + }, + "node_modules/gcp-metadata": { + "version": "8.1.2", + "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-8.1.2.tgz", + "integrity": "sha512-zV/5HKTfCeKWnxG0Dmrw51hEWFGfcF2xiXqcA3+J90WDuP0SvoiSO5ORvcBsifmx/FoIjgQN3oNOGaQ5PhLFkg==", + "license": "Apache-2.0", + "dependencies": { + "gaxios": "^7.0.0", + "google-logging-utils": "^1.0.0", + "json-bigint": "^1.0.0" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/get-caller-file": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", @@ -3415,6 +3530,32 @@ "node": ">= 0.4" } }, + "node_modules/google-auth-library": { + "version": "10.9.1", + "resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-10.9.1.tgz", + "integrity": "sha512-i1ydyHrqcIxXkWh/uBmVkzCvIuq5yiK2ATndIe5XxKholrG/MTYP9xGYka4sQhrbIAgGjL2B6NOE7rFaiF3fXw==", + "license": "Apache-2.0", + "dependencies": { + "base64-js": "^1.3.0", + "ecdsa-sig-formatter": "^1.0.11", + "gaxios": "^7.1.4", + "gcp-metadata": "8.1.2", + "google-logging-utils": "1.1.3", + "jws": "^4.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/google-logging-utils": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/google-logging-utils/-/google-logging-utils-1.1.3.tgz", + "integrity": "sha512-eAmLkjDjAFCVXg7A1unxHsLf961m6y17QFqXqAXGj/gVkKFrEICfStRfwUlGNfeCEjNRa32JEWOUTlYXPyyKvA==", + "license": "Apache-2.0", + "engines": { + "node": ">=14" + } + }, "node_modules/gopd": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", @@ -3492,6 +3633,19 @@ "dev": true, "license": "MIT" }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, "node_modules/husky": { "version": "9.1.7", "resolved": "https://registry.npmjs.org/husky/-/husky-9.1.7.tgz", @@ -3826,6 +3980,15 @@ "node": ">= 10.16.0" } }, + "node_modules/json-bigint": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-bigint/-/json-bigint-1.0.0.tgz", + "integrity": "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ==", + "license": "MIT", + "dependencies": { + "bignumber.js": "^9.0.0" + } + }, "node_modules/json-schema-typed": { "version": "8.0.2", "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz", @@ -3850,6 +4013,27 @@ "node": ">=18.0.0" } }, + "node_modules/jwa": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz", + "integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==", + "license": "MIT", + "dependencies": { + "buffer-equal-constant-time": "^1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jws": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz", + "integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==", + "license": "MIT", + "dependencies": { + "jwa": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, "node_modules/lightningcss": { "version": "1.33.0", "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", @@ -4602,6 +4786,26 @@ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" } }, + "node_modules/node-domexception": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", + "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", + "deprecated": "Use your platform's native DOMException instead", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ], + "license": "MIT", + "engines": { + "node": ">=10.5.0" + } + }, "node_modules/node-fetch": { "version": "2.7.0", "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", @@ -4697,6 +4901,19 @@ "url": "https://github.com/sponsors/panva" } }, + "node_modules/p-retry": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/p-retry/-/p-retry-4.6.2.tgz", + "integrity": "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ==", + "license": "MIT", + "dependencies": { + "@types/retry": "0.12.0", + "retry": "^0.13.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/patch-console": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/patch-console/-/patch-console-2.0.0.tgz", @@ -4956,6 +5173,15 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/retry": { + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz", + "integrity": "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==", + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, "node_modules/rfc4648": { "version": "1.5.4", "resolved": "https://registry.npmjs.org/rfc4648/-/rfc4648-1.5.4.tgz", @@ -5881,6 +6107,15 @@ } } }, + "node_modules/web-streams-polyfill": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz", + "integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==", + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, "node_modules/webidl-conversions": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", @@ -6022,7 +6257,6 @@ "version": "2.9.1", "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.1.tgz", "integrity": "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==", - "dev": true, "license": "ISC", "bin": { "yaml": "bin.mjs" @@ -6066,6 +6300,15 @@ "resolved": "https://registry.npmjs.org/yoga-layout/-/yoga-layout-3.2.1.tgz", "integrity": "sha512-0LPOt3AxKqMdFBZA3HBAt/t/8vIKq7VaQYbuA8WxCgung+p9TVyKRYdpvCb80HcdTN2NkbIKbhNwKUfm3tQywQ==", "license": "MIT" + }, + "node_modules/zod": { + "version": "3.25.76", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", + "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } } } } diff --git a/package.json b/package.json index 97bac484..c158c077 100644 --- a/package.json +++ b/package.json @@ -27,7 +27,8 @@ "LICENSE" ], "scripts": { - "build": "tsup src/index.ts --format esm && tsc --emitDeclarationOnly --declaration --outDir dist", + "prebuild": "rm -rf dist", + "build": "rm -rf dist && tsup src/index.ts --format esm && tsc --emitDeclarationOnly --declaration --outDir dist", "dev": "tsup src/index.ts --format esm --watch", "pretest": "npm run build", "test": "vitest run --pool=forks --maxWorkers=1", @@ -46,6 +47,7 @@ "author": "", "license": "AGPL-3.0-only", "dependencies": { + "@google/genai": "^1.30.0", "@kubernetes/client-node": "^1.4.0", "@vr_patel/tui": "^1.0.0", "chalk": "^6.0.0", @@ -53,14 +55,18 @@ "commander": "^15.0.0", "conf": "^16.0.0", "cosmiconfig": "^10.0.1", + "diff": "^8.0.3", "dockerode": "^5.0.0", "ink": "^8.0.0", "ink-spinner": "^5.0.0", "ink-text-input": "^6.0.0", "nodemailer": "^10.0.0", - "react": "^19.2.7" + "react": "^19.2.7", + "yaml": "^2.9.1", + "zod": "^3.25.76" }, "devDependencies": { + "@types/diff": "^8.0.0", "@types/dockerode": "^4.0.2", "@types/node": "^26.0.1", "@types/nodemailer": "^8.0.0", diff --git a/src/__tests__/agent-registry.test.ts b/src/__tests__/agent-registry.test.ts new file mode 100644 index 00000000..481e2342 --- /dev/null +++ b/src/__tests__/agent-registry.test.ts @@ -0,0 +1,225 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { z } from 'zod'; +import { AgentRegistry, defaultAgentRegistry } from '../agent/registry.js'; +import { AgentTool } from '../agent/agent-tool.js'; +import type { AgentDefinition } from '../agent/types.js'; +import { CodebaseInvestigatorAgent } from '../agent/investigator.js'; + +describe('AgentRegistry (F-04)', () => { + let registry: AgentRegistry; + + beforeEach(() => { + registry = new AgentRegistry(); + }); + + it('TC-REG-01: Agent registration and listing', () => { + const runtimeAgent: AgentDefinition = { + name: 'RuntimeLogAgent', + description: 'Analyzes container logs and exit codes', + inputSchema: z.object({ prompt: z.string() }), + outputSchema: z.object({ finding: z.string() }), + run: async (input) => ({ finding: `Logs checked for ${input.prompt}` }), + }; + + const configAgent: AgentDefinition = { + name: 'ConfigDependencyAgent', + description: 'Validates Kubernetes ConfigMaps, Secrets, Volumes', + inputSchema: z.object({ prompt: z.string() }), + outputSchema: z.object({ finding: z.string() }), + run: async (input) => ({ finding: `Config verified for ${input.prompt}` }), + }; + + registry.register(runtimeAgent); + registry.register(configAgent); + + const list = registry.list(); + expect(list).toHaveLength(2); + expect(registry.getNames()).toEqual(['RuntimeLogAgent', 'ConfigDependencyAgent']); + }); + + it('TC-REG-02: Agent retrieval by name', () => { + const resourceAgent: AgentDefinition = { + name: 'ClusterResourceAgent', + description: 'Evaluates node memory pressure and cgroups', + inputSchema: z.object({ prompt: z.string() }), + outputSchema: z.object({ status: z.string() }), + run: async () => ({ status: 'healthy' }), + }; + + registry.register(resourceAgent); + + expect(registry.get('ClusterResourceAgent')?.name).toBe('ClusterResourceAgent'); + expect(registry.get('NonExistentAgent')).toBeUndefined(); + expect(registry.has('ClusterResourceAgent')).toBe(true); + expect(registry.has('NonExistentAgent')).toBe(false); + }); + + it('TC-REG-03: Name, schema, and run validation on registration', () => { + // Missing or invalid object + expect(() => registry.register(null as any)).toThrow(/Agent definition must be a valid object/); + expect(() => registry.register(undefined as any)).toThrow(/Agent definition must be a valid object/); + + // Missing name + expect(() => + registry.register({ + name: '', + description: 'No name', + inputSchema: z.any(), + outputSchema: z.any(), + run: async () => {}, + } as any) + ).toThrow(/Agent name must be defined/); + + // Missing inputSchema + expect(() => + registry.register({ + name: 'BadAgent', + description: 'Missing inputSchema', + inputSchema: null as any, + outputSchema: z.any(), + run: async () => {}, + }) + ).toThrow(/must define inputSchema and outputSchema/); + + // Missing outputSchema + expect(() => + registry.register({ + name: 'BadAgent', + description: 'Missing outputSchema', + inputSchema: z.any(), + outputSchema: null as any, + run: async () => {}, + }) + ).toThrow(/must define inputSchema and outputSchema/); + + // Missing run function + expect(() => + registry.register({ + name: 'BadAgent', + description: 'Missing run', + inputSchema: z.any(), + outputSchema: z.any(), + run: 'not a function' as any, + }) + ).toThrow(/must define an executable run\(\) function/); + }); + + it('cannot reset recursive delegation depth through model input', async () => { + const tool = new AgentTool(registry, 2); + const run = vi.fn(async (_input, context) => + tool.execute({ agent_name: 'RecursiveAgent', prompt: 'delegate', depth: 0, context: { depth: 0 } }, context) + ); + registry.register({ + name: 'RecursiveAgent', description: 'Delegates again', + inputSchema: z.object({ prompt: z.string() }), outputSchema: z.unknown(), run, + }); + + await expect(tool.execute({ agent_name: 'RecursiveAgent', prompt: 'start' })) + .rejects.toThrow(/Depth 2 exceeded max limit 2/); + expect(run).toHaveBeenCalledTimes(2); + }); + + it('TC-REG-04: Input schema validation by agent definition', () => { + const agent: AgentDefinition<{ podName: string; tailLines: number }, { logs: string[] }> = { + name: 'LogAgent', + description: 'Fetches logs', + inputSchema: z.object({ + podName: z.string().min(1), + tailLines: z.number().int().positive(), + }), + outputSchema: z.object({ logs: z.array(z.string()) }), + run: async (input) => ({ logs: [`log line from ${input.podName}`] }), + }; + + registry.register(agent); + + const valid = agent.inputSchema.parse({ podName: 'payment-api', tailLines: 100 }); + expect(valid.podName).toBe('payment-api'); + + expect(() => agent.inputSchema.parse({ podName: '', tailLines: 100 })).toThrow(); + expect(() => agent.inputSchema.parse({ podName: 'payment-api', tailLines: -5 })).toThrow(); + }); + + it('TC-REG-05: Output schema validation by agent definition', () => { + const agent: AgentDefinition<{ prompt: string }, { finding: string; confidence: number }> = { + name: 'DiagnosticAgent', + description: 'Diagnoses issues', + inputSchema: z.object({ prompt: z.string() }), + outputSchema: z.object({ + finding: z.string(), + confidence: z.number().min(0).max(1), + }), + run: async () => ({ finding: 'OOM error', confidence: 0.95 }), + }; + + registry.register(agent); + + const validOutput = agent.outputSchema.parse({ finding: 'OOM error', confidence: 0.95 }); + expect(validOutput.confidence).toBe(0.95); + + expect(() => agent.outputSchema.parse({ finding: 'OOM error', confidence: 1.5 })).toThrow(); + }); + + it('TC-REG-06: Registry clear, unregister, and state isolation', () => { + const agentA: AgentDefinition = { + name: 'AgentA', + description: 'Agent A', + inputSchema: z.any(), + outputSchema: z.any(), + run: async () => ({}), + }; + const agentB: AgentDefinition = { + name: 'AgentB', + description: 'Agent B', + inputSchema: z.any(), + outputSchema: z.any(), + run: async () => ({}), + }; + + registry.registerAll([agentA, agentB]); + expect(registry.list()).toHaveLength(2); + + expect(registry.unregister('AgentA')).toBe(true); + expect(registry.has('AgentA')).toBe(false); + expect(registry.list()).toHaveLength(1); + + expect(registry.unregister('NonExistent')).toBe(false); + + registry.clear(); + expect(registry.list()).toHaveLength(0); + + // Isolation check: another registry instance is unaffected + const otherRegistry = new AgentRegistry(); + otherRegistry.register(agentA); + expect(otherRegistry.list()).toHaveLength(1); + expect(registry.list()).toHaveLength(0); + }); + + it('TC-REG-07: Specialist agent registration including CodebaseInvestigatorAgent', () => { + const codebaseAgentDef = CodebaseInvestigatorAgent.toDefinition(); + expect(codebaseAgentDef.name).toBe('CodebaseInvestigatorAgent'); + + registry.register(codebaseAgentDef); + expect(registry.has('CodebaseInvestigatorAgent')).toBe(true); + + const retrieved = registry.get('CodebaseInvestigatorAgent'); + expect(retrieved?.description).toContain('Specialized agent that inspects local workspace manifests'); + }); + + it('TC-REG-08: defaultAgentRegistry singleton operations', () => { + defaultAgentRegistry.clear(); + expect(defaultAgentRegistry.list()).toHaveLength(0); + + const testAgent: AgentDefinition = { + name: 'SingletonTestAgent', + description: 'Testing singleton', + inputSchema: z.any(), + outputSchema: z.any(), + run: async () => ({ ok: true }), + }; + + defaultAgentRegistry.register(testAgent); + expect(defaultAgentRegistry.has('SingletonTestAgent')).toBe(true); + defaultAgentRegistry.clear(); + }); +}); diff --git a/src/__tests__/ai-google-genai.test.ts b/src/__tests__/ai-google-genai.test.ts new file mode 100644 index 00000000..953659f4 --- /dev/null +++ b/src/__tests__/ai-google-genai.test.ts @@ -0,0 +1,534 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { GoogleGenAIClient } from '../ai/google-genai'; +import { GeminiSession } from '../ai/gemini-session'; +import { createAIClient } from '../ai/factory'; +import { AIProviderConfig } from '../config/schema'; +import { z } from 'zod'; + +describe('Feature F-02: Google Gemini Modern SDK Provider', () => { + beforeEach(() => { + vi.clearAllMocks(); + delete process.env.GEMINI_API_KEY; + delete process.env.GOOGLE_GENAI_API_KEY; + delete process.env.GOOGLE_API_KEY; + }); + + it('TC-AI-01: Client configuration and initialization via AIProviderConfig', async () => { + const client = new GoogleGenAIClient(); + const config: AIProviderConfig = { + name: 'google-genai', + provider: 'google-genai', + password: 'test-api-key-12345', + model: 'gemini-2.5-flash', + temperature: 0.3, + topP: 0.95, + maxTokens: 2048, + baseUrl: 'https://custom-gateway.googleapis.com', + customHeaders: { 'X-KDM-Test': 'true' }, + }; + + await client.configure(config); + expect(client.name).toBe('google-genai'); + expect((client as any).apiKey).toBe('test-api-key-12345'); + expect((client as any).model).toBe('gemini-2.5-flash'); + expect((client as any).temperature).toBe(0.3); + expect((client as any).topP).toBe(0.95); + expect((client as any).maxOutputTokens).toBe(2048); + expect((client as any).baseUrl).toBe('https://custom-gateway.googleapis.com'); + }); + + it('TC-AI-02: Missing API key rejection', async () => { + const client = new GoogleGenAIClient(); + const badConfig: AIProviderConfig = { + name: 'google-genai', + provider: 'google-genai', + password: '', + }; + + await expect(client.configure(badConfig)).rejects.toThrow( + /API key is required for Google GenAI provider/i + ); + }); + + it('TC-AI-03: Single-turn completion via client.getCompletion(prompt)', async () => { + const mockGenerateContent = vi.fn().mockResolvedValue({ + text: 'Container payment-service is healthy with 0 restarts.', + candidates: [ + { + content: { + parts: [{ text: 'Container payment-service is healthy with 0 restarts.' }], + role: 'model', + }, + }, + ], + }); + + const mockClient = { + models: { + generateContent: mockGenerateContent, + }, + }; + + const client = new GoogleGenAIClient(mockClient); + await client.configure({ + name: 'google-genai', + password: 'mock-key', + model: 'gemini-2.0-flash', + temperature: 0.5, + }); + + const completion = await client.getCompletion('Check health of payment-service'); + expect(completion).toBe('Container payment-service is healthy with 0 restarts.'); + expect(mockGenerateContent).toHaveBeenCalledWith({ + model: 'gemini-2.0-flash', + contents: 'Check health of payment-service', + config: { + temperature: 0.5, + topP: undefined, + topK: undefined, + maxOutputTokens: undefined, + }, + }); + }); + + it('TC-AI-04: Streaming content generation yielding StreamChunk async iterable', async () => { + const chunks = [ + { + text: 'Analyzing ', + candidates: [{ content: { parts: [{ text: 'Analyzing ' }] } }], + }, + { + text: 'cluster ', + candidates: [{ content: { parts: [{ text: 'cluster ' }] } }], + }, + { + text: 'metrics...', + candidates: [{ content: { parts: [{ text: 'metrics...' }] } }], + }, + ]; + + const mockStream = { + async *[Symbol.asyncIterator]() { + for (const c of chunks) { + yield c; + } + }, + }; + + const mockClient = { + models: { + generateContentStream: vi.fn().mockResolvedValue(mockStream), + }, + }; + + const client = new GoogleGenAIClient(mockClient); + await client.configure({ name: 'google-genai', password: 'mock' }); + + const receivedDeltas: string[] = []; + const onText = vi.fn((delta: string) => receivedDeltas.push(delta)); + + const stream = client.generateContentStream('Diagnose', { onText }); + const collected: string[] = []; + + for await (const chunk of stream) { + if (chunk.text) { + collected.push(chunk.text); + } + } + + expect(collected).toEqual(['Analyzing ', 'cluster ', 'metrics...']); + expect(receivedDeltas).toEqual(['Analyzing ', 'cluster ', 'metrics...']); + expect(onText).toHaveBeenCalledTimes(3); + }); + + it('TC-AI-05: Streaming failure handling (network disconnect mid-stream)', async () => { + const errorStream = { + async *[Symbol.asyncIterator]() { + yield { + text: 'Beginning analysis...', + candidates: [{ content: { parts: [{ text: 'Beginning analysis...' }] } }], + }; + throw new Error('ECONNRESET: Connection to Generative Language API lost'); + }, + }; + + const mockClient = { + models: { + generateContentStream: vi.fn().mockResolvedValue(errorStream), + }, + }; + + const client = new GoogleGenAIClient(mockClient); + await client.configure({ name: 'google-genai', password: 'mock' }); + + const iterate = async () => { + const stream = client.generateContentStream('Diagnose'); + for await (const chunk of stream) { + // iterate + } + }; + + await expect(iterate()).rejects.toThrow('ECONNRESET'); + }); + + it('TC-AI-06: Thinking mode token handling (thought: true)', async () => { + const streamWithThoughts = { + async *[Symbol.asyncIterator]() { + yield { + candidates: [ + { + content: { + parts: [{ thought: true, text: 'Thinking about exit code 137...' }], + }, + }, + ], + }; + yield { + candidates: [ + { + content: { + parts: [{ thought: true, text: 'Correlating with memory limits...' }], + }, + }, + ], + }; + yield { + text: 'Root Cause: Out of Memory error.', + candidates: [ + { + content: { + parts: [{ text: 'Root Cause: Out of Memory error.' }], + }, + }, + ], + }; + }, + }; + + const mockClient = { + models: { + generateContentStream: vi.fn().mockResolvedValue(streamWithThoughts), + }, + }; + + const client = new GoogleGenAIClient(mockClient); + await client.configure({ name: 'google-genai', password: 'mock' }); + + const thoughts: string[] = []; + const texts: string[] = []; + + const onThought = vi.fn((t: string) => thoughts.push(t)); + const onText = vi.fn((txt: string) => texts.push(txt)); + + const stream = client.generateContentStream('Analyze', { + thinkingConfig: { includeThoughts: true }, + onThought, + onText, + }); + + for await (const chunk of stream) { + if (chunk.isThought && chunk.thought) { + expect(chunk.text).toBeUndefined(); + } + } + + expect(thoughts).toEqual([ + 'Thinking about exit code 137...', + 'Correlating with memory limits...', + ]); + expect(texts).toEqual(['Root Cause: Out of Memory error.']); + expect(onThought).toHaveBeenCalledTimes(2); + expect(onText).toHaveBeenCalledTimes(1); + }); + + it('TC-AI-07: Function / tool calling schema delivery and parameter reception', async () => { + const toolCallStream = { + async *[Symbol.asyncIterator]() { + yield { + candidates: [ + { + content: { + parts: [ + { + functionCall: { + name: 'k8s_get_resources', + args: { kind: 'pod', namespace: 'production' }, + id: 'call-1', + }, + }, + ], + }, + }, + ], + }; + }, + }; + + const mockClient = { + models: { + generateContentStream: vi.fn().mockResolvedValue(toolCallStream), + }, + }; + + const client = new GoogleGenAIClient(mockClient); + await client.configure({ name: 'google-genai', password: 'mock' }); + + const onFunctionCall = vi.fn(); + const stream = client.generateContentStream('List pods', { onFunctionCall }); + + let functionCallsFound = 0; + for await (const chunk of stream) { + if (chunk.functionCalls) { + functionCallsFound += chunk.functionCalls.length; + expect(chunk.functionCalls[0].name).toBe('k8s_get_resources'); + expect(chunk.functionCalls[0].args).toEqual({ kind: 'pod', namespace: 'production' }); + } + } + + expect(functionCallsFound).toBe(1); + expect(onFunctionCall).toHaveBeenCalledWith({ + name: 'k8s_get_resources', + args: { kind: 'pod', namespace: 'production' }, + id: 'call-1', + }); + }); + + it('TC-AI-08: GeminiSession multi-turn conversation preserving history', async () => { + const responses = [ + 'Hello SRE! How can I assist with your cluster today?', + 'Cluster health check completed. All nodes are Ready.', + ]; + let callIdx = 0; + + const mockClient = { + models: { + generateContentStream: vi.fn().mockImplementation(async () => ({ + async *[Symbol.asyncIterator]() { + const resp = responses[callIdx++]; + yield { + text: resp, + candidates: [{ content: { parts: [{ text: resp }] } }], + }; + }, + })), + }, + }; + + const session = new GeminiSession(mockClient, { model: 'gemini-2.0-flash' }); + + // Turn 1 + const res1 = await session.sendMessage('Hello'); + expect(res1.text).toBe('Hello SRE! How can I assist with your cluster today?'); + expect(session.getHistory()).toHaveLength(2); + expect(session.getHistory()[0].role).toBe('user'); + expect(session.getHistory()[0].parts[0].text).toBe('Hello'); + expect(session.getHistory()[1].role).toBe('model'); + + // Turn 2 + const res2 = await session.sendMessage('Check cluster'); + expect(res2.text).toBe('Cluster health check completed. All nodes are Ready.'); + expect(session.getHistory()).toHaveLength(4); + expect(session.getHistory()[2].role).toBe('user'); + expect(session.getHistory()[2].parts[0].text).toBe('Check cluster'); + expect(session.getHistory()[3].role).toBe('model'); + }); + + const createSignedToolClient = () => { + let callStep = 0; + return { + models: { + generateContentStream: vi.fn().mockImplementation(async () => ({ + async *[Symbol.asyncIterator]() { + if (callStep === 0) { + callStep++; + yield { + candidates: [{ + content: { + parts: [{ + thoughtSignature: 'c2lnbmVk', + functionCall: { + name: 'k8s_get_resources', + args: { kind: 'pod', namespace: 'default' }, + id: 'call-abc', + }, + }], + }, + }], + }; + return; + } + yield { + text: 'Found 2 pods in default namespace: payment-api and web.', + candidates: [{ content: { parts: [{ text: 'Found 2 pods in default namespace: payment-api and web.' }] } }], + }; + }, + })), + }, + }; + }; + + it.each(['sendMessage', 'sendMessageStream'] as const)('preserves signed tool calls in %s', async method => { + const mockClient = createSignedToolClient(); + const toolHandler = vi.fn().mockResolvedValue({ count: 2, pods: ['payment-api', 'web'] }); + const session = new GeminiSession(mockClient, { model: 'gemini-2.0-flash', toolHandler }); + + if (method === 'sendMessage') { + const response = await session.sendMessage('Show pods'); + expect(response.text).toBe('Found 2 pods in default namespace: payment-api and web.'); + } else { + const text: string[] = []; + for await (const chunk of session.sendMessageStream('Show pods')) { + if (chunk.text) text.push(chunk.text); + } + expect(text.join('')).toBe('Found 2 pods in default namespace: payment-api and web.'); + } + expect(toolHandler).toHaveBeenCalledWith('k8s_get_resources', { kind: 'pod', namespace: 'default' }); + const history = session.getHistory(); + expect(history).toHaveLength(4); + expect(mockClient.models.generateContentStream.mock.calls[1][0].contents[1].parts[0]) + .toMatchObject({ thoughtSignature: 'c2lnbmVk', functionCall: { id: 'call-abc' } }); + expect(history[2].role).toBe('user'); + expect(history[2].parts[0].functionResponse?.name).toBe('k8s_get_resources'); + }); + + it('TC-AI-10: GeminiSession max tool roundtrips guard prevents infinite loop', async () => { + // Model continuously emits functionCalls without stopping + const mockClient = { + models: { + generateContentStream: vi.fn().mockImplementation(async () => ({ + async *[Symbol.asyncIterator]() { + yield { + candidates: [ + { + content: { + parts: [ + { + functionCall: { + name: 'infinite_tool', + args: {}, + id: 'loop-id', + }, + }, + ], + }, + }, + ], + }; + }, + })), + }, + }; + + const toolHandler = vi.fn().mockResolvedValue({ ok: true }); + const session = new GeminiSession(mockClient, { + model: 'gemini-2.0-flash', + toolHandler, + maxToolRoundtrips: 3, + }); + + const res = await session.sendMessage('Run infinite loop'); + expect(toolHandler).toHaveBeenCalledTimes(3); + expect(res.functionCalls).toHaveLength(1); + }); + + it('TC-AI-11: Structured JSON output validation with Zod schema', async () => { + const analysisSchema = z.object({ + rootCause: z.string(), + severity: z.enum(['low', 'medium', 'high', 'critical']), + recommendedAction: z.string(), + }); + + type AnalysisResult = z.infer; + + const mockOutput: AnalysisResult = { + rootCause: 'OOMKilled due to container memory limit exhaustion (512Mi)', + severity: 'high', + recommendedAction: 'Increase limits.memory to 1024Mi', + }; + + const mockClient = { + models: { + generateContent: vi.fn().mockResolvedValue({ + text: JSON.stringify(mockOutput), + candidates: [ + { + content: { + parts: [{ text: JSON.stringify(mockOutput) }], + }, + }, + ], + }), + }, + }; + + const client = new GoogleGenAIClient(mockClient); + await client.configure({ name: 'google-genai', password: 'mock' }); + + const result = await client.getStructuredOutput('Analyze crash', { + validator: analysisSchema, + }); + + expect(result.rootCause).toContain('OOMKilled'); + expect(result.severity).toBe('high'); + expect(result.recommendedAction).toBe('Increase limits.memory to 1024Mi'); + }); + + it('TC-AI-12: Structured JSON output error handling for malformed non-JSON output', async () => { + const mockClient = { + models: { + generateContent: vi.fn().mockResolvedValue({ + text: 'Sorry, I am unable to format this as valid JSON.', + }), + }, + }; + + const client = new GoogleGenAIClient(mockClient); + await client.configure({ name: 'google-genai', password: 'mock' }); + + await expect( + client.getStructuredOutput('Analyze crash', { schema: {} }) + ).rejects.toThrow(/Failed to parse structured JSON output/); + }); + + it('TC-AI-13: AIFactory resolution for "google-genai"', async () => { + process.env.GEMINI_API_KEY = 'factory-test-key'; + const client = await createAIClient('google-genai'); + expect(client).toBeInstanceOf(GoogleGenAIClient); + expect(client.name).toBe('google-genai'); + }); + + it('TC-AI-14: AIFactory backward compatibility for "google-gemini"', async () => { + await expect(createAIClient('google-gemini')).rejects.toThrow( + 'API key (password) is required for google-gemini provider' + ); + }); + + it('TC-AI-15: AIFactory alias resolution for "gemini"', async () => { + process.env.GEMINI_API_KEY = 'factory-test-key'; + const client = await createAIClient('gemini'); + expect(client).toBeInstanceOf(GoogleGenAIClient); + expect(client.name).toBe('google-genai'); + }); + + it('exposes original signed parts in generateContentStream and preserves session defaults', async () => { + const signedPart = { functionCall: { name: 'k8s_get_pod', args: { name: 'api' } }, thoughtSignature: 'sig-xyz' }; + const mockClient = { + models: { + generateContentStream: vi.fn().mockResolvedValue({ + async *[Symbol.asyncIterator]() { + yield { candidates: [{ content: { parts: [signedPart] } }] }; + }, + }), + }, + }; + const client = new GoogleGenAIClient(mockClient); + await client.configure({ name: 'google-genai', password: 'mock', model: 'gemini-2.5-pro', temperature: 0 }); + const chunks = []; + for await (const chunk of client.generateContentStream('check')) chunks.push(chunk); + expect(chunks[0].parts).toEqual([signedPart]); + + const session = client.createSession({ model: undefined, temperature: undefined }) as any; + expect(session.model).toBe('gemini-2.5-pro'); + expect(session.temperature).toBe(0); + }); +}); diff --git a/src/__tests__/build-foundation.test.ts b/src/__tests__/build-foundation.test.ts new file mode 100644 index 00000000..332f61bd --- /dev/null +++ b/src/__tests__/build-foundation.test.ts @@ -0,0 +1,237 @@ +import { describe, it, expect } from 'vitest'; +import fs from 'node:fs'; +import path from 'node:path'; +import EventEmitter from 'node:events'; +import { GoogleGenAI } from '@google/genai'; +import { z } from 'zod'; +import { createTwoFilesPatch, diffLines } from 'diff'; +import { createAIClient } from '../ai/factory'; + +describe('Milestone 1: Build & Foundation (F-01)', () => { + const rootDir = path.resolve(__dirname, '../..'); + + describe('package.json dependencies', () => { + it('declares required runtime and dev dependencies with expected versions', () => { + const packageJsonPath = path.join(rootDir, 'package.json'); + expect(fs.existsSync(packageJsonPath)).toBe(true); + + const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')); + + expect(pkg.dependencies).toBeDefined(); + expect(pkg.dependencies['@google/genai']).toBe('^1.30.0'); + expect(pkg.dependencies['zod']).toBe('^3.25.76'); + expect(pkg.dependencies['diff']).toBe('^8.0.3'); + + expect(pkg.devDependencies).toBeDefined(); + expect(pkg.devDependencies['@types/diff']).toBe('^8.0.0'); + }); + + it('configures an automated clean step in the build pipeline', () => { + const packageJsonPath = path.join(rootDir, 'package.json'); + const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')); + + expect(pkg.scripts).toBeDefined(); + const hasCleanInBuild = typeof pkg.scripts.build === 'string' && pkg.scripts.build.includes('rm -rf dist'); + const hasPrebuildClean = typeof pkg.scripts.prebuild === 'string' && pkg.scripts.prebuild.includes('rm -rf dist'); + expect(hasCleanInBuild || hasPrebuildClean).toBe(true); + }); + }); + + describe('@google/genai SDK availability', () => { + it('imports @google/genai and exports the GoogleGenAI class', () => { + expect(GoogleGenAI).toBeDefined(); + expect(typeof GoogleGenAI).toBe('function'); + + const ai = new GoogleGenAI({ apiKey: 'test-fake-key' }); + expect(ai).toBeInstanceOf(GoogleGenAI); + expect(ai.models).toBeDefined(); + }); + }); + + describe('zod schema parsing and validation', () => { + it('parses valid objects and rejects invalid structures with ZodError', () => { + const ToolCallSchema = z.object({ + name: z.string().min(1), + args: z.record(z.unknown()), + timeout: z.number().int().positive().default(5000), + }); + + const validPayload = { + name: 'k8s_get_pods', + args: { namespace: 'default' }, + }; + + const parsed = ToolCallSchema.parse(validPayload); + expect(parsed.name).toBe('k8s_get_pods'); + expect(parsed.args).toEqual({ namespace: 'default' }); + expect(parsed.timeout).toBe(5000); + + const invalidPayload = { + name: '', + args: 'not-an-object', + timeout: -10, + }; + + const result = ToolCallSchema.safeParse(invalidPayload); + expect(result.success).toBe(false); + if (!result.success) { + expect(result.error.issues.length).toBeGreaterThan(0); + } + }); + }); + + describe('diff patch generation', () => { + it('creates unified two-file patches and computes line diffs', () => { + const oldYaml = 'apiVersion: v1\nkind: Pod\nspec:\n replicas: 1\n'; + const newYaml = 'apiVersion: v1\nkind: Pod\nspec:\n replicas: 3\n'; + + const patch = createTwoFilesPatch('pod-v1.yaml', 'pod-v2.yaml', oldYaml, newYaml); + expect(patch).toContain('--- pod-v1.yaml'); + expect(patch).toContain('+++ pod-v2.yaml'); + expect(patch).toContain('- replicas: 1'); + expect(patch).toContain('+ replicas: 3'); + + const changes = diffLines(oldYaml, newYaml); + expect(changes.some((c) => c.added && c.value.includes('replicas: 3'))).toBe(true); + expect(changes.some((c) => c.removed && c.value.includes('replicas: 1'))).toBe(true); + }); + }); + + describe('tsconfig.json compiler options & exclusions', () => { + it('configures proper exclusion rules for test files and directories', () => { + const tsconfigPath = path.join(rootDir, 'tsconfig.json'); + expect(fs.existsSync(tsconfigPath)).toBe(true); + + const tsconfig = JSON.parse(fs.readFileSync(tsconfigPath, 'utf8')); + + expect(tsconfig.compilerOptions).toBeDefined(); + expect(tsconfig.compilerOptions.target).toBe('es2022'); + expect(tsconfig.compilerOptions.jsx).toBe('react-jsx'); + expect(tsconfig.compilerOptions.strict).toBe(true); + + expect(tsconfig.exclude).toBeDefined(); + expect(tsconfig.exclude).toContain('node_modules'); + expect(tsconfig.exclude).toContain('dist'); + expect(tsconfig.exclude).toContain('**/*.test.ts'); + expect(tsconfig.exclude).toContain('**/*.test.tsx'); + expect(tsconfig.exclude).toContain('src/__tests__/**'); + expect(tsconfig.exclude).toContain('src/**/__tests__/**'); + }); + }); + + describe('dist/ output verification', () => { + function getAllEntriesRecursive(dir: string): string[] { + if (!fs.existsSync(dir)) return []; + const entries = fs.readdirSync(dir, { withFileTypes: true }); + const paths: string[] = []; + for (const entry of entries) { + const fullPath = path.join(dir, entry.name); + paths.push(fullPath); + if (entry.isDirectory()) { + paths.push(...getAllEntriesRecursive(fullPath)); + } + } + return paths; + } + + it('confirms zero test declaration files and zero __tests__ directories exist in dist/', () => { + const distDir = path.join(rootDir, 'dist'); + expect(fs.existsSync(distDir)).toBe(true); + + const allEntries = getAllEntriesRecursive(distDir); + expect(allEntries.length).toBeGreaterThan(0); + + const testDeclarationFiles = allEntries.filter( + (filePath) => filePath.endsWith('.test.d.ts') || /\.test\.[a-z]+\.d\.ts$/.test(filePath), + ); + const testDirectories = allEntries.filter((filePath) => { + const relative = path.relative(distDir, filePath); + return relative.split(path.sep).includes('__tests__'); + }); + const anyTestDeclarationFiles = allEntries.filter((filePath) => { + const base = path.basename(filePath); + return base.includes('test') && base.endsWith('.d.ts'); + }); + + expect(testDeclarationFiles).toEqual([]); + expect(testDirectories).toEqual([]); + expect(anyTestDeclarationFiles).toEqual([]); + + // Verify that standard declarations are emitted cleanly + expect(fs.existsSync(path.join(distDir, 'index.d.ts'))).toBe(true); + expect(fs.existsSync(path.join(distDir, 'index.js'))).toBe(true); + }); + }); + + describe('Node stream mocking compatibility for Ink components', () => { + it('supports mock stdin/stdout event emission and stream casting', async () => { + class MockStdin extends EventEmitter { + isTTY = true; + setRawMode = () => this; + resume = () => this; + pause = () => this; + ref = () => this; + unref = () => this; + send(data: string) { + this.emit('data', Buffer.from(data)); + } + } + + class MockStdout extends EventEmitter { + output = ''; + columns = 80; + rows = 24; + write = (chunk: string | Buffer) => { + this.output += chunk.toString(); + return true; + }; + } + + const stdin = new MockStdin(); + const stdout = new MockStdout(); + + // Verify defensive casting compatibility + const renderOptions = { + stdin: stdin as any, + stdout: stdout as any, + debug: true, + }; + + expect(renderOptions.stdin).toBe(stdin); + expect(renderOptions.stdout).toBe(stdout); + + let receivedData = ''; + stdin.on('data', (buf: Buffer) => { + receivedData += buf.toString(); + }); + + stdin.send('q'); + expect(receivedData).toBe('q'); + + stdout.write('Rendered UI output'); + expect(stdout.output).toBe('Rendered UI output'); + }); + }); + + describe('AI client factory importability', () => { + it('imports createAIClient and can instantiate the noop client', async () => { + expect(typeof createAIClient).toBe('function'); + + const noopClient = await createAIClient('noop'); + expect(noopClient).toBeDefined(); + expect(typeof noopClient.configure).toBe('function'); + expect(typeof noopClient.getCompletion).toBe('function'); + + const response = await noopClient.getCompletion('test prompt'); + expect(response).toBeDefined(); + expect(typeof response).toBe('string'); + expect(response).toBe('noop completion explanation'); + }); + + it('throws error for unsupported provider backend', async () => { + await expect(createAIClient('unsupported-backend-xyz')).rejects.toThrow( + /Unsupported AI provider/, + ); + }); + }); +}); diff --git a/src/__tests__/cli-flags.test.ts b/src/__tests__/cli-flags.test.ts index 13361556..11093790 100644 --- a/src/__tests__/cli-flags.test.ts +++ b/src/__tests__/cli-flags.test.ts @@ -1,5 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { Command } from 'commander'; +import { registry } from '../analyzers'; import { runAnalysis } from '../analysis/analysis'; import { registerAnalyzeCommand } from '../commands/analyze'; import { registerConfigCommand } from '../commands/config'; @@ -31,7 +32,8 @@ const MOCK_CONSENSUS: ConsensusDiagnosis = { }, }; -vi.mock('../agent/python-bridge', () => ({ +vi.mock('../agent/python-bridge', async importOriginal => ({ + ...await importOriginal(), runAgentCouncilProcess: vi.fn(), runPythonAgentCouncil: vi.fn(), isPythonAgentAvailable: vi.fn(async () => true), @@ -94,6 +96,20 @@ describe('Phase 23 - Feature Flags, Rollout Modes & Legacy Fallback (Issue #294) }); describe('Flag & Config Routing in Analysis Engine', () => { + beforeEach(() => { + vi.spyOn(registry, 'get').mockImplementation(kind => kind === 'Pod' ? { + name: 'Pod', analyze: async () => [{ kind, namespace: 'production', name: 'payment', errors: [{ text: 'Pod unhealthy' }] }], + } : undefined); + }); + afterEach(() => vi.restoreAllMocks()); + + it('skips council when analyzers report no failures', async () => { + vi.mocked(registry.get).mockReturnValue({ name: 'Pod', analyze: async () => [] }); + const output = await runAnalysis({ filters: ['Pod'], multiAgent: true }); + expect(output.problems).toBe(0); + expect(pythonBridge.runAgentCouncilProcess).not.toHaveBeenCalled(); + }); + it('asserts --multi-agent flag routes to multi-agent bridge', async () => { const output = await runAnalysis({ multiAgent: true, @@ -105,7 +121,7 @@ describe('Phase 23 - Feature Flags, Rollout Modes & Legacy Fallback (Issue #294) expect.objectContaining({ context: expect.objectContaining({ namespace: 'production', - name: 'app=payment', + name: 'payment', }), }), ); @@ -116,6 +132,43 @@ describe('Phase 23 - Feature Flags, Rollout Modes & Legacy Fallback (Issue #294) ); }); + it('restores masked names in the local diagnosis and suggested fix', async () => { + vi.mocked(registry.get).mockReturnValue({ + name: 'Pod', + analyze: async () => [{ + kind: 'Pod', namespace: 'production', name: 'checkout-api', errors: [{ text: 'checkout-api failed' }], + }], + }); + vi.mocked(pythonBridge.runAgentCouncilProcess).mockResolvedValueOnce({ + ...MOCK_CONSENSUS, + rootCause: 'MASKED_0 crashed', + bestSolution: { ...MOCK_CONSENSUS.bestSolution, actionTitle: 'Inspect MASKED_0' }, + }); + const output = await runAnalysis({ filters: ['Pod'], multiAgent: true, anonymize: true, interactive: true }); + expect(pythonBridge.runAgentCouncilProcess).toHaveBeenCalledWith(expect.objectContaining({ + context: { kind: 'Pod' }, failureText: 'MASKED_0 failed', + })); + expect(output.results[0].consensus?.bestSolution.actionTitle).toBe('Inspect checkout-api'); + expect(output.results[0].details).toContain('checkout-api crashed'); + }); + + it('shares one time budget across workload diagnoses', async () => { + vi.mocked(registry.get).mockReturnValue({ + name: 'Pod', + analyze: async () => ['api', 'db'].map(name => ({ + kind: 'Pod', namespace: 'default', name, errors: [{ text: 'OOMKilled' }], + })), + }); + vi.mocked(pythonBridge.runAgentCouncilProcess).mockImplementationOnce(async () => { + vi.spyOn(performance, 'now').mockReturnValue(performance.now() + 10_000); + return MOCK_CONSENSUS; + }); + const output = await runAnalysis({ filters: ['Pod'], multiAgent: true, councilTimeoutMs: 500 }); + expect(pythonBridge.runAgentCouncilProcess).toHaveBeenCalledTimes(1); + expect(output.results[0].fallbackStep).toBe('council'); + expect(output.results[1].fallbackStep).toBeDefined(); + }); + it('asserts absence of flag routes to legacy pipeline and emits deprecation notice', async () => { const output = await runAnalysis({ multiAgent: false, @@ -126,7 +179,7 @@ describe('Phase 23 - Feature Flags, Rollout Modes & Legacy Fallback (Issue #294) expect(logger.warn).toHaveBeenCalledWith( expect.stringContaining(LEGACY_DEPRECATION_WARNING), ); - expect(output.status).toBe('OK'); + expect(output.status).toBe('ProblemDetected'); }); it('routes to multi-agent bridge when KDM_MULTI_AGENT environment variable is true', async () => { diff --git a/src/__tests__/codebase-investigator.test.ts b/src/__tests__/codebase-investigator.test.ts new file mode 100644 index 00000000..57aaf41e --- /dev/null +++ b/src/__tests__/codebase-investigator.test.ts @@ -0,0 +1,258 @@ +import { describe, it, expect, vi } from 'vitest'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; +import { + CodebaseInvestigatorAgent, + CodebaseInvestigatorInputSchema, + CodebaseInvestigationReportSchema, + parseMemoryBytes, + isBinaryFile, + isManifestFile, +} from '../agent/investigator.js'; + +describe('CodebaseInvestigatorAgent (F-05)', () => { + it('TC-INV-01: Workspace manifest discovery in virtual files', async () => { + const mockFiles: Record = { + 'charts/payment/values.yaml': 'image:\n repository: payment-service\n', + 'k8s/deployment.yaml': 'apiVersion: apps/v1\nkind: Deployment\n', + 'Dockerfile': 'FROM node:20-alpine\n', + 'src/server.ts': 'console.log("running");\n', + 'docs/README.md': '# Payment Service\n', + }; + + const report = await CodebaseInvestigatorAgent.run({ workspaceFiles: mockFiles }); + expect(report.discoveredManifests).toContain('charts/payment/values.yaml'); + expect(report.discoveredManifests).toContain('k8s/deployment.yaml'); + expect(report.discoveredManifests).toContain('Dockerfile'); + expect(report.discoveredManifests).not.toContain('src/server.ts'); + expect(report.discoveredManifests).not.toContain('docs/README.md'); + }); + + it('TC-INV-02: Dockerfile JVM heap vs container cgroup limit analysis', async () => { + const mockFiles: Record = { + Dockerfile: + 'FROM eclipse-temurin:17\nENV JAVA_OPTS="-Xmx768m"\nENTRYPOINT ["sh", "-c", "java $JAVA_OPTS -jar app.jar"]\n', + }; + + const report = await CodebaseInvestigatorAgent.run({ + workspaceFiles: mockFiles, + liveClusterState: { memoryLimit: '512Mi', containerName: 'payment' }, + }); + + expect(report.findings).toHaveLength(1); + expect(report.findings[0].file).toBe('Dockerfile'); + expect(report.findings[0].issue).toContain('-Xmx768m'); + expect(report.findings[0].issue).toContain('512Mi'); + expect(report.driftDetected).toBe(true); + }); + + it.each([ + { keys: ['DATABASE_URL'], missing: true }, + { keys: ['db-url'], missing: false }, + { keys: undefined, missing: false }, + ])('checks references only against observed Secret keys ($keys)', async ({ keys, missing }) => { + const mockFiles: Record = { + 'k8s/auth-deployment.yaml': + 'apiVersion: apps/v1\nkind: Deployment\nspec:\n template:\n spec:\n containers:\n - name: auth\n env:\n - name: DATABASE_URL\n valueFrom:\n secretKeyRef:\n name: auth-secrets\n key: db-url\n', + }; + + const report = await CodebaseInvestigatorAgent.run({ + workspaceFiles: mockFiles, + liveClusterState: { secretKeys: keys && { 'auth-secrets': keys } }, + }); + + expect(report.driftDetected).toBe(missing); + if (missing) { + expect(report.findings[0].issue).toContain('db-url'); + expect(report.findings[0].patch).toBeUndefined(); + } + }); + + it('TC-INV-04: Remediation unified diff patch generation', async () => { + const mockFiles: Record = { + 'deploy/payment-service.yaml': + 'apiVersion: apps/v1\nkind: Deployment\nspec:\n template:\n spec:\n containers:\n - name: payment\n resources:\n requests:\n memory: 256Mi\n limits:\n memory: 512Mi\n env:\n - name: JAVA_OPTS\n value: "-Xmx768m"\n', + }; + + const report = await CodebaseInvestigatorAgent.run({ + workspaceFiles: mockFiles, + liveClusterState: { memoryLimit: '512Mi' }, + }); + + expect(report.findings[0].patch).toBeDefined(); + expect(report.findings[0].patch).toContain('--- deploy/payment-service.yaml'); + expect(report.findings[0].patch).toContain('+++ deploy/payment-service.yaml.patched'); + expect(report.findings[0].patch).toContain('- memory: 512Mi'); + expect(report.findings[0].patch).toContain('+ memory: 1024Mi'); + expect(report.findings[0].patch).not.toContain('- memory: 256Mi'); + }); + + it('TC-INV-05: Missing resource definition graceful fallback on empty workspace', async () => { + const report = await CodebaseInvestigatorAgent.run({ workspaceFiles: {} }); + expect(report.discoveredManifests).toHaveLength(0); + expect(report.findings[0].file).toBe('none'); + expect(report.findings[0].issue).toContain('No relevant configuration or manifest files discovered'); + expect(report.driftDetected).toBe(false); + }); + + it('compares JVM arguments with the limit in Helm values', async () => { + const report = await CodebaseInvestigatorAgent.run({ + workspaceFiles: { + 'charts/payment/values.yaml': 'env:\n JAVA_OPTS: "-Xmx768m"\nresources:\n limits:\n memory: 512Mi\n', + }, + }); + expect(report.findings[0]?.patch).toContain('+ memory: 1024Mi'); + }); + + it('uses a live limit only for the matching workload and namespace', async () => { + const pod = (namespace: string) => + `kind: Pod\nmetadata:\n name: api\n namespace: ${namespace}\nspec:\n containers:\n - name: app\n args: ["-Xmx768m"]\n resources:\n limits:\n memory: 2Gi\n`; + const report = await CodebaseInvestigatorAgent.run({ + workspaceFiles: { 'prod.yaml': pod('production'), 'dev.yaml': pod('development') }, + liveClusterState: { podName: 'api', namespace: 'production', containerName: 'app', memoryLimit: '512Mi' }, + }); + expect(report.findings.map(finding => finding.file)).toEqual(['prod.yaml']); + expect(report.findings[0].patch).toBeUndefined(); + }); + + it('TC-INV-06: Syntactically broken YAML skipped safely without throwing', async () => { + const mockFiles = { + 'broken.yaml': ':::broken syntax: [unclosed list', + 'valid.yaml': 'apiVersion: v1\nkind: Service\n', + }; + + const report = await CodebaseInvestigatorAgent.run({ workspaceFiles: mockFiles }); + expect(report.discoveredManifests).toContain('valid.yaml'); + expect(report.ExplorationTrace.some((t) => t.includes('Skipping syntactically invalid'))).toBe(true); + }); + + it('TC-INV-08: Giant binary files skipped safely', () => { + expect(isBinaryFile('database.bin')).toBe(true); + expect(isBinaryFile('archive.tar.gz')).toBe(true); + expect(isBinaryFile('package.zip')).toBe(true); + expect(isBinaryFile('libcore.so')).toBe(true); + expect(isBinaryFile('deployment.yaml')).toBe(false); + expect(isBinaryFile('Dockerfile')).toBe(false); + + expect(isManifestFile('database.bin')).toBe(false); + expect(isManifestFile('values.yaml')).toBe(true); + expect(isManifestFile('service.yml')).toBe(true); + expect(isManifestFile('Dockerfile')).toBe(true); + }); + + it('TC-INV-09: EACCES permission denied handling', async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'kdm-investigator-test-')); + const readFile = vi.spyOn(fs.promises, 'readFile').mockRejectedValueOnce(new Error('EACCES: permission denied')); + try { + fs.writeFileSync(path.join(root, 'secret.yaml'), ''); + const report = await CodebaseInvestigatorAgent.run({ workspaceRoot: root }); + expect(report.ExplorationTrace.join('\n')).toContain('EACCES: permission denied'); + expect(report.discoveredManifests).toEqual([]); + } finally { + readFile.mockRestore(); + fs.rmSync(root, { recursive: true, force: true }); + } + }); + + it('TC-INV-10: Dual-schema report compliance validation', async () => { + const mockFiles = { + 'k8s/deployment.yaml': 'apiVersion: apps/v1\nkind: Deployment\n', + }; + + const report = await CodebaseInvestigatorAgent.run({ workspaceFiles: mockFiles }); + const validated = CodebaseInvestigationReportSchema.parse(report); + + // gemini-cli contract fields + expect(validated.SummaryOfFindings).toBeDefined(); + expect(Array.isArray(validated.ExplorationTrace)).toBe(true); + expect(Array.isArray(validated.RelevantLocations)).toBe(true); + + // KDM SRE contract fields + expect(Array.isArray(validated.discoveredManifests)).toBe(true); + expect(Array.isArray(validated.findings)).toBe(true); + expect(typeof validated.driftDetected).toBe('boolean'); + }); + + it('TC-INV-11: AgentDefinition factory and execution via toDefinition()', async () => { + const agentDef = CodebaseInvestigatorAgent.toDefinition(); + expect(agentDef.name).toBe('CodebaseInvestigatorAgent'); + expect(agentDef.inputSchema).toBe(CodebaseInvestigatorInputSchema); + expect(agentDef.outputSchema).toBe(CodebaseInvestigationReportSchema); + + const result = await agentDef.run({ + workspaceFiles: { + 'Chart.yaml': 'name: payment\nversion: 1.0.0\n', + }, + }); + + expect(result.discoveredManifests).toContain('Chart.yaml'); + }); + + it('uses delegated AgentContext.cwd when workspaceRoot is omitted', async () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'kdm-investigator-cwd-')); + try { + fs.writeFileSync(path.join(tmpDir, 'Chart.yaml'), 'name: delegated\nversion: 1.0.0\n'); + const agentDef = CodebaseInvestigatorAgent.toDefinition(); + const result = await agentDef.run({}, { cwd: tmpDir }); + expect(result.discoveredManifests).toContain('Chart.yaml'); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }); + + it('TC-INV-12: Real filesystem workspace discovery with temp directory', async () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'kdm-investigator-test-')); + try { + // Create test manifest structure + fs.writeFileSync(path.join(tmpDir, 'Dockerfile'), 'FROM alpine:3.18\n'); + const k8sDir = path.join(tmpDir, 'k8s'); + fs.mkdirSync(k8sDir); + fs.writeFileSync(path.join(k8sDir, 'pod.yaml'), 'apiVersion: v1\nkind: Pod\n'); + fs.writeFileSync(path.join(tmpDir, 'main.ts'), 'console.log("hello");\n'); + fs.writeFileSync(path.join(tmpDir, 'data.bin'), Buffer.from([0x00, 0x01, 0x02])); + + const report = await CodebaseInvestigatorAgent.run({ workspaceRoot: tmpDir }); + expect(report.discoveredManifests).toContain('Dockerfile'); + expect(report.discoveredManifests).toContain(path.join('k8s', 'pod.yaml')); + expect(report.discoveredManifests).not.toContain('main.ts'); + expect(report.discoveredManifests).not.toContain('data.bin'); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }); + + it('TC-INV-13: parseMemoryBytes unit conversion', () => { + expect(parseMemoryBytes('512Mi')).toBe(512 * 1024 * 1024); + expect(parseMemoryBytes('1Gi')).toBe(1024 * 1024 * 1024); + expect(parseMemoryBytes('768m')).toBe(768 * 1024 * 1024); + expect(parseMemoryBytes('1024K')).toBe(1024 * 1024); + expect(parseMemoryBytes('invalid')).toBe(0); + }); + + it('distinguishes decimal Kubernetes quantities from binary JVM heap sizes and matches Pod name', async () => { + const podManifest = [ + 'apiVersion: v1', + 'kind: Pod', + 'metadata:', + ' name: api-pod-1', + ' namespace: production', + 'spec:', + ' containers:', + ' - name: api', + ' env:', + ' - name: JAVA_OPTS', + ' value: "-Xmx512m"', + ' resources:', + ' limits:', + ' memory: "512M"', + ].join('\n'); + + const report = await CodebaseInvestigatorAgent.run({ + workspaceFiles: { 'k8s/pod.yaml': podManifest }, + liveClusterState: { podName: 'api-pod-1', workloadName: 'api', namespace: 'production', memoryLimit: '512M' }, + }); + expect(report.driftDetected).toBe(true); + expect(report.findings[0].issue).toContain('-Xmx512m'); + }); +}); diff --git a/src/__tests__/composer.test.tsx b/src/__tests__/composer.test.tsx new file mode 100644 index 00000000..e0e2afde --- /dev/null +++ b/src/__tests__/composer.test.tsx @@ -0,0 +1,271 @@ +import React from 'react'; +import { describe, it, expect, vi } from 'vitest'; +import { renderTUI, stripAnsi } from './e2e/harness/tui-test-utils.js'; +import { Composer, parseSlashCommand, executeSlashCommand } from '../ui/components/Composer.js'; + +describe('F-08: Interactive Prompt & Slash Command Composer', () => { + it('TC-COMPOSER-01: Initial placeholder rendering with prompt symbol ❯', () => { + const onSubmit = vi.fn(); + const { getCleanOutput, unmount } = renderTUI( + + ); + + const output = getCleanOutput(); + expect(output).toContain('❯'); + expect(output).toContain('Type a prompt or / command...'); + unmount(); + }); + + it('TC-COMPOSER-02: Interactive character typing accumulates in buffer', async () => { + const onSubmit = vi.fn(); + const { stdin, wait, getCleanOutput, unmount } = renderTUI( + + ); + + stdin.send('pods'); + await wait(30); + + const output = getCleanOutput(); + expect(output).toContain('❯'); + expect(output).toContain('pods'); + unmount(); + }); + + it('TC-COMPOSER-03: Backspace editing modifies input buffer', async () => { + const onSubmit = vi.fn(); + const { stdin, wait, getCleanOutput, unmount } = renderTUI( + + ); + + stdin.send('helm'); + await wait(20); + // Send backspace character (\x08) + stdin.send('\x08'); + await wait(20); + stdin.send('p'); + await wait(20); + + const output = getCleanOutput(); + expect(output).toContain('help'); + unmount(); + }); + + it('TC-COMPOSER-04: Command submission on Enter invokes onSubmit with trimmed prompt', async () => { + const onSubmit = vi.fn(); + const { stdin, wait, getCleanOutput, unmount } = renderTUI( + + ); + + stdin.send(' diagnose oom in checkout '); + await wait(20); + stdin.sendEnter(); + await wait(40); + + expect(onSubmit).toHaveBeenCalledTimes(1); + expect(onSubmit).toHaveBeenCalledWith('diagnose oom in checkout'); + + // Buffer is cleared after submit + const output = getCleanOutput(); + expect(output).toContain('Type a prompt or / command...'); + unmount(); + }); + + it('TC-COMPOSER-05: Empty / whitespace prompt debounce ignores submission', async () => { + const onSubmit = vi.fn(); + const { stdin, wait, unmount } = renderTUI( + + ); + + stdin.sendEnter(); + await wait(20); + stdin.send(' '); + await wait(20); + stdin.sendEnter(); + await wait(20); + + expect(onSubmit).not.toHaveBeenCalled(); + unmount(); + }); + + it('TC-COMPOSER-06: Command history navigation Up and Down arrows preserves draft', async () => { + const onSubmit = vi.fn(); + const history = ['/pods', '/watch -n staging', '/health']; + const { stdin, wait, getCleanOutput, unmount } = renderTUI( + + ); + + // Type a draft + stdin.send('my draft query'); + await wait(20); + expect(getCleanOutput()).toContain('my draft query'); + + // Press Up arrow -> should recall latest history '/health' + stdin.sendUp(); + await wait(30); + expect(getCleanOutput()).toContain('/health'); + + // Press Up arrow again -> '/watch -n staging' + stdin.sendUp(); + await wait(30); + expect(getCleanOutput()).toContain('/watch -n staging'); + + // Press Up arrow again -> clamped to index 0 '/pods' + stdin.sendUp(); + await wait(30); + expect(getCleanOutput()).toContain('/pods'); + + // Press Up arrow once more -> remains clamped at '/pods' + stdin.sendUp(); + await wait(30); + expect(getCleanOutput()).toContain('/pods'); + + // Press Down arrow -> returns forward to '/watch -n staging' + stdin.sendDown(); + await wait(30); + expect(getCleanOutput()).toContain('/watch -n staging'); + + // Press Down arrow -> '/health' + stdin.sendDown(); + await wait(30); + expect(getCleanOutput()).toContain('/health'); + + // Press Down arrow past end of history -> restores 'my draft query' + stdin.sendDown(); + await wait(30); + expect(getCleanOutput()).toContain('my draft query'); + + unmount(); + }); + + it('TC-COMPOSER-07: Slash command autocompletion menu opens on "/"', async () => { + const onSubmit = vi.fn(); + const { stdin, wait, getCleanOutput, unmount } = renderTUI( + + ); + + stdin.send('/'); + await wait(30); + + const output = getCleanOutput(); + expect(output).toContain('Available Commands:'); + expect(output).toContain('/pods'); + expect(output).toContain('/containers'); + expect(output).toContain('/watch'); + expect(output).toContain('/analyze'); + expect(output).toContain('/health'); + expect(output).toContain('/help'); + unmount(); + }); + + it('TC-COMPOSER-08: Slash command prefix filtering (/p and /co)', async () => { + const onSubmit = vi.fn(); + const { stdin, wait, getLastFrame, unmount } = renderTUI( + + ); + + stdin.send('/p'); + await wait(30); + + let output = stripAnsi(getLastFrame()); + expect(output).toContain('/pods'); + expect(output).not.toContain('/containers'); + + // Backspace 'p' and type 'co' + stdin.send('\x08'); + await wait(20); + stdin.send('co'); + await wait(30); + + output = stripAnsi(getLastFrame()); + expect(output).toContain('/containers'); + expect(output).not.toContain('/pods'); + + unmount(); + }); + + it.each([ + { input: '/w', key: '\t', expected: '/watch ' }, + { input: '/po', key: '\u001b', expected: '/po' }, + ])('closes autocomplete after $input and $key', async ({ input, key, expected }) => { + const { stdin, wait, getLastFrame, unmount } = renderTUI(); + try { + stdin.send(input); + await wait(30); + expect(getLastFrame()).toContain('Available Commands:'); + stdin.send(key); + await wait(30); + expect(getLastFrame()).not.toContain('Available Commands:'); + expect(getLastFrame()).toContain(expected); + } finally { + unmount(); + } + }); + + it('TC-COMPOSER-11: Multiline prompt input inserts newline character', async () => { + const onSubmit = vi.fn(); + const { stdin, wait, getCleanOutput, unmount } = renderTUI( + + ); + + stdin.send('Line 1'); + await wait(20); + // Send newline \n directly + stdin.send('\n'); + await wait(20); + stdin.send('Line 2'); + await wait(30); + + const output = getCleanOutput(); + expect(output).toContain('Line 1'); + expect(output).toContain('Line 2'); + expect(onSubmit).not.toHaveBeenCalled(); + unmount(); + }); + + it('TC-COMPOSER-12: Extreme paste input (>5,000 characters) handled safely without throwing', async () => { + const onSubmit = vi.fn(); + const hugeInput = 'A'.repeat(6000); + const { stdin, wait, getCleanOutput, unmount } = renderTUI( + + ); + + expect(() => stdin.send(hugeInput)).not.toThrow(); + await wait(50); + + const output = getCleanOutput(); + expect(output.length).toBeGreaterThan(0); + unmount(); + }); + + it('TC-COMPOSER-13: Displays helpful error on unknown slash command', async () => { + const onSubmit = vi.fn(); + const { stdin, wait, getCleanOutput, unmount } = renderTUI( + + ); + + stdin.send('/unknowncmd'); + await wait(30); + stdin.sendEnter(); + await wait(30); + + const output = getCleanOutput(); + expect(output).toContain("Unknown command '/unknowncmd'. Type /help for available commands."); + expect(onSubmit).not.toHaveBeenCalled(); + unmount(); + }); + + it('TC-COMPOSER-14: Slash command parsing and execution helpers', () => { + const parsed = parseSlashCommand('/pods -n staging --filter redis'); + expect(parsed).toEqual({ + isSlash: true, + command: '/pods', + args: ['-n', 'staging', '--filter', 'redis'], + raw: '/pods -n staging --filter redis', + }); + + expect(parseSlashCommand('normal text')).toBeNull(); + + expect(executeSlashCommand('/pods').success).toBe(true); + expect(executeSlashCommand('/unknown').success).toBe(false); + }); +}); diff --git a/src/__tests__/copilot-command.test.tsx b/src/__tests__/copilot-command.test.tsx new file mode 100644 index 00000000..a21ac12b --- /dev/null +++ b/src/__tests__/copilot-command.test.tsx @@ -0,0 +1,63 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { Command } from 'commander'; +import { registerCopilotCommand } from '../commands/copilot'; +import { render } from 'ink'; + +// Mock process.stdout.write +const stdoutWriteSpy = vi.spyOn(process.stdout, 'write').mockImplementation(() => true); + +vi.mock('ink', async () => { + const actual = await vi.importActual('ink'); + return { + ...actual, + render: vi.fn().mockReturnValue({ + unmount: vi.fn(), + waitUntilExit: vi.fn().mockResolvedValue(undefined), + }), + }; +}); + +vi.mock('../ui/CopilotShell', () => ({ + CopilotShell: () => null, +})); + +describe('copilot command', () => { + let program: Command; + const stdin = process.stdin; + const stdout = process.stdout; + + beforeEach(() => { + vi.clearAllMocks(); + vi.stubEnv('CI', 'false'); + vi.stubEnv('GITHUB_ACTIONS', 'false'); + vi.spyOn(process, 'stdin', 'get').mockReturnValue(Object.create(stdin, { isTTY: { value: true } })); + vi.spyOn(process, 'stdout', 'get').mockReturnValue(Object.create(stdout, { isTTY: { value: true } })); + program = new Command().exitOverride(); + registerCopilotCommand(program); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + vi.spyOn(process, 'stdin', 'get').mockRestore(); + vi.spyOn(process, 'stdout', 'get').mockRestore(); + }); + + it('should register copilot command and aliases', () => { + const copilotCmd = program.commands.find((c) => c.name() === 'copilot'); + expect(copilotCmd).toBeDefined(); + expect(copilotCmd?.aliases()).toContain('agent'); + expect(copilotCmd?.aliases()).toContain('chat'); + }); + + it('should clear screen and render CopilotShell on copilot', async () => { + await program.parseAsync(['node', 'test', 'copilot', 'deployment/checkout-api', '--tab', '2']); + expect(stdoutWriteSpy).toHaveBeenCalledWith('\x1Bc'); + expect(render).toHaveBeenCalled(); + }); + + it('rejects interactive startup in CI even when a terminal is attached', async () => { + vi.stubEnv('CI', 'true'); + await expect(program.parseAsync(['node', 'test', 'copilot'])).rejects.toThrow(/interactive terminal/); + expect(render).not.toHaveBeenCalled(); + }); +}); diff --git a/src/__tests__/declarative-tools.test.ts b/src/__tests__/declarative-tools.test.ts new file mode 100644 index 00000000..b2fab149 --- /dev/null +++ b/src/__tests__/declarative-tools.test.ts @@ -0,0 +1,693 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { z } from 'zod'; +import { Type } from '@google/genai'; +import { + createDeclarativeTool, + zodToGenAiSchema, +} from '../tools/declarative-tool'; +import { + k8sGetResourcesTool, + k8sDescribeResourceTool, + k8sGetLogsTool, + k8sGetEventsTool, + k8sApplyManifestTool, + k8sDeleteResourceTool, + k8sGetPodTool, + k8sListPodsTool, + k8sApplyPatchTool, +} from '../tools/k8s-tools'; +import { + dockerListContainersTool, + dockerInspectContainerTool, + dockerGetLogsTool, + dockerRestartContainerTool, +} from '../tools/docker-tools'; +import { + ToolRegistry, + DeclarativeToolRegistry, + defaultToolRegistry, +} from '../tools/tool-registry'; +import * as k8sResources from '../kubernetes/resources'; +import * as k8sClient from '../kubernetes/client'; +import * as dockerClient from '../docker/client'; +import * as remediationExecutor from '../remediation/executor'; + +describe('Feature F-03: Declarative Cluster Tools', () => { + beforeEach(() => { + vi.restoreAllMocks(); + }); + + // ─── 1. BaseDeclarativeTool & Schema Validation ────────────────────────── + + it('TC-TOOL-01: BaseDeclarativeTool parameter validation with valid inputs calling execute()', async () => { + const executeMock = vi.fn().mockResolvedValue({ status: 'success' }); + const tool = createDeclarativeTool({ + name: 'test_tool', + description: 'A test declarative tool', + schema: z.object({ + host: z.string().min(1), + port: z.number().int().positive(), + }), + execute: executeMock, + }); + + const result = await tool.execute({ host: 'localhost', port: 8080 }); + expect(result).toEqual({ status: 'success' }); + expect(executeMock).toHaveBeenCalledWith({ host: 'localhost', port: 8080 }, undefined); + }); + + it('TC-TOOL-02: BaseDeclarativeTool invalid parameter rejection throwing ZodError before execute()', async () => { + const executeMock = vi.fn().mockResolvedValue({ status: 'success' }); + const tool = createDeclarativeTool({ + name: 'test_tool', + description: 'A test declarative tool', + schema: z.object({ + host: z.string().min(1), + port: z.number().int().positive(), + }), + execute: executeMock, + }); + + // Missing port + expect(() => tool.validate({ host: 'localhost' })).toThrow(); + // Negative port + expect(() => tool.validate({ host: 'localhost', port: -1 })).toThrow(); + // Non-integer port + expect(() => tool.validate({ host: 'localhost', port: '8080' })).toThrow(); + // Execute was never called + expect(executeMock).not.toHaveBeenCalled(); + }); + + // ─── 2. Safety Classification & Risk Levels ────────────────────────────── + + it('TC-TOOL-03: Safety classification for read-only tools (safety: "read_only", riskLevel: "low")', () => { + const readOnlyTools = [ + k8sGetResourcesTool, + k8sDescribeResourceTool, + k8sGetLogsTool, + k8sGetEventsTool, + k8sGetPodTool, + k8sListPodsTool, + dockerListContainersTool, + dockerInspectContainerTool, + dockerGetLogsTool, + ]; + + for (const tool of readOnlyTools) { + expect(tool.safetyLevel).toBe('read_only'); + expect(tool.safety).toBe('read_only'); + expect(tool.riskLevel).toBe('low'); + } + }); + + it('TC-TOOL-04: Safety classification for mutating tools (safety: "mutating", riskLevel: "medium" | "high")', () => { + expect(k8sApplyManifestTool.safetyLevel).toBe('mutating'); + expect(k8sApplyManifestTool.safety).toBe('mutating'); + expect(k8sApplyManifestTool.riskLevel).toBe('high'); + + expect(k8sDeleteResourceTool.safetyLevel).toBe('mutating'); + expect(k8sDeleteResourceTool.safety).toBe('mutating'); + expect(k8sDeleteResourceTool.riskLevel).toBe('high'); + + expect(k8sApplyPatchTool.safetyLevel).toBe('mutating'); + expect(k8sApplyPatchTool.safety).toBe('mutating'); + expect(k8sApplyPatchTool.riskLevel).toBe('high'); + + expect(dockerRestartContainerTool.safetyLevel).toBe('mutating'); + expect(dockerRestartContainerTool.safety).toBe('mutating'); + expect(dockerRestartContainerTool.riskLevel).toBe('medium'); + }); + + // ─── 3. Gemini Schema Converter ────────────────────────────────────────── + + it('TC-TOOL-05: zodToGenAiSchema converts complex Zod schemas to OpenAPI 3.03 format', () => { + const testSchema = z.object({ + name: z.string().describe('Target workload name'), + replicas: z.number().int().describe('Replica count'), + ratio: z.number().describe('Float ratio'), + enabled: z.boolean().describe('Feature status'), + tags: z.array(z.string()).describe('Workload tags'), + environment: z.enum(['dev', 'staging', 'production']).describe('Deployment env'), + optionalNote: z.string().optional().describe('Optional note'), + timeoutSeconds: z.number().int().default(30).describe('Timeout with default'), + }); + + const genAiSchema = zodToGenAiSchema(testSchema); + expect(genAiSchema.type).toBe(Type.OBJECT); + expect(genAiSchema.properties).toBeDefined(); + + const props = genAiSchema.properties!; + expect(props.name.type).toBe(Type.STRING); + expect(props.name.description).toBe('Target workload name'); + + expect(props.replicas.type).toBe(Type.INTEGER); + expect(props.ratio.type).toBe(Type.NUMBER); + expect(props.enabled.type).toBe(Type.BOOLEAN); + + expect(props.tags.type).toBe(Type.ARRAY); + expect(props.tags.items?.type).toBe(Type.STRING); + + expect(props.environment.type).toBe(Type.STRING); + expect(props.environment.enum).toEqual(['dev', 'staging', 'production']); + + expect(props.timeoutSeconds.default).toBe(30); + + // Required array should include non-optional, non-default fields + expect(genAiSchema.required).toContain('name'); + expect(genAiSchema.required).toContain('replicas'); + expect(genAiSchema.required).toContain('ratio'); + expect(genAiSchema.required).toContain('enabled'); + expect(genAiSchema.required).toContain('tags'); + expect(genAiSchema.required).toContain('environment'); + expect(genAiSchema.required).not.toContain('optionalNote'); + expect(genAiSchema.required).not.toContain('timeoutSeconds'); + }); + + // ─── 4. Kubernetes Tools ───────────────────────────────────────────────── + + it('TC-TOOL-06: k8s_get_resources queries pods with namespace and label selector', async () => { + const spy = vi.spyOn(k8sResources, 'listPods').mockResolvedValueOnce([ + { + metadata: { name: 'payment-api-9f8a', namespace: 'production', creationTimestamp: new Date() }, + status: { phase: 'Running' }, + } as any, + ]); + + const result = await k8sGetResourcesTool.execute({ + kind: 'pod', + namespace: 'production', + labelSelector: 'app=payment', + }); + + expect(spy).toHaveBeenCalledWith({ namespace: 'production', labelSelector: 'app=payment' }); + expect(result.count).toBe(1); + expect(result.items[0].name).toBe('payment-api-9f8a'); + expect(result.items[0].status).toBe('Running'); + }); + + it('TC-TOOL-07: k8s_get_resources dispatches to services, deployments, and nodes', async () => { + const svcSpy = vi.spyOn(k8sResources, 'listServices').mockResolvedValueOnce([ + { metadata: { name: 'payment-svc', namespace: 'default' }, status: {} } as any, + ]); + const deploySpy = vi.spyOn(k8sResources, 'listDeployments').mockResolvedValueOnce([ + { metadata: { name: 'payment-deploy', namespace: 'default' }, status: {} } as any, + ]); + const nodeSpy = vi.spyOn(k8sResources, 'listNodes').mockResolvedValueOnce([ + { metadata: { name: 'worker-node-1' }, status: { phase: 'Ready' } } as any, + ]); + + const svcRes = await k8sGetResourcesTool.execute({ kind: 'service' }); + expect(svcSpy).toHaveBeenCalled(); + expect(svcRes.items[0].name).toBe('payment-svc'); + + const deployRes = await k8sGetResourcesTool.execute({ kind: 'deployment' }); + expect(deploySpy).toHaveBeenCalled(); + expect(deployRes.items[0].name).toBe('payment-deploy'); + + const nodeRes = await k8sGetResourcesTool.execute({ kind: 'node' }); + expect(nodeSpy).toHaveBeenCalled(); + expect(nodeRes.items[0].name).toBe('worker-node-1'); + }); + + it('TC-TOOL-08: k8s_describe_resource returns structured details and events for existing resource', async () => { + const mockPod = { + metadata: { name: 'payment-pod', namespace: 'default' }, + spec: { containers: [{ name: 'app', image: 'payment:v1' }] }, + status: { phase: 'Running' }, + }; + + vi.spyOn(k8sClient, 'getK8sApi').mockReturnValueOnce({ + readNamespacedPod: vi.fn().mockResolvedValueOnce(mockPod), + } as any); + + vi.spyOn(k8sResources, 'listEvents').mockResolvedValueOnce([ + { + type: 'Warning', + reason: 'BackOff', + message: 'Back-off restarting failed container', + involvedObject: { name: 'payment-pod' }, + lastTimestamp: new Date(), + } as any, + ]); + + const result = await k8sDescribeResourceTool.execute({ + kind: 'pod', + name: 'payment-pod', + namespace: 'default', + }); + + expect(result.found).toBe(true); + expect(result.name).toBe('payment-pod'); + expect(result.events).toHaveLength(1); + expect(result.events[0].reason).toBe('BackOff'); + }); + + it('TC-TOOL-09: k8s_describe_resource handles 404 / not found gracefully', async () => { + vi.spyOn(k8sClient, 'getK8sApi').mockReturnValueOnce({ + readNamespacedPod: vi.fn().mockRejectedValueOnce({ statusCode: 404 }), + } as any); + + vi.spyOn(remediationExecutor, 'executeRemediationCommand').mockResolvedValueOnce({ + success: false, + exitCode: 1, + stdout: '', + stderr: 'Error from server (NotFound): pods "non-existent" not found', + durationMs: 10, + command: 'kubectl describe pod non-existent -n default', + }); + + const result = await k8sDescribeResourceTool.execute({ + kind: 'pod', + name: 'non-existent', + namespace: 'default', + }); + + expect(result.found).toBe(false); + expect(result.description).toContain('not found'); + }); + + it('TC-TOOL-10: k8s_get_logs retrieves container logs with tailLines', async () => { + vi.spyOn(k8sClient, 'getK8sApi').mockReturnValueOnce({ + readNamespacedPodLog: vi.fn().mockResolvedValueOnce('Log line 1\nLog line 2\nLog line 3\n'), + } as any); + + const result = await k8sGetLogsTool.execute({ + name: 'auth-pod', + namespace: 'default', + container: 'auth-container', + tailLines: 50, + }); + + expect(result.pod).toBe('auth-pod'); + expect(result.linesCount).toBe(3); + expect(result.lines).toEqual(['Log line 1', 'Log line 2', 'Log line 3']); + }); + + it('TC-TOOL-11: k8s_get_events lists events filtered by namespace and type', async () => { + vi.spyOn(k8sResources, 'listEvents').mockResolvedValueOnce([ + { + type: 'Normal', + reason: 'Scheduled', + message: 'Successfully assigned default/pod-1 to node-1', + involvedObject: { kind: 'Pod', name: 'pod-1' }, + lastTimestamp: new Date('2026-11-15T10:00:00Z'), + } as any, + { + type: 'Warning', + reason: 'OOMKilled', + message: 'Container app killed by OOM killer', + involvedObject: { kind: 'Pod', name: 'pod-2' }, + lastTimestamp: new Date('2026-11-15T10:05:00Z'), + } as any, + ]); + + const warnings = await k8sGetEventsTool.execute({ + namespace: 'default', + type: 'Warning', + }); + + expect(warnings.count).toBe(1); + expect(warnings.events[0].reason).toBe('OOMKilled'); + }); + + it('TC-TOOL-12: k8s_apply_manifest applies manifest patch with dryRun option', async () => { + const execSpy = vi.spyOn(remediationExecutor, 'executeRemediationCommand').mockResolvedValueOnce({ + success: true, + exitCode: 0, + stdout: 'deployment.apps/payment-service patched', + stderr: '', + durationMs: 25, + command: 'kubectl patch deployment payment-service ...', + }); + + const result = await k8sApplyManifestTool.execute({ + manifest: '{"spec":{"replicas":3}}', + resource: 'deployment/payment-service', + namespace: 'production', + dryRun: true, + }); + + expect(result.success).toBe(true); + expect(result.appliedTo).toBe('production/deployment/payment-service'); + expect(result.dryRun).toBe(true); + expect(execSpy).toHaveBeenCalled(); + }); + + it('TC-TOOL-13: k8s_apply_manifest rejects malformed YAML patch structure before applying', async () => { + await expect( + k8sApplyManifestTool.execute({ + manifest: ':::broken-yaml unparseable content', + namespace: 'default', + }) + ).rejects.toThrow(/YAML syntax error/i); + + await expect( + k8sApplyManifestTool.execute({ + manifest: 'spec:\n\treplicas: 3', // tabs in YAML + namespace: 'default', + }) + ).rejects.toThrow(/YAML syntax error/i); + }); + + it('TC-TOOL-14: k8s_delete_resource deletes resource and enforces protected namespace block', async () => { + // Protected namespace block + await expect( + k8sDeleteResourceTool.execute({ + kind: 'namespace', + name: 'kube-system', + }) + ).rejects.toThrow(/Policy violation: deletion of protected namespace/i); + + await expect( + k8sDeleteResourceTool.execute({ + kind: 'ns', + name: 'production', + }) + ).rejects.toThrow(/Policy violation/i); + + // Valid deletion + vi.spyOn(remediationExecutor, 'executeRemediationCommand').mockResolvedValueOnce({ + success: true, + exitCode: 0, + stdout: 'pod "stuck-pod" deleted', + stderr: '', + durationMs: 15, + command: 'kubectl delete pod stuck-pod -n default', + }); + + const result = await k8sDeleteResourceTool.execute({ + kind: 'pod', + name: 'stuck-pod', + namespace: 'default', + }); + + expect(result.success).toBe(true); + expect(result.deleted).toBe('pod/stuck-pod'); + }); + + it.each(['namespace', 'namespaces', 'ns'])('blocks protected namespace deletion via %s', async kind => { + const execute = vi.spyOn(remediationExecutor, 'executeRemediationCommand'); + await expect(k8sDeleteResourceTool.execute({ kind, name: 'production' })).rejects.toThrow(/protected namespace/); + expect(execute).not.toHaveBeenCalled(); + }); + + it('rejects a resource name that is not a single identifier', async () => { + const execute = vi.spyOn(remediationExecutor, 'executeRemediationCommand'); + await expect(k8sDeleteResourceTool.execute({ kind: 'namespace', name: '-invalid' })).rejects.toThrow(/resource name/); + expect(execute).not.toHaveBeenCalled(); + }); + + it('submits an approved manifest via stdin and surfaces failed applies', async () => { + const execute = vi.spyOn(remediationExecutor, 'executeRemediationCommand').mockResolvedValue({ + success: false, exitCode: 1, stdout: '', stderr: 'Forbidden', durationMs: 1, + }); + const tools = new ToolRegistry(); + tools.register(k8sApplyManifestTool); + const manifest = "apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: test\ndata:\n key: \"it's quoted\""; + const args = { manifest, namespace: 'test', dryRun: true }; + + await expect(tools.invoke('k8s_apply_manifest', args)).rejects.toThrow(/explicit approval/); + expect(execute).not.toHaveBeenCalled(); + + const approveMutation = vi.fn().mockResolvedValue(true); + await expect(tools.invoke('k8s_apply_manifest', args, { approveMutation })).rejects.toThrow(/Forbidden/); + expect(approveMutation).toHaveBeenCalledWith('k8s_apply_manifest', args); + expect(execute).toHaveBeenCalledWith( + ['kubectl', 'apply', '-n', 'test', '-f', '-', '--dry-run=server'], { stdin: manifest } + ); + }); + + it('uses describe fallback for kinds without a direct SDK lookup', async () => { + vi.spyOn(remediationExecutor, 'executeRemediationCommand').mockResolvedValueOnce({ + success: true, exitCode: 0, stdout: 'Name: cart', stderr: '', durationMs: 1, + }); + const result = await k8sDescribeResourceTool.execute({ kind: 'deployment', name: 'cart', namespace: 'test' }); + expect(result).toMatchObject({ found: true, description: 'Name: cart' }); + }); + + it('keeps successful empty pod lists empty and surfaces list failures', async () => { + const listPods = vi.spyOn(k8sResources, 'listPods') + .mockResolvedValueOnce([]).mockRejectedValueOnce(new Error('Kubernetes unavailable')); + await expect(k8sListPodsTool.execute({ namespace: 'test' })).resolves.toEqual({ namespace: 'test', pods: [] }); + await expect(k8sListPodsTool.execute({ namespace: 'test' })).rejects.toThrow('Kubernetes unavailable'); + expect(listPods).toHaveBeenCalledWith({ namespace: 'test' }); + }); + + it('surfaces Docker inspection and log retrieval failures', async () => { + const failure = new Error('Docker unavailable'); + vi.spyOn(dockerClient, 'getDockerClient').mockImplementation(() => { throw failure; }); + vi.spyOn(remediationExecutor, 'executeRemediationCommand').mockResolvedValueOnce({ + success: false, exitCode: 1, stdout: '', stderr: 'Permission denied', durationMs: 1, + }); + await expect(dockerInspectContainerTool.execute({ containerId: 'redis' })).rejects.toThrow(failure); + await expect(dockerGetLogsTool.execute({ containerId: 'redis' })).rejects.toThrow('Permission denied'); + }); + + // ─── 5. Docker Tools ───────────────────────────────────────────────────── + + it('TC-TOOL-15: docker_list_containers lists containers with state filtering', async () => { + vi.spyOn(dockerClient, 'getDockerClient').mockReturnValueOnce({ + listContainers: vi.fn().mockResolvedValueOnce([ + { + Id: 'c1e2d3f4a5b67890', + Names: ['/web-frontend'], + Image: 'nginx:alpine', + State: 'running', + Status: 'Up 2 hours', + Created: 1700000000, + Ports: [{ PrivatePort: 80, PublicPort: 8080, Type: 'tcp' }], + }, + { + Id: 'b9a8c7d6e5f43210', + Names: ['/db-postgres'], + Image: 'postgres:15', + State: 'restarting', + Status: 'Restarting (1) 2s ago', + Created: 1700000000, + Ports: [], + }, + ]), + } as any); + + const result = await dockerListContainersTool.execute({ + all: true, + status: 'restarting', + }); + + expect(result.count).toBe(1); + expect(result.containers[0].name).toBe('db-postgres'); + expect(result.containers[0].state).toBe('restarting'); + }); + + it('TC-TOOL-16: docker_inspect_container returns container configuration and health', async () => { + vi.spyOn(dockerClient, 'getDockerClient').mockReturnValueOnce({ + getContainer: vi.fn().mockReturnValueOnce({ + inspect: vi.fn().mockResolvedValueOnce({ + Id: 'c1e2d3f4a5b67890', + Name: '/payment-redis', + Config: { Image: 'redis:7-alpine', Env: ['PORT=6379'] }, + State: { Status: 'running', ExitCode: 0, OOMKilled: false, Restarting: false }, + Mounts: [{ Source: '/data', Destination: '/data' }], + }), + }), + } as any); + + const result = await dockerInspectContainerTool.execute({ + containerId: 'c1e2d3f4a5b6', + }); + + expect(result.name).toBe('payment-redis'); + expect(result.state).toBe('running'); + expect(result.exitCode).toBe(0); + expect(result.oomKilled).toBe(false); + }); + + it('TC-TOOL-17: docker_get_logs retrieves stdout and stderr logs', async () => { + function frame(stream: number, message: string) { + const header = Buffer.alloc(8); + header[0] = stream; + header.writeUInt32BE(Buffer.byteLength(message), 4); + return Buffer.concat([header, Buffer.from(message)]); + } + vi.spyOn(dockerClient, 'getDockerClient').mockReturnValueOnce({ + getContainer: vi.fn().mockReturnValueOnce({ + inspect: vi.fn().mockResolvedValueOnce({ Config: { Tty: false } }), + logs: vi.fn().mockResolvedValueOnce( + Buffer.concat([frame(1, '[INFO] Server started\n'), frame(2, '[WARN] Slow query detected\n')]) + ), + }), + } as any); + + const result = await dockerGetLogsTool.execute({ + containerId: 'c1e2d3f4a5b6', + tail: 50, + stdout: true, + stderr: true, + }); + + expect(result.containerId).toBe('c1e2d3f4a5b6'); + expect(result.linesCount).toBe(2); + expect(result.lines[0]).toContain('[INFO] Server started'); + expect(result.lines[1]).toContain('[WARN] Slow query detected'); + expect(result.logs).toBe('[INFO] Server started\n[WARN] Slow query detected\n'); + }); + + it('TC-TOOL-18: docker_restart_container restarts container with timeout', async () => { + const restartMock = vi.fn().mockResolvedValueOnce({}); + vi.spyOn(dockerClient, 'getDockerClient').mockReturnValueOnce({ + getContainer: vi.fn().mockReturnValueOnce({ + restart: restartMock, + }), + } as any); + + const result = await dockerRestartContainerTool.execute({ + containerId: 'c1e2d3f4a5b6', + timeoutSeconds: 5, + }); + + expect(result.success).toBe(true); + expect(restartMock).toHaveBeenCalledWith({ t: 5 }); + }); + + // ─── 6. ToolRegistry Operations ────────────────────────────────────────── + + it('TC-TOOL-19: ToolRegistry registers, retrieves, and lists tools', () => { + const registry = new ToolRegistry(); + expect(registry.list()).toHaveLength(0); + + registry.register(k8sGetResourcesTool); + registry.register(dockerListContainersTool); + + expect(registry.has('k8s_get_resources')).toBe(true); + expect(registry.has('docker_list_containers')).toBe(true); + expect(registry.has('non_existent')).toBe(false); + + expect(registry.get('k8s_get_resources')?.name).toBe('k8s_get_resources'); + expect(registry.list()).toHaveLength(2); + }); + + it('TC-TOOL-20: ToolRegistry filters tools by safety level and risk level', () => { + const registry = new ToolRegistry(); + registry.registerAll([ + k8sGetResourcesTool, + k8sApplyManifestTool, + dockerRestartContainerTool, + ]); + + const readOnly = registry.filterBySafety('read_only'); + expect(readOnly).toHaveLength(1); + expect(readOnly[0].name).toBe('k8s_get_resources'); + + const mutating = registry.filterBySafety('mutating'); + expect(mutating).toHaveLength(2); + + const highRisk = registry.filterByRisk('high'); + expect(highRisk).toHaveLength(1); + expect(highRisk[0].name).toBe('k8s_apply_manifest'); + + const mediumRisk = registry.filterByRisk('medium'); + expect(mediumRisk).toHaveLength(1); + expect(mediumRisk[0].name).toBe('docker_restart_container'); + }); + + it('TC-TOOL-21: ToolRegistry.invoke() executes tool with validated arguments', async () => { + const registry = new ToolRegistry(); + const mockTool = createDeclarativeTool({ + name: 'echo_tool', + description: 'Echos message', + schema: z.object({ message: z.string() }), + execute: async ({ message }) => ({ echo: message }), + }); + + registry.register(mockTool); + const result = await registry.invoke('echo_tool', { message: 'hello world' }); + expect(result).toEqual({ echo: 'hello world' }); + }); + + it('TC-TOOL-22: ToolRegistry.invoke() rejects invalid arguments before execution', async () => { + const registry = new ToolRegistry(); + const execMock = vi.fn(); + const mockTool = createDeclarativeTool({ + name: 'strict_tool', + description: 'Strict tool', + schema: z.object({ count: z.number().int().positive() }), + execute: execMock, + }); + + registry.register(mockTool); + + // Missing field + await expect(registry.invoke('strict_tool', {})).rejects.toThrow(); + // Negative integer + await expect(registry.invoke('strict_tool', { count: -5 })).rejects.toThrow(); + // String instead of number + await expect(registry.invoke('strict_tool', { count: '10' })).rejects.toThrow(); + + expect(execMock).not.toHaveBeenCalled(); + }); + + it('TC-TOOL-23: ToolRegistry.invoke() throws on unregistered tool', async () => { + const registry = new ToolRegistry(); + await expect(registry.invoke('unknown_tool', {})).rejects.toThrow( + "Declarative tool 'unknown_tool' not found." + ); + }); + + it('TC-TOOL-24: ToolRegistry exports FunctionDeclarations and Tools for Gemini SDK', () => { + const registry = new ToolRegistry(); + registry.register(k8sGetResourcesTool); + registry.register(dockerListContainersTool); + + const declarations = registry.getDeclarations(); + expect(declarations).toHaveLength(2); + expect(declarations[0].name).toBe('k8s_get_resources'); + expect(declarations[0].description).toBeDefined(); + expect(declarations[0].parameters).toBeDefined(); + + const geminiTools = registry.toGeminiTools(); + expect(geminiTools).toHaveLength(1); + expect(geminiTools[0].functionDeclarations).toHaveLength(2); + }); + + it('TC-TOOL-25: Dual interface compatibility (safety/safetyLevel, parameters/schema, invoke/execute)', async () => { + const tool = k8sGetPodTool; + // Dual safety getters + expect(tool.safety).toBe(tool.safetyLevel); + // Dual schema getters + expect(tool.parameters).toBe(tool.schema); + + // Registry dual dispatch methods + const registry = new DeclarativeToolRegistry(); + registry.register(tool); + + vi.spyOn(k8sClient, 'getK8sApi').mockReturnValue({ + readNamespacedPod: vi.fn().mockResolvedValue({ + metadata: { name: 'test-pod', namespace: 'default' }, + status: { phase: 'Running', containerStatuses: [{ name: 'app', restartCount: 3, lastState: { terminated: { exitCode: 42 } } }] }, + spec: { containers: [{ name: 'app', resources: { limits: { memory: '256Mi' } } }] }, + }), + } as ReturnType); + + const res1 = await registry.invoke('k8s_get_pod', { name: 'test-pod' }); + const res2 = await registry.execute('k8s_get_pod', { name: 'test-pod' }); + expect(res1.pod).toBe('test-pod'); + expect(res2.pod).toBe('test-pod'); + expect(res2).toMatchObject({ found: true, exitCode: 42, restartCount: 3, memoryLimit: '256Mi' }); + + // Default tool registry has pre-populated standard tools + expect(defaultToolRegistry.has('k8s_get_resources')).toBe(true); + expect(defaultToolRegistry.has('docker_list_containers')).toBe(true); + }); + + it('converts numeric native enums cleanly and ignores inherited API_READERS keys', async () => { + enum Mode { Off = 0, On = 1 } + const schema = zodToGenAiSchema(z.nativeEnum(Mode)); + expect(schema).toEqual({ type: Type.INTEGER, format: 'enum', enum: ['0', '1'] }); + + vi.spyOn(remediationExecutor, 'executeRemediationCommand').mockResolvedValue({ + success: false, stdout: '', stderr: 'NotFound', exitCode: 1, + }); + const res = await k8sDescribeResourceTool.execute({ kind: 'constructor', name: 'x', namespace: 'default' }); + expect(res.found).toBe(false); + }); +}); diff --git a/src/__tests__/degraded-mode.test.ts b/src/__tests__/degraded-mode.test.ts index c96d3b96..9292a985 100644 --- a/src/__tests__/degraded-mode.test.ts +++ b/src/__tests__/degraded-mode.test.ts @@ -172,12 +172,13 @@ describe('Graceful Degradation & Fallback Ladder (Phase 18)', () => { expect(result.details).toContain("Exit code 137 detected in container 'checkout'"); expect(result.details).toContain('Memory limit 256Mi exceeded'); expect(result.details).toContain('Confidence: 100%'); - expect(loggerInfoSpy).toHaveBeenCalledWith( + expect(loggerWarnSpy).toHaveBeenCalledWith( expect.stringContaining('Python 3 or ollama package is not available') ); - expect(loggerInfoSpy).toHaveBeenCalledWith( + expect(loggerWarnSpy).toHaveBeenCalledWith( expect.stringContaining('Running in Deterministic Rule Mode') ); + expect(loggerInfoSpy).not.toHaveBeenCalled(); }); it('simulates Ollama connection refused -> cleanly falls back to Deterministic Rule Engine', async () => { @@ -194,9 +195,10 @@ describe('Graceful Degradation & Fallback Ladder (Phase 18)', () => { expect(result.details).toContain('Exit code 1 detected'); expect(result.details).toContain('Restart count: 8'); expect(result.details).toContain('Confidence: 100%'); - expect(loggerInfoSpy).toHaveBeenCalledWith( + expect(loggerWarnSpy).toHaveBeenCalledWith( expect.stringContaining('Local Ollama service is unreachable') ); + expect(loggerInfoSpy).not.toHaveBeenCalled(); }); it('simulates ImagePull failure under Ollama outage -> triggers ImagePull rule', async () => { diff --git a/src/__tests__/diff-confirmation.test.tsx b/src/__tests__/diff-confirmation.test.tsx new file mode 100644 index 00000000..8cd5232a --- /dev/null +++ b/src/__tests__/diff-confirmation.test.tsx @@ -0,0 +1,762 @@ +import React, { useState, useEffect } from 'react'; +import { describe, it, expect, vi } from 'vitest'; +import { Text } from 'ink'; +import { renderTUI, stripAnsi } from './e2e/harness/tui-test-utils.js'; +import { + DiffRenderer, + parseDiffWithLineNumbers, +} from '../ui/components/DiffRenderer.js'; +import { + ToolConfirmationQueue, + evaluateSafetyPolicy, + type ConfirmationRequest, +} from '../ui/components/ToolConfirmationQueue.js'; +import { UIStateProvider, useUIState } from '../ui/contexts/UIStateContext.js'; + +describe('F-07: Manifest Diff & Confirmation Queue', () => { + it('TC-DIFF-01: Unified diff header and color-coded lines (DiffRenderer)', () => { + const sampleDiff = + '--- deployment.yaml\n+++ deployment.yaml.patched\n@@ -10,4 +10,4 @@\n- memory: 512Mi\n+ memory: 1024Mi\n'; + + const { getCleanOutput, unmount } = renderTUI(); + const output = getCleanOutput(); + + expect(output).toContain('── Manifest Unified Diff ───────────────────'); + expect(output).toContain('--- deployment.yaml'); + expect(output).toContain('+++ deployment.yaml.patched'); + expect(output).toContain('@@ -10,4 +10,4 @@'); + expect(output).toContain('- memory: 512Mi'); + expect(output).toContain('+ memory: 1024Mi'); + unmount(); + }); + + it('TC-DIFF-02: Empty diff displays clean notice', () => { + const { getCleanOutput, unmount } = renderTUI(); + const output = getCleanOutput(); + expect(output).toContain('No configuration differences detected.'); + unmount(); + + const { getCleanOutput: getCleanWhitespace, unmount: unmountWs } = renderTUI( + + ); + expect(getCleanWhitespace()).toContain('No configuration differences detected.'); + unmountWs(); + }); + + it('TC-DIFF-03: Max lines truncation renders ... and X more lines', () => { + const lines = Array.from({ length: 60 }, (_, i) => `+ line #${i + 1}`); + const longDiff = lines.join('\n'); + + const { getCleanOutput, unmount } = renderTUI( + + ); + + const output = getCleanOutput(); + expect(output).toContain('+ line #1'); + expect(output).toContain('+ line #20'); + expect(output).toContain('... and 40 more lines'); + expect(output).not.toContain('+ line #25'); + unmount(); + }); + + it('renders updates from an empty diff to a change and back', async () => { + const { instance, wait, getLastFrame, unmount } = renderTUI(); + try { + instance.rerender(); + await wait(); + expect(getLastFrame()).toContain('+new'); + instance.rerender(); + await wait(); + expect(getLastFrame()).toContain('No configuration differences detected.'); + } finally { + unmount(); + } + }); + + it('TC-DIFF-04: Line numbers gutter and parseDiffWithLineNumbers helper', () => { + const sampleDiff = + '@@ -5,2 +5,2 @@\n-old line\n+new line\n context line\n'; + + const parsed = parseDiffWithLineNumbers(sampleDiff); + expect(parsed.length).toBeGreaterThanOrEqual(3); + expect(parsed.some((p) => p.type === 'del' && p.oldLine === 5)).toBe(true); + expect(parsed.some((p) => p.type === 'add' && p.newLine === 5)).toBe(true); + + const { getCleanOutput, unmount } = renderTUI( + + ); + + const output = getCleanOutput(); + expect(output).toContain('5'); + expect(output).toContain('-old line'); + expect(output).toContain('+new line'); + unmount(); + }); + + it.each([ + { + id: 'delete-pod', toolName: 'k8s_delete_pod', args: { pod: 'auth-svc' }, + riskLevel: 'high', prompt: 'Permanently delete pod auth-svc?', + }, + { + id: 'apply-patch', toolName: 'k8s_apply_patch', args: { resource: 'payment-service' }, + riskLevel: 'medium', prompt: 'Apply memory limit increase?', + }, + { + id: 'label-pod', toolName: 'k8s_label_pod', args: { pod: 'checkout-api' }, + riskLevel: 'low', prompt: 'Attach diagnostic label?', + }, + ])('shows the $riskLevel risk and action details', request => { + const { getCleanOutput, unmount } = renderTUI( + + ); + try { + const output = getCleanOutput(); + expect(output).toContain(`[${request.riskLevel.toUpperCase()} RISK ACTION REQUIRED]`); + expect(output).toContain(request.id); + expect(output).toContain(request.toolName); + expect(output).toContain(request.prompt); + } finally { + unmount(); + } + }); + + it.each([ + { + label: 'TC-DIFF-08: Interactive approval flow ("y" -> ALLOW)', + request: { + id: 'conf-req-allow', + toolName: 'k8s_apply_patch', + args: { file: 'patch.yaml' }, + riskLevel: 'medium' as const, + prompt: 'Approve rollout patch?', + }, + trigger: (stdin: { send: (v: string) => void; sendCtrlC: () => void }) => stdin.send('y'), + expectedDecision: 'ALLOW' as const, + }, + { + label: 'TC-DIFF-10: Interactive edit flow ("e" -> EDIT)', + request: { + id: 'conf-req-edit', + toolName: 'k8s_apply_patch', + args: { memory: '2Gi' }, + riskLevel: 'medium' as const, + prompt: 'Review and edit configuration before apply?', + }, + trigger: (stdin: { send: (v: string) => void; sendCtrlC: () => void }) => stdin.send('e'), + expectedDecision: 'EDIT' as const, + }, + { + label: 'TC-DIFF-14: SIGINT (Ctrl+C) records denial', + request: { + id: 'conf-req-ctrlc', + toolName: 'k8s_cordon_node', + args: { node: 'worker-node-1' }, + riskLevel: 'high' as const, + prompt: 'Cordon node worker-node-1?', + }, + trigger: (stdin: { send: (v: string) => void; sendCtrlC: () => void }) => stdin.sendCtrlC(), + expectedDecision: 'DENY' as const, + }, + ])('$label', async ({ request, trigger, expectedDecision }) => { + const onDecision = vi.fn(); + const { stdin, wait, unmount } = renderTUI( + + ); + try { + trigger(stdin); + await wait(30); + expect(onDecision).toHaveBeenCalledTimes(1); + expect(onDecision).toHaveBeenCalledWith(expectedDecision, request); + } finally { + unmount(); + } + }); + + it('TC-DIFF-09: Interactive denial flow ("n" keypress or Enter -> DENY)', async () => { + const request: ConfirmationRequest = { + id: 'conf-req-deny', + toolName: 'docker_rm', + args: { container: 'db-local' }, + riskLevel: 'high', + prompt: 'Force delete container?', + }; + + const onDecision = vi.fn(); + const { stdin, wait, unmount } = renderTUI( + + ); + + stdin.send('n'); + await wait(30); + + expect(onDecision).toHaveBeenCalledTimes(1); + expect(onDecision).toHaveBeenCalledWith('DENY', request); + unmount(); + + const onEnterDecision = vi.fn(); + const { stdin: stdinEnter, wait: waitEnter, unmount: unmountEnter } = renderTUI( + + ); + + stdinEnter.sendEnter(); + await waitEnter(30); + + expect(onEnterDecision).toHaveBeenCalledTimes(1); + expect(onEnterDecision).toHaveBeenCalledWith('DENY', request); + unmountEnter(); + }); + + it('TC-DIFF-11: Destructive safety policy auto-blocks hazardous commands', async () => { + expect(evaluateSafetyPolicy('rm -rf /').allowed).toBe(false); + expect(evaluateSafetyPolicy('kubectl delete namespace kube-system').allowed).toBe(false); + expect(evaluateSafetyPolicy('kubectl delete namespace default').allowed).toBe(false); + expect(evaluateSafetyPolicy('kubectl delete namespace production').allowed).toBe(false); + expect(evaluateSafetyPolicy('mkfs.ext4 /dev/sda1').allowed).toBe(false); + expect(evaluateSafetyPolicy('kubectl get pods').allowed).toBe(true); + + const destructiveRequest: ConfirmationRequest = { + id: 'destructive-001', + toolName: 'exec_command', + args: { command: 'rm -rf / --no-preserve-root' }, + riskLevel: 'high', + prompt: 'Execute destructive root deletion?', + }; + + const onDecision = vi.fn(); + const { stdin, wait, getCleanOutput, unmount } = renderTUI( + + ); + + const output = getCleanOutput(); + expect(output).toContain('⛔ POLICY VIOLATION: COMMAND BLOCKED'); + expect(output).toContain('Destructive command permanently blocked by safety policy'); + + // Attempting to type 'y' does NOT trigger approval + stdin.send('y'); + await wait(30); + expect(onDecision).not.toHaveBeenCalled(); + + unmount(); + }); + + it('TC-DIFF-12: Multi-item queue progression', async () => { + const queue: ConfirmationRequest[] = [ + { + id: 'req-multi-1', + toolName: 'patch_memory', + args: { limit: '1024Mi' }, + riskLevel: 'medium', + prompt: 'First remediation patch', + }, + { + id: 'req-multi-2', + toolName: 'patch_cpu', + args: { limit: '2000m' }, + riskLevel: 'low', + prompt: 'Second remediation patch', + }, + ]; + + const onDecision = vi.fn(); + const { stdin, wait, getLastFrame, unmount } = renderTUI( + + ); + + expect(stripAnsi(getLastFrame())).toContain('Queue: 1 of 2'); + expect(stripAnsi(getLastFrame())).toContain('req-multi-1'); + + // Approve first request + stdin.send('y'); + await wait(50); + + expect(onDecision).toHaveBeenCalledWith('ALLOW', queue[0]); + + // UI advances to second request + expect(stripAnsi(getLastFrame())).toContain('Queue: 2 of 2'); + expect(stripAnsi(getLastFrame())).toContain('req-multi-2'); + + // Deny second request + stdin.send('n'); + await wait(50); + + expect(onDecision).toHaveBeenCalledWith('DENY', queue[1]); + unmount(); + }); + + it('TC-DIFF-13: Unrecognized keystrokes are ignored; prompt remains active', async () => { + const request: ConfirmationRequest = { + id: 'conf-req-ignore', + toolName: 'k8s_patch', + args: {}, + riskLevel: 'low', + prompt: 'Awaiting operator input', + }; + + const onDecision = vi.fn(); + const { stdin, wait, getCleanOutput, unmount } = renderTUI( + + ); + + // Send random unmapped keys + stdin.send('x'); + await wait(20); + stdin.send('1'); + await wait(20); + stdin.send(' '); + await wait(20); + + expect(onDecision).not.toHaveBeenCalled(); + + // Now send 'y' + stdin.send('y'); + await wait(30); + expect(onDecision).toHaveBeenCalledTimes(1); + expect(onDecision).toHaveBeenCalledWith('ALLOW', request); + + unmount(); + }); + + it('TC-DIFF-15: Embedded DiffRenderer renders diff inside ToolConfirmationQueue', () => { + const request: ConfirmationRequest = { + id: 'conf-req-with-diff', + toolName: 'k8s_apply_patch', + args: { file: 'deployment.yaml' }, + diff: '@@ -1,2 +1,2 @@\n- replicas: 1\n+ replicas: 3\n', + riskLevel: 'medium', + prompt: 'Scale deployment replicas from 1 to 3?', + }; + + const onDecision = vi.fn(); + const { getCleanOutput, unmount } = renderTUI( + + ); + + const output = getCleanOutput(); + expect(output).toContain('── Manifest Unified Diff ───────────────────'); + expect(output).toContain('- replicas: 1'); + expect(output).toContain('+ replicas: 3'); + unmount(); + }); + + it('TC-DIFF-16: Case-insensitive and flag-tolerant safety policy regex', () => { + expect(evaluateSafetyPolicy('RM -RF /').allowed).toBe(false); + expect(evaluateSafetyPolicy('rm -fr /').allowed).toBe(false); + expect(evaluateSafetyPolicy('rm -r -f /').allowed).toBe(false); + expect(evaluateSafetyPolicy('rm -f -r /').allowed).toBe(false); + expect(evaluateSafetyPolicy('rm --recursive --force /').allowed).toBe(false); + expect(evaluateSafetyPolicy('rm --force --recursive /').allowed).toBe(false); + expect(evaluateSafetyPolicy('KUBECTL delete namespace kube-system').allowed).toBe(false); + expect(evaluateSafetyPolicy('kubectl delete ns kube-system').allowed).toBe(false); + expect(evaluateSafetyPolicy('kubectl delete ns default').allowed).toBe(false); + expect(evaluateSafetyPolicy('kubectl delete ns production').allowed).toBe(false); + expect(evaluateSafetyPolicy('MKFS.ext4 /dev/sda1').allowed).toBe(false); + expect(evaluateSafetyPolicy('DD IF=/dev/zero OF=/dev/sda').allowed).toBe(false); + expect(evaluateSafetyPolicy('kubectl get pods').allowed).toBe(true); + }); + + it('TC-DIFF-17: Policy-blocked commands permit denial via n, Enter, or Escape, but block approval', async () => { + const destructiveRequest: ConfirmationRequest = { + id: 'conf-req-blocked-dismiss', + toolName: 'bash_exec', + args: { script: 'rm -rf /' }, + riskLevel: 'high', + prompt: 'Execute root deletion?', + }; + + // 1. Approval 'y' is blocked + const onDecisionY = vi.fn(); + const { stdin: stdinY, wait: waitY, unmount: unmountY } = renderTUI( + + ); + stdinY.send('y'); + await waitY(30); + expect(onDecisionY).not.toHaveBeenCalled(); + unmountY(); + + // 2. Edit 'e' is blocked + const onDecisionE = vi.fn(); + const { stdin: stdinE, wait: waitE, unmount: unmountE } = renderTUI( + + ); + stdinE.send('e'); + await waitE(30); + expect(onDecisionE).not.toHaveBeenCalled(); + unmountE(); + + // 3. 'n' dismisses with DENY + const onDecisionN = vi.fn(); + const { stdin: stdinN, wait: waitN, unmount: unmountN } = renderTUI( + + ); + stdinN.send('n'); + await waitN(30); + expect(onDecisionN).toHaveBeenCalledTimes(1); + expect(onDecisionN).toHaveBeenCalledWith('DENY', destructiveRequest); + unmountN(); + + // 4. Enter dismisses with DENY + const onDecisionEnter = vi.fn(); + const { stdin: stdinEnter, wait: waitEnter, unmount: unmountEnter } = renderTUI( + + ); + stdinEnter.sendEnter(); + await waitEnter(30); + expect(onDecisionEnter).toHaveBeenCalledTimes(1); + expect(onDecisionEnter).toHaveBeenCalledWith('DENY', destructiveRequest); + unmountEnter(); + + // 5. Escape dismisses with DENY + const onDecisionEsc = vi.fn(); + const { stdin: stdinEsc, wait: waitEsc, unmount: unmountEsc } = renderTUI( + + ); + stdinEsc.sendEscape(); + await waitEsc(30); + expect(onDecisionEsc).toHaveBeenCalledTimes(1); + expect(onDecisionEsc).toHaveBeenCalledWith('DENY', destructiveRequest); + unmountEsc(); + }); + + it('TC-DIFF-18: Command inspection across multiple argument keys (script, raw, cmd, command)', () => { + const reqWithScript: ConfirmationRequest = { + id: 'req-script', + toolName: 'bash_exec', + args: { script: 'rm -rf /' }, + riskLevel: 'high', + prompt: 'Execute script?', + }; + const { getCleanOutput: getScriptOutput, unmount: unmountScript } = renderTUI( + + ); + expect(getScriptOutput()).toContain('⛔ POLICY VIOLATION: COMMAND BLOCKED'); + unmountScript(); + + const reqWithRaw: ConfirmationRequest = { + id: 'req-raw', + toolName: 'sh_exec', + args: { raw: 'kubectl delete ns kube-system' }, + riskLevel: 'high', + prompt: 'Execute raw command?', + }; + const { getCleanOutput: getRawOutput, unmount: unmountRaw } = renderTUI( + + ); + expect(getRawOutput()).toContain('⛔ POLICY VIOLATION: COMMAND BLOCKED'); + unmountRaw(); + }); + + it('TC-DIFF-19: Queue state synchronization with single-request controlled wrapper', async () => { + const req1: ConfirmationRequest = { + id: 'req-controlled-1', + toolName: 'k8s_restart', + args: { pod: 'pod-1' }, + riskLevel: 'low', + prompt: 'Restart pod 1?', + }; + const req2: ConfirmationRequest = { + id: 'req-controlled-2', + toolName: 'k8s_restart', + args: { pod: 'pod-2' }, + riskLevel: 'medium', + prompt: 'Restart pod 2?', + }; + + const decisions: Array<{ decision: string; id: string }> = []; + + const ControlledWrapper: React.FC = () => { + const [current, setCurrent] = useState(req1); + + return ( + { + decisions.push({ decision, id: r.id }); + if (r.id === 'req-controlled-1') { + setCurrent(req2); + } else { + setCurrent(undefined); + } + }} + /> + ); + }; + + const { stdin, wait, getLastFrame, unmount } = renderTUI(); + + expect(stripAnsi(getLastFrame())).toContain('Restart pod 1?'); + + // Approve first request + stdin.send('y'); + await wait(50); + + expect(decisions).toHaveLength(1); + expect(decisions[0]).toEqual({ decision: 'ALLOW', id: 'req-controlled-1' }); + + // UI should now show request 2 and accept input + expect(stripAnsi(getLastFrame())).toContain('Restart pod 2?'); + + // Deny second request + stdin.send('n'); + await wait(50); + + expect(decisions).toHaveLength(2); + expect(decisions[1]).toEqual({ decision: 'DENY', id: 'req-controlled-2' }); + + unmount(); + }); + + it('TC-DIFF-20: Sequential multi-item processing when items are removed via onResolve', async () => { + const initialQueue: ConfirmationRequest[] = [ + { + id: 'shift-req-1', + toolName: 'k8s_scale', + args: { replicas: 3 }, + riskLevel: 'low', + prompt: 'Scale service?', + }, + { + id: 'shift-req-2', + toolName: 'k8s_drain', + args: { node: 'node-2' }, + riskLevel: 'high', + prompt: 'Drain node 2?', + }, + ]; + + const decisions: Array<{ decision: string; id: string }> = []; + + const ShiftingQueueWrapper: React.FC = () => { + const [queue, setQueue] = useState(initialQueue); + + return ( + { + decisions.push({ decision, id: r.id }); + }} + onResolve={(id) => { + setQueue((prev) => prev.filter((item) => item.id !== id)); + }} + /> + ); + }; + + const { stdin, wait, getLastFrame, unmount } = renderTUI(); + + expect(stripAnsi(getLastFrame())).toContain('Scale service?'); + + stdin.send('y'); + await wait(60); + + expect(decisions).toHaveLength(1); + expect(decisions[0]).toEqual({ decision: 'ALLOW', id: 'shift-req-1' }); + + // After resolution, second item must be visible and interactive + expect(stripAnsi(getLastFrame())).toContain('Drain node 2?'); + + stdin.send('n'); + await wait(60); + + expect(decisions).toHaveLength(2); + expect(decisions[1]).toEqual({ decision: 'DENY', id: 'shift-req-2' }); + + unmount(); + }); + + it('TC-DIFF-21: DiffRenderer handles escaped literal newlines (\\n)', () => { + const escapedDiff = + '--- deployment.yaml\\n+++ deployment.yaml.patched\\n@@ -1,2 +1,2 @@\\n-replicas: 1\\n+replicas: 3'; + + const { getCleanOutput, unmount } = renderTUI( + + ); + + const output = getCleanOutput(); + expect(output).toContain('--- deployment.yaml'); + expect(output).toContain('+++ deployment.yaml.patched'); + expect(output).toContain('-replicas: 1'); + expect(output).toContain('+replicas: 3'); + unmount(); + }); + + it('TC-DIFF-22: Identical file comparison renders empty diff notice', () => { + const sameContent = 'apiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: auth\n'; + + const { getCleanOutput, unmount } = renderTUI( + + ); + + const output = getCleanOutput(); + expect(output).toContain('No configuration differences detected.'); + expect(output).not.toContain('--- manifest.yaml'); + unmount(); + }); + + it('TC-DIFF-23: Line gutter alignment in DiffRenderer with git headers and blank lines', () => { + const gitDiffWithHeaders = + 'diff --git a/foo.txt b/foo.txt\nnew file mode 100644\nindex 0000000..e69de29\n--- /dev/null\n+++ b/foo.txt\n@@ -0,0 +1,2 @@\n+line 1\n+line 2'; + + const parsed = parseDiffWithLineNumbers(gitDiffWithHeaders); + const rawLines = gitDiffWithHeaders.split('\n'); + expect(parsed.length).toBe(rawLines.length); + + // Header lines should have no line numbers + expect(parsed[0].type).toBe('header'); + expect(parsed[1].type).toBe('header'); // new file mode 100644 + expect(parsed[2].type).toBe('header'); // index ... + expect(parsed[5].type).toBe('hunk'); // @@ hunk header + expect(parsed[5].newLine).toBeUndefined(); + + // Line 1 and 2 + expect(parsed[6].type).toBe('add'); + expect(parsed[6].newLine).toBe(1); + expect(parsed[7].type).toBe('add'); + expect(parsed[7].newLine).toBe(2); + + const { getCleanOutput, unmount } = renderTUI( + + ); + + const output = getCleanOutput(); + expect(output).toContain('new file mode 100644'); + expect(output).toContain('+line 1'); + expect(output).toContain('+line 2'); + unmount(); + }); + + it('TC-DIFF-24: UIStateContext closeConfirmation invokes onDecision with DENY', async () => { + const onDecision = vi.fn(); + const testReq: ConfirmationRequest = { + id: 'conf-close-001', + toolName: 'k8s_delete', + args: {}, + riskLevel: 'high', + prompt: 'Delete resource?', + }; + + const TestConsumer: React.FC = () => { + const { closeConfirmation, state } = useUIState(); + + useEffect(() => { + closeConfirmation(); + }, [closeConfirmation]); + + return Queue: {state.confirmationQueue.length}; + }; + + const { wait, unmount } = renderTUI( + + + + ); + + await wait(40); + + expect(onDecision).toHaveBeenCalledTimes(1); + expect(onDecision).toHaveBeenCalledWith('conf-close-001', 'DENY'); + unmount(); + }); + + it('advances confirmation focus and restores the composer when the queue empties', async () => { + const onDecision = vi.fn(); + const first: ConfirmationRequest = { + id: 'first', toolName: 'k8s_apply_patch', args: {}, riskLevel: 'medium', prompt: 'Apply first?', + }; + const second = { ...first, id: 'second', prompt: 'Apply second?' }; + let session: ReturnType; + function Consumer() { + session = useUIState(); + return {session.focusedComponent} {session.activeConfirmation?.id}; + } + const { wait, getLastFrame, unmount } = renderTUI( + + ); + try { + session!.enqueueConfirmation(first); + session!.enqueueConfirmation(first); + session!.openConfirmation(second); + await wait(); + expect(session!.confirmationQueue).toHaveLength(2); + expect(getLastFrame()).toContain('confirmationQueue first'); + + session!.resolveConfirmation('first', 'ALLOW'); + await wait(); + expect(getLastFrame()).toContain('confirmationQueue second'); + session!.closeConfirmation(); + await wait(); + expect(getLastFrame()).toContain('composer'); + expect(onDecision.mock.calls).toEqual([['first', 'ALLOW'], ['second', 'DENY']]); + + session!.toggleHelp(); + session!.setCardExpanded('runtime', false); + session!.toggleCardExpansion('config'); + session!.setActiveTab(2); + session!.setTerminalDimensions({ columns: 90, rows: 25 }); + session!.expandAllCards(); + await wait(); + expect(session!.isHelpOpen).toBe(true); + expect(session!.expandedCards).toEqual({ runtime: true, config: true }); + expect(session!.terminalDimensions).toEqual({ columns: 90, rows: 25 }); + expect(session!.activeTab).toBe(2); + session!.collapseAllCards(); + session!.toggleHelp(); + await wait(); + expect(session!.expandedCards).toEqual({}); + expect(session!.isHelpOpen).toBe(false); + } finally { + unmount(); + } + }); + + it('preserves literal backslash-n sequences inside multiline diffs', () => { + const multiline = '--- app.yaml\n+++ app.yaml.patched\n@@ -1 +1 @@\n-format: "\\n"\n+format: "\\r\\n"\n'; + const { getCleanOutput, unmount } = renderTUI(); + const output = getCleanOutput(); + expect(output).toContain('-format: "\\n"'); + expect(output).toContain('+format: "\\r\\n"'); + unmount(); + }); + + it('publishes each confirmation decision at most once on repeated resolve or close calls', async () => { + const onDecision = vi.fn(); + const req: ConfirmationRequest = { + id: 'once-1', toolName: 'k8s_apply_patch', args: {}, riskLevel: 'medium', prompt: 'Apply once?', + }; + let session: ReturnType; + function Consumer() { + session = useUIState(); + return {session.confirmationQueue.length}; + } + const { wait, unmount } = renderTUI(); + try { + session!.enqueueConfirmation(req); + session!.resolveConfirmation('once-1', 'ALLOW'); + session!.resolveConfirmation('once-1', 'DENY'); + session!.closeConfirmation(); + await wait(); + expect(onDecision.mock.calls).toEqual([['once-1', 'ALLOW']]); + } finally { + unmount(); + } + }); + + it('blocks duplicate decisions while current request stays active across queue length changes', async () => { + const req1: ConfirmationRequest = { id: 'q-1', toolName: 'k8s_apply_patch', args: {}, riskLevel: 'low', prompt: 'One?' }; + const req2: ConfirmationRequest = { id: 'q-2', toolName: 'k8s_apply_patch', args: {}, riskLevel: 'low', prompt: 'Two?' }; + const onDecision = vi.fn(); + const { stdin, instance, wait, unmount } = renderTUI( + + ); + try { + stdin.send('y'); + await wait(10); + instance.rerender(); + stdin.send('y'); + await wait(10); + expect(onDecision).toHaveBeenCalledTimes(1); + } finally { + unmount(); + } + }); +}); diff --git a/src/__tests__/e2e/harness/cli-runner.ts b/src/__tests__/e2e/harness/cli-runner.ts new file mode 100644 index 00000000..2839c253 --- /dev/null +++ b/src/__tests__/e2e/harness/cli-runner.ts @@ -0,0 +1,213 @@ +import { Command } from 'commander'; +import { vi } from 'vitest'; +import { execFile } from 'node:child_process'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { registerShowCommand } from '../../../commands/show'; +import { registerHealthCommand } from '../../../commands/health'; +import { registerWatchCommand } from '../../../commands/watch'; +import { registerLogsCommand } from '../../../commands/logs'; +import { registerConfigCommand } from '../../../commands/config'; +import { registerAnalyzeCommand } from '../../../commands/analyze'; +import { registerFiltersCommand } from '../../../commands/filters'; +import { registerAuthCommand } from '../../../commands/auth'; +import { registerCacheCommand } from '../../../commands/cache'; +import { registerServeCommand } from '../../../commands/serve'; +import { registerCustomAnalyzerCommand } from '../../../commands/custom-analyzer'; +import { registerIntegrations } from '../../../integrations/integrations'; +import { getInstalledVersion } from '../../../utils/version-check'; +import { checkDockerConnection } from '../../../docker/client'; +import { checkK8sConnection } from '../../../kubernetes/client'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const ROOT_DIR = path.resolve(__dirname, '../../../../'); + +export interface CLIExecutionResult { + stdout: string; + stderr: string; + exitCode: number; +} + +export interface RunCLIOptions { + isTTY?: boolean; + env?: NodeJS.ProcessEnv; + cwd?: string; +} + +function formatArgs(msgs: unknown[]): string { + return msgs.map((m) => (typeof m === 'object' ? JSON.stringify(m) : String(m))).join(' ') + '\n'; +} + +function overrideTTY(isTTY?: boolean): () => void { + if (isTTY === undefined) return () => {}; + const originalStdout = process.stdout.isTTY; + const originalStdin = process.stdin.isTTY; + Object.defineProperty(process.stdout, 'isTTY', { value: isTTY, configurable: true }); + Object.defineProperty(process.stdin, 'isTTY', { value: isTTY, configurable: true }); + return () => { + Object.defineProperty(process.stdout, 'isTTY', { value: originalStdout, configurable: true }); + Object.defineProperty(process.stdin, 'isTTY', { value: originalStdin, configurable: true }); + }; +} + +function captureProcessIO() { + let stdout = ''; + let stderr = ''; + let exitCode = 0; + + const writeSpy = (stream: NodeJS.WriteStream, append: (str: string) => void) => + vi.spyOn(stream, 'write').mockImplementation(((chunk: any, encoding?: any, cb?: any) => { + append(typeof chunk === 'string' ? chunk : chunk.toString(encoding)); + if (typeof cb === 'function') cb(); + return true; + }) as any); + + const spies = [ + vi.spyOn(console, 'log').mockImplementation((...msgs) => { stdout += formatArgs(msgs); }), + vi.spyOn(console, 'error').mockImplementation((...msgs) => { stderr += formatArgs(msgs); }), + vi.spyOn(console, 'warn').mockImplementation((...msgs) => { stderr += formatArgs(msgs); }), + writeSpy(process.stdout, (s) => { stdout += s; }), + writeSpy(process.stderr, (s) => { stderr += s; }), + vi.spyOn(process, 'exit').mockImplementation(((code?: number) => { + exitCode = typeof code === 'number' ? code : 0; + const err: any = new Error(`process.exit(${exitCode})`); + err.exitCode = exitCode; + throw err; + }) as any), + ]; + + return { + read: () => ({ stdout, stderr, exitCode }), + restore: () => spies.forEach((s) => s.mockRestore()), + }; +} + +function resolveParseErrorExitCode(err: any, currentExitCode: number): number { + if (err.exitCode !== undefined) return err.exitCode; + if (err.code === 'commander.helpDisplayed' || err.code === 'commander.version') return 0; + return currentExitCode === 0 ? 1 : currentExitCode; +} + +function isFulfilledConnected(res: PromiseSettledResult<{ connected: boolean }>): boolean { + return res.status === 'fulfilled' && res.value.connected; +} + +/** + * Creates a fresh, isolated Commander instance with all KDM commands registered, + * exitOverride() enabled, and no global side-effects. + */ +export function createE2EProgram(): Command { + const program = new Command(); + const version = getInstalledVersion(); + + program + .name('kdm') + .description('Kubernetes and Docker Monitoring CLI') + .version(version) + .exitOverride() + .action(async () => { + if (process.stdout.isTTY && process.stdin.isTTY) { + console.log('Launching interactive copilot shell...'); + return; + } + try { + const [dockerRes, k8sRes] = await Promise.allSettled([ + checkDockerConnection(), + checkK8sConnection(), + ]); + console.log('KDM Non-Interactive Status Summary:'); + console.log(`Docker: ${isFulfilledConnected(dockerRes) ? 'Connected' : 'Disconnected'}`); + console.log(`Kubernetes: ${isFulfilledConnected(k8sRes) ? 'Connected' : 'Disconnected'}`); + program.outputHelp(); + } catch { + // ignore in fallback + } + }); + + registerShowCommand(program); + registerHealthCommand(program); + registerWatchCommand(program); + registerLogsCommand(program); + registerConfigCommand(program); + registerAnalyzeCommand(program); + registerFiltersCommand(program); + registerAuthCommand(program); + registerCacheCommand(program); + registerServeCommand(program); + registerCustomAnalyzerCommand(program); + + registerIntegrations(); + + return program; +} + +/** + * Executes a CLI command string in-process with full stream capture and process.exit protection. + */ +export async function runCLI( + args: string[], + options: RunCLIOptions = {} +): Promise { + const program = createE2EProgram(); + const restoreTTY = overrideTTY(options.isTTY); + const io = captureProcessIO(); + const previousProcessExitCode = process.exitCode; + process.exitCode = undefined; + let exitCodeOverride: number | undefined; + let commandProcessExitCode: number | undefined; + + try { + await program.parseAsync(['node', 'kdm', ...args]); + if (typeof process.exitCode === 'number') { + commandProcessExitCode = process.exitCode; + } + } catch (err: any) { + exitCodeOverride = resolveParseErrorExitCode(err, io.read().exitCode); + } finally { + process.exitCode = previousProcessExitCode; + io.restore(); + restoreTTY(); + } + + const captured = io.read(); + return { + stdout: captured.stdout, + stderr: captured.stderr, + exitCode: exitCodeOverride ?? (captured.exitCode !== 0 ? captured.exitCode : (commandProcessExitCode ?? 0)), + }; +} + +/** + * Executes the compiled KDM CLI binary as an external child process (black-box). + */ +export function execCLI( + args: string[], + options: { timeout?: number; env?: NodeJS.ProcessEnv; cwd?: string } = {} +): Promise { + const binaryPath = path.join(ROOT_DIR, 'bin', 'kdm.js'); + return new Promise((resolve) => { + execFile( + process.execPath, + [binaryPath, ...args], + { + cwd: options.cwd || ROOT_DIR, + timeout: options.timeout || 15000, + env: { + ...process.env, + NODE_ENV: 'test', + ...options.env, + }, + }, + (error, stdout, stderr) => { + const exitCode = error ? (error.code as number) || error.signal ? 1 : (error as any).status ?? 1 : 0; + resolve({ + stdout: stdout.toString(), + stderr: stderr.toString(), + exitCode: typeof error?.code === 'number' ? error.code : exitCode, + }); + } + ); + }); +} diff --git a/src/__tests__/e2e/harness/contracts.tsx b/src/__tests__/e2e/harness/contracts.tsx new file mode 100644 index 00000000..09dd2908 --- /dev/null +++ b/src/__tests__/e2e/harness/contracts.tsx @@ -0,0 +1,478 @@ +import { z } from 'zod'; +import React, { useState } from 'react'; +import { Box, Text, useInput } from 'ink'; +import { MockClusterEnvironment, type MockClusterState, type MockContainerState, type MockPodState } from './mock-cluster-env'; + +// ─── Utilities ────────────────────────────────────────────────────────────── + +export { parseSlashCommand } from '../../../ui/components/Composer'; + +// ─── F-04: Subagent Progress & Event Translation Protocol ─────────────────── + +export { translateNDJSONToSubagentProgress } from '../../../agent/event-translator'; +export type { SubagentProgress } from '../../../agent/types'; + +// ─── F-04: Subagent Registry & Invocation Protocol ─────────────────────────── + +export { AgentRegistry } from '../../../agent/registry'; +export { AgentTool } from '../../../agent/agent-tool'; +export type { AgentContext, AgentDefinition } from '../../../agent/types'; + +// ─── F-03: Declarative Cluster Tools Protocol ─────────────────────────────── + +export interface DeclarativeTool { + name: string; + description: string; + safety: 'read_only' | 'mutating'; + riskLevel?: 'low' | 'medium' | 'high'; + parameters: z.ZodType; + execute: (args: TParams) => Promise; +} + +export class DeclarativeToolRegistry { + private tools = new Map(); + + register(tool: DeclarativeTool): void { + this.tools.set(tool.name, tool); + } + + get(name: string): DeclarativeTool | undefined { + return this.tools.get(name); + } + + list(): DeclarativeTool[] { + return Array.from(this.tools.values()); + } + + getDeclarations(): Array<{ name: string; description: string; parameters: Record }> { + return this.list().map((t) => ({ + name: t.name, + description: t.description, + parameters: { type: 'object' }, + })); + } + + async invoke(name: string, rawArgs: unknown): Promise { + const tool = this.get(name); + if (!tool) { + throw new Error(`Declarative tool '${name}' not found.`); + } + const validated = tool.parameters.parse(rawArgs); + return await tool.execute(validated); + } +} + +function requireK8sConnected(state: MockClusterState): void { + if (!state.k8sConnected) { + throw new Error('Kubernetes API connection refused: ETIMEDOUT'); + } +} + +function requireDockerConnected(state: MockClusterState): void { + if (!state.dockerConnected) { + throw new Error('Cannot connect to the Docker daemon. Is Docker running?'); + } +} + +async function waitForHangingCluster(state: MockClusterState, timeoutMs?: number): Promise { + if (!(state as any).hanging) return; + const effectiveTimeout = timeoutMs || 5000; + await new Promise((_, reject) => + setTimeout( + () => reject(new Error(`ClusterTimeoutError: Control plane did not respond in ${effectiveTimeout}ms`)), + Math.min(effectiveTimeout, 20) + ) + ); +} + +function findMatchingPod(pods: MockPodState[], name: string, namespace: string): MockPodState { + const found = pods.find( + (p) => p.name === name && (p.namespace === namespace || !p.namespace) + ); + if (!found) { + const err: any = new Error(`Pod '${name}' not found in namespace '${namespace}'`); + err.statusCode = 404; + throw err; + } + return found; +} + +function formatPodDetail(found: MockPodState) { + return { + pod: found.name, + namespace: found.namespace, + phase: found.phase || 'Running', + status: found.status, + exitCode: found.exitCode ?? 0, + restartCount: found.restarts, + memoryLimit: found.memoryLimit || '512Mi', + rawPod: found.rawPod, + }; +} + +function filterClusterPods(pods: MockPodState[], namespace: string): MockPodState[] { + if (namespace === 'all') return pods; + return pods.filter((p) => p.namespace === namespace || !p.namespace); +} + +function findMatchingContainer(containers: MockContainerState[], containerId: string): MockContainerState { + const found = containers.find( + (c) => c.id === containerId || c.name === containerId || c.name === `/${containerId}` + ); + if (!found) { + const err: any = new Error(`Container '${containerId}' not found`); + err.statusCode = 404; + throw err; + } + return found; +} + +function validatePatchPayload(resource: string, patch: string): void { + if (patch.startsWith(':::broken-yaml')) { + throw new Error('YAML syntax error: unparseable patch structure'); + } + if (patch.startsWith(':::conflict')) { + const err: any = new Error(`Error from server (Conflict): Operation cannot be fulfilled on ${resource}`); + err.statusCode = 409; + throw err; + } +} + +export const k8sGetPodTool: DeclarativeTool = { + name: 'k8s_get_pod', + description: 'Inspect status, exit codes, and restart counts of a Kubernetes pod', + safety: 'read_only', + riskLevel: 'low', + parameters: z.object({ + name: z.string().min(1, 'Pod name is required'), + namespace: z.string().default('default'), + timeoutMs: z.number().optional(), + }), + execute: async ({ name, namespace = 'default', timeoutMs }: { name: string; namespace?: string; timeoutMs?: number }) => { + const activeCluster = MockClusterEnvironment.getActive(); + if (!activeCluster) { + return { + pod: name, + namespace, + phase: 'Running', + status: 'OOMKilled', + exitCode: 137, + restartCount: 5, + memoryLimit: '512Mi', + }; + } + const state = activeCluster.getState(); + requireK8sConnected(state); + await waitForHangingCluster(state, timeoutMs); + return formatPodDetail(findMatchingPod(state.pods, name, namespace)); + }, +}; + +export const k8sListPodsTool: DeclarativeTool = { + name: 'k8s_list_pods', + description: 'List pods in a specified namespace', + safety: 'read_only', + riskLevel: 'low', + parameters: z.object({ + namespace: z.string().default('default'), + }), + execute: async ({ namespace }) => { + const activeCluster = MockClusterEnvironment.getActive(); + if (!activeCluster) { + return { + namespace, + pods: [ + { name: 'payment-service-8f4b-2x9p', namespace, status: 'OOMKilled', restarts: 5 }, + { name: 'auth-api-v2-7c91', namespace, status: 'CrashLoopBackOff', restarts: 12 }, + ], + }; + } + const state = activeCluster.getState(); + requireK8sConnected(state); + const filtered = filterClusterPods(state.pods, namespace); + return { + namespace, + pods: filtered.map((p) => ({ + name: p.name, + namespace: p.namespace, + status: p.status, + restarts: p.restarts, + node: p.node, + })), + }; + }, +}; + +export const dockerInspectContainerTool: DeclarativeTool = { + name: 'docker_inspect_container', + description: 'Inspect detailed state and exit code of a Docker container', + safety: 'read_only', + riskLevel: 'low', + parameters: z.object({ + containerId: z.string().min(1, 'containerId is required'), + }), + execute: async ({ containerId }) => { + const activeCluster = MockClusterEnvironment.getActive(); + if (!activeCluster) { + return { + containerId, + state: 'restarting', + exitCode: 1, + oomKilled: false, + status: 'Restarting (1) 3 seconds ago', + }; + } + const state = activeCluster.getState(); + requireDockerConnected(state); + const found = findMatchingContainer(state.containers, containerId); + return { + containerId, + id: found.id, + name: found.name, + state: found.state, + exitCode: found.exitCode ?? 0, + oomKilled: found.exitCode === 137, + status: found.status, + rawContainer: found.rawContainer, + }; + }, +}; + +export const k8sApplyPatchTool: DeclarativeTool = { + name: 'k8s_apply_patch', + description: 'Apply an approved YAML manifest patch to a Kubernetes resource', + safety: 'mutating', + riskLevel: 'high', + parameters: z.object({ + resource: z.string().min(1), + namespace: z.string().default('default'), + patch: z.string().min(1, 'Patch payload is required'), + }), + execute: async ({ resource, namespace, patch }) => { + validatePatchPayload(resource, patch); + const activeCluster = MockClusterEnvironment.getActive(); + if (activeCluster) { + const state = activeCluster.getState(); + requireK8sConnected(state); + const pod = state.pods.find((p) => resource.includes(p.name) || p.name === resource); + if (pod && patch.includes('1024Mi')) { + pod.memoryLimit = '1024Mi'; + pod.status = 'Running'; + } + } + + return { + success: true, + appliedTo: `${namespace}/${resource}`, + status: 'Patched successfully', + patch, + }; + }, +}; + +export const k8sGetLogsTool: DeclarativeTool = { + name: 'k8s_get_logs', + description: 'Fetch runtime container logs', + safety: 'read_only', + riskLevel: 'low', + parameters: z.object({ + pod: z.string().min(1), + namespace: z.string().default('default'), + }), + execute: async ({ pod, namespace }) => { + const activeCluster = MockClusterEnvironment.getActive(); + if (activeCluster) requireK8sConnected(activeCluster.getState()); + if (pod === 'just-started-pod') { + return { logs: '', note: 'Log stream empty' }; + } + return { + logs: `[INFO] ${pod} started\n[INFO] listening on port 8080`, + pod, + namespace, + }; + }, +}; + +// ─── F-05: Codebase Investigator Agent Implementation ─────────────────────── + +export { CodebaseInvestigatorAgent } from '../../../agent/investigator'; + +// ─── F-07: Tool Confirmation Queue & Diff Renderer Protocol ───────────────── + +export { ThinkingMessage } from '../../../ui/components/ThinkingMessage'; +export { DiffRenderer } from '../../../ui/components/DiffRenderer'; +export { ToolConfirmationQueueView, evaluateSafetyPolicy } from '../../../ui/components/ToolConfirmationQueue'; +export type { ConfirmationRequest, ConfirmationDecision } from '../../../ui/components/ToolConfirmationQueue'; + +export { Composer as ComposerView } from '../../../ui/components/Composer'; + +export interface DashboardWithTroubleshootTriggerProps { + dashboardType: 'watch' | 'show' | 'health' | 'logs'; + targetResource?: string | null; + currentLogLines?: string[]; + onTrigger?: (resource: string) => void; + onTroubleshootTriggered?: (resource: string) => void; + onDismiss?: () => void; + onDismissal?: () => void; + isHeadless?: boolean; +} + +function DashboardOverviewView({ dashboardType, targetResource, currentLogLines }: { + dashboardType: string; + targetResource?: string | null; + currentLogLines: string[]; +}) { + return ( + + Active Dashboard: {dashboardType.toUpperCase()} + Selected Resource: {targetResource || 'None'} + {currentLogLines.map((l, i) => ( + {l} + ))} + Press [t] to trigger AI troubleshooting + + ); +} + +function TroubleshootingOverlayView({ dashboardType, targetResource }: { + dashboardType: string; + targetResource?: string | null; +}) { + return ( + + 🤖 AI Troubleshooting Session: {targetResource} + Dispatching Multi-Agent Council... + Press [Esc] to return to {dashboardType} + + ); +} + +function applyTroubleshootStart(ctx: { + targetResource?: string; + inTroubleshootingRef: React.MutableRefObject; + setHintMessage: (msg: string | null) => void; + setInTroubleshooting: (val: boolean) => void; + onTrigger?: (resource: string) => void; + onTroubleshootTriggered?: (resource: string) => void; +}) { + if (!ctx.targetResource) { + ctx.setHintMessage('No workload selected. Use arrow keys to select a workload.'); + return; + } + ctx.setHintMessage(null); + if (ctx.inTroubleshootingRef.current) return; + ctx.inTroubleshootingRef.current = true; + ctx.setInTroubleshooting(true); + ctx.onTrigger?.(ctx.targetResource); + ctx.onTroubleshootTriggered?.(ctx.targetResource); +} + +function applyTroubleshootDismiss(ctx: { + inTroubleshootingRef: React.MutableRefObject; + setInTroubleshooting: (val: boolean) => void; + onDismiss?: () => void; + onDismissal?: () => void; +}) { + if (!ctx.inTroubleshootingRef.current) return; + ctx.inTroubleshootingRef.current = false; + ctx.setInTroubleshooting(false); + ctx.onDismiss?.(); + ctx.onDismissal?.(); +} + +function TroubleshootHintBanner({ hintMessage }: { hintMessage: string | null }) { + if (!hintMessage) return null; + return ( + + ⚠️ {hintMessage} + + ); +} + +export const DashboardWithTroubleshootTrigger: React.FC = ({ + dashboardType, + targetResource, + currentLogLines = [], + onTrigger, + onTroubleshootTriggered, + onDismiss, + onDismissal, + isHeadless = false, +}) => { + const [inTroubleshooting, setInTroubleshooting] = useState(false); + const [hintMessage, setHintMessage] = useState(null); + const inTroubleshootingRef = React.useRef(false); + inTroubleshootingRef.current = inTroubleshooting; + + useInput( + (input, key) => { + if (isHeadless) return; + if (input.toLowerCase().includes('t')) { + applyTroubleshootStart({ + targetResource, + inTroubleshootingRef, + setHintMessage, + setInTroubleshooting, + onTrigger, + onTroubleshootTriggered, + }); + return; + } + if (key.escape) { + applyTroubleshootDismiss({ inTroubleshootingRef, setInTroubleshooting, onDismiss, onDismissal }); + } + }, + { exitOnCtrlC: false } + ); + + return ( + + + {inTroubleshooting ? ( + + ) : ( + + )} + + ); +}; + +export { AppContainerView } from '../../../ui/AppContainer'; + +export function debounceResize( + callback: (cols: number, rows?: number) => void, + delayMs = 50 +): ((cols: number, rows?: number) => void) & { cancel: () => void; flush: () => void } { + let timer: NodeJS.Timeout | null = null; + let lastCols = 0; + let lastRows = 0; + + const debounced = (cols: number, rows = 24) => { + lastCols = cols; + lastRows = rows; + if (timer) clearTimeout(timer); + timer = setTimeout(() => { + callback(lastCols, lastRows); + timer = null; + }, delayMs); + }; + + debounced.cancel = () => { + if (!timer) return; + clearTimeout(timer); + timer = null; + }; + + debounced.flush = () => { + if (!timer) return; + clearTimeout(timer); + timer = null; + callback(lastCols, lastRows); + }; + + return debounced; +} diff --git a/src/__tests__/e2e/harness/index.ts b/src/__tests__/e2e/harness/index.ts new file mode 100644 index 00000000..187017f6 --- /dev/null +++ b/src/__tests__/e2e/harness/index.ts @@ -0,0 +1,6 @@ +export * from './cli-runner'; +export * from './mock-genai-stream'; +export * from './mock-cluster-env'; +export * from './mock-python-council'; +export * from './tui-test-utils'; +export * from './contracts'; diff --git a/src/__tests__/e2e/harness/mock-cluster-env.ts b/src/__tests__/e2e/harness/mock-cluster-env.ts new file mode 100644 index 00000000..0007dce0 --- /dev/null +++ b/src/__tests__/e2e/harness/mock-cluster-env.ts @@ -0,0 +1,359 @@ +import { vi } from 'vitest'; +import * as podsModule from '../../../kubernetes/pods'; +import * as resourcesModule from '../../../kubernetes/resources'; +import * as containersModule from '../../../docker/containers'; +import * as k8sClientModule from '../../../kubernetes/client'; +import * as dockerClientModule from '../../../docker/client'; +import * as minikubeClientModule from '../../../minikube/client'; + +export interface MockPodState { + name: string; + namespace: string; + status: string; + restarts: number; + node: string; + phase?: string; + exitCode?: number; + reason?: string; + memoryLimit?: string; + memoryRequest?: string; + rawPod?: any; +} + +export interface MockContainerState { + id: string; + name: string; + image: string; + state: string; + status: string; + exitCode?: number; + rawContainer?: any; +} + +export interface MockNodeState { + name: string; + status: string; + roles: string[]; + version: string; + memoryPressure?: boolean; + diskPressure?: boolean; + cpuCapacity?: string; + memoryCapacity?: string; +} + +export class MockClusterEnvironment { + private static activeInstance: MockClusterEnvironment | null = null; + + static getActive(): MockClusterEnvironment | null { + return this.activeInstance; + } + + static resetActive(): void { + if (this.activeInstance) { + this.activeInstance.reset(); + this.activeInstance = null; + } + } + + private pods: MockPodState[] = []; + private containers: MockContainerState[] = []; + private nodes: MockNodeState[] = []; + private k8sConnected = true; + private dockerConnected = true; + private minikubeConnected = false; + private hanging = false; + + private spies: Array<{ mockRestore: () => void }> = []; + + setOOMKilledScenario(podName = 'payment-service-8f4b-2x9p', namespace = 'production') { + this.pods = [ + { + name: podName, + namespace, + status: 'OOMKilled', + restarts: 5, + node: 'worker-node-4', + phase: 'Running', + exitCode: 137, + reason: 'OOMKilled', + memoryLimit: '512Mi', + memoryRequest: '256Mi', + rawPod: { + metadata: { name: podName, namespace }, + status: { + phase: 'Running', + containerStatuses: [ + { + name: 'payment-gateway', + restartCount: 5, + lastState: { + terminated: { exitCode: 137, reason: 'OOMKilled' }, + }, + }, + ], + }, + spec: { + containers: [ + { + name: 'payment-gateway', + resources: { limits: { memory: '512Mi' }, requests: { memory: '256Mi' } }, + }, + ], + }, + }, + }, + ]; + this.nodes = [ + { + name: 'worker-node-4', + status: 'Ready', + roles: ['worker'], + version: 'v1.30.0', + memoryPressure: false, + memoryCapacity: '16Gi', + }, + ]; + return this; + } + + setCrashLoopBackOffScenario(podName = 'auth-api-v2-7c91', namespace = 'auth') { + this.pods = [ + { + name: podName, + namespace, + status: 'CrashLoopBackOff', + restarts: 12, + node: 'worker-node-1', + phase: 'Running', + exitCode: 1, + reason: 'CrashLoopBackOff', + rawPod: { + metadata: { name: podName, namespace }, + status: { + phase: 'Running', + containerStatuses: [ + { + name: 'auth-server', + restartCount: 12, + state: { + waiting: { + reason: 'CrashLoopBackOff', + message: 'Back-off restarting failed container', + }, + }, + }, + ], + }, + spec: { + containers: [ + { + name: 'auth-server', + env: [ + { + name: 'DATABASE_URL', + valueFrom: { secretKeyRef: { name: 'auth-secrets', key: 'db-url' } }, + }, + ], + }, + ], + }, + }, + }, + ]; + return this; + } + + setDockerRestartLoopScenario(containerName = 'postgres-local') { + this.containers = [ + { + id: 'c1e2d3f4a5b6', + name: containerName, + image: 'postgres:15-alpine', + state: 'restarting', + status: 'Restarting (1) 3 seconds ago', + exitCode: 1, + rawContainer: { + Id: 'c1e2d3f4a5b6', + Names: [`/${containerName}`], + Image: 'postgres:15-alpine', + State: 'restarting', + Status: 'Restarting (1) 3 seconds ago', + }, + }, + ]; + return this; + } + + setHealthyScenario() { + this.pods = [ + { + name: 'frontend-service-6a4d-1z8k', + namespace: 'default', + status: 'Running', + restarts: 0, + node: 'worker-node-1', + phase: 'Running', + }, + { + name: 'cache-redis-0', + namespace: 'default', + status: 'Running', + restarts: 0, + node: 'worker-node-2', + phase: 'Running', + }, + ]; + this.containers = [ + { + id: 'a9b8c7d6e5f4', + name: 'nginx-proxy', + image: 'nginx:alpine', + state: 'running', + status: 'Up 4 hours', + }, + ]; + this.nodes = [ + { + name: 'worker-node-1', + status: 'Ready', + roles: ['worker'], + version: 'v1.30.0', + }, + ]; + return this; + } + + setNodePressureScenario(nodeName = 'worker-node-3') { + this.nodes = [ + { + name: nodeName, + status: 'MemoryPressure', + roles: ['worker'], + version: 'v1.30.0', + memoryPressure: true, + }, + ]; + return this; + } + + setEmptyScenario() { + this.pods = []; + this.containers = []; + this.nodes = []; + return this; + } + + setDisconnectedScenario(k8sDown = true, dockerDown = true) { + this.k8sConnected = !k8sDown; + this.dockerConnected = !dockerDown; + return this; + } + + setHangingScenario(isHanging = true) { + this.hanging = isHanging; + return this; + } + + /** + * Installs vi.spyOn hooks on all cluster getters and client singletons. + */ + install(): this { + this.reset(); + MockClusterEnvironment.activeInstance = this; + + // Mock getRunningPods + const podsSpy = vi.spyOn(podsModule, 'getRunningPods').mockImplementation(async () => { + if (!this.k8sConnected) { + throw new Error('Kubernetes API connection refused: ETIMEDOUT'); + } + return this.pods.map((p) => ({ + name: p.name, + namespace: p.namespace, + status: p.status, + restarts: p.restarts, + node: p.node, + })); + }); + this.spies.push(podsSpy); + + // Mock getRunningContainers + const containersSpy = vi + .spyOn(containersModule, 'getRunningContainers') + .mockImplementation(async () => { + if (!this.dockerConnected) { + throw new Error('Cannot connect to the Docker daemon. Is Docker running?'); + } + return this.containers.map((c) => ({ + id: c.id, + name: c.name, + image: c.image, + state: c.state, + status: c.status, + })); + }); + this.spies.push(containersSpy); + + // Mock listNodes + const nodesSpy = vi.spyOn(resourcesModule, 'listNodes').mockImplementation(async () => { + if (!this.k8sConnected) { + throw new Error('Kubernetes API connection refused'); + } + return this.nodes.map((n) => ({ + name: n.name, + status: n.status, + roles: n.roles.join(','), + version: n.version, + })) as any; + }); + this.spies.push(nodesSpy); + + // Mock checkK8sConnection + const k8sConnSpy = vi.spyOn(k8sClientModule, 'checkK8sConnection').mockImplementation(async () => { + return this.k8sConnected; + }); + this.spies.push(k8sConnSpy); + + // Mock checkDockerConnection + const dockerConnSpy = vi + .spyOn(dockerClientModule, 'checkDockerConnection') + .mockImplementation(async () => { + return this.dockerConnected; + }); + this.spies.push(dockerConnSpy); + + // Mock checkMinikubeConnection + const minikubeConnSpy = vi + .spyOn(minikubeClientModule, 'checkMinikubeConnection') + .mockImplementation(async () => { + return this.minikubeConnected; + }); + this.spies.push(minikubeConnSpy); + + return this; + } + + /** + * Restores all installed spies. + */ + reset(): this { + if (MockClusterEnvironment.activeInstance === this) { + MockClusterEnvironment.activeInstance = null; + } + for (const spy of this.spies) { + spy.mockRestore(); + } + this.spies = []; + return this; + } + + getState() { + return { + pods: this.pods, + containers: this.containers, + nodes: this.nodes, + k8sConnected: this.k8sConnected, + dockerConnected: this.dockerConnected, + hanging: this.hanging, + }; + } +} diff --git a/src/__tests__/e2e/harness/mock-genai-stream.ts b/src/__tests__/e2e/harness/mock-genai-stream.ts new file mode 100644 index 00000000..ad27fdd7 --- /dev/null +++ b/src/__tests__/e2e/harness/mock-genai-stream.ts @@ -0,0 +1,180 @@ +import { vi } from 'vitest'; + +export interface MockGenAIPart { + text?: string; + thought?: boolean; + functionCall?: { + name: string; + args: Record; + }; +} + +export interface MockGenAICandidate { + content: { + parts: MockGenAIPart[]; + role?: string; + }; + finishReason?: string; +} + +export interface MockGenAIChunk { + text?: string; + candidates?: MockGenAICandidate[]; + thought?: string; + functionCalls?: Array<{ name: string; args: Record }>; +} + +export interface MockGenAIClientOptions { + shouldFail?: boolean; + failError?: Error; +} + +function buildFallbackParts(chunk: MockGenAIChunk): MockGenAIPart[] { + if (chunk.thought) return [{ thought: true, text: chunk.thought }]; + if (chunk.text) return [{ text: chunk.text }]; + return []; +} + +function normalizeStreamChunk(chunk: MockGenAIChunk) { + return { + text: chunk.text ?? '', + candidates: chunk.candidates ?? [{ content: { parts: buildFallbackParts(chunk), role: 'model' } }], + }; +} + +export class MockGenAIStreamBuilder { + private chunks: MockGenAIChunk[] = []; + private shouldFail = false; + private failAfterChunks = -1; + private failError: Error = new Error('Simulated GenAI stream failure'); + + private pushPartChunk(part: MockGenAIPart, meta: Partial): this { + this.chunks.push({ + ...meta, + candidates: [{ content: { parts: [part], role: 'model' } }], + }); + return this; + } + + /** + * Appends reasoning/thought tokens (thinking mode). + */ + addThought(thought: string): this { + return this.pushPartChunk({ thought: true, text: thought }, { thought }); + } + + /** + * Appends regular generated text chunk. + */ + addText(text: string): this { + return this.pushPartChunk({ text }, { text }); + } + + /** + * Appends a function call / tool invocation part. + */ + addFunctionCall(name: string, args: Record): this { + return this.pushPartChunk({ functionCall: { name, args } }, { functionCalls: [{ name, args }] }); + } + + /** + * Configures the stream to abort with an error after yielding N chunks. + */ + simulateError(error: Error, afterChunks = 0): this { + this.shouldFail = true; + this.failError = error; + this.failAfterChunks = afterChunks; + return this; + } + + private checkStreamFailure(count: number): void { + if (this.shouldFail && count >= this.failAfterChunks) { + throw this.failError; + } + } + + /** + * Converts the recorded chunks into an AsyncIterable compatible with @google/genai stream. + */ + toAsyncIterable(): AsyncIterable<{ text?: string; candidates?: MockGenAICandidate[] }> { + const builder = this; + const chunks = this.chunks; + + return { + async *[Symbol.asyncIterator]() { + let count = 0; + for (const chunk of chunks) { + builder.checkStreamFailure(count); + count++; + yield normalizeStreamChunk(chunk); + } + builder.checkStreamFailure(count); + }, + }; + } + + /** + * Returns complete text aggregated across all text chunks. + */ + getFullText(): string { + return this.chunks.map((c) => c.text || '').join(''); + } + + /** + * Returns all thoughts aggregated across all thought chunks. + */ + getFullThoughts(): string[] { + return this.chunks.filter((c) => c.thought).map((c) => c.thought as string); + } + + /** + * Returns all function calls in sequence. + */ + getFunctionCalls(): Array<{ name: string; args: Record }> { + const calls: Array<{ name: string; args: Record }> = []; + for (const chunk of this.chunks) { + if (chunk.functionCalls) { + calls.push(...chunk.functionCalls); + } + } + return calls; + } + + /** + * Instantiates a mock GoogleGenAI client instance with generateContentStream and generateContent. + */ + createMockClient() { + const stream = this.toAsyncIterable(); + const fullText = this.getFullText(); + const functionCalls = this.getFunctionCalls(); + + const generateContentStream = vi.fn().mockImplementation(async () => stream); + const generateContent = vi.fn().mockImplementation(async () => { + if (this.shouldFail) { + throw this.failError; + } + return { + text: fullText, + candidates: [ + { + content: { + parts: [ + ...this.getFullThoughts().map((t) => ({ thought: true, text: t })), + ...(fullText ? [{ text: fullText }] : []), + ...functionCalls.map((fc) => ({ functionCall: fc })), + ], + role: 'model', + }, + }, + ], + }; + }); + + return { + models: { + generateContentStream, + generateContent, + }, + }; + } +} diff --git a/src/__tests__/e2e/harness/mock-python-council.ts b/src/__tests__/e2e/harness/mock-python-council.ts new file mode 100644 index 00000000..1ecc923a --- /dev/null +++ b/src/__tests__/e2e/harness/mock-python-council.ts @@ -0,0 +1,279 @@ +import { EventEmitter } from 'node:events'; +import { Readable } from 'node:stream'; +import { vi } from 'vitest'; +import type { NDJSONEvent, ConsensusDiagnosis } from '../../../agent/types'; + +export interface MockProcessOptions { + exitCode?: number; + emitError?: boolean; + malformedLines?: string[]; + delayMs?: number; +} + +export class MockPythonCouncil { + /** + * Creates a mock ChildProcess emitting line-delimited NDJSON events on stdout. + */ + static createMockProcess(events: NDJSONEvent[], options: MockProcessOptions = {}) { + const { exitCode = 0, emitError = false, malformedLines = [], delayMs = 5 } = options; + + const proc = new EventEmitter() as any; + const stdout = new Readable({ read() {} }); + const stderr = new Readable({ read() {} }); + + proc.stdout = stdout; + proc.stderr = stderr; + proc.stdin = { + write: vi.fn(), + end: vi.fn(), + destroyed: false, + }; + let closed = false; + let closeTimer: NodeJS.Timeout | undefined; + const finish = (code: number | null, signal: string | null, exited = true) => { + if (closed) return; + closed = true; + clearTimeout(producer); + clearTimeout(closeTimer); + if (exited) proc.emit('exit', code, signal); + proc.emit('close', code, signal); + }; + const producer = setTimeout(() => { + if (emitError) { + proc.emit('error', new Error('Python Council process crashed: spawn ENOENT')); + stdout.push(null); + stderr.push(null); + finish(-2, null, false); + return; + } + + for (const badLine of malformedLines) { + stdout.push(badLine + '\n'); + } + + for (const ev of events) { + stdout.push(JSON.stringify(ev) + '\n'); + } + + stdout.push(null); + stderr.push(null); + + stdout.once('end', () => setImmediate(() => finish(exitCode, null))); + setImmediate(() => stdout.resume()); + closeTimer = setTimeout(() => finish(exitCode, null), 50); + }, delayMs); + proc.kill = vi.fn().mockImplementation((signal = 'SIGTERM') => { + if (closed) return false; + stdout.destroy(); + stderr.destroy(); + finish(null, signal); + return true; + }); + + return proc; + } + + private static createOOMKilledConsensus(podName: string, namespace: string): ConsensusDiagnosis { + return { + rootCause: `Pod ${podName} killed due to misaligned JVM heap (-Xmx768m) exceeding container cgroup memory limit (512Mi).`, + confidence: 'high', + findings: [ + { + role: 'runtime', + status: 'confirmed', + summary: 'Detected exit code 137 (OOMKilled) in container payment-gateway with Java heap space error in logs.', + evidence: ['exitCode: 137', 'java.lang.OutOfMemoryError: Java heap space'], + }, + { + role: 'config', + status: 'confirmed', + summary: 'Container limits.memory is configured to 512Mi in production deployment.', + evidence: ['limits.memory: 512Mi'], + }, + { + role: 'resource', + status: 'confirmed', + summary: 'Node worker-node-4 has sufficient memory; failure is localized to container cgroup quota.', + evidence: ['nodeMemoryFree: 8Gi'], + }, + ], + bestSolution: { + actionTitle: 'Align JVM heap size and increase pod memory limit', + steps: [ + 'Increase container resources.limits.memory to 1024Mi', + 'Adjust JAVA_OPTS to -Xmx768m -XX:+UseContainerSupport', + 'Apply deployment patch and verify rollout', + ], + commandToRun: `kubectl patch deployment payment-service -n ${namespace} --patch '{"spec":{"template":{"spec":{"containers":[{"name":"payment-gateway","resources":{"limits":{"memory":"1024Mi"}}}]}}}}'`, + riskLevel: 'medium', + }, + evidenceCitations: ['ev-log-137', 'ev-manifest-cgroup-512', 'ev-node-mem-ok'], + }; + } + + /** + * Generates a realistic NDJSON sequence for an OOMKilled Pod triage session. + */ + static createOOMKilledCouncilEvents(podName = 'payment-service-8f4b-2x9p', namespace = 'production'): NDJSONEvent[] { + const now = new Date().toISOString(); + const consensus = this.createOOMKilledConsensus(podName, namespace); + + return [ + { event: 'analysis_start', analysisId: 'triage-oom-001', timestamp: now }, + { event: 'evidence_collected', count: 3, ids: ['ev-log-137', 'ev-manifest-cgroup-512', 'ev-node-mem-ok'], timestamp: now }, + { event: 'agent_start', role: 'runtime', message: 'Analyzing pod termination reason and logs...', timestamp: now }, + { event: 'agent_tool_call', role: 'runtime', tool: 'k8s_get_logs', args: { pod: podName, namespace, tail: 100 }, timestamp: now }, + { event: 'agent_tool_result', role: 'runtime', tool: 'k8s_get_logs', durationMs: 42, timestamp: now }, + { event: 'agent_complete', role: 'runtime', summary: 'Found OutOfMemoryError in logs.', timestamp: now }, + { event: 'agent_start', role: 'config', message: 'Verifying container resource limits vs codebase manifests...', timestamp: now }, + { event: 'agent_tool_call', role: 'config', tool: 'inspect_manifests', args: { file: 'charts/payment-service/values.yaml' }, timestamp: now }, + { event: 'agent_tool_result', role: 'config', tool: 'inspect_manifests', durationMs: 15, timestamp: now }, + { event: 'agent_complete', role: 'config', summary: 'Discovered JAVA_OPTS -Xmx768m exceeding 512Mi limit.', timestamp: now }, + { event: 'diagnosis_ready', consensus, timestamp: now }, + ]; + } + + /** + * Generates a realistic NDJSON sequence for a CrashLoopBackOff Pod remediation session. + */ + static createCrashLoopCouncilEvents(podName = 'auth-api-v2-7c91', namespace = 'auth'): NDJSONEvent[] { + const now = new Date().toISOString(); + const consensus: ConsensusDiagnosis = { + rootCause: `Pod ${podName} is in CrashLoopBackOff because of mismatched secretKeyRef: secret contains key DATABASE_URL, but deployment expects db-url.`, + confidence: 'high', + findings: [ + { + role: 'runtime', + status: 'confirmed', + summary: 'Container auth-server exited with code 1: Missing required environment variable DATABASE_URL', + evidence: ['exitCode: 1', 'Missing required environment variable DATABASE_URL'], + }, + { + role: 'config', + status: 'confirmed', + summary: 'secretKeyRef specifies db-url which does not exist in secret auth-secrets', + evidence: ['secretKeyRef: db-url'], + }, + ], + bestSolution: { + actionTitle: 'Fix secret key reference in deployment manifest', + steps: [ + 'Update deployment manifest secretKeyRef to DATABASE_URL', + 'Apply patch to deployment auth-api-v2', + 'Wait for rollout completion', + ], + commandToRun: `kubectl patch deployment auth-api-v2 -n ${namespace} --type=json -p='[{"op":"replace","path":"/spec/template/spec/containers/0/env/0/valueFrom/secretKeyRef/key","value":"DATABASE_URL"}]'`, + riskLevel: 'medium', + }, + evidenceCitations: ['ev-missing-env', 'ev-secret-mismatch'], + }; + + return [ + { event: 'analysis_start', analysisId: 'triage-crashloop-002', timestamp: now }, + { event: 'evidence_collected', count: 2, ids: ['ev-missing-env', 'ev-secret-mismatch'], timestamp: now }, + { event: 'agent_start', role: 'runtime', message: 'Inspecting container crash logs...', timestamp: now }, + { + event: 'agent_tool_call', + role: 'runtime', + tool: 'k8s_get_logs', + args: { pod: podName, namespace }, + timestamp: now, + }, + { event: 'agent_complete', role: 'runtime', summary: 'Missing required env DATABASE_URL.', timestamp: now }, + { event: 'agent_start', role: 'config', message: 'Checking secret dependencies...', timestamp: now }, + { event: 'agent_complete', role: 'config', summary: 'Found mismatched key reference.', timestamp: now }, + { event: 'diagnosis_ready', consensus, timestamp: now }, + ]; + } + + /** + * Generates a sequence for Docker container restart loop with destructive proposal. + */ + static createDockerRestartCouncilEvents(containerName = 'postgres-local'): NDJSONEvent[] { + const now = new Date().toISOString(); + const consensus: ConsensusDiagnosis = { + rootCause: `Docker container ${containerName} is failing to start because of a stale postmaster.pid lock file from previous crash.`, + confidence: 'high', + findings: [ + { + role: 'runtime', + status: 'confirmed', + summary: 'Container repeatedly exits with code 1. Logs show FATAL: lock file "postmaster.pid" already exists.', + evidence: ['FATAL: lock file "postmaster.pid" already exists'], + }, + ], + bestSolution: { + actionTitle: 'Remove container and recreate (destructive)', + steps: [ + 'docker rm -f postgres-local', + 'docker run --name postgres-local ...', + ], + commandToRun: 'docker rm -f postgres-local', + riskLevel: 'high', + }, + evidenceCitations: ['ev-docker-stale-lock'], + }; + + return [ + { event: 'analysis_start', analysisId: 'triage-docker-003', timestamp: now }, + { event: 'agent_start', role: 'runtime', message: 'Inspecting container logs...', timestamp: now }, + { + event: 'agent_tool_call', + role: 'runtime', + tool: 'docker_inspect_container', + args: { containerId: containerName }, + timestamp: now, + }, + { event: 'agent_complete', role: 'runtime', summary: 'Stale lock file detected.', timestamp: now }, + { event: 'diagnosis_ready', consensus, timestamp: now }, + ]; + } + + /** + * Generates a cross-service cascading failure sequence. + */ + static createCascadingFailureCouncilEvents(): NDJSONEvent[] { + const now = new Date().toISOString(); + const consensus: ConsensusDiagnosis = { + rootCause: 'Cascading failure: api-gateway CPU throttling caused liveness probe timeout (>1s), triggering container restart and upstream ingress 502 Bad Gateway drops.', + confidence: 'high', + findings: [ + { + role: 'runtime', + status: 'confirmed', + summary: 'Ingress logs show connection refused to api-gateway during liveness restart cycle.', + }, + { + role: 'resource', + status: 'confirmed', + summary: 'api-gateway CPU utilization at 98% cgroup limit due to regex parsing backlog.', + }, + { + role: 'config', + status: 'confirmed', + summary: 'Liveness probe timeoutSeconds is set to 1s with failureThreshold 2.', + }, + ], + bestSolution: { + actionTitle: 'Increase liveness probe timeout and scale CPU limits', + steps: [ + 'Increase liveness probe timeoutSeconds to 5', + 'Increase CPU limit to 1500m', + ], + commandToRun: 'kubectl patch deployment api-gateway -n prod --patch \'{"spec":{"template":{"spec":{"containers":[{"name":"api","resources":{"limits":{"cpu":"1500m"}}}]}}}}\'', + riskLevel: 'medium', + }, + }; + + return [ + { event: 'analysis_start', analysisId: 'triage-cascade-005', timestamp: now }, + { event: 'agent_start', role: 'runtime', message: 'Correlating ingress error spikes...', timestamp: now }, + { event: 'agent_complete', role: 'runtime', summary: 'Ingress 502s correlate with gateway restart.', timestamp: now }, + { event: 'agent_start', role: 'resource', message: 'Checking resource throttling...', timestamp: now }, + { event: 'agent_complete', role: 'resource', summary: 'CPU throttling detected.', timestamp: now }, + { event: 'agent_start', role: 'config', message: 'Inspecting probe settings...', timestamp: now }, + { event: 'agent_complete', role: 'config', summary: 'Liveness probe timeout is too aggressive (1s).', timestamp: now }, + { event: 'diagnosis_ready', consensus, timestamp: now }, + ]; + } +} diff --git a/src/__tests__/e2e/harness/tui-test-utils.tsx b/src/__tests__/e2e/harness/tui-test-utils.tsx new file mode 100644 index 00000000..2c194fb3 --- /dev/null +++ b/src/__tests__/e2e/harness/tui-test-utils.tsx @@ -0,0 +1,138 @@ +import React from 'react'; +import { render, type Instance } from 'ink'; +import { Readable, Writable } from 'node:stream'; +import { vi } from 'vitest'; + +/** + * Removes ANSI escape codes, terminal cursor controls, and alternate screen sequences. + */ +export function stripAnsi(str: string): string { + return str + .replace(/\u001b\[[0-9;?]*[a-zA-Z]/g, '') + .replace(/\u001b\][^\u0007\u001b]*(\u0007|\u001b\\)/g, '') + .replace(/\u001bc/g, ''); +} + +export class TestStdout extends Writable { + output = ''; + frames: string[] = []; + isTTY = true; + columns = 120; + rows = 40; + + _write(chunk: any, _encoding: BufferEncoding, callback: (error?: Error | null) => void): void { + const text = chunk.toString(); + this.output += text; + this.frames.push(text); + callback(); + } + + clear(): void { + this.output = ''; + this.frames = []; + } + + getLastFrame(): string { + return this.frames.length > 0 ? this.frames[this.frames.length - 1] : this.output; + } +} + +export class TestStdin extends Readable { + isTTY = true; + setRawMode = vi.fn(); + setEncoding = vi.fn(); + ref = vi.fn(); + unref = vi.fn(); + + _read(): void {} + + send(val: string): void { + this.push(Buffer.from(val)); + } + + sendEnter(): void { + this.send('\r'); + } + + sendEscape(): void { + this.send('\u001b'); + } + + sendUp(): void { + this.send('\u001b[A'); + } + + sendDown(): void { + this.send('\u001b[B'); + } + + sendRight(): void { + this.send('\u001b[C'); + } + + sendLeft(): void { + this.send('\u001b[D'); + } + + sendTab(): void { + this.send('\t'); + } + + sendCtrlC(): void { + this.send('\u0003'); + } +} + +export interface RenderTUIOptions { + columns?: number; + rows?: number; +} + +export interface TUIRenderResult { + instance: Instance; + stdin: TestStdin; + stdout: TestStdout; + sendKey: (key: string) => void; + wait: (ms?: number) => Promise; + unmount: () => void; + getCleanOutput: () => string; + getFrames: () => string[]; + getLastFrame: () => string; +} + +export function renderTUI( + element: React.ReactElement, + options: RenderTUIOptions = {} +): TUIRenderResult { + const stdin = new TestStdin(); + const stdout = new TestStdout(); + + if (options.columns) stdout.columns = options.columns; + if (options.rows) stdout.rows = options.rows; + + const instance = render(element, { + stdin: stdin as unknown as NodeJS.ReadStream, + stdout: stdout as unknown as NodeJS.WriteStream, + debug: true, + exitOnCtrlC: false, + }); + + return { + instance, + stdin, + stdout, + sendKey: (key: string) => stdin.send(key), + wait: (ms = 50) => new Promise((resolve) => setTimeout(resolve, ms)), + unmount: () => { + try { + instance.unmount(); + } catch { + // ignore already unmounted + } + stdin.push(null); + }, + getCleanOutput: () => stripAnsi(stdout.output), + getFrames: () => stdout.frames.map(stripAnsi), + getLastFrame: () => stripAnsi(stdout.getLastFrame()), + }; +} diff --git a/src/__tests__/e2e/tier1-features/f01-build-pipeline.test.ts b/src/__tests__/e2e/tier1-features/f01-build-pipeline.test.ts new file mode 100644 index 00000000..9d295977 --- /dev/null +++ b/src/__tests__/e2e/tier1-features/f01-build-pipeline.test.ts @@ -0,0 +1,79 @@ +import { describe, it, expect } from 'vitest'; +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { GoogleGenAI } from '@google/genai'; +import { z } from 'zod'; +import { createTwoFilesPatch } from 'diff'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const ROOT_DIR = path.resolve(__dirname, '../../../../'); + +describe('Tier 1: F-01 Build & Pipeline Hardening', () => { + it('TC-E2E-T1-F01-01: Clean TypeScript build with no test exclusion leakage', () => { + const distPath = path.join(ROOT_DIR, 'dist'); + expect(fs.existsSync(distPath)).toBe(true); + + const indexPath = path.join(distPath, 'index.js'); + expect(fs.existsSync(indexPath)).toBe(true); + const indexContent = fs.readFileSync(indexPath, 'utf-8'); + expect(indexContent.length).toBeGreaterThan(1000); + + // Verify no test files are emitted into dist/ + const distFiles = fs.readdirSync(distPath); + const testFiles = distFiles.filter((f) => f.includes('.test.') || f.includes('.spec.')); + expect(testFiles).toEqual([]); + }); + + it('TC-E2E-T1-F01-02: Runtime ESM import resolution of core modern dependencies', async () => { + // 1. Verify @google/genai runtime availability + expect(GoogleGenAI).toBeDefined(); + const ai = new GoogleGenAI({ apiKey: 'mock-key-for-test' }); + expect(ai).toBeInstanceOf(GoogleGenAI); + expect(ai.models).toBeDefined(); + + // 2. Verify zod validation + const Schema = z.object({ + name: z.string(), + count: z.number().int().positive(), + }); + const parsed = Schema.parse({ name: 'kdm-worker', count: 4 }); + expect(parsed).toEqual({ name: 'kdm-worker', count: 4 }); + + // 3. Verify diff line-by-line patch computation + const patch = createTwoFilesPatch('a.yaml', 'b.yaml', 'line1\nline2\n', 'line1\nline2-changed\n'); + expect(patch).toContain('--- a.yaml'); + expect(patch).toContain('+++ b.yaml'); + expect(patch).toContain('-line2'); + expect(patch).toContain('+line2-changed'); + }); + + it('TC-E2E-T1-F01-03: Vitest test runner execution on forked pool baseline', () => { + const packageJsonPath = path.join(ROOT_DIR, 'package.json'); + const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8')); + + expect(pkg.scripts.test).toContain('vitest'); + expect(pkg.scripts.test).toContain('--pool=forks'); + expect(pkg.scripts.test).toContain('--maxWorkers=1'); + }); + + it('TC-E2E-T1-F01-04: TypeScript strictness and JSX preservation for React 19 / Ink 8 components without type errors', () => { + const tsconfigPath = path.join(ROOT_DIR, 'tsconfig.json'); + const tsconfig = JSON.parse(fs.readFileSync(tsconfigPath, 'utf-8')); + + expect(tsconfig.compilerOptions.strict).toBe(true); + expect(tsconfig.compilerOptions.jsx).toBe('react-jsx'); + expect(tsconfig.compilerOptions.target.toLowerCase()).toBe('es2022'); + expect(tsconfig.compilerOptions.declaration).toBe(true); + }); + + it('TC-E2E-T1-F01-05: Pre-commit / check code pipeline verification', () => { + const packageJsonPath = path.join(ROOT_DIR, 'package.json'); + const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8')); + + expect(pkg.scripts['check:code']).toBeDefined(); + expect(pkg.scripts['check:code']).toContain('npm run build'); + expect(pkg.scripts['check:code']).toContain('npm test'); + }); +}); diff --git a/src/__tests__/e2e/tier1-features/f02-modern-gemini.test.ts b/src/__tests__/e2e/tier1-features/f02-modern-gemini.test.ts new file mode 100644 index 00000000..9726b8a1 --- /dev/null +++ b/src/__tests__/e2e/tier1-features/f02-modern-gemini.test.ts @@ -0,0 +1,146 @@ +import { describe, it, expect, vi } from 'vitest'; +import { GoogleGeminiAIClient } from '../../../ai/google-gemini'; +import type { AIProviderConfig } from '../../../config/schema'; +import { MockGenAIStreamBuilder } from '../harness'; + +function extractChunkParts(chunk: any): any[] { + const candidate = chunk.candidates ? chunk.candidates[0] : undefined; + const content = candidate ? candidate.content : undefined; + return content && content.parts ? content.parts : []; +} + +function appendContentPart(ctx: { part: any; thoughts: string[]; texts: string[] }): void { + if (ctx.part.thought) ctx.thoughts.push(ctx.part.text || ''); + else if (ctx.part.text) ctx.texts.push(ctx.part.text); +} + +async function collectThoughtAndTextParts(stream: AsyncIterable) { + const thoughts: string[] = []; + const texts: string[] = []; + for await (const chunk of stream) { + for (const part of extractChunkParts(chunk)) { + appendContentPart({ part, thoughts, texts }); + } + } + return { thoughts, texts }; +} + +describe('Tier 1: F-02 Google Gemini Modern SDK Provider', () => { + it('TC-E2E-T1-F02-01: Client configuration and initialization via AIProviderConfig', async () => { + const client = new GoogleGeminiAIClient(); + const config: AIProviderConfig = { + provider: 'google-gemini', + password: 'test-gemini-api-key', + model: 'gemini-2.5-flash', + temperature: 0.2, + customHeaders: { 'x-client-id': 'kdm-e2e' }, + }; + + await client.configure(config); + expect(client.name).toBe('google-gemini'); + + // Reject missing password + const badConfig: AIProviderConfig = { + provider: 'google-gemini', + password: '', + }; + await expect(client.configure(badConfig)).rejects.toThrow('API key (password) is required'); + }); + + it('TC-E2E-T1-F02-02: Backward-compatible single-turn completion (client.getCompletion())', async () => { + const client = new GoogleGeminiAIClient(); + await client.configure({ + provider: 'google-gemini', + password: 'test-api-key', + model: 'gemini-pro', + }); + + const mockResponseText = 'Pod terminated with exit code 137 due to memory limit exhaustion.'; + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce({ + ok: true, + json: async () => ({ + candidates: [ + { + content: { + parts: [{ text: mockResponseText }], + }, + }, + ], + }), + } as Response); + + const result = await client.getCompletion('Explain exit code 137 in Kubernetes'); + expect(result).toBe(mockResponseText); + expect(fetchSpy).toHaveBeenCalledTimes(1); + + fetchSpy.mockRestore(); + }); + + it('TC-E2E-T1-F02-03: Streaming content generation with token chunk callbacks', async () => { + const builder = new MockGenAIStreamBuilder(); + builder + .addText('Workload ') + .addText('auth-api ') + .addText('is failing readiness probe.'); + + const mockClient = builder.createMockClient(); + const stream = await mockClient.models.generateContentStream({ + model: 'gemini-2.5-flash', + contents: 'Analyze auth-api', + }); + + const collectedChunks: string[] = []; + for await (const chunk of stream) { + if (chunk.text) { + collectedChunks.push(chunk.text); + } + } + + expect(collectedChunks).toEqual(['Workload ', 'auth-api ', 'is failing readiness probe.']); + expect(collectedChunks.join('')).toBe('Workload auth-api is failing readiness probe.'); + }); + + it('TC-E2E-T1-F02-04: Declarative function / tool calling schema delivery and parameter reception', async () => { + const builder = new MockGenAIStreamBuilder(); + builder.addFunctionCall('k8s_get_pod', { + name: 'payment-service-8f4b-2x9p', + namespace: 'production', + }); + + const mockClient = builder.createMockClient(); + const response = await mockClient.models.generateContent({ + model: 'gemini-2.5-flash', + contents: 'Inspect payment-service pod', + }); + + const parts = response.candidates?.[0]?.content?.parts ?? []; + const functionCallPart = parts.find((p: any) => p.functionCall); + expect(functionCallPart).toBeDefined(); + expect(functionCallPart?.functionCall?.name).toBe('k8s_get_pod'); + expect(functionCallPart?.functionCall?.args).toEqual({ + name: 'payment-service-8f4b-2x9p', + namespace: 'production', + }); + }); + + it('TC-E2E-T1-F02-05: Thinking mode and reasoning token extraction (thought: true)', async () => { + const builder = new MockGenAIStreamBuilder(); + builder + .addThought('Correlating exit code 137 with pod cgroup limit...') + .addThought('Comparing JVM -Xmx768m against container 512Mi limit...') + .addText('Root Cause: OOMKilled caused by JVM heap exceeding container limit.'); + + const mockClient = builder.createMockClient(); + const stream = await mockClient.models.generateContentStream({ + model: 'gemini-2.5-flash', + contents: 'Diagnose OOM', + }); + + const { thoughts, texts } = await collectThoughtAndTextParts(stream); + + expect(thoughts).toHaveLength(2); + expect(thoughts[0]).toContain('Correlating exit code 137'); + expect(thoughts[1]).toContain('Comparing JVM -Xmx768m'); + expect(texts.join('')).toContain('Root Cause: OOMKilled'); + }); +}); diff --git a/src/__tests__/e2e/tier1-features/f03-declarative-tools.test.ts b/src/__tests__/e2e/tier1-features/f03-declarative-tools.test.ts new file mode 100644 index 00000000..a3f3094e --- /dev/null +++ b/src/__tests__/e2e/tier1-features/f03-declarative-tools.test.ts @@ -0,0 +1,87 @@ +import { describe, it, expect } from 'vitest'; +import { + DeclarativeToolRegistry, + k8sGetPodTool, + k8sListPodsTool, + dockerInspectContainerTool, + k8sApplyPatchTool, +} from '../harness'; + +describe('Tier 1: F-03 Declarative Cluster Tools', () => { + it('TC-E2E-T1-F03-01: Read-only Kubernetes tool execution (k8s_get_pod, safety: "read_only")', async () => { + expect(k8sGetPodTool.safety).toBe('read_only'); + expect(k8sGetPodTool.riskLevel).toBe('low'); + + const result = await k8sGetPodTool.execute({ + name: 'payment-service-8f4b-2x9p', + namespace: 'production', + }); + + expect(result).toBeDefined(); + expect(result.pod).toBe('payment-service-8f4b-2x9p'); + expect(result.namespace).toBe('production'); + expect(result.exitCode).toBe(137); + }); + + it('TC-E2E-T1-F03-02: Read-only Docker tool execution (docker_inspect_container, safety: "read_only")', async () => { + expect(dockerInspectContainerTool.safety).toBe('read_only'); + expect(dockerInspectContainerTool.riskLevel).toBe('low'); + + const result = await dockerInspectContainerTool.execute({ + containerId: 'c1e2d3f4a5b6', + }); + + expect(result.containerId).toBe('c1e2d3f4a5b6'); + expect(result.state).toBe('restarting'); + expect(result.exitCode).toBe(1); + expect(result.status).toContain('Restarting'); + }); + + it('TC-E2E-T1-F03-03: Mutating Kubernetes remediation tool safety tagging (k8s_apply_patch, safety: "mutating")', async () => { + expect(k8sApplyPatchTool.safety).toBe('mutating'); + expect(k8sApplyPatchTool.riskLevel).toBe('high'); + + const patchPayload = '{"spec":{"replicas":3}}'; + const result = await k8sApplyPatchTool.execute({ + resource: 'deployment/payment-service', + namespace: 'production', + patch: patchPayload, + }); + + expect(result.success).toBe(true); + expect(result.appliedTo).toBe('production/deployment/payment-service'); + }); + + it('TC-E2E-T1-F03-04: Parameter schema validation failure rejection via Zod before cluster call', async () => { + const registry = new DeclarativeToolRegistry(); + registry.register(k8sGetPodTool); + + // Missing required field 'name' + await expect(registry.invoke('k8s_get_pod', { namespace: 'default' })).rejects.toThrow(); + + // Invalid type for 'name' + await expect(registry.invoke('k8s_get_pod', { name: 12345 })).rejects.toThrow(); + }); + + it('TC-E2E-T1-F03-05: Cluster tool registry discovery and listing for Gemini SDK function declarations', () => { + const registry = new DeclarativeToolRegistry(); + registry.register(k8sGetPodTool); + registry.register(k8sListPodsTool); + registry.register(dockerInspectContainerTool); + registry.register(k8sApplyPatchTool); + + const declarations = registry.getDeclarations(); + expect(declarations).toHaveLength(4); + + const names = declarations.map((d) => d.name); + expect(names).toContain('k8s_get_pod'); + expect(names).toContain('k8s_list_pods'); + expect(names).toContain('docker_inspect_container'); + expect(names).toContain('k8s_apply_patch'); + + for (const decl of declarations) { + expect(decl.description).toBeDefined(); + expect(decl.parameters).toBeDefined(); + } + }); +}); diff --git a/src/__tests__/e2e/tier1-features/f04-agent-registry.test.ts b/src/__tests__/e2e/tier1-features/f04-agent-registry.test.ts new file mode 100644 index 00000000..6a579050 --- /dev/null +++ b/src/__tests__/e2e/tier1-features/f04-agent-registry.test.ts @@ -0,0 +1,128 @@ +import { describe, it, expect } from 'vitest'; +import { z } from 'zod'; +import { + AgentRegistry, + AgentTool, + translateNDJSONToSubagentProgress, + type AgentDefinition, +} from '../harness'; +import type { NDJSONEvent } from '../../../agent/types'; + +describe('Tier 1: F-04 Subagent Registry & Invocation Protocol', () => { + it('TC-E2E-T1-F04-01: Agent registration and capability retrieval in AgentRegistry', () => { + const registry = new AgentRegistry(); + + const runtimeAgent: AgentDefinition = { + name: 'RuntimeLogAgent', + description: 'Analyzes container exit codes, panic traces, and kernel OOM signals.', + inputSchema: z.object({ prompt: z.string() }), + outputSchema: z.object({ finding: z.string(), status: z.string() }), + run: async (input) => ({ finding: `Analyzed logs for ${input.prompt}`, status: 'success' }), + }; + + const configAgent: AgentDefinition = { + name: 'ConfigDependencyAgent', + description: 'Validates Kubernetes ConfigMaps, Secrets, Volumes, and probe timeouts.', + inputSchema: z.object({ prompt: z.string() }), + outputSchema: z.object({ finding: z.string(), status: z.string() }), + run: async (input) => ({ finding: `Verified configs for ${input.prompt}`, status: 'success' }), + }; + + registry.register(runtimeAgent); + registry.register(configAgent); + + expect(registry.list()).toHaveLength(2); + expect(registry.get('RuntimeLogAgent')?.name).toBe('RuntimeLogAgent'); + expect(registry.get('ConfigDependencyAgent')?.name).toBe('ConfigDependencyAgent'); + expect(registry.get('NonExistentAgent')).toBeUndefined(); + }); + + it('TC-E2E-T1-F04-02: Orchestrator delegation via delegate_to_agent tool', async () => { + const registry = new AgentRegistry(); + + registry.register({ + name: 'RuntimeLogAgent', + description: 'Specialist for runtime container diagnostics', + inputSchema: z.object({ prompt: z.string() }), + outputSchema: z.object({ rootCause: z.string(), confidence: z.string() }), + run: async (input) => ({ + rootCause: `Diagnosed root cause for: ${input.prompt}`, + confidence: 'high', + }), + }); + + const agentTool = new AgentTool(registry); + const result = await agentTool.execute({ + agent_name: 'RuntimeLogAgent', + prompt: 'CrashLoopBackOff in auth-api', + }); + + expect(result.rootCause).toContain('CrashLoopBackOff in auth-api'); + expect(result.confidence).toBe('high'); + }); + + it('TC-E2E-T1-F04-03: EventTranslator NDJSON to SubagentProgress event conversion', () => { + const toolCallEvent: NDJSONEvent = { + event: 'agent_tool_call', + role: 'runtime', + tool: 'k8s_get_logs', + args: { pod: 'payment-service', tail: 50 }, + timestamp: '2026-11-15T12:00:00Z', + }; + + const progress = translateNDJSONToSubagentProgress(toolCallEvent); + expect(progress).not.toBeNull(); + expect(progress?.agentName).toBe('runtime'); + expect(progress?.state).toBe('running'); + expect(progress?.toolCall?.name).toBe('k8s_get_logs'); + expect(progress?.toolCall?.args).toEqual({ pod: 'payment-service', tail: 50 }); + }); + + it('TC-E2E-T1-F04-04: Subagent lifecycle state machine progression (pending -> running -> completed)', () => { + const now = new Date().toISOString(); + + const startEv: NDJSONEvent = { + event: 'agent_start', + role: 'resource', + message: 'Checking node CPU limits...', + timestamp: now, + }; + const runningProgress = translateNDJSONToSubagentProgress(startEv); + expect(runningProgress?.state).toBe('running'); + expect(runningProgress?.thought).toBe('Checking node CPU limits...'); + + const completeEv: NDJSONEvent = { + event: 'agent_complete', + role: 'resource', + summary: 'Node memory is healthy.', + timestamp: now, + }; + const completedProgress = translateNDJSONToSubagentProgress(completeEv); + expect(completedProgress?.state).toBe('completed'); + expect(completedProgress?.result).toBe('Node memory is healthy.'); + }); + + it('TC-E2E-T1-F04-05: Bidirectional event translation for diagnosis_ready consensus output', () => { + const now = new Date().toISOString(); + const diagnosisEv: NDJSONEvent = { + event: 'diagnosis_ready', + timestamp: now, + consensus: { + rootCause: 'JVM heap -Xmx768m exceeded container 512Mi limit', + confidence: 'high', + findings: [], + bestSolution: { + actionTitle: 'Increase memory limit', + steps: ['Patch deployment memory limit to 1024Mi'], + riskLevel: 'low', + }, + }, + }; + + const progress = translateNDJSONToSubagentProgress(diagnosisEv); + expect(progress).not.toBeNull(); + expect(progress?.agentName).toBe('SynthesizerAgent'); + expect(progress?.state).toBe('completed'); + expect(progress?.result).toContain('JVM heap -Xmx768m exceeded container 512Mi limit'); + }); +}); diff --git a/src/__tests__/e2e/tier1-features/f05-codebase-investigator.test.ts b/src/__tests__/e2e/tier1-features/f05-codebase-investigator.test.ts new file mode 100644 index 00000000..ab7203db --- /dev/null +++ b/src/__tests__/e2e/tier1-features/f05-codebase-investigator.test.ts @@ -0,0 +1,75 @@ +import { describe, it, expect } from 'vitest'; +import { CodebaseInvestigatorAgent } from '../../../agent/investigator'; + +describe('Tier 1: F-05 Codebase Investigator Agent Port', () => { + it('TC-E2E-T1-F05-01: Workspace manifest discovery (Kubernetes YAML & Helm values)', async () => { + const mockFiles: Record = { + 'charts/payment/values.yaml': 'image:\n repository: payment-service\n', + 'k8s/deployment.yaml': 'apiVersion: apps/v1\nkind: Deployment\n', + 'src/server.ts': 'console.log("running");\n', + 'README.md': '# Payment Service\n', + }; + + const report = await CodebaseInvestigatorAgent.run({ workspaceFiles: mockFiles }); + expect(report.discoveredManifests).toContain('charts/payment/values.yaml'); + expect(report.discoveredManifests).toContain('k8s/deployment.yaml'); + expect(report.discoveredManifests).not.toContain('src/server.ts'); + expect(report.discoveredManifests).not.toContain('README.md'); + }); + + it('TC-E2E-T1-F05-02: Dockerfile and container build spec analysis for JVM/cgroup flags', async () => { + const mockFiles: Record = { + 'Dockerfile': 'FROM eclipse-temurin:17\nENV JAVA_OPTS="-Xmx768m"\nENTRYPOINT ["sh", "-c", "java $JAVA_OPTS -jar app.jar"]\n', + }; + + const report = await CodebaseInvestigatorAgent.run({ + workspaceFiles: mockFiles, + liveClusterState: { memoryLimit: '512Mi' }, + }); + + expect(report.findings).toHaveLength(1); + expect(report.findings[0].file).toBe('Dockerfile'); + expect(report.findings[0].issue).toContain('-Xmx768m'); + expect(report.findings[0].issue).toContain('512Mi'); + }); + + it('TC-E2E-T1-F05-03: Local manifest vs live cluster config discrepancy detection', async () => { + const mockFiles: Record = { + 'k8s/auth-deployment.yaml': 'apiVersion: apps/v1\nkind: Deployment\nspec:\n template:\n spec:\n containers:\n - name: auth\n env:\n - name: DATABASE_URL\n valueFrom:\n secretKeyRef:\n name: auth-secrets\n key: db-url\n', + }; + + const report = await CodebaseInvestigatorAgent.run({ + workspaceFiles: mockFiles, + liveClusterState: { secretKeys: { 'auth-secrets': ['DATABASE_URL'] } }, + }); + + expect(report.driftDetected).toBe(true); + expect(report.findings[0].issue).toContain('db-url'); + expect(report.findings[0].patch).toBeUndefined(); + }); + + it('TC-E2E-T1-F05-04: Remediation patch generation for local workspace manifest', async () => { + const mockFiles: Record = { + 'deploy/payment-service.yaml': 'apiVersion: apps/v1\nkind: Deployment\nspec:\n template:\n spec:\n containers:\n - name: payment\n resources:\n limits:\n memory: 512Mi\n env:\n - name: JAVA_OPTS\n value: "-Xmx768m"\n', + }; + + const report = await CodebaseInvestigatorAgent.run({ + workspaceFiles: mockFiles, + liveClusterState: { memoryLimit: '512Mi' }, + }); + + expect(report.findings[0].patch).toBeDefined(); + expect(report.findings[0].patch).toContain('--- deploy/payment-service.yaml'); + expect(report.findings[0].patch).toContain('+++ deploy/payment-service.yaml.patched'); + expect(report.findings[0].patch).toContain('- memory: 512Mi'); + expect(report.findings[0].patch).toContain('+ memory: 1024Mi'); + }); + + it('TC-E2E-T1-F05-05: Reports an empty workspace', async () => { + // Empty workspace directory with 0 manifests + const report = await CodebaseInvestigatorAgent.run({ workspaceFiles: {} }); + expect(report.discoveredManifests).toHaveLength(0); + expect(report.findings[0].file).toBe('none'); + expect(report.findings[0].issue).toContain('No relevant configuration or manifest files discovered'); + }); +}); diff --git a/src/__tests__/e2e/tier1-features/f06-subagent-progress-ui.test.tsx b/src/__tests__/e2e/tier1-features/f06-subagent-progress-ui.test.tsx new file mode 100644 index 00000000..6ac266b4 --- /dev/null +++ b/src/__tests__/e2e/tier1-features/f06-subagent-progress-ui.test.tsx @@ -0,0 +1,89 @@ +import React from 'react'; +import { describe, it, expect } from 'vitest'; +import { Box } from 'ink'; +import { renderTUI } from '../harness'; +import { ThinkingMessage } from '../../../ui/components/ThinkingMessage'; +import { AgentCard } from '../../../ui/components/AgentCard'; +import { ActiveToolPanel } from '../../../ui/components/ActiveToolPanel'; + +describe('Tier 1: F-06 Subagent Progress & Thought UI', () => { + it('TC-E2E-T1-F06-01: Subagent card rendering with status badges and animated spinners', async () => { + const { getCleanOutput, unmount } = renderTUI( + + ); + + const output = getCleanOutput(); + expect(output).toContain('Runtime & Log Agent'); + expect(output).toContain('Analyzing exit code 137'); + unmount(); + }); + + it('TC-E2E-T1-F06-02: Live streaming thought display (ThinkingMessage with 💭)', async () => { + const thoughtText = 'Correlating exit code 137 with pod cgroup limit...'; + const { getCleanOutput, unmount } = renderTUI(); + + const output = getCleanOutput(); + expect(output).toContain('💭'); + expect(output).toContain(thoughtText); + unmount(); + }); + + it('TC-E2E-T1-F06-03: Active tool call sub-panel display with running timers', async () => { + const { getCleanOutput, unmount } = renderTUI( + + ); + + const output = getCleanOutput(); + expect(output).toContain('Active Tool'); + expect(output).toContain('k8s_get_logs'); + expect(output).toContain('45ms'); + unmount(); + }); + + it('TC-E2E-T1-F06-04: Multi-agent parallel progress cards stacked layout', async () => { + const { getCleanOutput, unmount } = renderTUI( + + + + + + ); + + const output = getCleanOutput(); + expect(output).toContain('Runtime Agent'); + expect(output).toContain('Config Agent'); + expect(output).toContain('Resource Agent'); + expect(output).toContain('Found OOM error'); + expect(output).toContain('Scanning manifests'); + unmount(); + }); + + it('TC-E2E-T1-F06-05: Error state display on subagent failure with red border and message', async () => { + const { getCleanOutput, unmount } = renderTUI( + + ); + + const output = getCleanOutput(); + expect(output).toContain('Runtime Agent'); + expect(output).toContain('✖'); + expect(output).toContain('Kubernetes API connection refused: ETIMEDOUT'); + unmount(); + }); +}); diff --git a/src/__tests__/e2e/tier1-features/f07-diff-confirmation-queue.test.tsx b/src/__tests__/e2e/tier1-features/f07-diff-confirmation-queue.test.tsx new file mode 100644 index 00000000..7b7f0d5c --- /dev/null +++ b/src/__tests__/e2e/tier1-features/f07-diff-confirmation-queue.test.tsx @@ -0,0 +1,129 @@ +import React from 'react'; +import { describe, it, expect, vi } from 'vitest'; +import { + renderTUI, + DiffRenderer, + ToolConfirmationQueueView, + evaluateSafetyPolicy, + type ConfirmationRequest, +} from '../harness'; + +describe('Tier 1: F-07 Manifest Diff & Confirmation Queue', () => { + it('TC-E2E-T1-F07-01: Unified color-coded diff rendering (DiffRenderer with line numbers)', () => { + const sampleDiff = + '--- deployment.yaml\n+++ deployment.yaml.patched\n@@ -10,4 +10,4 @@\n- memory: 512Mi\n+ memory: 1024Mi\n'; + + const { getCleanOutput, unmount } = renderTUI(); + const output = getCleanOutput(); + + expect(output).toContain('Manifest Unified Diff'); + expect(output).toContain('- memory: 512Mi'); + expect(output).toContain('+ memory: 1024Mi'); + expect(output).toContain('@@ -10,4 +10,4 @@'); + unmount(); + }); + + it('TC-E2E-T1-F07-02: Confirmation queue item display with risk badge (LOW, MEDIUM, HIGH)', () => { + const request: ConfirmationRequest = { + id: 'conf-req-001', + toolName: 'k8s_apply_patch', + args: { command: 'kubectl apply -f patch.yaml' }, + riskLevel: 'high', + prompt: 'Apply memory limit patch (512Mi -> 1024Mi) to payment-service deployment?', + }; + + const onDecision = vi.fn(); + const { getCleanOutput, unmount } = renderTUI( + + ); + + const output = getCleanOutput(); + expect(output).toContain('[HIGH RISK ACTION REQUIRED]'); + expect(output).toContain('conf-req-001'); + expect(output).toContain('Apply memory limit patch'); + unmount(); + }); + + it('TC-E2E-T1-F07-03: Interactive human approval flow ("y" keypress -> ALLOW)', async () => { + const request: ConfirmationRequest = { + id: 'conf-req-002', + toolName: 'k8s_apply_patch', + args: { command: 'kubectl apply -f patch.yaml' }, + riskLevel: 'medium', + prompt: 'Approve patch rollout?', + }; + + let decisionMade: string | null = null; + const { sendKey, wait, unmount } = renderTUI( + { + decisionMade = d; + }} + /> + ); + + // Keystroke 'y' is processed by useInput in ToolConfirmationQueueView + sendKey('y'); + await wait(50); + + expect(decisionMade).toBe('ALLOW'); + unmount(); + }); + + it('TC-E2E-T1-F07-04: Interactive human denial flow ("n" keypress -> DENY)', async () => { + const request: ConfirmationRequest = { + id: 'conf-req-003', + toolName: 'docker_restart_container', + args: { command: 'docker rm -f postgres-local' }, + riskLevel: 'high', + prompt: 'Delete and recreate database container?', + }; + + let decisionMade: string | null = null; + const { sendKey, wait, unmount } = renderTUI( + { + decisionMade = d; + }} + /> + ); + + // Keystroke 'n' is processed by useInput in ToolConfirmationQueueView + sendKey('n'); + await wait(50); + + expect(decisionMade).toBe('DENY'); + unmount(); + }); + + it('TC-E2E-T1-F07-05: Destructive command policy auto-block (e.g. rm -rf /, kubectl delete ns)', () => { + const destructiveCommand = 'rm -rf /'; + const policyResult = evaluateSafetyPolicy(destructiveCommand); + expect(policyResult.allowed).toBe(false); + expect(policyResult.violation).toContain('Destructive command permanently blocked'); + + const k8sDestructive = 'kubectl delete namespace production'; + const k8sPolicyResult = evaluateSafetyPolicy(k8sDestructive); + expect(k8sPolicyResult.allowed).toBe(false); + + // Verify rendering of blocked policy + const request: ConfirmationRequest = { + id: 'conf-req-blocked', + toolName: 'shell_exec', + args: { command: destructiveCommand }, + riskLevel: 'high', + prompt: 'Wipe cluster filesystem', + }; + + const { getCleanOutput, unmount } = renderTUI( + {}} /> + ); + + const output = getCleanOutput(); + expect(output).toContain('POLICY VIOLATION'); + expect(output).toContain('permanently blocked'); + unmount(); + }); +}); diff --git a/src/__tests__/e2e/tier1-features/f08-composer-slash-commands.test.tsx b/src/__tests__/e2e/tier1-features/f08-composer-slash-commands.test.tsx new file mode 100644 index 00000000..c923133b --- /dev/null +++ b/src/__tests__/e2e/tier1-features/f08-composer-slash-commands.test.tsx @@ -0,0 +1,103 @@ +import React from 'react'; +import { describe, it, expect, vi } from 'vitest'; +import { renderTUI, stripAnsi, ComposerView } from '../harness'; + +describe('Tier 1: F-08 Interactive Prompt & Slash Command Composer', () => { + it('TC-E2E-T1-F08-01: Multiline prompt input and editing in Composer', async () => { + const onSubmit = vi.fn(); + const promptText = 'Diagnose why pod checkout-api is restarting in staging'; + + const { sendKey, wait, getCleanOutput, unmount } = renderTUI( + + ); + + sendKey(promptText); + await wait(50); + + const output = getCleanOutput(); + expect(output).toContain('❯'); + expect(output).toContain(promptText); + unmount(); + }); + + it('TC-E2E-T1-F08-02: Slash command autocompletion dropdown on "/"', async () => { + const onSubmit = vi.fn(); + const { sendKey, wait, getCleanOutput, unmount } = renderTUI( + + ); + + // Typing '/' opens autocomplete dropdown + sendKey('/'); + await wait(50); + + const output = getCleanOutput(); + expect(output).toContain('Available Commands:'); + expect(output).toContain('/pods'); + expect(output).toContain('/containers'); + expect(output).toContain('/watch'); + expect(output).toContain('/analyze'); + unmount(); + }); + + it('TC-E2E-T1-F08-03: Slash command selection and parameter parsing (/pods -n staging)', async () => { + const onSubmit = vi.fn(); + const { sendKey, stdin, wait, unmount } = renderTUI( + + ); + + sendKey('/pods -n staging'); + await wait(20); + stdin.sendEnter(); + await wait(50); + + expect(onSubmit).toHaveBeenCalledWith('/pods -n staging'); + unmount(); + }); + + it('TC-E2E-T1-F08-04: Command history navigation with Up / Down arrow keys', async () => { + const history = ['/pods', 'diagnose payment', '/watch']; + const onSubmit = vi.fn(); + + const { stdin, wait, getLastFrame, unmount } = renderTUI( + + ); + + // Navigate Up to most recent command + stdin.sendUp(); + await wait(20); + expect(stripAnsi(getLastFrame())).toContain('/watch'); + + // Navigate Up again + stdin.sendUp(); + await wait(20); + expect(stripAnsi(getLastFrame())).toContain('diagnose payment'); + + // Navigate Down back to /watch + stdin.sendDown(); + await wait(20); + expect(stripAnsi(getLastFrame())).toContain('/watch'); + + unmount(); + }); + + it('TC-E2E-T1-F08-05: Escape key autocomplete dismissal preserving input buffer', async () => { + const onSubmit = vi.fn(); + const { sendKey, stdin, wait, getLastFrame, unmount } = renderTUI( + + ); + + // Type partial slash command + sendKey('/po'); + await wait(20); + expect(getLastFrame()).toContain('Available Commands:'); + + // Press Escape + stdin.sendEscape(); + await wait(50); + + const output = getLastFrame(); + expect(output).not.toContain('Available Commands:'); + expect(output).toContain('/po'); // Buffer preserved + unmount(); + }); +}); diff --git a/src/__tests__/e2e/tier1-features/f09-unified-workspace-shell.test.tsx b/src/__tests__/e2e/tier1-features/f09-unified-workspace-shell.test.tsx new file mode 100644 index 00000000..183b687b --- /dev/null +++ b/src/__tests__/e2e/tier1-features/f09-unified-workspace-shell.test.tsx @@ -0,0 +1,109 @@ +import React from 'react'; +import { describe, it, expect } from 'vitest'; +import { Box, Text } from 'ink'; +import { renderTUI, AppContainerView, runCLI, MockClusterEnvironment } from '../harness'; + +describe('Tier 1: F-09 Unified Interactive Copilot Workspace', () => { + it('TC-E2E-T1-F09-01: Default TTY launch into AppContainer with alternate screen buffer', () => { + const { getCleanOutput, unmount } = renderTUI( + + + Cluster Overview: 4 Pods, 2 Containers + + + ); + + const output = getCleanOutput(); + expect(output).toContain('KDM Copilot Shell'); + expect(output).toContain('[Alt+1: Monitor]'); + expect(output).toContain('Cluster Overview'); + unmount(); + }); + + it('TC-E2E-T1-F09-02: Non-interactive / non-TTY fallback to static status summary', async () => { + const cluster = new MockClusterEnvironment().setHealthyScenario().install(); + + // In non-TTY mode with no subcommands, KDM displays non-interactive connection summary + const result = await runCLI([], { isTTY: false }); + + cluster.reset(); + expect(result.exitCode).toBe(0); + }); + + it('TC-E2E-T1-F09-03: Responsive terminal resize handling in AppContainer', () => { + // Test render at 80 columns + const { getCleanOutput, unmount } = renderTUI( + + + Compact View + + , + { columns: 80, rows: 24 } + ); + + const output80 = getCleanOutput(); + expect(output80).toContain('KDM Copilot Shell'); + unmount(); + + // Test render at 140 columns + const expanded = renderTUI( + + + Wide Screen View + + , + { columns: 140, rows: 40 } + ); + + const output140 = expanded.getCleanOutput(); + expect(output140).toContain('Wide Screen View'); + expanded.unmount(); + }); + + it('TC-E2E-T1-F09-04: Workspace tab / view switching via keyboard shortcuts (1-4)', () => { + // Render with Tab 2 (Agents) + const { getCleanOutput: getAgentsOutput, unmount: unmountAgents } = renderTUI( + + Subagents Execution Log + + ); + expect(getAgentsOutput()).toContain('[Alt+2: Agents]'); + expect(getAgentsOutput()).toContain('Subagents Execution Log'); + unmountAgents(); + + // Render with Tab 3 (Diffs) + const { getCleanOutput: getDiffsOutput, unmount: unmountDiffs } = renderTUI( + + Pending Manifest Diff Proposals + + ); + expect(getDiffsOutput()).toContain('[Alt+3: Diffs]'); + expect(getDiffsOutput()).toContain('Pending Manifest Diff Proposals'); + unmountDiffs(); + }); + + it('TC-E2E-T1-F09-05: Graceful exit on Ctrl+C / q keypress with cursor restore', async () => { + let unmounted = false; + let exitTriggered = false; + + const onExit = () => { + exitTriggered = true; + unmounted = true; + }; + + const { sendKey, wait, unmount } = renderTUI( + + Interactive shell content + + ); + + // Send genuine 'q' keystroke to mounted AppContainerView + sendKey('q'); + await wait(50); + + expect(exitTriggered).toBe(true); + expect(unmounted).toBe(true); + + unmount(); + }); +}); diff --git a/src/__tests__/e2e/tier1-features/f10-dashboard-troubleshooting-triggers.test.tsx b/src/__tests__/e2e/tier1-features/f10-dashboard-troubleshooting-triggers.test.tsx new file mode 100644 index 00000000..d1c0ea1a --- /dev/null +++ b/src/__tests__/e2e/tier1-features/f10-dashboard-troubleshooting-triggers.test.tsx @@ -0,0 +1,114 @@ +import React from 'react'; +import { describe, it, expect, vi } from 'vitest'; +import { renderTUI, DashboardWithTroubleshootTrigger } from '../harness'; + +describe('Tier 1: F-10 In-Dashboard Troubleshooting Trigger', () => { + it('TC-E2E-T1-F10-01: Trigger troubleshooting from kdm watch via "t" key', async () => { + const onTrigger = vi.fn(); + const { sendKey, wait, getLastFrame, unmount } = renderTUI( + + ); + + expect(getLastFrame()).toContain('Active Dashboard: WATCH'); + expect(getLastFrame()).toContain('payment-service-8f4b-2x9p'); + + sendKey('t'); + await wait(50); + + expect(onTrigger).toHaveBeenCalledWith('payment-service-8f4b-2x9p'); + const output = getLastFrame(); + expect(output).toContain('🤖 AI Troubleshooting Session: payment-service-8f4b-2x9p'); + expect(output).toContain('Dispatching Multi-Agent Council'); + unmount(); + }); + + it('TC-E2E-T1-F10-02: Trigger troubleshooting from kdm show pods via "t" key', async () => { + const onTrigger = vi.fn(); + const { sendKey, wait, getLastFrame, unmount } = renderTUI( + + ); + + expect(getLastFrame()).toContain('Active Dashboard: SHOW'); + sendKey('t'); + await wait(50); + + expect(onTrigger).toHaveBeenCalledWith('pod/auth-api-v2-7c91'); + expect(getLastFrame()).toContain('🤖 AI Troubleshooting Session: pod/auth-api-v2-7c91'); + unmount(); + }); + + it('TC-E2E-T1-F10-03: Trigger troubleshooting from kdm health via "t" key', async () => { + const onTrigger = vi.fn(); + const { sendKey, wait, getLastFrame, unmount } = renderTUI( + + ); + + expect(getLastFrame()).toContain('Active Dashboard: HEALTH'); + sendKey('t'); + await wait(50); + + expect(onTrigger).toHaveBeenCalledWith('order-service'); + expect(getLastFrame()).toContain('🤖 AI Troubleshooting Session: order-service'); + unmount(); + }); + + it('TC-E2E-T1-F10-04: Trigger troubleshooting from kdm logs via "t" key', async () => { + const onTrigger = vi.fn(); + const { sendKey, wait, getLastFrame, unmount } = renderTUI( + + ); + + expect(getLastFrame()).toContain('Active Dashboard: LOGS'); + expect(getLastFrame()).toContain('FATAL: connection refused'); + sendKey('t'); + await wait(50); + + expect(onTrigger).toHaveBeenCalledWith('payment-service [FATAL: connection refused]'); + expect(getLastFrame()).toContain('payment-service [FATAL: connection refused]'); + unmount(); + }); + + it('TC-E2E-T1-F10-05: Seamless return to monitoring dashboard after triage dismissal (Esc)', async () => { + const onDismissal = vi.fn(); + const { sendKey, stdin, wait, getLastFrame, unmount } = renderTUI( + + ); + + // 1. Enter troubleshooting + sendKey('t'); + await wait(50); + expect(getLastFrame()).toContain('🤖 AI Troubleshooting Session'); + + // 2. Press Escape + stdin.sendEscape(); + await wait(50); + + expect(onDismissal).toHaveBeenCalled(); + const output = getLastFrame(); + expect(output).toContain('Active Dashboard: WATCH'); + expect(output).toContain('Press [t] to trigger AI troubleshooting'); + expect(output).not.toContain('Dispatching Multi-Agent Council'); + unmount(); + }); +}); diff --git a/src/__tests__/e2e/tier2-boundaries/f01-build-boundaries.test.ts b/src/__tests__/e2e/tier2-boundaries/f01-build-boundaries.test.ts new file mode 100644 index 00000000..3d009c39 --- /dev/null +++ b/src/__tests__/e2e/tier2-boundaries/f01-build-boundaries.test.ts @@ -0,0 +1,107 @@ +import { describe, it, expect } from 'vitest'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; +import { execSync } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; +import { z } from 'zod'; +import { AgentRegistry, MockClusterEnvironment } from '../harness'; +import { GoogleGeminiAIClient } from '../../../ai/google-gemini'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const ROOT_DIR = path.resolve(__dirname, '../../../../'); + +describe('Tier 2: F-01 Build & Pipeline Boundaries', () => { + it('TC-E2E-T2-F01-01: Zero-byte / empty TypeScript source file handling without compiler panic', () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'kdm-empty-ts-')); + const emptyTsFile = path.join(tmpDir, 'empty.ts'); + fs.writeFileSync(emptyTsFile, ''); + + expect(fs.existsSync(emptyTsFile)).toBe(true); + + // Genuinely invoke TypeScript compiler to verify empty file parses with zero errors + const checkCommand = `npx tsc --noEmit --target es2022 --skipLibCheck "${emptyTsFile}" --ignoreConfig`; + expect(() => execSync(checkCommand, { stdio: 'pipe' })).not.toThrow(); + + // Cleanup + fs.rmSync(tmpDir, { recursive: true, force: true }); + }); + + it('TC-E2E-T2-F01-02: Missing optional peer dependencies handled cleanly with informative skips', async () => { + let caught: any = null; + try { + // @ts-ignore + await import('nonexistent-optional-kdm-plugin'); + } catch (err: any) { + caught = err; + } + + expect(caught).not.toBeNull(); + expect(caught.code).toBe('ERR_MODULE_NOT_FOUND'); + }); + + it('TC-E2E-T2-F01-03: Deeply nested source file path resolution (>200 chars)', () => { + const deepSubdir = 'a'.repeat(50) + '/' + 'b'.repeat(50) + '/' + 'c'.repeat(50) + '/' + 'd'.repeat(50); + const resolvedPath = path.resolve(ROOT_DIR, deepSubdir, 'deeplyNestedModule.ts'); + + expect(resolvedPath.length).toBeGreaterThan(200); + expect(path.isAbsolute(resolvedPath)).toBe(true); + expect(path.basename(resolvedPath)).toBe('deeplyNestedModule.ts'); + }); + + it('TC-E2E-T2-F01-04: Concurrency isolation in Vitest single-worker execution', () => { + // Harness component isolation test + const registryA = new AgentRegistry(); + const registryB = new AgentRegistry(); + + const sampleAgent = { + name: 'SampleWorkerAgent', + description: 'Isolated test worker', + inputSchema: z.object({ prompt: z.string() }), + outputSchema: z.object({ result: z.string() }), + run: async () => ({ result: 'done' }), + }; + + registryA.register(sampleAgent); + expect(registryA.get('SampleWorkerAgent')).toBeDefined(); + expect(registryB.get('SampleWorkerAgent')).toBeUndefined(); + + // Verify cluster environment isolation + const envHealthy = new MockClusterEnvironment().setHealthyScenario(); + const envEmpty = new MockClusterEnvironment().setEmptyScenario(); + + expect(envHealthy.getState().pods.length).toBeGreaterThan(0); + expect(envEmpty.getState().pods.length).toBe(0); + }); + + it('TC-E2E-T2-F01-05: Missing environment variables at build/test time fall back to mocks cleanly', async () => { + const origKey = process.env.GEMINI_API_KEY; + const origKube = process.env.KUBECONFIG; + const origDocker = process.env.DOCKER_HOST; + + try { + delete process.env.GEMINI_API_KEY; + delete process.env.KUBECONFIG; + delete process.env.DOCKER_HOST; + + const client = new GoogleGeminiAIClient(); + // Configure rejects when credentials are completely missing + await expect(client.configure({ name: 'google-gemini' })).rejects.toThrow( + 'API key (password) is required for google-gemini provider' + ); + + // Falls back cleanly when mock or test config is provided + await client.configure({ + name: 'google-gemini', + password: 'mock-test-key', + model: 'gemini-1.5-flash', + }); + expect(client.name).toBe('google-gemini'); + } finally { + if (origKey !== undefined) process.env.GEMINI_API_KEY = origKey; + if (origKube !== undefined) process.env.KUBECONFIG = origKube; + if (origDocker !== undefined) process.env.DOCKER_HOST = origDocker; + } + }); +}); diff --git a/src/__tests__/e2e/tier2-boundaries/f02-gemini-boundaries.test.ts b/src/__tests__/e2e/tier2-boundaries/f02-gemini-boundaries.test.ts new file mode 100644 index 00000000..ac949297 --- /dev/null +++ b/src/__tests__/e2e/tier2-boundaries/f02-gemini-boundaries.test.ts @@ -0,0 +1,111 @@ +import { describe, it, expect, vi } from 'vitest'; +import { MockGenAIStreamBuilder } from '../harness'; +import { GoogleGeminiAIClient } from '../../../ai/google-gemini'; +import { parseNDJSONLine } from '../../../agent/event-schema'; + +describe('Tier 2: F-02 Gemini Boundaries & Corner Cases', () => { + it('TC-E2E-T2-F02-01: Socket termination and network disconnect mid-stream (ECONNRESET)', async () => { + const builder = new MockGenAIStreamBuilder(); + builder.addText('Streaming diagnostic start...'); + + const connResetError = new Error('read ECONNRESET'); + (connResetError as any).code = 'ECONNRESET'; + builder.simulateError(connResetError, 1); + + const stream = builder.toAsyncIterable(); + let receivedChunks = 0; + let caughtError: any = null; + + try { + for await (const chunk of stream) { + receivedChunks++; + } + } catch (err) { + caughtError = err; + } + + expect(receivedChunks).toBe(1); + expect(caughtError).not.toBeNull(); + expect(caughtError.code).toBe('ECONNRESET'); + }); + + it('TC-E2E-T2-F02-02: HTTP 429 quota exhaustion (RESOURCE_EXHAUSTED) with retry notice', async () => { + const client = new GoogleGeminiAIClient(); + await client.configure({ + provider: 'google-gemini', + password: 'test-api-key', + }); + + const rateLimitError = { + ok: false, + status: 429, + statusText: 'Too Many Requests', + json: async () => ({ + error: { + code: 429, + message: 'Resource exhausted: quota limit exceeded for model gemini-2.5-flash', + status: 'RESOURCE_EXHAUSTED', + }, + }), + }; + + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(rateLimitError as any); + + await expect(client.getCompletion('Explain high CPU usage')).rejects.toThrow( + 'Google Gemini API call failed with status 429' + ); + + fetchSpy.mockRestore(); + }); + + it('TC-E2E-T2-F02-03: HTTP 401 unauthorized / invalid API key rejection notice', async () => { + const client = new GoogleGeminiAIClient(); + await client.configure({ + provider: 'google-gemini', + password: 'invalid-or-revoked-key', + }); + + const authError = { + ok: false, + status: 401, + statusText: 'Unauthorized', + json: async () => ({ + error: { + code: 401, + message: 'API key not valid. Please pass a valid API key.', + status: 'UNAUTHENTICATED', + }, + }), + }; + + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(authError as any); + + await expect(client.getCompletion('Diagnose pod')).rejects.toThrow( + 'Google Gemini API call failed with status 401' + ); + + fetchSpy.mockRestore(); + }); + + it('TC-E2E-T2-F02-04: Extreme token input / massive cluster log (>2MB) sliding window truncation', () => { + const client = new GoogleGeminiAIClient(); + const massiveLog = 'A'.repeat(3 * 1024 * 1024); + const maxAllowedChars = 100_000; + + const { text, truncated } = client.truncatePrompt(massiveLog, maxAllowedChars); + expect(truncated).toBe(true); + expect(text.length).toBeLessThan(100_100); + expect(text).toContain('[... Truncated earlier log entries ...]'); + }); + + it('TC-E2E-T2-F02-05: Malformed JSON or truncated function call response recovery', () => { + const client = new GoogleGeminiAIClient(); + const truncatedPayload = '{"name": "k8s_get_pod", "args": {"pod": "paym'; + + const result = client.safeParseToolCall(truncatedPayload); + expect(result.success).toBe(false); + expect(result.error).toContain('Truncated function call JSON'); + + expect(parseNDJSONLine(truncatedPayload)).toBeNull(); + }); +}); diff --git a/src/__tests__/e2e/tier2-boundaries/f03-tools-boundaries.test.ts b/src/__tests__/e2e/tier2-boundaries/f03-tools-boundaries.test.ts new file mode 100644 index 00000000..ade832f9 --- /dev/null +++ b/src/__tests__/e2e/tier2-boundaries/f03-tools-boundaries.test.ts @@ -0,0 +1,62 @@ +import { describe, it, expect } from 'vitest'; +import { + k8sApplyPatchTool, + k8sGetPodTool, + k8sGetLogsTool, + MockClusterEnvironment, +} from '../harness'; + +describe('Tier 2: F-03 Declarative Tools Boundaries & Corner Cases', () => { + it('TC-E2E-T2-F03-01: Kubernetes control plane timeout (5000ms watchdog abort)', async () => { + const cluster = new MockClusterEnvironment().setHangingScenario().install(); + + await expect( + k8sGetPodTool.execute({ name: 'payment-service', namespace: 'default', timeoutMs: 5000 }) + ).rejects.toThrow('ClusterTimeoutError: Control plane did not respond in 5000ms'); + + cluster.reset(); + }); + + it('TC-E2E-T2-F03-02: Docker daemon socket unreachable (/var/run/docker.sock inactive)', async () => { + const cluster = new MockClusterEnvironment().setDisconnectedScenario(false, true).install(); + + const { getRunningContainers } = await import('../../../docker/containers'); + await expect(getRunningContainers()).rejects.toThrow( + 'Cannot connect to the Docker daemon. Is Docker running?' + ); + + cluster.reset(); + }); + + it('TC-E2E-T2-F03-03: Resource not found (404) in target namespace', async () => { + const cluster = new MockClusterEnvironment().setHealthyScenario().install(); + + await expect( + k8sGetPodTool.execute({ name: 'nonexistent-pod', namespace: 'prod' }) + ).rejects.toThrow("Pod 'nonexistent-pod' not found in namespace 'prod'"); + + cluster.reset(); + }); + + it('TC-E2E-T2-F03-04: Zero-byte / empty pod log stream handling', async () => { + const cluster = new MockClusterEnvironment().setHealthyScenario().install(); + + const result = await k8sGetLogsTool.execute({ pod: 'just-started-pod', namespace: 'default' }); + expect(result.logs).toBe(''); + expect(result.note).toBe('Log stream empty'); + + cluster.reset(); + }); + + it('TC-E2E-T2-F03-05: Malformed YAML syntax patch rejected before cluster submission', async () => { + const malformedPatch = ':::broken-yaml invalid: [unclosed'; + + await expect( + k8sApplyPatchTool.execute({ + resource: 'deployment/cart', + namespace: 'default', + patch: malformedPatch, + }) + ).rejects.toThrow('YAML syntax error'); + }); +}); diff --git a/src/__tests__/e2e/tier2-boundaries/f04-registry-boundaries.test.ts b/src/__tests__/e2e/tier2-boundaries/f04-registry-boundaries.test.ts new file mode 100644 index 00000000..020d41f9 --- /dev/null +++ b/src/__tests__/e2e/tier2-boundaries/f04-registry-boundaries.test.ts @@ -0,0 +1,105 @@ +import { describe, it, expect } from 'vitest'; +import { + AgentRegistry, + AgentTool, + MockPythonCouncil, + translateNDJSONToSubagentProgress, +} from '../harness'; +import { parseNDJSONLine } from '../../../agent/event-schema'; +import { EventTranslator } from '../../../agent/event-translator'; + +describe('Tier 2: F-04 Agent Registry Boundaries & Corner Cases', () => { + it('TC-E2E-T2-F04-01: Delegation to unregistered subagent name returns error without crash', async () => { + const registry = new AgentRegistry(); + const tool = new AgentTool(registry); + + await expect( + tool.execute({ + agent_name: 'UnregisteredSpecialist', + prompt: 'Investigate leak', + }) + ).rejects.toThrow("Agent 'UnregisteredSpecialist' not found"); + }); + + it('TC-E2E-T2-F04-02: Subagent execution timeout triggers agent_failed state', () => { + const timeoutEvent = { + event: 'agent_failed' as const, + role: 'runtime', + error: 'CouncilTimeoutError: Agent execution timed out after 10000ms', + timestamp: new Date().toISOString(), + }; + + const progress = translateNDJSONToSubagentProgress(timeoutEvent); + expect(progress?.state).toBe('error'); + expect(progress?.result).toContain('CouncilTimeoutError'); + }); + + it('TC-E2E-T2-F04-03: Corrupted / partial NDJSON stream lines skipped silently', () => { + const corruptLines = [ + 'not a valid json object', + '{"partial": true, ', + '', + '{"missing_event": 123}', + ]; + + for (const badLine of corruptLines) { + const parsed = parseNDJSONLine(badLine); + expect(parsed).toBeNull(); + } + + // Valid line adjacent to bad line parses properly + const validLine = JSON.stringify({ + event: 'agent_progress', + role: 'runtime', + message: 'Processing memory metrics', + timestamp: new Date().toISOString(), + }); + const parsedValid = parseNDJSONLine(validLine); + expect(parsedValid).not.toBeNull(); + expect(parsedValid?.event).toBe('agent_progress'); + + const secondLine = JSON.stringify({ + event: 'agent_complete', + role: 'runtime', + summary: 'Finished memory check', + timestamp: new Date().toISOString(), + }); + const translator = new EventTranslator(); + const splitAt = Math.floor(validLine.length / 2); + expect(translator.pushChunk(validLine.slice(0, splitAt))).toEqual([]); + const events = [ + ...translator.pushChunk(`${validLine.slice(splitAt)}\n{bad json\n${secondLine}`), + ...translator.flush(), + ]; + expect(events).toHaveLength(2); + expect(events[0]?.thought).toBe('Processing memory metrics'); + expect(events[1]?.result).toBe('Finished memory check'); + }); + + it('TC-E2E-T2-F04-04: Circular subagent delegation prevention via max depth clamp', async () => { + const registry = new AgentRegistry(); + const tool = new AgentTool(registry, 2); + + // Attempting depth 2 when maxDepth is 2 throws + await expect( + tool.execute({ + agent_name: 'RecursiveAgent', + prompt: 'Self delegation', + depth: 2, + }) + ).rejects.toThrow('MaxDelegationDepthExceededError'); + }); + + it('TC-E2E-T2-F04-05: Unexpected subagent child process crash (SIGKILL/exit 137) handled gracefully', async () => { + const proc = MockPythonCouncil.createMockProcess([], { exitCode: 137 }); + + const exitPromise = new Promise<{ code: number }>((resolve) => { + proc.on('close', (code: number) => { + resolve({ code }); + }); + }); + + const result = await exitPromise; + expect(result.code).toBe(137); + }); +}); diff --git a/src/__tests__/e2e/tier2-boundaries/f05-investigator-boundaries.test.ts b/src/__tests__/e2e/tier2-boundaries/f05-investigator-boundaries.test.ts new file mode 100644 index 00000000..14d521d0 --- /dev/null +++ b/src/__tests__/e2e/tier2-boundaries/f05-investigator-boundaries.test.ts @@ -0,0 +1,56 @@ +import { describe, it, expect } from 'vitest'; +import { mkdtemp, rm, symlink, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { CodebaseInvestigatorAgent } from '../../../agent/investigator'; + +describe('Tier 2: F-05 Codebase Investigator Boundaries & Corner Cases', () => { + it('TC-E2E-T2-F05-01: Empty workspace directory (zero manifests) returns clean finding', async () => { + const report = await CodebaseInvestigatorAgent.run({ workspaceFiles: {} }); + expect(report.discoveredManifests).toHaveLength(0); + expect(report.findings[0].issue).toContain('No relevant configuration or manifest files discovered'); + }); + + it('TC-E2E-T2-F05-02: Syntactically broken YAML/Dockerfile in repository skipped with warning', async () => { + const mockFiles = { + 'broken.yaml': ':::broken syntax: [unclosed list\nmemory: 256Mi\nJAVA_OPTS: "-Xmx768m"', + 'valid.yaml': 'apiVersion: v1\nkind: Service\n', + }; + + const report = await CodebaseInvestigatorAgent.run({ workspaceFiles: mockFiles }); + expect(report.discoveredManifests).toContain('valid.yaml'); + expect(report.ExplorationTrace.some((line) => line.includes('Skipping syntactically invalid manifest: broken.yaml'))).toBe(true); + expect(report.driftDetected).toBe(false); + expect(report.findings.some((finding) => finding.file === 'broken.yaml')).toBe(false); + }); + + it('TC-E2E-T2-F05-03: Circular filesystem symlink loop detection and avoidance', async () => { + const root = await mkdtemp(join(tmpdir(), 'kdm-investigator-')); + try { + await writeFile(join(root, 'Chart.yaml'), 'name: frontend\nversion: 1.0.0\n'); + await symlink(root, join(root, 'loop'), 'dir'); + await symlink(join(root, 'Chart.yaml'), join(root, 'linked.yaml')); + const report = await CodebaseInvestigatorAgent.run({ workspaceRoot: root }); + expect(report.discoveredManifests).toEqual(['Chart.yaml']); + expect(report.ExplorationTrace).toContain('Skipping symbolic link: loop'); + } finally { + await rm(root, { recursive: true, force: true }); + } + }); + + it('TC-E2E-T2-F05-04: Giant binary files in repository root skipped safely', async () => { + const mockFiles = { + 'database.bin': '\x00\x01\x02\x03\x04BINARY_PAYLOAD', + 'archive.tar.gz': '\x1f\x8b\x08ARCHIVE_PAYLOAD', + 'deployment.yaml': 'apiVersion: apps/v1\nkind: Deployment\n', + 'Dockerfile': 'FROM node:20-alpine\n', + }; + + const report = await CodebaseInvestigatorAgent.run({ workspaceFiles: mockFiles }); + expect(report.discoveredManifests).toContain('deployment.yaml'); + expect(report.discoveredManifests).toContain('Dockerfile'); + expect(report.discoveredManifests).not.toContain('database.bin'); + expect(report.discoveredManifests).not.toContain('archive.tar.gz'); + }); + +}); diff --git a/src/__tests__/e2e/tier2-boundaries/f06-progress-ui-boundaries.test.tsx b/src/__tests__/e2e/tier2-boundaries/f06-progress-ui-boundaries.test.tsx new file mode 100644 index 00000000..c98557c9 --- /dev/null +++ b/src/__tests__/e2e/tier2-boundaries/f06-progress-ui-boundaries.test.tsx @@ -0,0 +1,84 @@ +import React from 'react'; +import { describe, it, expect } from 'vitest'; +import { Box } from 'ink'; +import { renderTUI, ThinkingMessage, stripAnsi, translateNDJSONToSubagentProgress } from '../harness'; +import { AgentCard } from '../../../ui/components/AgentCard'; + +describe('Tier 2: F-06 Progress UI Boundaries & Corner Cases', () => { + it('TC-E2E-T2-F06-01: Terminal viewport narrower than card minimum width (40 columns)', () => { + const { getCleanOutput, unmount } = renderTUI( + + + , + { columns: 40, rows: 20 } + ); + + const output = getCleanOutput(); + expect(output.length).toBeGreaterThan(0); + expect(output).toContain('Runtime'); + unmount(); + }); + + it('TC-E2E-T2-F06-02: Rapid high-frequency progress event storm (100 events/sec) batched smoothly', async () => { + let latestProgress: ReturnType = null; + + // Stream 100 events in rapid succession through NDJSON translation + for (let i = 0; i < 100; i++) { + latestProgress = translateNDJSONToSubagentProgress({ + event: 'agent_progress', + role: 'RuntimeAgent', + message: `Progress step #${i}`, + }); + } + + expect(latestProgress).not.toBeNull(); + expect(latestProgress?.thought).toBe('Progress step #99'); + + const { getCleanOutput, unmount } = renderTUI( + + ); + + const frame = getCleanOutput(); + expect(frame).toContain('RuntimeAgent'); + expect(frame).toContain('Progress step #99'); + unmount(); + }); + + it('TC-E2E-T2-F06-03: Empty thought stream (thought: "") consumes zero vertical rows', () => { + const { getCleanOutput, unmount } = renderTUI(); + const output = getCleanOutput(); + expect(output.trim()).toBe(''); + unmount(); + }); + + it('TC-E2E-T2-F06-04: Long reasoning trace (>1500 chars) rendered with compact preview', () => { + const longTrace = 'A'.repeat(2000); + + const { getCleanOutput, unmount } = renderTUI( + + ); + + const output = getCleanOutput(); + expect(output.length).toBeLessThan(140); + expect(output).toContain('... [+more]'); + unmount(); + }); + + it('TC-E2E-T2-F06-05: Unicode and raw ANSI color injection in progress messages sanitized', () => { + const injectedMessage = '\u001b[31;1mDanger Red\u001b[0m 🚀 Pod crash detected'; + const sanitized = stripAnsi(injectedMessage); + + expect(sanitized).toBe('Danger Red 🚀 Pod crash detected'); + expect(sanitized).not.toContain('\u001b'); + }); +}); diff --git a/src/__tests__/e2e/tier2-boundaries/f07-diff-queue-boundaries.test.tsx b/src/__tests__/e2e/tier2-boundaries/f07-diff-queue-boundaries.test.tsx new file mode 100644 index 00000000..6a2f10d2 --- /dev/null +++ b/src/__tests__/e2e/tier2-boundaries/f07-diff-queue-boundaries.test.tsx @@ -0,0 +1,118 @@ +import React from 'react'; +import { describe, it, expect, vi } from 'vitest'; +import { + renderTUI, + DiffRenderer, + ToolConfirmationQueueView, + type ConfirmationRequest, + type ConfirmationDecision, +} from '../harness'; + +describe('Tier 2: F-07 Manifest Diff & Queue Boundaries & Corner Cases', () => { + it('TC-E2E-T2-F07-01: Empty diff preview (no changes detected) displays clean notice', () => { + const { getCleanOutput, unmount } = renderTUI(); + const output = getCleanOutput(); + expect(output).toContain('No configuration differences detected'); + unmount(); + }); + + it('TC-E2E-T2-F07-02: Unrecognized keystrokes ignored; prompt stays active', async () => { + const request: ConfirmationRequest = { + id: 'conf-req-unrec', + toolName: 'k8s_apply_patch', + args: { command: 'kubectl apply -f patch.yaml' }, + riskLevel: 'medium', + prompt: 'Approve patch rollout?', + }; + + let decisionMade: ConfirmationDecision | null = null; + const { sendKey, wait, getCleanOutput, unmount } = renderTUI( + { + decisionMade = d; + }} + /> + ); + + // Send unrecognized keys + sendKey('x'); + await wait(20); + sendKey('1'); + await wait(20); + sendKey(' '); + await wait(20); + + expect(decisionMade).toBeNull(); // remains active and unconfirmed + expect(getCleanOutput()).toContain('Approve patch rollout?'); + + // Confirm that valid 'y' key continues to work afterwards + sendKey('y'); + await wait(50); + expect(decisionMade).toBe('ALLOW'); + unmount(); + }); + + it('TC-E2E-T2-F07-03: SIGINT (Ctrl+C) during pending confirmation records ABORTED_BY_USER', async () => { + const request: ConfirmationRequest = { + id: 'conf-req-abort', + toolName: 'docker_restart_container', + args: { command: 'docker restart pg' }, + riskLevel: 'high', + prompt: 'Restart container?', + }; + + let decisionMade: ConfirmationDecision | null = null; + let aborted = false; + + const { stdin, wait, unmount } = renderTUI( + { + decisionMade = d; + }} + onAbort={() => { + aborted = true; + }} + /> + ); + + stdin.sendCtrlC(); + await wait(50); + + expect(aborted).toBe(true); + expect(decisionMade).toBe('DENY'); + unmount(); + }); + + it('TC-E2E-T2-F07-04: Giant multi-file diff (>500 lines) truncated with line count note', () => { + const lines = Array.from({ length: 600 }, (_, i) => `+ Line ${i + 1}`); + const giantDiff = lines.join('\n'); + + const { getCleanOutput, unmount } = renderTUI(); + const output = getCleanOutput(); + + expect(output).toContain('... and 570 more lines'); + unmount(); + }); + + it('TC-E2E-T2-F07-05: Remediation execution failure (non-zero exit from kubectl) captures stderr', async () => { + // Tests real executeRemediationCommand failure handling + const { executeRemediationCommand } = await import('../../../remediation/executor'); + + const failingExec = vi.fn().mockRejectedValue({ + code: 1, + stdout: '', + stderr: 'Error from server (Conflict): Operation cannot be fulfilled on deployments.apps', + }); + + const result = await executeRemediationCommand('kubectl apply -f patch.yaml', { + execFileFn: failingExec, + }); + + expect(result.success).toBe(false); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('Conflict'); + expect(failingExec).toHaveBeenCalledTimes(1); + }); +}); diff --git a/src/__tests__/e2e/tier2-boundaries/f08-composer-boundaries.test.tsx b/src/__tests__/e2e/tier2-boundaries/f08-composer-boundaries.test.tsx new file mode 100644 index 00000000..abbc09e4 --- /dev/null +++ b/src/__tests__/e2e/tier2-boundaries/f08-composer-boundaries.test.tsx @@ -0,0 +1,113 @@ +import React from 'react'; +import { describe, it, expect, vi } from 'vitest'; +import { renderTUI, ComposerView } from '../harness'; + +describe('Tier 2: F-08 Composer Boundaries & Corner Cases', () => { + it('TC-E2E-T2-F08-01: Whitespace-only / empty prompt submission ignored', async () => { + const onSubmit = vi.fn(); + const { sendKey, stdin, wait, unmount } = renderTUI( + + ); + + // Empty enter + stdin.sendEnter(); + await wait(20); + + // Whitespace enter + sendKey(' '); + await wait(20); + stdin.sendEnter(); + await wait(20); + + expect(onSubmit).not.toHaveBeenCalled(); + + // Valid prompt succeeds + sendKey('diagnose auth'); + await wait(20); + stdin.sendEnter(); + await wait(50); + + expect(onSubmit).toHaveBeenCalledTimes(1); + expect(onSubmit).toHaveBeenCalledWith('diagnose auth'); + unmount(); + }); + + it('TC-E2E-T2-F08-02: Unknown slash command (/unknowncommand) displays helpful error', async () => { + const onSubmit = vi.fn(); + const { sendKey, stdin, wait, getLastFrame, unmount } = renderTUI( + + ); + + sendKey('/unknowncommand'); + await wait(20); + stdin.sendEnter(); + await wait(50); + + expect(onSubmit).not.toHaveBeenCalled(); + const output = getLastFrame(); + expect(output).toContain("Unknown command '/unknowncommand'. Type /help for available commands."); + unmount(); + }); + + it('TC-E2E-T2-F08-03: Rapid double Enter keystroke debounced to single dispatch', async () => { + const onSubmit = vi.fn(); + const { sendKey, stdin, wait, unmount } = renderTUI( + + ); + + sendKey('diagnose pod'); + await wait(20); + + // Rapid double enter + stdin.sendEnter(); + stdin.sendEnter(); + await wait(50); + + expect(onSubmit).toHaveBeenCalledTimes(1); + expect(onSubmit).toHaveBeenCalledWith('diagnose pod'); + unmount(); + }); + + it('TC-E2E-T2-F08-04: Extreme input string length (10,000 characters pasted) handled safely', async () => { + const hugeInput = 'x'.repeat(10000); + const onSubmit = vi.fn(); + + const { sendKey, stdin, wait, unmount } = renderTUI( + + ); + + sendKey(hugeInput); + await wait(50); + stdin.sendEnter(); + await wait(50); + + expect(onSubmit).toHaveBeenCalledTimes(1); + expect(onSubmit.mock.calls[0][0].length).toBe(10000); + unmount(); + }); + + it('TC-E2E-T2-F08-05: Arrow key navigation at history boundaries clamped safely', async () => { + const history = ['first', 'second', 'third']; + const onSubmit = vi.fn(); + + const { stdin, wait, getLastFrame, unmount } = renderTUI( + + ); + + // Spam Up Arrow beyond upper bound + for (let i = 0; i < 10; i++) { + stdin.sendUp(); + } + await wait(50); + expect(getLastFrame()).toContain('first'); + + // Spam Down Arrow beyond lower bound + for (let i = 0; i < 10; i++) { + stdin.sendDown(); + } + await wait(50); + // Returns cleanly to empty prompt buffer + expect(getLastFrame()).toContain('Type a prompt or / command...'); + unmount(); + }); +}); diff --git a/src/__tests__/e2e/tier2-boundaries/f09-workspace-boundaries.test.tsx b/src/__tests__/e2e/tier2-boundaries/f09-workspace-boundaries.test.tsx new file mode 100644 index 00000000..36b0a514 --- /dev/null +++ b/src/__tests__/e2e/tier2-boundaries/f09-workspace-boundaries.test.tsx @@ -0,0 +1,95 @@ +import React from 'react'; +import { describe, it, expect } from 'vitest'; +import { Box, Text } from 'ink'; +import { renderTUI, stripAnsi, AppContainerView, debounceResize } from '../harness'; + +describe('Tier 2: F-09 Workspace Shell Boundaries & Corner Cases', () => { + it('TC-E2E-T2-F09-01: Rapid window resizing storm (10 events/sec) debounced', async () => { + let appliedWidth = 80; + let callCount = 0; + + const handleResize = debounceResize((cols) => { + appliedWidth = cols; + callCount++; + }, 25); + + const { getCleanOutput, wait, unmount } = renderTUI( + + Terminal Width: {appliedWidth} + + ); + + // Rapid successive resize storm (11 events in quick succession) + for (let c = 80; c <= 120; c += 4) { + handleResize(c, 24); + } + + // Trailing debounce prevents synchronous spam execution + expect(callCount).toBe(0); + + // Allow debounce timer to settle + await wait(60); + + // Exactly one trailing update performed with final target dimension + expect(callCount).toBe(1); + expect(appliedWidth).toBe(120); + + expect(getCleanOutput()).toContain('KDM Copilot Shell'); + unmount(); + }); + + it('TC-E2E-T2-F09-02: NO_COLOR=1 or TERM=dumb environment strips ANSI styling', () => { + const coloredString = '\u001b[32mActive (1/1)\u001b[0m'; + const plain = stripAnsi(coloredString); + expect(plain).toBe('Active (1/1)'); + }); + + it('TC-E2E-T2-F09-03: Background cluster polling timeout isolated to banner without freezing shell', () => { + const { getLastFrame, getCleanOutput, unmount } = renderTUI( + + Active Workloads Table + + ); + + const frame = getLastFrame() || ''; + expect(frame).toContain('Cluster poll warning: ETIMEDOUT'); + expect(frame).toContain('KDM Copilot Shell'); + expect(frame).toContain('Active Workloads Table'); + unmount(); + }); + + it('TC-E2E-T2-F09-04: Zero resources returned in monitor pane displays informative empty state', () => { + const { getCleanOutput, unmount } = renderTUI( + + No active workloads found in current context + + ); + + expect(getCleanOutput()).toContain('No active workloads found in current context'); + unmount(); + }); + + it('TC-E2E-T2-F09-05: Host SIGTERM/SIGHUP triggers graceful terminal restoration and exit 143', () => { + let terminalRestored = false; + let recordedSignal = ''; + + const { unmount } = renderTUI( + { + recordedSignal = sig; + terminalRestored = true; + }} + > + Shell active with signal handlers + + ); + + process.emit('SIGTERM'); + + expect(recordedSignal).toBe('SIGTERM'); + expect(terminalRestored).toBe(true); + + unmount(); + }); +}); diff --git a/src/__tests__/e2e/tier2-boundaries/f10-triggers-boundaries.test.tsx b/src/__tests__/e2e/tier2-boundaries/f10-triggers-boundaries.test.tsx new file mode 100644 index 00000000..3855cd3c --- /dev/null +++ b/src/__tests__/e2e/tier2-boundaries/f10-triggers-boundaries.test.tsx @@ -0,0 +1,99 @@ +import React from 'react'; +import { describe, it, expect, vi } from 'vitest'; +import { renderTUI, DashboardWithTroubleshootTrigger } from '../harness'; +import { AgentCard } from '../../../ui/components/AgentCard'; + +describe('Tier 2: F-10 Dashboard Triggers Boundaries & Corner Cases', () => { + it('TC-E2E-T2-F10-01: Pressing "t" with no selected resource shows guidance hint', async () => { + const onTrigger = vi.fn(); + const { sendKey, wait, getLastFrame, unmount } = renderTUI( + + ); + + sendKey('t'); + await wait(50); + + expect(onTrigger).not.toHaveBeenCalled(); + expect(getLastFrame()).toContain('No workload selected. Use arrow keys to select a workload.'); + unmount(); + }); + + it('TC-E2E-T2-F10-02: Rapid repeated pressing of "t" key spammed ignores duplicates', async () => { + const onTrigger = vi.fn(); + const { sendKey, wait, unmount } = renderTUI( + + ); + + // Spam 't' 5 times rapidly + for (let i = 0; i < 5; i++) { + sendKey('t'); + } + await wait(50); + + expect(onTrigger).toHaveBeenCalledTimes(1); + unmount(); + }); + + it('TC-E2E-T2-F10-03: Pressing "t" on healthy workload runs verification without false alarms', async () => { + const onTrigger = vi.fn(); + const { sendKey, wait, getLastFrame, unmount } = renderTUI( + + ); + + sendKey('t'); + await wait(50); + + expect(onTrigger).toHaveBeenCalledWith('healthy-pod-zero-restarts'); + expect(getLastFrame()).toContain('🤖 AI Troubleshooting Session: healthy-pod-zero-restarts'); + unmount(); + }); + + it('TC-E2E-T2-F10-04: Network disconnect mid-troubleshooting marks subagent failed with retry option', () => { + const { getLastFrame, unmount } = renderTUI( + + ); + + const output = getLastFrame(); + expect(output).toContain('Runtime Agent'); + expect(output).toContain('Network disconnected mid-investigation'); + expect(output).toContain('Press [r] to retry'); + unmount(); + }); + + it('TC-E2E-T2-F10-05: Headless flag (--no-interactive) disables "t" keyboard shortcut', async () => { + const onTrigger = vi.fn(); + const { sendKey, wait, getLastFrame, unmount } = renderTUI( + + ); + + sendKey('t'); + await wait(50); + + expect(onTrigger).not.toHaveBeenCalled(); + expect(getLastFrame()).not.toContain('🤖 AI Troubleshooting Session'); + expect(getLastFrame()).toContain('Active Dashboard: WATCH'); + unmount(); + }); +}); diff --git a/src/__tests__/e2e/tier3-combinations/cross-feature-flows.test.tsx b/src/__tests__/e2e/tier3-combinations/cross-feature-flows.test.tsx new file mode 100644 index 00000000..79efde86 --- /dev/null +++ b/src/__tests__/e2e/tier3-combinations/cross-feature-flows.test.tsx @@ -0,0 +1,346 @@ +import React from 'react'; +import { describe, it, expect, afterEach, vi } from 'vitest'; +import { z } from 'zod'; +import { + renderTUI, + MockGenAIStreamBuilder, + MockPythonCouncil, + MockClusterEnvironment, + AgentRegistry, + AgentTool, + DeclarativeToolRegistry, + CodebaseInvestigatorAgent, + DiffRenderer, + ThinkingMessage, + translateNDJSONToSubagentProgress, + k8sGetPodTool, + k8sListPodsTool, + dockerInspectContainerTool, + runCLI, + ToolConfirmationQueueView, + ComposerView, + DashboardWithTroubleshootTrigger, + parseSlashCommand, + type ConfirmationRequest, + type ConfirmationDecision, +} from '../harness'; +import { executeRemediationCommand } from '../../../remediation/executor'; + +describe('Tier 3: Cross-Feature Interactions & Pairwise Integration Flows', () => { + let activeCluster: MockClusterEnvironment | null = null; + + afterEach(() => { + if (activeCluster) { + activeCluster.reset(); + activeCluster = null; + } + MockClusterEnvironment.resetActive(); + vi.restoreAllMocks(); + }); + + it('TC-E2E-T3-PAIR-01: Composer Slash Command -> Declarative Tool Execution (F-08 + F-03)', async () => { + let submittedCommand = ''; + const { sendKey, stdin, wait, unmount, getLastFrame } = renderTUI( + { submittedCommand = cmd; }} /> + ); + + sendKey('/pods -n staging'); + await wait(20); + expect(getLastFrame()).toContain('/pods -n staging'); + + stdin.sendEnter(); + await wait(50); + unmount(); + + expect(submittedCommand).toBe('/pods -n staging'); + + const parsed = parseSlashCommand(submittedCommand); + expect(parsed?.command).toBe('/pods'); + expect(parsed?.args).toEqual(['-n', 'staging']); + + const registry = new DeclarativeToolRegistry(); + registry.register(k8sListPodsTool); + + const result = await registry.invoke('k8s_list_pods', { namespace: parsed?.args[1] }); + expect(result.namespace).toBe('staging'); + expect(result.pods).toHaveLength(2); + }); + + it('TC-E2E-T3-PAIR-02: Copilot Orchestrator Delegation -> EventTranslator -> Subagent Progress UI (F-04 + F-06)', async () => { + const toolCallEv = { + event: 'agent_tool_call' as const, + role: 'runtime', + tool: 'k8s_get_logs', + args: { pod: 'payment-service', tail: 50 }, + timestamp: new Date().toISOString(), + }; + + const progress = translateNDJSONToSubagentProgress(toolCallEv); + expect(progress).not.toBeNull(); + expect(progress?.agentName).toBe('runtime'); + + const { getCleanOutput, unmount } = renderTUI( + + ); + + const output = getCleanOutput(); + expect(output).toContain('Executing tool: k8s_get_logs'); + unmount(); + }); + + it('TC-E2E-T3-PAIR-03: Codebase Investigator -> Manifest Diff Generation -> DiffRenderer (F-05 + F-07)', async () => { + const mockFiles = { + 'charts/payment/values.yaml': 'resources:\n limits:\n memory: 512Mi\nJAVA_OPTS: "-Xmx768m"\n', + }; + + const report = await CodebaseInvestigatorAgent.run({ + workspaceFiles: mockFiles, + liveClusterState: { memoryLimit: '512Mi' }, + }); + + expect(report.findings[0].patch).toBeDefined(); + + const { getCleanOutput, unmount } = renderTUI( + + ); + + const output = getCleanOutput(); + expect(output).toContain('Manifest Unified Diff'); + expect(output).toContain('memory: 512Mi'); + expect(output).toContain('memory: 1024Mi'); + unmount(); + }); + + it('TC-E2E-T3-PAIR-04: ToolConfirmationQueue -> RemediationExecutor -> Post-Fix Verification (F-07 + F-03)', async () => { + const confirmationRequest: ConfirmationRequest = { + id: 'remed-001', + toolName: 'k8s_apply_patch', + args: { command: 'echo "patch applied successfully"' }, + riskLevel: 'medium', + prompt: 'Apply patch to memory limits?', + }; + + let decision: ConfirmationDecision | null = null; + const { sendKey, wait, unmount, getLastFrame } = renderTUI( + { + decision = d; + }} + /> + ); + + expect(getLastFrame()).toContain('MEDIUM RISK ACTION REQUIRED'); + expect(getLastFrame()).toContain('Apply patch to memory limits?'); + + sendKey('y'); + await wait(50); + unmount(); + + expect(decision).toBe('ALLOW'); + + let execResult; + if (decision === 'ALLOW') { + execResult = await executeRemediationCommand('echo "patch applied successfully"', { + timeoutMs: 5000, + }); + } + expect(execResult).toBeDefined(); + expect(execResult?.success).toBe(true); + expect(execResult?.stdout).toContain('patch applied successfully'); + + const postFixCheck = await k8sGetPodTool.execute({ + name: 'payment-service-8f4b-2x9p', + namespace: 'production', + }); + expect(postFixCheck.pod).toBe('payment-service-8f4b-2x9p'); + }); + + it('TC-E2E-T3-PAIR-05: In-Dashboard "t" Trigger -> Subagent Orchestration -> Live Stream Display (F-10 + F-06)', async () => { + const targetPod = 'payment-service-8f4b-2x9p'; + let triggeredResource = ''; + + const { sendKey, wait, unmount, getLastFrame } = renderTUI( + { + triggeredResource = res; + }} + /> + ); + + sendKey('t'); + await wait(50); + expect(getLastFrame()).toContain(`AI Troubleshooting Session: ${targetPod}`); + expect(triggeredResource).toBe(targetPod); + unmount(); + + const events = MockPythonCouncil.createOOMKilledCouncilEvents(targetPod, 'production'); + const proc = MockPythonCouncil.createMockProcess(events); + + const progressItems: any[] = []; + await new Promise((resolve, reject) => { + proc.on('error', reject); + proc.stdout.on('data', (chunk: Buffer) => { + const lines = chunk.toString().trim().split('\n'); + for (const line of lines) { + if (!line) continue; + const parsed = JSON.parse(line); + const prog = translateNDJSONToSubagentProgress(parsed); + if (prog) progressItems.push(prog); + } + }); + proc.on('close', () => resolve()); + }); + + expect(progressItems.length).toBeGreaterThan(0); + const completedProgress = progressItems.find((p) => p.state === 'completed'); + expect(completedProgress).toBeDefined(); + }); + + it('TC-E2E-T3-PAIR-06: Modern Gemini Client -> Declarative Tools via Function Calling (F-02 + F-03)', async () => { + const builder = new MockGenAIStreamBuilder(); + builder.addFunctionCall('docker_inspect_container', { containerId: 'postgres-local' }); + + const mockClient = builder.createMockClient(); + const response = await mockClient.models.generateContent({ + model: 'gemini-2.5-flash', + contents: 'Inspect postgres-local', + }); + + const call = response.candidates?.[0]?.content?.parts?.find(part => part.functionCall)?.functionCall; + if (!call?.name) throw new Error('Gemini should request a Docker inspection'); + + const registry = new DeclarativeToolRegistry(); + registry.register(dockerInspectContainerTool); + + const toolResult = await registry.invoke(call.name, call.args); + + expect(toolResult.containerId).toBe('postgres-local'); + expect(toolResult.state).toBe('restarting'); + }); + + it('TC-E2E-T3-PAIR-07: Composer accepts /analyze with an explicit workload', async () => { + let submittedCommand = ''; + const { sendKey, stdin, wait, unmount, getLastFrame } = renderTUI( + { submittedCommand = cmd; }} /> + ); + + sendKey('/an'); + await wait(20); + expect(getLastFrame()).toContain('Available Commands:'); + expect(getLastFrame()).toContain('/analyze'); + + sendKey('alyze pod/payment-service'); + await wait(20); + expect(getLastFrame()).toContain('/analyze pod/payment-service'); + + stdin.sendEnter(); + await wait(50); + unmount(); + + expect(submittedCommand).toBe('/analyze pod/payment-service'); + + const parsed = parseSlashCommand(submittedCommand); + expect(parsed?.command).toBe('/analyze'); + expect(parsed?.args).toEqual(['pod/payment-service']); + }); + + it('TC-E2E-T3-PAIR-08: Codebase Investigator -> Multi-Agent Council Synthesis (F-05 + F-04)', async () => { + const registry = new AgentRegistry(); + + registry.register({ + name: 'CodebaseInvestigatorAgent', + description: 'Local repo manifest investigator', + inputSchema: z.object({ prompt: z.string() }), + outputSchema: z.object({ findings: z.array(z.string()) }), + run: async () => ({ findings: ['Discovered JAVA_OPTS -Xmx768m exceeding 512Mi'] }), + }); + + registry.register({ + name: 'SynthesizerAgent', + description: 'Consensus root cause synthesizer', + inputSchema: z.object({ prompt: z.string() }), + outputSchema: z.object({ consensus: z.string() }), + run: async () => ({ consensus: 'Misaligned JVM memory configuration vs cgroup quota' }), + }); + + const agentTool = new AgentTool(registry); + const codebaseRes = await agentTool.execute({ + agent_name: 'CodebaseInvestigatorAgent', + prompt: 'Check Helm charts', + }); + expect(codebaseRes.findings[0]).toContain('-Xmx768m'); + + const synthRes = await agentTool.execute({ + agent_name: 'SynthesizerAgent', + prompt: 'Synthesize findings', + }); + expect(synthRes.consensus).toContain('Misaligned JVM memory'); + }); + + it('TC-E2E-T3-PAIR-09: ToolConfirmationQueue Denial -> Synthesizer Alternative Suggestion (F-07 + F-02)', async () => { + const destructiveRequest: ConfirmationRequest = { + id: 'remed-002', + toolName: 'docker_remove_container', + args: { command: 'docker rm -f postgres-local' }, + riskLevel: 'high', + prompt: 'Permanently remove container postgres-local?', + }; + + let decision: ConfirmationDecision | null = null; + const { sendKey, wait, unmount, getLastFrame } = renderTUI( + { + decision = d; + }} + /> + ); + + expect(getLastFrame()).toContain('HIGH RISK ACTION REQUIRED'); + expect(getLastFrame()).toContain('Permanently remove container'); + + sendKey('n'); + await wait(50); + unmount(); + + expect(decision).toBe('DENY'); + + let mutationExecuted = false; + if (decision === 'ALLOW') { + await executeRemediationCommand('docker rm -f postgres-local'); + mutationExecuted = true; + } + expect(mutationExecuted).toBe(false); + + const builder = new MockGenAIStreamBuilder(); + builder.addText( + 'Remediation was denied by user. Alternative safe recommendation: inspect volume logs or run non-destructive lock file cleanup.' + ); + + const mockClient = builder.createMockClient(); + const response = await mockClient.models.generateContent({ + model: 'gemini-2.5-flash', + contents: `Operator ${decision}ed container removal. Propose non-destructive alternative.`, + }); + + expect(response.text).toContain('Remediation was denied by user'); + expect(response.text).toContain('Alternative safe recommendation'); + }); + + it('TC-E2E-T3-PAIR-10: Non-Interactive CLI Mode -> Declarative Tools -> Structured JSON Output (F-03 + F-09)', async () => { + activeCluster = new MockClusterEnvironment().setHealthyScenario().install(); + + const result = await runCLI(['analyze', '-o', 'json'], { isTTY: false }); + + expect(result.exitCode).toBe(0); + expect(result.stdout).not.toContain('\u001b'); + + expect(result.stdout.trim().startsWith('{')).toBe(true); + const parsed = JSON.parse(result.stdout.trim()); + expect(parsed).toBeDefined(); + expect(['OK', 'ProblemDetected']).toContain(parsed.status); + }); +}); diff --git a/src/__tests__/e2e/tier4-scenarios/scenario-ci-noninteractive-audit.test.ts b/src/__tests__/e2e/tier4-scenarios/scenario-ci-noninteractive-audit.test.ts new file mode 100644 index 00000000..b4eb51c4 --- /dev/null +++ b/src/__tests__/e2e/tier4-scenarios/scenario-ci-noninteractive-audit.test.ts @@ -0,0 +1,66 @@ +import { describe, it, expect, afterEach, vi } from 'vitest'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; +import { runCLI, MockClusterEnvironment } from '../harness'; + +describe('Tier 4: Scenario 4 — Non-Interactive CI Automation: Cluster Health & Log Audit', () => { + let cluster: MockClusterEnvironment | null = null; + let tmpDir = ''; + + afterEach(() => { + if (cluster) { + cluster.reset(); + cluster = null; + } + MockClusterEnvironment.resetActive(); + if (tmpDir && fs.existsSync(tmpDir)) { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + vi.restoreAllMocks(); + }); + + it('executes headless CI audit with pure JSON stdout, audit trail export, and clean zero exit', async () => { + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'kdm-ci-audit-')); + const auditExportPath = path.join(tmpDir, 'audit-session.json'); + + cluster = new MockClusterEnvironment().setHealthyScenario().install(); + + const result = await runCLI( + [ + 'analyze', + '--output', + 'json', + '--namespace', + 'staging', + '--council-timeout', + '10000', + '--export-audit', + auditExportPath, + ], + { isTTY: false } + ); + + // 1. Process exit code must be 0 + expect(result.exitCode).toBe(0); + + // 2. stdout must not contain ANSI escape sequences + expect(result.stdout).not.toContain('\u001b'); + + // 3. stdout must be pure valid JSON directly without substring slicing + expect(result.stdout.trim().startsWith('{')).toBe(true); + const parsedOutput = JSON.parse(result.stdout.trim()); + + expect(parsedOutput).toBeDefined(); + expect(['OK', 'ProblemDetected']).toContain(parsedOutput.status); + expect(typeof parsedOutput.problems).toBe('number'); + + // 4. Verify audit file was exported and contains valid JSON + expect(fs.existsSync(auditExportPath)).toBe(true); + const auditContent = JSON.parse(fs.readFileSync(auditExportPath, 'utf-8')); + expect(auditContent).toBeDefined(); + expect(auditContent.sessionId).toBeDefined(); + expect(auditContent.timestamp).toBeDefined(); + expect(auditContent.target).toBeDefined(); + }); +}); diff --git a/src/__tests__/e2e/tier4-scenarios/scenario-crashloop-patch-approved.test.ts b/src/__tests__/e2e/tier4-scenarios/scenario-crashloop-patch-approved.test.ts new file mode 100644 index 00000000..9f9f8cfd --- /dev/null +++ b/src/__tests__/e2e/tier4-scenarios/scenario-crashloop-patch-approved.test.ts @@ -0,0 +1,99 @@ +import React from 'react'; +import { createTwoFilesPatch } from 'diff'; +import { describe, it, expect, afterEach, vi } from 'vitest'; +import { + renderTUI, + MockClusterEnvironment, + CodebaseInvestigatorAgent, + ToolConfirmationQueueView, + type ConfirmationRequest, + type ConfirmationDecision, +} from '../harness'; +import { executeRemediationCommand, RemediationAuditTrail } from '../../../remediation/executor'; + +async function approveRemediation(confirmationRequest: ConfirmationRequest): Promise { + let userDecision: ConfirmationDecision | null = null; + const { sendKey, wait, unmount, getCleanOutput } = renderTUI( + React.createElement(ToolConfirmationQueueView, { + request: confirmationRequest, + onDecision: (d: ConfirmationDecision) => { userDecision = d; }, + }) + ); + await wait(); + expect(getCleanOutput()).toContain('MEDIUM RISK ACTION REQUIRED'); + expect(getCleanOutput()).toContain('Apply secretKeyRef patch'); + sendKey('y'); + await wait(50); + unmount(); + return userDecision; +} + +describe('Tier 4: Scenario 2 — Incident Triage: CrashLoopBackOff Pod Remediation with Approved Manifest Patch', () => { + let cluster: MockClusterEnvironment | null = null; + + afterEach(() => { + if (cluster) { + cluster.reset(); + cluster = null; + } + MockClusterEnvironment.resetActive(); + vi.restoreAllMocks(); + }); + + it('executes full automated remediation cycle: triage -> diff -> approval -> execution -> audit', async () => { + const podName = 'auth-api-v2-7c91'; + const namespace = 'auth'; + cluster = new MockClusterEnvironment().setCrashLoopBackOffScenario(podName, namespace).install(); + + const manifest = ` +apiVersion: apps/v1 +kind: Deployment +spec: + template: + spec: + containers: + - name: auth-server + env: + - name: DATABASE_URL + valueFrom: + secretKeyRef: + name: auth-secrets + key: db-url +`; + + const investigation = await CodebaseInvestigatorAgent.run({ + workspaceFiles: { 'k8s/auth/deployment.yaml': manifest }, + liveClusterState: { podName, namespace, secretKeys: { 'auth-secrets': ['DATABASE_URL'] } }, + }); + expect(investigation.driftDetected).toBe(true); + expect(investigation.findings[0].issue).toContain('db-url'); + + const corrected = manifest.replace('key: db-url', 'key: DATABASE_URL'); + const diff = createTwoFilesPatch('deployment.yaml', 'deployment.yaml', manifest, corrected); + const command = ['kubectl', 'patch', 'deployment/auth-api-v2', '-n', namespace, '--patch', corrected] as const; + + const confirmationRequest: ConfirmationRequest = { + id: 'conf-auth-001', + toolName: 'k8s_apply_patch', + args: { command: command.join(' '), diff }, + riskLevel: 'medium', + prompt: 'Apply secretKeyRef patch to auth-api-v2 deployment in namespace auth?', + diff, + }; + expect(confirmationRequest.diff).toContain('key: DATABASE_URL'); + + const userDecision = await approveRemediation(confirmationRequest); + expect(userDecision).toBe('ALLOW'); + + const auditTrail = new RemediationAuditTrail(); + const execFileFn = vi.fn().mockResolvedValue({ stdout: 'deployment.apps/auth-api-v2 configured', stderr: '' }); + const result = await executeRemediationCommand(command, { auditTrail, execFileFn }); + + expect(result.success).toBe(true); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('deployment.apps/auth-api-v2 configured'); + expect(execFileFn).toHaveBeenCalledWith('kubectl', command.slice(1), expect.any(Object)); + expect(auditTrail.getRecords()).toHaveLength(1); + expect(auditTrail.getRecords()[0].success).toBe(true); + }); +}); diff --git a/src/__tests__/e2e/tier4-scenarios/scenario-cross-module-synthesis.test.ts b/src/__tests__/e2e/tier4-scenarios/scenario-cross-module-synthesis.test.ts new file mode 100644 index 00000000..53288a04 --- /dev/null +++ b/src/__tests__/e2e/tier4-scenarios/scenario-cross-module-synthesis.test.ts @@ -0,0 +1,41 @@ +import { describe, it, expect, vi } from 'vitest'; +import { + MockPythonCouncil, + translateNDJSONToSubagentProgress, +} from '../harness'; +import { runAgentCouncilProcess, type CouncilBridgeOptions } from '../../../agent/python-bridge'; + +async function runCascadingCouncil(proc: ReturnType) { + const agents = new Set(); + const finalConsensus = await runAgentCouncilProcess({ + failureText: 'Ingress reports 502', + context: { kind: 'Deployment', name: 'checkout' }, + spawnFn: vi.fn(() => proc) as CouncilBridgeOptions['spawnFn'], + onEvent: (event) => { + const progress = translateNDJSONToSubagentProgress(event); + if (progress?.state === 'completed') agents.add(progress.agentName); + }, + }); + return { agents, finalConsensus }; +} + +describe('Tier 4: Scenario 5 — Multi-Agent Synthesis: Cross-Module Root Cause Analysis', () => { + it('correlates multi-agent evidence across ingress, cgroups, and liveness probes to diagnose cascading 502 failure', async () => { + const events = MockPythonCouncil.createCascadingFailureCouncilEvents(); + const proc = MockPythonCouncil.createMockProcess(events); + + const { agents, finalConsensus } = await runCascadingCouncil(proc); + + expect(agents).toEqual(new Set(['runtime', 'resource', 'config', 'SynthesizerAgent'])); + expect(finalConsensus).not.toBeNull(); + expect(finalConsensus.confidence).toBe('high'); + expect(finalConsensus.rootCause).toContain('Cascading failure'); + expect(finalConsensus.rootCause).toContain('CPU throttling'); + expect(finalConsensus.rootCause).toContain('liveness probe timeout'); + expect(finalConsensus.rootCause).toContain('502 Bad Gateway'); + + expect(finalConsensus.bestSolution.steps).toContain('Increase liveness probe timeoutSeconds to 5'); + expect(finalConsensus.bestSolution.steps).toContain('Increase CPU limit to 1500m'); + expect(finalConsensus.bestSolution.commandToRun).toContain('resources":{"limits":{"cpu":"1500m"}}'); + }); +}); diff --git a/src/__tests__/e2e/tier4-scenarios/scenario-docker-restart-denied.test.ts b/src/__tests__/e2e/tier4-scenarios/scenario-docker-restart-denied.test.ts new file mode 100644 index 00000000..611dddc5 --- /dev/null +++ b/src/__tests__/e2e/tier4-scenarios/scenario-docker-restart-denied.test.ts @@ -0,0 +1,91 @@ +import React from 'react'; +import { describe, it, expect, afterEach, vi } from 'vitest'; +import { + renderTUI, + MockClusterEnvironment, + MockGenAIStreamBuilder, + ToolConfirmationQueueView, + dockerInspectContainerTool, + type ConfirmationRequest, + type ConfirmationDecision, +} from '../harness'; +import { executeRemediationCommand } from '../../../remediation/executor'; + +describe('Tier 4: Scenario 3 — Docker Container Restart Loop Investigation with Denied Remediation', () => { + let cluster: MockClusterEnvironment | null = null; + + afterEach(() => { + if (cluster) { + cluster.reset(); + cluster = null; + } + MockClusterEnvironment.resetActive(); + vi.restoreAllMocks(); + }); + + it('handles safety denial gracefully and generates non-destructive alternative recommendation', async () => { + // 1. Setup Docker environment with restarting postgres-local container + const containerName = 'postgres-local'; + cluster = new MockClusterEnvironment().setDockerRestartLoopScenario(containerName).install(); + + // 2. Inspect container state using declarative Docker tool + const inspection = await dockerInspectContainerTool.execute({ containerId: containerName }); + expect(inspection.containerId).toBe(containerName); + expect(inspection.state).toBe('restarting'); + expect(inspection.exitCode).toBe(1); + + // 3. AI proposes destructive container deletion + const destructiveProposal: ConfirmationRequest = { + id: 'conf-docker-001', + toolName: 'docker_remove_container', + args: { command: `docker rm -f ${containerName}` }, + riskLevel: 'high', + prompt: `Permanently delete and recreate container ${containerName}? (Data Loss Risk)`, + }; + + expect(destructiveProposal.riskLevel).toBe('high'); + expect(destructiveProposal.args.command).toContain('docker rm -f'); + + // 4. Operator denies destructive action with 'n' -> 'DENY' via ToolConfirmationQueueView + let operatorDecision: ConfirmationDecision | null = null; + const { sendKey, wait, unmount, getLastFrame } = renderTUI( + React.createElement(ToolConfirmationQueueView, { + request: destructiveProposal, + onDecision: (d: ConfirmationDecision) => { + operatorDecision = d; + }, + }) + ); + + expect(getLastFrame()).toContain('HIGH RISK ACTION REQUIRED'); + expect(getLastFrame()).toContain('Permanently delete and recreate'); + + sendKey('n'); + await wait(50); + unmount(); + + expect(operatorDecision).toBe('DENY'); + + let executedDestructiveCommand = false; + if (operatorDecision === 'ALLOW') { + await executeRemediationCommand(destructiveProposal.args.command as string); + executedDestructiveCommand = true; + } + expect(executedDestructiveCommand).toBe(false); + + // 5. Synthesizer receives denial notice and recommends non-destructive fix + const builder = new MockGenAIStreamBuilder(); + builder.addText( + 'Destructive remediation denied. Non-destructive alternative: Remove the stale postmaster.pid lock file by running `docker exec postgres-local rm /var/lib/postgresql/data/postmaster.pid` or inspect volume mount.' + ); + + const mockClient = builder.createMockClient(); + const alternativeAdvice = await mockClient.models.generateContent({ + model: 'gemini-2.5-flash', + contents: 'User denied docker rm -f. Propose non-destructive fix.', + }); + + expect(alternativeAdvice.text).toContain('Non-destructive alternative'); + expect(alternativeAdvice.text).toContain('postmaster.pid'); + }); +}); diff --git a/src/__tests__/e2e/tier4-scenarios/scenario-oomkilled-triage.test.ts b/src/__tests__/e2e/tier4-scenarios/scenario-oomkilled-triage.test.ts new file mode 100644 index 00000000..072f82d8 --- /dev/null +++ b/src/__tests__/e2e/tier4-scenarios/scenario-oomkilled-triage.test.ts @@ -0,0 +1,100 @@ +import React from 'react'; +import { describe, it, expect, afterEach, vi } from 'vitest'; +import { + renderTUI, + MockClusterEnvironment, + MockPythonCouncil, + CodebaseInvestigatorAgent, + DashboardWithTroubleshootTrigger, + translateNDJSONToSubagentProgress, +} from '../harness'; +import { getRunningPods } from '../../../kubernetes/pods'; + +function collectCouncilStream(proc: ReturnType) { + const rawStreamEvents: any[] = []; + const translatedProgress: any[] = []; + return new Promise<{ rawStreamEvents: any[]; translatedProgress: any[] }>((resolve, reject) => { + proc.on('error', reject); + proc.stdout.on('data', (chunk: Buffer) => { + for (const line of chunk.toString().trim().split('\n')) { + if (!line) continue; + const parsed = JSON.parse(line); + rawStreamEvents.push(parsed); + const prog = translateNDJSONToSubagentProgress(parsed); + if (prog) translatedProgress.push(prog); + } + }); + proc.on('close', () => resolve({ rawStreamEvents, translatedProgress })); + }); +} + +describe('Tier 4: Scenario 1 — Incident Triage: OOMKilled Pod in Production', () => { + let cluster: MockClusterEnvironment | null = null; + + afterEach(() => { + if (cluster) { + cluster.reset(); + cluster = null; + } + MockClusterEnvironment.resetActive(); + vi.restoreAllMocks(); + }); + + it('executes complete 6-stage SRE triage workflow for OOMKilled payment-service pod', async () => { + // Stage 1: Detection + const podName = 'payment-service-8f4b-2x9p'; + const namespace = 'production'; + cluster = new MockClusterEnvironment().setOOMKilledScenario(podName, namespace).install(); + + const failingPod = (await getRunningPods()).find((p) => p.name === podName); + expect(failingPod?.status).toBe('OOMKilled'); + expect(failingPod?.restarts).toBe(5); + + // Stage 2: Trigger + let triggeredPod = ''; + const { sendKey, wait, unmount, getLastFrame } = renderTUI( + React.createElement(DashboardWithTroubleshootTrigger, { + dashboardType: 'watch', + targetResource: failingPod!.name, + onTrigger: (res: string) => { triggeredPod = res; }, + }) + ); + expect(getLastFrame()).toContain(`Selected Resource: ${podName}`); + sendKey('t'); + await wait(50); + expect(getLastFrame()).toContain(`AI Troubleshooting Session: ${podName}`); + expect(triggeredPod).toBe(podName); + unmount(); + + // Stage 3: Specialist Council Dispatch + const proc = MockPythonCouncil.createMockProcess(MockPythonCouncil.createOOMKilledCouncilEvents(podName, namespace)); + const { rawStreamEvents, translatedProgress } = await collectCouncilStream(proc); + expect(translatedProgress.length).toBeGreaterThan(0); + + // Stage 4: Codebase Investigation + const valuesYaml = 'resources:\n limits:\n memory: 512Mi\nenv:\n JAVA_OPTS: "-Xmx768m"\n'; + const codebaseReport = await CodebaseInvestigatorAgent.run({ + workspaceFiles: { 'charts/payment-service/values.yaml': valuesYaml }, + liveClusterState: { memoryLimit: '512Mi', podName }, + }); + expect(codebaseReport.driftDetected).toBe(true); + expect(codebaseReport.findings[0].issue).toContain('-Xmx768m'); + expect(codebaseReport.findings[0].issue).toContain('512Mi'); + + const healthyCheck = await CodebaseInvestigatorAgent.run({ + workspaceFiles: { 'charts/payment-service/values.yaml': valuesYaml.replace('512Mi', '2048Mi') }, + }); + expect(healthyCheck.driftDetected).toBe(false); + + // Stage 5 & 6: Consensus Synthesis & Remediation Proposal + const synthProgress = translatedProgress.find((p) => p.agentName === 'SynthesizerAgent' && p.state === 'completed'); + expect(synthProgress?.result).toContain('misaligned JVM heap (-Xmx768m)'); + const diagnosisEvent = rawStreamEvents.find((e) => e.event === 'diagnosis_ready'); + expect(diagnosisEvent.consensus.confidence).toBe('high'); + expect(diagnosisEvent.consensus.bestSolution.actionTitle).toContain('Align JVM heap'); + + const patch = codebaseReport.findings[0].patch; + expect(patch).toContain('memory: 512Mi'); + expect(patch).toContain('memory: 1024Mi'); + }); +}); diff --git a/src/__tests__/event-translator.test.ts b/src/__tests__/event-translator.test.ts new file mode 100644 index 00000000..7027447d --- /dev/null +++ b/src/__tests__/event-translator.test.ts @@ -0,0 +1,323 @@ +import { describe, it, expect } from 'vitest'; +import { + translateNDJSONToSubagentProgress, + translateNDJSONToAgentEvent, + translateAgentEventToNDJSON, + translateSubagentProgressToNDJSON, + EventTranslator, +} from '../agent/event-translator.js'; +import type { NDJSONEvent, SubagentProgress } from '../agent/types.js'; + +describe('EventTranslator (F-04)', () => { + const timestamp = '2026-11-15T12:00:00Z'; + + it('assembles an event when a multibyte character spans chunks', () => { + const translator = new EventTranslator(); + const message = 'Reading logs 🔍'; + const data = Buffer.from(JSON.stringify({ event: 'agent_progress', role: 'runtime', message, timestamp }) + '\n'); + const boundary = data.indexOf(Buffer.from('🔍')) + 2; + expect(translator.pushChunk(data.subarray(0, boundary))).toEqual([]); + expect(translator.pushChunk(data.subarray(boundary))).toEqual([ + { agentName: 'runtime', state: 'running', thought: message }, + ]); + }); + + it.each([ + [{ type: 'progress', agent: 'runtime', message: 'working' }, { state: 'running', thought: 'working' }], + [{ type: 'agent_completed', finding: { role: 'config', summary: 'checked' } }, { agentName: 'config', state: 'completed', result: 'checked' }], + [{ type: 'complete', consensus: { rootCause: 'Memory limit' } }, { agentName: 'SynthesizerAgent', result: 'Memory limit' }], + [{ type: 'error', message: 'disconnected' }, { agentName: 'council', state: 'error', result: 'disconnected' }], + ])('interprets legacy council event %#', (event, expected) => { + expect(translateNDJSONToSubagentProgress(JSON.stringify(event))).toMatchObject(expected); + }); + + const progressCases: Array<{ event: NDJSONEvent; expected: SubagentProgress }> = [ + { + event: { event: 'agent_start', role: 'runtime', message: 'Inspecting exit codes', timestamp }, + expected: { agentName: 'runtime', state: 'running', thought: 'Inspecting exit codes' }, + }, + { + event: { event: 'agent_tool_call', role: 'config', tool: 'k8s_get_resources', args: { kind: 'configmap' }, timestamp }, + expected: { + agentName: 'config', state: 'running', + toolCall: { name: 'k8s_get_resources', args: { kind: 'configmap' }, status: 'running' }, + }, + }, + { + event: { event: 'agent_tool_result', role: 'config', tool: 'k8s_get_resources', durationMs: 142, timestamp }, + expected: { + agentName: 'config', state: 'running', + toolCall: { name: 'k8s_get_resources', args: {}, status: 'success', output: 'completed in 142ms' }, + }, + }, + { + event: { event: 'agent_progress', role: 'resource', message: 'Evaluating memory counters', timestamp }, + expected: { agentName: 'resource', state: 'running', thought: 'Evaluating memory counters' }, + }, + { + event: { event: 'agent_complete', role: 'runtime', summary: 'Container was OOMKilled', timestamp }, + expected: { agentName: 'runtime', state: 'completed', result: 'Container was OOMKilled' }, + }, + { + event: { event: 'agent_failed', role: 'config', error: 'Config query failed', timestamp }, + expected: { agentName: 'config', state: 'error', result: 'Config query failed' }, + }, + ]; + + it.each(progressCases)('translates $event.event to subagent progress', ({ event, expected }) => { + expect(translateNDJSONToSubagentProgress(event)).toEqual(expected); + }); + + it('TC-EVT-07: Translate diagnosis_ready to SubagentProgress with SynthesizerAgent', () => { + const event: NDJSONEvent = { + event: 'diagnosis_ready', + timestamp, + consensus: { + rootCause: 'JVM -Xmx768m exceeded container 512Mi limit', + confidence: 'high', + findings: [], + bestSolution: { + actionTitle: 'Increase memory limit to 1024Mi', + steps: ['kubectl set resources deployment/app --limits=memory=1024Mi'], + riskLevel: 'low', + }, + }, + }; + + const progress = translateNDJSONToSubagentProgress(event); + expect(progress).toEqual({ + agentName: 'SynthesizerAgent', + state: 'completed', + result: 'JVM -Xmx768m exceeded container 512Mi limit', + }); + }); + + it('TC-EVT-08: Non-agent lifecycle events return null', () => { + expect( + translateNDJSONToSubagentProgress({ + event: 'analysis_start', + analysisId: 'ana-123', + timestamp, + }) + ).toBeNull(); + + expect( + translateNDJSONToSubagentProgress({ + event: 'evidence_collected', + count: 5, + ids: ['ev-1', 'ev-2'], + timestamp, + }) + ).toBeNull(); + + expect( + translateNDJSONToSubagentProgress({ + event: 'rule_matched', + ruleId: 'R-01', + title: 'OOMKilled Rule', + timestamp, + }) + ).toBeNull(); + + // Non-fatal error returns null + expect( + translateNDJSONToSubagentProgress({ + event: 'error', + message: 'minor warning', + fatal: false, + timestamp, + }) + ).toBeNull(); + + // Fatal error maps to council error + expect( + translateNDJSONToSubagentProgress({ + event: 'error', + message: 'fatal crash', + fatal: true, + timestamp, + }) + ).toEqual({ + agentName: 'council', + state: 'error', + result: 'fatal crash', + }); + }); + + it('TC-EVT-09: Malformed, corrupt, or invalid NDJSON input returns null safely', () => { + expect(translateNDJSONToSubagentProgress(null)).toBeNull(); + expect(translateNDJSONToSubagentProgress(undefined)).toBeNull(); + expect(translateNDJSONToSubagentProgress('')).toBeNull(); + expect(translateNDJSONToSubagentProgress(' ')).toBeNull(); + expect(translateNDJSONToSubagentProgress('not json')).toBeNull(); + expect(translateNDJSONToSubagentProgress('{ corrupt: json')).toBeNull(); + expect(translateNDJSONToSubagentProgress(12345 as any)).toBeNull(); + expect(translateNDJSONToSubagentProgress({ unknown: 'field' } as any)).toBeNull(); + }); + + it('TC-EVT-10: Legacy Python council event backward compatibility', () => { + expect( + translateNDJSONToSubagentProgress({ + type: 'progress', + agent: 'RuntimeLogAgent', + message: 'Processing stack traces...', + }) + ).toEqual({ + agentName: 'RuntimeLogAgent', + state: 'running', + thought: 'Processing stack traces...', + }); + + expect( + translateNDJSONToSubagentProgress({ + type: 'agent_completed', + agent: 'ConfigDependencyAgent', + finding: { summary: 'Missing configmap app-config' }, + }) + ).toEqual({ + agentName: 'ConfigDependencyAgent', + state: 'completed', + result: 'Missing configmap app-config', + }); + + expect( + translateNDJSONToSubagentProgress({ + type: 'complete', + consensus: { rootCause: 'OOMKill verified' }, + }) + ).toEqual({ + agentName: 'SynthesizerAgent', + state: 'completed', + result: 'OOMKill verified', + }); + }); + + it('TC-EVT-11: Bidirectional translation between NDJSONEvent and AgentEvent', () => { + const ndjson: NDJSONEvent = { + event: 'agent_tool_call', + role: 'runtime', + tool: 'docker_logs', + args: { containerId: 'c123', tail: 50 }, + timestamp, + }; + + const agentEvent = translateNDJSONToAgentEvent(ndjson); + expect(agentEvent).not.toBeNull(); + expect(agentEvent?.type).toBe('tool_call'); + expect(agentEvent?.agentName).toBe('runtime'); + expect(agentEvent?.payload.tool).toBe('docker_logs'); + expect(agentEvent?.payload.args).toEqual({ containerId: 'c123', tail: 50 }); + + const backToNDJSON = translateAgentEventToNDJSON(agentEvent!); + expect(backToNDJSON).toEqual({ + event: 'agent_tool_call', + role: 'runtime', + tool: 'docker_logs', + args: { containerId: 'c123', tail: 50 }, + timestamp, + }); + }); + + it('TC-EVT-12: SubagentProgress translation back to NDJSON', () => { + const progress: SubagentProgress = { + agentName: 'resource', + state: 'completed', + result: 'Node memory is healthy', + }; + + const ndjson = translateSubagentProgressToNDJSON(progress); + expect(ndjson).not.toBeNull(); + expect(ndjson?.event).toBe('agent_complete'); + expect((ndjson as any).role).toBe('resource'); + expect((ndjson as any).summary).toBe('Node memory is healthy'); + }); + + it('preserves failed tool call error state when translating to NDJSON and back', () => { + const failedTool: SubagentProgress = { + agentName: 'runtime', + state: 'running', + toolCall: { name: 'k8s_get_logs', args: { pod: 'api' }, status: 'error', output: 'Forbidden' }, + }; + const ndjson = translateSubagentProgressToNDJSON(failedTool); + expect(ndjson?.event).toBe('agent_failed'); + expect(translateNDJSONToSubagentProgress(ndjson)).toEqual({ + agentName: 'runtime', + state: 'error', + result: 'Forbidden', + }); + }); + + it('preserves durationMs across tool_result AgentEvent round-trip', () => { + const ndjsonEvent = { + event: 'agent_tool_result' as const, + role: 'runtime', + tool: 'k8s_get_logs', + durationMs: 142, + timestamp, + }; + const agentEvent = translateNDJSONToAgentEvent(ndjsonEvent); + expect(agentEvent?.payload.durationMs).toBe(142); + expect(translateAgentEventToNDJSON(agentEvent!)).toEqual(ndjsonEvent); + }); + + it('TC-EVT-13: EventTranslator stateful chunk buffer and reassembly', () => { + const translator = new EventTranslator(); + + const line1 = JSON.stringify({ + event: 'agent_start', + role: 'runtime', + message: 'Started step 1', + timestamp, + }); + const line2 = JSON.stringify({ + event: 'agent_complete', + role: 'runtime', + summary: 'Completed step 1', + timestamp, + }); + + // Split line1 into two chunks across arbitrary byte boundary + const chunk1 = line1.slice(0, 20); + const chunk2 = line1.slice(20) + '\n' + line2.slice(0, 25); + const chunk3 = line2.slice(25) + '\n'; + + const res1 = translator.pushChunk(chunk1); + expect(res1).toHaveLength(0); // Incomplete line buffered + + const res2 = translator.pushChunk(chunk2); + expect(res2).toHaveLength(1); // line1 complete! + expect(res2[0].state).toBe('running'); + expect(res2[0].thought).toBe('Started step 1'); + + const res3 = translator.pushChunk(chunk3); + expect(res3).toHaveLength(1); // line2 complete! + expect(res3[0].state).toBe('completed'); + expect(res3[0].result).toBe('Completed step 1'); + + // Test flush with trailing fragment without newline + const line3 = JSON.stringify({ + event: 'agent_progress', + role: 'resource', + message: 'Trailing item', + timestamp, + }); + translator.pushChunk(line3); // No trailing newline + const flushed = translator.flush(); + expect(flushed).toHaveLength(1); + expect(flushed[0].thought).toBe('Trailing item'); + }); + + it('TC-EVT-14: EventTranslator.serializeNDJSON', () => { + const serialized = EventTranslator.serializeNDJSON({ + event: 'agent_start', + role: 'runtime', + message: 'Starting inspection', + timestamp, + }); + + expect(serialized.endsWith('\n')).toBe(true); + const parsed = JSON.parse(serialized.trim()); + expect(parsed.event).toBe('agent_start'); + expect(parsed.role).toBe('runtime'); + }); +}); diff --git a/src/__tests__/multi-agent-coordination.test.ts b/src/__tests__/multi-agent-coordination.test.ts new file mode 100644 index 00000000..4c879079 --- /dev/null +++ b/src/__tests__/multi-agent-coordination.test.ts @@ -0,0 +1,265 @@ +import { describe, it, expect, beforeEach } from 'vitest'; +import { z } from 'zod'; +import { AgentRegistry } from '../agent/registry.js'; +import { AgentTool } from '../agent/agent-tool.js'; +import { CodebaseInvestigatorAgent } from '../agent/investigator.js'; +import { EventTranslator } from '../agent/event-translator.js'; +import type { AgentContext, NDJSONEvent } from '../agent/types.js'; + +describe('Multi-Agent Coordination Protocol (F-04, F-05)', () => { + let registry: AgentRegistry; + let agentTool: AgentTool; + + beforeEach(() => { + registry = new AgentRegistry(); + agentTool = new AgentTool(registry, 2); + }); + + it('TC-COORD-01: Orchestrator delegates to registered agent via AgentTool', async () => { + registry.register({ + name: 'RuntimeLogAgent', + description: 'Analyzes runtime logs and exit codes', + inputSchema: z.object({ prompt: z.string() }), + outputSchema: z.object({ finding: z.string(), exitCode: z.number() }), + run: async (input) => ({ + finding: `Analyzed logs for: ${input.prompt}`, + exitCode: 137, + }), + }); + + const result = await agentTool.execute({ + agent_name: 'RuntimeLogAgent', + prompt: 'pod payment-api-7b89 crashed', + }); + + expect(result.exitCode).toBe(137); + expect(result.finding).toContain('pod payment-api-7b89 crashed'); + }); + + it('TC-COORD-02: Delegation to missing agent throws informative error', async () => { + registry.register({ + name: 'ConfigDependencyAgent', + description: 'Config specialist', + inputSchema: z.object({ prompt: z.string() }), + outputSchema: z.object({ ok: z.boolean() }), + run: async () => ({ ok: true }), + }); + + await expect( + agentTool.execute({ + agent_name: 'UnknownSpecialist', + prompt: 'investigate', + }) + ).rejects.toThrow(/Agent 'UnknownSpecialist' not found\. Available: ConfigDependencyAgent/); + }); + + it('TC-COORD-03: Max delegation recursion depth throws MaxDelegationDepthExceededError', async () => { + registry.register({ + name: 'RecursiveAgent', + description: 'Calls itself', + inputSchema: z.object({ prompt: z.string() }), + outputSchema: z.object({ result: z.string() }), + run: async (_input, ctx) => { + // Delegate again using tool + return agentTool.execute({ + agent_name: 'RecursiveAgent', + prompt: 'recursive call', + depth: (ctx?.depth ?? 0), + }); + }, + }); + + // Start at depth 2 (maxDepth is 2) + await expect( + agentTool.execute({ + agent_name: 'RecursiveAgent', + prompt: 'trigger recursion', + depth: 2, + }) + ).rejects.toThrow(/MaxDelegationDepthExceededError: Depth 2 exceeded max limit 2/); + }); + + it('TC-COORD-04: Parameter and output schema validation across delegation boundary', async () => { + registry.register({ + name: 'StrictAgent', + description: 'Strict schema agent', + inputSchema: z.object({ + prompt: z.string(), + mode: z.enum(['fast', 'deep']), + }), + outputSchema: z.object({ + status: z.literal('SUCCESS'), + score: z.number().min(0).max(100), + }), + run: async (input) => ({ + status: 'SUCCESS' as const, + score: input.mode === 'deep' ? 95 : 60, + }), + }); + + // Valid call with direct input object + const validResult = await agentTool.execute({ + agent_name: 'StrictAgent', + prompt: 'diagnose', + input: { prompt: 'diagnose', mode: 'deep' }, + }); + expect(validResult.score).toBe(95); + + // Invalid call violating agent inputSchema + await expect( + agentTool.execute({ + agent_name: 'StrictAgent', + prompt: 'diagnose', + input: { prompt: 'diagnose', mode: 'invalid-mode' as any }, + }) + ).rejects.toThrow(); + }); + + it('TC-COORD-05: Context propagation through delegation tool', async () => { + let capturedContext: AgentContext | undefined; + + registry.register({ + name: 'ContextObservingAgent', + description: 'Inspects context', + inputSchema: z.object({ prompt: z.string() }), + outputSchema: z.object({ captured: z.boolean() }), + run: async (_input, ctx) => { + capturedContext = ctx; + return { captured: true }; + }, + }); + + const abortController = new AbortController(); + await agentTool.execute( + { + agent_name: 'ContextObservingAgent', + prompt: 'test context', + context: { namespace: 'production', clusterContext: 'gke-us-east1' }, + }, + { + signal: abortController.signal, + dryRun: true, + } + ); + + expect(capturedContext).toBeDefined(); + expect(capturedContext?.namespace).toBe('production'); + expect(capturedContext?.clusterContext).toBe('gke-us-east1'); + expect(capturedContext?.signal).toBe(abortController.signal); + expect(capturedContext?.dryRun).toBe(true); + expect(capturedContext?.depth).toBe(1); + }); + + it('TC-COORD-06: Unified OOMKill triage pipeline with specialists + CodebaseInvestigator', async () => { + // 1. Register domain specialists + registry.register({ + name: 'RuntimeLogAgent', + description: 'Container logs and exit code specialist', + inputSchema: z.object({ prompt: z.string() }), + outputSchema: z.object({ exitCode: z.number(), reason: z.string() }), + run: async () => ({ exitCode: 137, reason: 'OOMKilled' }), + }); + + registry.register({ + name: 'ClusterResourceAgent', + description: 'Node pressure and cgroup specialist', + inputSchema: z.object({ prompt: z.string() }), + outputSchema: z.object({ containerLimit: z.string(), nodePressure: z.boolean() }), + run: async () => ({ containerLimit: '512Mi', nodePressure: false }), + }); + + // 2. Register CodebaseInvestigatorAgent + registry.register(CodebaseInvestigatorAgent.toDefinition()); + + // 3. Execute specialist diagnostics + const runtimeResult = await agentTool.execute({ + agent_name: 'RuntimeLogAgent', + prompt: 'Check auth-service pod termination', + }); + expect(runtimeResult.exitCode).toBe(137); + + const resourceResult = await agentTool.execute({ + agent_name: 'ClusterResourceAgent', + prompt: 'Check auth-service memory limits', + }); + expect(resourceResult.containerLimit).toBe('512Mi'); + + // 4. Codebase investigator searches workspace manifests with cluster context + const codebaseResult = await agentTool.execute({ + agent_name: 'CodebaseInvestigatorAgent', + prompt: 'Inspect workspace Dockerfiles and manifests for JVM memory mismatch', + input: { + workspaceFiles: { + Dockerfile: + 'FROM eclipse-temurin:17\nENV JAVA_OPTS="-Xmx768m"\nENTRYPOINT ["java", "$JAVA_OPTS", "-jar", "app.jar"]\n', + }, + liveClusterState: { + memoryLimit: resourceResult.containerLimit, + exitCode: runtimeResult.exitCode, + }, + }, + }); + + expect(codebaseResult.driftDetected).toBe(true); + expect(codebaseResult.findings).toHaveLength(1); + expect(codebaseResult.findings[0].issue).toContain('-Xmx768m'); + expect(codebaseResult.findings[0].issue).toContain('512Mi'); + }); + + it('TC-COORD-07: Multi-agent stream event translation to UI progress state', () => { + const translator = new EventTranslator(); + const timestamp = '2026-11-15T12:00:00Z'; + + const events: NDJSONEvent[] = [ + { event: 'agent_start', role: 'runtime', message: 'Analyzing container crash', timestamp }, + { + event: 'agent_tool_call', + role: 'runtime', + tool: 'k8s_get_logs', + args: { pod: 'auth-api' }, + timestamp, + }, + { + event: 'agent_tool_result', + role: 'runtime', + tool: 'k8s_get_logs', + durationMs: 45, + timestamp, + }, + { event: 'agent_complete', role: 'runtime', summary: 'Exit code 137 verified', timestamp }, + { + event: 'diagnosis_ready', + timestamp, + consensus: { + rootCause: 'OOMKilled due to JVM heap mismatch', + confidence: 'high', + findings: [], + bestSolution: { + actionTitle: 'Increase memory limit', + steps: ['Apply manifest patch'], + riskLevel: 'low', + }, + }, + }, + ]; + + const streamChunk = events.map((e) => JSON.stringify(e)).join('\n') + '\n'; + const progressList = translator.pushChunk(streamChunk); + + expect(progressList).toHaveLength(5); + expect(progressList[0].state).toBe('running'); + expect(progressList[1].toolCall?.name).toBe('k8s_get_logs'); + expect(progressList[2].toolCall?.status).toBe('success'); + expect(progressList[3].state).toBe('completed'); + expect(progressList[4].agentName).toBe('SynthesizerAgent'); + expect(progressList[4].result).toContain('OOMKilled due to JVM heap mismatch'); + }); + + it('TC-COORD-08: Gemini FunctionDeclaration conversion via toGeminiToolDeclaration()', () => { + const declaration = agentTool.toGeminiToolDeclaration(); + expect(declaration.name).toBe('delegate_to_agent'); + expect(declaration.description).toContain('Delegates a specialized investigation'); + expect(declaration.parameters).toBeDefined(); + expect(declaration.parameters?.type).toBe('OBJECT'); + }); +}); diff --git a/src/__tests__/resource-table.test.tsx b/src/__tests__/resource-table.test.tsx index d32dfea8..e7af33d8 100644 --- a/src/__tests__/resource-table.test.tsx +++ b/src/__tests__/resource-table.test.tsx @@ -46,7 +46,7 @@ describe('ResourceTable', () => { ]; const app = render( , - { stdin, stdout, debug: true }, + { stdin: stdin as any, stdout: stdout as any, debug: true }, ); await new Promise((resolve) => setTimeout(resolve, 50)); diff --git a/src/__tests__/subagent-progress-ui.test.tsx b/src/__tests__/subagent-progress-ui.test.tsx new file mode 100644 index 00000000..fb0d10c0 --- /dev/null +++ b/src/__tests__/subagent-progress-ui.test.tsx @@ -0,0 +1,516 @@ +import React, { useEffect } from 'react'; +import { describe, it, expect } from 'vitest'; +import { Text } from 'ink'; +import { renderTUI, stripAnsi } from './e2e/harness/tui-test-utils.js'; +import { + ThinkingMessage, + compactPreview, + isNoise, + normalizeEscapedNewlines, +} from '../ui/components/ThinkingMessage.js'; +import { + SubagentProgressDisplay, + formatToolArgs, + type SubagentProgress, +} from '../ui/components/SubagentProgressDisplay.js'; +import { StreamingProvider, useStreaming } from '../ui/contexts/StreamingContext.js'; + +describe('F-06: Subagent Progress & Thought UI', () => { + it('TC-PROGRESS-01: Subagent status: running renders spinner and agent name', () => { + const progress: SubagentProgress = { + agentName: 'RuntimeLogAgent', + state: 'running', + thought: 'Analyzing container stdout logs for fatal panics', + }; + + const { getCleanOutput, unmount } = renderTUI( + + ); + + const output = getCleanOutput(); + expect(output).toContain('Runtime Agent'); + expect(output).toContain('Analyzing container stdout logs'); + expect(output).toContain('1 running'); + unmount(); + }); + + it('TC-PROGRESS-02: Subagent status: completed renders green checkmark ✔ and result text', () => { + const progress: SubagentProgress = { + agentName: 'ConfigDependencyAgent', + state: 'completed', + result: 'Identified secretKeyRef mismatch: db-url vs DATABASE_URL', + }; + + const { getCleanOutput, unmount } = renderTUI( + + ); + + const output = getCleanOutput(); + expect(output).toContain('✔'); + expect(output).toContain('Config Agent'); + expect(output).toContain('Identified secretKeyRef mismatch'); + expect(output).toContain('1 completed'); + unmount(); + }); + + it('TC-PROGRESS-03: Subagent status: error renders red ✖ and error message', () => { + const progress: SubagentProgress = { + agentName: 'ClusterResourceAgent', + state: 'error', + result: 'Kubernetes API connection refused: ETIMEDOUT', + }; + + const { getCleanOutput, unmount } = renderTUI( + + ); + + const output = getCleanOutput(); + expect(output).toContain('✖'); + expect(output).toContain('Resource Agent'); + expect(output).toContain('Kubernetes API connection refused: ETIMEDOUT'); + expect(output).toContain('1 failed'); + unmount(); + }); + + it('TC-PROGRESS-04: Subagent status: cancelled renders warning indicator and cancellation notice', () => { + const progress: SubagentProgress = { + agentName: 'SynthesizerAgent', + state: 'cancelled', + toolCall: { + name: 'k8s_delete_pod', + args: { pod: 'auth-svc-123' }, + status: 'running', + }, + }; + + const { getCleanOutput, unmount } = renderTUI( + + ); + + const output = getCleanOutput(); + expect(output).toContain('ℹ'); + expect(output).toContain('Subagent SynthesizerAgent was cancelled.'); + expect(output).toContain('1 cancelled'); + unmount(); + }); + + it('TC-PROGRESS-05: Streaming thoughts (ThinkingMessage with 💭)', () => { + const thoughtText = 'Correlating exit code 137 with pod cgroup limit'; + const { getCleanOutput, unmount } = renderTUI( + + ); + + const output = getCleanOutput(); + expect(output).toContain('💭'); + expect(output).toContain(thoughtText); + unmount(); + }); + + it('TC-PROGRESS-06: Empty thought stream consumes zero vertical space', () => { + const { getCleanOutput, unmount } = renderTUI( + + ); + + const output = getCleanOutput(); + expect(output.trim()).toBe(''); + unmount(); + + const { getCleanOutput: getWhitespaceOutput, unmount: unmountWs } = renderTUI( + + ); + expect(getWhitespaceOutput().trim()).toBe(''); + unmountWs(); + }); + + it('TC-PROGRESS-07: ThinkingMessage filters noise dots ("...")', () => { + expect(isNoise('...')).toBe(true); + expect(isNoise('......')).toBe(true); + expect(isNoise('Real thought')).toBe(false); + + const { getCleanOutput, unmount } = renderTUI( + + ); + + expect(getCleanOutput().trim()).toBe(''); + unmount(); + }); + + it('TC-PROGRESS-08: ThinkingMessage compact preview truncates long reasoning traces (>1500 chars)', () => { + const longTrace = 'Z'.repeat(2000); + const { getCleanOutput, unmount } = renderTUI( + + ); + + const output = getCleanOutput(); + expect(output).toContain('... [+more]'); + unmount(); + + expect(compactPreview('Short text', 120)).toBe('Short text'); + expect(compactPreview('A'.repeat(150), 120)).toContain('... [+more]'); + }); + + it('TC-PROGRESS-09: Active tool invocation sub-panel renders tool name and arguments', () => { + const progress: SubagentProgress = { + agentName: 'RuntimeLogAgent', + state: 'running', + toolCall: { + name: 'k8s_get_logs', + args: { pod: 'auth-svc', tail: 50, namespace: 'production' }, + status: 'running', + }, + }; + + const { getCleanOutput, unmount } = renderTUI( + + ); + + const output = getCleanOutput(); + expect(output).toContain('⚡ Active Tool:'); + expect(output).toContain('k8s_get_logs'); + expect(output).toContain('pod="auth-svc"'); + expect(output).toContain('tail=50'); + unmount(); + }); + + it('TC-PROGRESS-10: Tool call completion duration display', () => { + const progress: SubagentProgress = { + agentName: 'ConfigDependencyAgent', + state: 'completed', + toolCall: { + name: 'k8s_get_manifest', + args: { file: 'deployment.yaml' }, + status: 'success', + output: 'completed in 45ms', + }, + }; + + const { getCleanOutput, unmount } = renderTUI( + + ); + + const output = getCleanOutput(); + expect(output).toContain('⚡ Active Tool:'); + expect(output).toContain('k8s_get_manifest'); + expect(output).toContain('completed in 45ms'); + unmount(); + }); + + it('TC-PROGRESS-11: Stacked parallel multi-agent progress cards layout', () => { + const subagents: SubagentProgress[] = [ + { agentName: 'RuntimeLogAgent', state: 'completed', result: 'Exit code 137 found' }, + { agentName: 'ConfigDependencyAgent', state: 'running', thought: 'Checking memory requests' }, + { agentName: 'ClusterResourceAgent', state: 'running', thought: 'Inspecting node allocatable' }, + { agentName: 'SynthesizerAgent', state: 'completed', result: 'OOMKilled root cause verified' }, + ]; + + const { getCleanOutput, unmount } = renderTUI( + + ); + + const output = getCleanOutput(); + expect(output).toContain('Runtime Agent'); + expect(output).toContain('Config Agent'); + expect(output).toContain('Resource Agent'); + expect(output).toContain('Lead SRE'); + expect(output).toContain('Exit code 137 found'); + expect(output).toContain('Checking memory requests'); + expect(output).toContain('OOMKilled root cause verified'); + unmount(); + }); + + it('TC-PROGRESS-12: Interactive card expansion via Ctrl+O keypress', async () => { + const subagents: SubagentProgress[] = [ + { + agentName: 'RuntimeLogAgent', + state: 'completed', + thought: 'Deep memory investigation details here', + toolCall: { + name: 'k8s_get_logs', + args: { pod: 'auth-svc' }, + status: 'success', + output: 'Full 500 lines of container output logs', + }, + result: 'Root cause confirmed', + }, + ]; + + const { stdin, wait, getLastFrame, unmount } = renderTUI( + + ); + + expect(stripAnsi(getLastFrame())).toContain('ctrl+o to expand'); + + // Send Ctrl+O (\u000f) + stdin.send('\u000f'); + await wait(40); + + const expandedOutput = stripAnsi(getLastFrame()); + expect(expandedOutput).toContain('ctrl+o to collapse'); + expect(expandedOutput).toContain('Output: Full 500 lines of container output logs'); + + // Send Ctrl+O again to collapse + stdin.send('\u000f'); + await wait(40); + + const collapsedOutput = stripAnsi(getLastFrame()); + expect(collapsedOutput).toContain('ctrl+o to expand'); + + unmount(); + }); + + it('TC-PROGRESS-13: Reactivity via StreamingContext and NDJSON mapping', async () => { + const TestConsumer: React.FC = () => { + const { subagents, processNDJSON } = useStreaming(); + + useEffect(() => { + // Emit simulated agent events + processNDJSON({ + event: 'agent_start', + role: 'runtime', + message: 'Inspecting auth container logs', + timestamp: new Date().toISOString(), + }); + processNDJSON({ + event: 'agent_tool_call', + role: 'runtime', + tool: 'k8s_get_logs', + args: { pod: 'auth-api', lines: 100 }, + timestamp: new Date().toISOString(), + }); + }, [processNDJSON]); + + return ; + }; + + const { wait, getLastFrame, unmount } = renderTUI( + + + + ); + + await wait(50); + const output = stripAnsi(getLastFrame()); + expect(output).toContain('Runtime Agent'); + expect(output).toContain('k8s_get_logs'); + expect(output).toContain('pod="auth-api"'); + unmount(); + }); + + it('TC-PROGRESS-14: Terminal viewport narrower than card minimum width (40 cols) wraps safely', () => { + const progress: SubagentProgress = { + agentName: 'RuntimeLogAgent', + state: 'running', + thought: 'A very long diagnostic reasoning string that must wrap properly without throwing any bounds error', + }; + + const { getCleanOutput, unmount } = renderTUI( + , + { columns: 35, rows: 20 } + ); + + const output = getCleanOutput(); + expect(output.length).toBeGreaterThan(0); + expect(output).toContain('Runtime'); + unmount(); + }); + + it('TC-PROGRESS-15: formatToolArgs and normalizeEscapedNewlines helpers', () => { + expect(formatToolArgs({ pod: 'checkout', tail: 50 })).toBe('pod="checkout", tail=50'); + expect(formatToolArgs('{"pod":"checkout"}')).toBe('pod="checkout"'); + expect(formatToolArgs(undefined)).toBe(''); + + expect(normalizeEscapedNewlines('Line 1\\nLine 2')).toBe('Line 1\nLine 2'); + expect(normalizeEscapedNewlines(undefined)).toBe(''); + }); + + it('TC-PROGRESS-16: formatToolArgs safely handles BigInt and circular structures without crashing', () => { + // BigInt handling + const bigIntArgs = { memoryBytes: BigInt(1073741824) }; + expect(formatToolArgs(bigIntArgs)).toBe('memoryBytes=1073741824n'); + + // Circular reference handling + const circ: any = { key: 'value' }; + circ.self = circ; + expect(() => formatToolArgs({ circ })).not.toThrow(); + expect(formatToolArgs({ circ })).toContain('circ=[Complex]'); + }); + + it('TC-PROGRESS-17: isNoise recognizes unicode ellipsis and spaced dot patterns', () => { + expect(isNoise('…')).toBe(true); + expect(isNoise('...')).toBe(true); + expect(isNoise('. . .')).toBe(true); + expect(isNoise('… …')).toBe(true); + expect(isNoise(' . . ')).toBe(true); + expect(isNoise('Thinking...')).toBe(false); + + const { getCleanOutput, unmount } = renderTUI(); + expect(getCleanOutput().trim()).toBe(''); + unmount(); + }); + + it('TC-PROGRESS-18: ThinkingMessage caps ThoughtSummary description lines', () => { + const manyLines = Array.from({ length: 100 }, (_, i) => `Thought line ${i + 1}`).join('\n'); + const thoughtObj = { + subject: 'Root Cause Investigation', + description: manyLines, + }; + + // Full view caps at 50 description lines + const { getCleanOutput, unmount } = renderTUI( + + ); + const output = getCleanOutput(); + expect(output).toContain('Thought line 1'); + expect(output).toContain('Thought line 50'); + expect(output).toContain('... [+more]'); + expect(output).not.toContain('Thought line 55'); + unmount(); + + // Compact view caps at 3 lines + const { getCleanOutput: getCompactOutput, unmount: unmountCompact } = renderTUI( + + ); + const compactOutput = getCompactOutput(); + expect(compactOutput).toContain('Thought line 1'); + expect(compactOutput).toContain('Thought line 3'); + expect(compactOutput).toContain('... [+more]'); + expect(compactOutput).not.toContain('Thought line 10'); + unmountCompact(); + }); + + it('TC-PROGRESS-19: StreamingContext maps agent_tool_result to subagent toolCall success status', async () => { + const TestConsumer: React.FC = () => { + const { subagents, processNDJSON } = useStreaming(); + + useEffect(() => { + processNDJSON({ + event: 'agent_start', + role: 'runtime', + message: 'Inspecting auth container logs', + timestamp: new Date().toISOString(), + }); + processNDJSON({ + event: 'agent_tool_call', + role: 'runtime', + tool: 'k8s_get_logs', + args: { pod: 'auth-api' }, + timestamp: new Date().toISOString(), + }); + // Immediately complete tool call + processNDJSON({ + event: 'agent_tool_result', + role: 'runtime', + tool: 'k8s_get_logs', + durationMs: 45, + timestamp: new Date().toISOString(), + }); + }, [processNDJSON]); + + return ; + }; + + const { wait, getLastFrame, unmount } = renderTUI( + + + + ); + + await wait(60); + const output = stripAnsi(getLastFrame()); + expect(output).toContain('Runtime Agent'); + expect(output).toContain('k8s_get_logs'); + expect(output).toContain('pod="auth-api"'); + expect(output).toContain('completed in 45ms'); + expect(output).toContain('✔'); // Green checkmark for toolCall success + unmount(); + }); + + it('tracks concurrent tool calls independently without overwriting arguments', async () => { + let session: ReturnType; + function Consumer() { + session = useStreaming(); + return {session.activeTools.map((t) => `${t.agentName}:${t.status}`).join(',')}; + } + const { wait, unmount } = renderTUI(); + try { + const idA = session!.startToolCall({ agentName: 'runtime', toolName: 'k8s_get_logs', args: { pod: 'api-a' } }); + const idB = session!.startToolCall({ agentName: 'config', toolName: 'k8s_get_logs', args: { pod: 'api-b' } }); + await wait(); + expect(session!.activeTools).toHaveLength(2); + session!.finishToolCall({ id: idA, toolName: 'k8s_get_logs', status: 'success', output: 'ok', durationMs: 12 }); + await wait(); + expect(session!.activeTools.find((t) => t.id === idA)?.status).toBe('success'); + expect(session!.activeTools.find((t) => t.id === idB)?.status).toBe('running'); + } finally { + unmount(); + } + }); + + it('tracks tool output, errors, and stream reset through the provider', async () => { + let session: ReturnType; + function Consumer() { + session = useStreaming(); + return {session.activeThought}; + } + const { wait, unmount } = renderTUI(); + try { + session!.updateSubagentProgress({ agentName: 'runtime', state: 'running' }); + session!.setThought('runtime', 'Reading'); + session!.appendThought('runtime', ' pod status'); + const id = session!.startToolCall({ agentName: 'runtime', toolName: 'list', args: {} }); + session!.finishToolCall({ toolName: 'list', status: 'error', output: 'Unavailable' }); + await wait(); + expect(session!.activeThought).toBe('Reading pod status'); + expect(session!.activeTool).toMatchObject({ id, status: 'error', output: 'Unavailable' }); + expect(session!.isStreaming).toBe(true); + + session!.setStreamingThought('Finishing'); + session!.setStreamError('Connection closed'); + session!.setActiveTool(null); + await wait(); + expect(session!.activeThought).toBe('Finishing'); + expect(session!.activeTool).toBeNull(); + expect(session!.streamError).toBe('Connection closed'); + expect(session!.isStreaming).toBe(false); + + session!.clearStream(); + await wait(); + expect(session!.streamError).toBeNull(); + expect(session!.subagents).toEqual([]); + } finally { + unmount(); + } + }); + + it('keeps agent constraint on finishToolCall fallback and isolates fresh invocation args', async () => { + let session: ReturnType; + function Consumer() { + session = useStreaming(); + return {session.activeTools.map((t) => t.status).join(',')}; + } + const { wait, unmount } = renderTUI(); + try { + const idA = session!.startToolCall({ agentName: 'runtime', toolName: 'list', args: { ns: 'a' } }); + session!.finishToolCall({ id: idA, toolName: 'list', status: 'success' }); + session!.finishToolCall({ agentName: 'config', toolName: 'list', status: 'error', output: 'missing' }); + await wait(); + expect(session!.activeTools).toHaveLength(1); + expect(session!.activeTools[0].status).toBe('success'); + + session!.updateSubagentProgress({ + agentName: 'runtime', + state: 'completed', + toolCall: { name: 'list', args: { ns: 'staging' }, status: 'success' }, + }); + session!.updateSubagentProgress({ + agentName: 'runtime', + state: 'running', + toolCall: { name: 'list', args: {}, status: 'running' }, + }); + await wait(); + expect(session!.subagents[0].toolCall?.args).toEqual({}); + } finally { + unmount(); + } + }); +}); diff --git a/src/__tests__/watch-dashboard-actions.test.tsx b/src/__tests__/watch-dashboard-actions.test.tsx index 4cf4a40f..4d6946d9 100644 --- a/src/__tests__/watch-dashboard-actions.test.tsx +++ b/src/__tests__/watch-dashboard-actions.test.tsx @@ -3,23 +3,34 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { render } from 'ink'; import { Readable, Writable } from 'node:stream'; import { WatchDashboard } from '../ui/WatchDashboard'; +import { CopilotShell } from '../ui/CopilotShell'; const k8sApiMock = vi.hoisted(() => ({ deleteNamespacedPod: vi.fn(async () => undefined), readNamespacedPodLog: vi.fn(async () => 'sample log'), })); +const inspectDocker = vi.hoisted(() => vi.fn(async () => ({ + Name: '/redis', State: { Status: 'exited', ExitCode: 42 }, +}))); +const getCompletion = vi.hoisted(() => vi.fn(async () => 'Container exited with code 42')); +vi.mock('../ai/factory', () => ({ createAIClient: vi.fn(async () => ({ getCompletion })) })); +vi.mock('../docker/client', () => ({ + getDockerClient: () => ({ getContainer: () => ({ inspect: inspectDocker }) }), + checkDockerConnection: vi.fn(async () => true), +})); vi.mock('../kubernetes/pods', () => ({ getRunningPods: vi.fn(async () => [{ name: 'api-pod', namespace: 'default', status: 'Running', restarts: 0, node: 'node-1' }]), getK8sClusterStats: vi.fn(async () => null), })); vi.mock('../docker/containers', () => ({ - getRunningContainers: vi.fn(async () => []), + getRunningContainers: vi.fn(async () => [{ id: 'abcdef', name: 'redis', image: 'redis', state: 'exited', status: 'Exited (42)' }]), getDockerSystemStats: vi.fn(async () => null), formatDockerBytes: vi.fn(() => '0 B'), })); vi.mock('../kubernetes/client', () => ({ getK8sApi: vi.fn(() => k8sApiMock), + checkK8sConnection: vi.fn(async () => false), })); class TestStdout extends Writable { @@ -60,7 +71,7 @@ describe('WatchDashboard actions', () => { stdin = new TestStdin(); k8sApiMock.deleteNamespacedPod.mockClear(); k8sApiMock.readNamespacedPodLog.mockClear(); - app = render(, { stdin, stdout, debug: true }); + app = render(, { stdin: stdin as any, stdout: stdout as any, debug: true }); await wait(); stdin.send('r'); @@ -86,4 +97,71 @@ describe('WatchDashboard actions', () => { expect(stdout.output).toContain('KDM Split-Pane Monitoring Dashboard'); }); + + it('keeps Docker troubleshooting in Copilot and inspects the selected container', async () => { + const stdout = new TestStdout(); + stdin = new TestStdin(); + app = render(, { stdin: stdin as any, stdout: stdout as any, debug: true }); + await wait(); + stdin.send('\t'); + await wait(); + stdin.send('t'); + await wait(); + stdout.output = ''; + stdin.send('b'); + await wait(); + expect(stdout.output).toContain('KDM Copilot Shell'); + expect(stdout.output).not.toContain('KDM Split-Pane Monitoring Dashboard'); + // Clear the composer before invoking a diagnostic. + stdin.send('\x7f'); + await wait(); + stdin.send('/analyze '); + await wait(); + stdin.send('\r'); + await wait(); + expect(inspectDocker).toHaveBeenCalledOnce(); + expect(getCompletion).toHaveBeenCalledWith(expect.stringContaining('"exitCode":42')); + expect(stdout.output).toContain('Container exited with code 42'); + }); + + it.each([ + ['/pods -n default', 'default/api-pod'], + ['/pods -n missing', 'No matching pods.'], + ['/containers', 'redis Exited (42)'], + ['/health', 'Kubernetes connected: false'], + ['/help', 'Inspect Kubernetes pods'], + ])('renders the result of %s in the Copilot composer', async (command, result) => { + const stdout = new TestStdout(); + stdin = new TestStdin(); + app = render(, { stdin: stdin as any, stdout: stdout as any, debug: true }); + await wait(); + stdin.send(command + ' '); + await wait(); + stdin.send('\r'); + await wait(); + expect(stdout.output).toContain(result); + }); + + it('supports /exit shortcut and preserves unsent Composer draft across tab switches', async () => { + const onExit = vi.fn(); + const stdout = new TestStdout(); + stdin = new TestStdin(); + app = render(, { stdin: stdin as any, stdout: stdout as any, debug: true }); + await wait(); + stdin.send('unsent query'); + await wait(); + stdin.send('\x1b2'); + await wait(); + expect(stdout.output).toContain('Specialist Agents'); + stdin.send('\x1b1'); + await wait(); + expect(stdout.output).toContain('unsent query'); + stdin.send('\r'); + await wait(); + stdin.send('/exit '); + await wait(); + stdin.send('\r'); + await wait(); + expect(onExit).toHaveBeenCalledOnce(); + }); }); diff --git a/src/agent/agent-tool.ts b/src/agent/agent-tool.ts new file mode 100644 index 00000000..a4b4ca01 --- /dev/null +++ b/src/agent/agent-tool.ts @@ -0,0 +1,136 @@ +import { z } from 'zod'; +import { BaseDeclarativeTool, type ToolExecutionContext } from '../tools/declarative-tool.js'; +import { AgentRegistry, defaultAgentRegistry } from './registry.js'; +import type { AgentContext, AgentDefinition } from './types.js'; + +export const DelegateToAgentInputSchema = z.object({ + agent_name: z + .string() + .min(1, 'Agent name is required') + .describe( + 'The name of the registered specialist subagent to invoke (e.g. RuntimeLogAgent, ConfigDependencyAgent, ClusterResourceAgent, SynthesizerAgent, CodebaseInvestigatorAgent)' + ), + prompt: z + .string() + .describe('The diagnostic prompt, inspection goal, or query for the specialist agent'), + depth: z + .number() + .int() + .nonnegative() + .optional() + .default(0) + .describe('Current delegation recursion depth level'), + input: z + .record(z.unknown()) + .optional() + .describe('Optional structured input arguments passed directly to the subagent'), + context: z + .record(z.unknown()) + .optional() + .describe('Optional context parameters (e.g. namespace, clusterContext)'), +}); + +export type DelegateToAgentInput = z.infer; + +function parseAgentInput(schema: z.ZodType, raw: unknown, prompt: string): unknown { + const result = schema.safeParse(raw); + if (result.success) return result.data; + for (const candidate of [{ prompt }, prompt]) { + const fallback = schema.safeParse(candidate); + if (fallback.success) return fallback.data; + } + throw result.error; +} + +function resolveDelegationLimits( + inputDepth: number | undefined, + defaultMaxDepth: number, + context?: ToolExecutionContext +): { depth: number; maxDepth: number } { + const depth = typeof context?.depth === 'number' ? context.depth : (inputDepth ?? 0); + const maxDepth = typeof context?.maxDepth === 'number' + ? Math.min(context.maxDepth, defaultMaxDepth) + : defaultMaxDepth; + if (depth >= maxDepth) { + throw new Error(`MaxDelegationDepthExceededError: Depth ${depth} exceeded max limit ${maxDepth}`); + } + return { depth, maxDepth }; +} + +function resolveAgentOrThrow(registry: AgentRegistry, agentName: string): AgentDefinition { + const agent = registry.get(agentName); + if (!agent) { + const available = registry.list().map((a) => a.name).join(', '); + throw new Error(`Agent '${agentName}' not found. Available: ${available || 'none'}`); + } + return agent; +} + +function buildSubagentContext(params: { + inputContext?: Record; + context?: ToolExecutionContext; + registry: AgentRegistry; + depth: number; + maxDepth: number; +}): AgentContext { + const ctx = params.context ?? {}; + const inputCtx = params.inputContext ?? {}; + return { + cwd: (ctx as any).cwd ?? process.cwd(), + namespace: ctx.namespace ?? (inputCtx.namespace as string | undefined), + clusterContext: inputCtx.clusterContext as string | undefined, + signal: ctx.signal, + dryRun: ctx.dryRun, + registry: params.registry, + ...inputCtx, + ...ctx, + depth: params.depth + 1, + maxDepth: params.maxDepth, + }; +} + +/** + * AgentTool (`delegate_to_agent`) — Declarative tool enabling orchestrators + * and Gemini sessions to dispatch subtasks to specialized subagents. + * + * Conforms to BaseDeclarativeTool and PROJECT.md § Interface Contracts. + */ +export class AgentTool extends BaseDeclarativeTool { + readonly name = 'delegate_to_agent'; + readonly description = + 'Delegates a specialized investigation, diagnostic, or remediating subtask to a registered specialist agent in the KDM multi-agent council (e.g. RuntimeLogAgent, ConfigDependencyAgent, ClusterResourceAgent, SynthesizerAgent, CodebaseInvestigatorAgent).'; + readonly safetyLevel = 'read_only' as const; + readonly riskLevel = 'low' as const; + readonly schema: z.ZodType = DelegateToAgentInputSchema as any; + + constructor( + private registry: AgentRegistry = defaultAgentRegistry, + private maxDepth: number = 2 + ) { + super(); + } + + /** + * Executes the agent delegation with recursion protection, parameter validation, + * context propagation, and result schema validation. + */ + async execute(input: DelegateToAgentInput, context?: ToolExecutionContext): Promise { + const { depth, maxDepth } = resolveDelegationLimits(input.depth, this.maxDepth, context); + const agent = resolveAgentOrThrow(this.registry, input.agent_name); + + const { agent_name: _, depth: _d, input: directInput, context: directContext, prompt, ...rest } = input; + const rawInput = directInput ?? { prompt, ...rest, ...directContext }; + const validatedInput = parseAgentInput(agent.inputSchema, rawInput, prompt); + + const agentContext = buildSubagentContext({ + inputContext: directContext, + context, + registry: this.registry, + depth, + maxDepth, + }); + + const rawOutput = await agent.run(validatedInput, agentContext); + return agent.outputSchema.parse(rawOutput); + } +} diff --git a/src/agent/event-translator.ts b/src/agent/event-translator.ts new file mode 100644 index 00000000..5cb54270 --- /dev/null +++ b/src/agent/event-translator.ts @@ -0,0 +1,288 @@ +/** + * Bidirectional Event Translator — KDM v4.0.0 + * ============================================ + * Translates bidirectionally between KDM's Python Council NDJSON event stream + * and gemini-cli's AgentEvent / SubagentProgress protocol. + * + * Enforces: + * - Robust parsing of chunked stdout streams with line buffering. + * - Silent fail-safe handling of corrupt, partial, or non-JSON log lines. + * - Complete compliance with PROJECT.md § Interface Contracts. + */ + +import { StringDecoder } from 'node:string_decoder'; +import type { + NDJSONEvent, + SubagentProgress, + AgentEvent, + AgentRole, + ConsensusDiagnosis, +} from './types.js'; + +/** Returns current UTC ISO-8601 timestamp with 'Z' suffix. */ +function utcIso(): string { + return new Date().toISOString(); +} + +/** + * Translates a single KDM Python Council NDJSON event into a SubagentProgress object. + * Conforms to PROJECT.md § Interface Contracts. + * + * @param event Parsed NDJSONEvent object or raw line string. + * @returns SubagentProgress object or null if event is non-subagent or unparseable. + */ +export function translateNDJSONToSubagentProgress(event: unknown): SubagentProgress | null { + return translateProgress(readEvent(event)); +} + +type EventFields = Record; +type ProgressTranslator = (event: EventFields) => SubagentProgress | null; + +function asFields(value: unknown): EventFields | undefined { + return value !== null && typeof value === 'object' && !Array.isArray(value) + ? value as EventFields : undefined; +} + +function startProgress(event: EventFields): SubagentProgress { + return { agentName: String(event.role ?? 'council'), state: 'running', thought: String(event.message ?? '') }; +} + +function toolProgress(event: EventFields, toolCall: NonNullable): SubagentProgress { + return { agentName: String(event.role ?? 'council'), state: 'running', toolCall }; +} + +function completedDiagnosis(event: EventFields, fallback: string): SubagentProgress { + const rootCause = asFields(event.consensus)?.rootCause; + return { agentName: 'SynthesizerAgent', state: 'completed', result: String(rootCause ?? fallback) }; +} + +const councilProgress: Record = { + agent_start: startProgress, + agent_progress: startProgress, + agent_tool_call: event => toolProgress(event, { + name: String(event.tool ?? ''), + args: asFields(event.args) ?? {}, + status: 'running', + }), + agent_tool_result: event => toolProgress(event, { + name: String(event.tool ?? ''), + args: {}, + status: 'success', + output: `completed in ${event.durationMs}ms`, + }), + agent_complete: event => ({ + agentName: String(event.role ?? 'council'), state: 'completed', result: String(event.summary ?? ''), + }), + agent_failed: event => ({ + agentName: String(event.role ?? 'council'), state: 'error', result: String(event.error ?? ''), + }), + diagnosis_ready: event => completedDiagnosis(event, 'Consensus diagnosis formulated'), + error: event => event.fatal === true + ? { agentName: 'council', state: 'error', result: String(event.message ?? '') } + : null, +}; + +const legacyProgress: Record = { + progress: event => startProgress({ role: event.agent || event.role, message: event.message }), + agent_completed: event => { + const finding = asFields(event.finding); + const agentName = String(event.agent || finding?.role || 'council'); + return { agentName, state: 'completed', result: String(finding?.summary || `${agentName} finished inspection`) }; + }, + complete: event => completedDiagnosis(event, 'Consensus complete'), + error: event => ({ agentName: 'council', state: 'error', result: String(event.message || 'Unknown error') }), +}; + +function translateProgress(event: EventFields | undefined): SubagentProgress | null { + if (!event) return null; + const modern = typeof event.event === 'string'; + const label = modern ? event.event : event.type; + const translators = modern ? councilProgress : legacyProgress; + if (typeof label !== 'string' || !Object.hasOwn(translators, label)) return null; + return translators[label](event); +} + +function readEvent(event: unknown): EventFields | undefined { + if (typeof event !== 'string') return asFields(event); + try { + return asFields(JSON.parse(event)); + } catch { + return undefined; + } +} + +/** Translates a KDM NDJSON event into a gemini-cli AgentEvent. */ +export function translateNDJSONToAgentEvent(input: unknown): AgentEvent | null { + const event = readEvent(input); + const progress = translateProgress(event); + if (!event || !progress) return null; + + const common = { agentName: progress.agentName, timestamp: typeof event.timestamp === 'string' ? event.timestamp : utcIso() }; + const translated = progress.toolCall + ? makeToolEvent(progress.toolCall, event) + : makeAgentEvent(event, progress); + return { ...common, ...translated }; +} + +function makeToolResultPayload(tool: NonNullable, event?: EventFields) { + const base = { tool: tool.name, output: tool.output }; + const durationMs = event && typeof event.durationMs === 'number' ? event.durationMs : undefined; + return durationMs !== undefined ? { ...base, durationMs } : base; +} + +function makeToolEvent( + tool: NonNullable, + event?: EventFields +): Pick { + return tool.status === 'running' + ? { type: 'tool_call', payload: { tool: tool.name, args: tool.args } } + : { type: 'tool_result', payload: makeToolResultPayload(tool, event) }; +} + +function makeAgentEvent(event: EventFields, progress: SubagentProgress): Pick { + const { thought, result } = progress; + if (event.event === 'agent_start') return { type: 'agent_start', payload: { message: thought } }; + if (event.event === 'diagnosis_ready') { + return { type: 'diagnosis_ready', payload: { result, consensus: event.consensus as ConsensusDiagnosis } }; + } + const states: Record> = { + running: { type: 'thought', payload: { thought } }, + completed: { type: 'agent_complete', payload: { summary: result, result } }, + error: { type: 'agent_error', payload: { error: result } }, + cancelled: { type: 'agent_cancelled', payload: { message: result } }, + }; + return states[progress.state]; +} + +/** + * Translates a KDM NDJSON event into a gemini-cli AgentEvent. + */ + +/** + * Translates a gemini-cli AgentEvent into a KDM NDJSONEvent. + */ +type AgentEventTranslator = (event: AgentEvent, timestamp: string) => NDJSONEvent | null; + +const agentToCouncil: Partial> = { + agent_start: ({ agentName, payload }, timestamp) => ({ + event: 'agent_start', role: agentName as AgentRole, message: payload.message || `Agent ${agentName} started`, timestamp, + }), + thought: ({ agentName, payload }, timestamp) => ({ + event: 'agent_progress', role: agentName, message: payload.thought || '', timestamp, + }), + tool_call: ({ agentName, payload }, timestamp) => ({ + event: 'agent_tool_call', role: agentName, tool: payload.tool || 'unknown_tool', args: payload.args || {}, timestamp, + }), + tool_result: ({ agentName, payload }, timestamp) => ({ + event: 'agent_tool_result', role: agentName, tool: payload.tool || 'unknown_tool', durationMs: payload.durationMs ?? 0, timestamp, + }), + agent_complete: ({ agentName, payload }, timestamp) => ({ + event: 'agent_complete', role: agentName, summary: payload.summary || payload.result || `Agent ${agentName} completed`, timestamp, + }), + agent_error: ({ agentName, payload }, timestamp) => ({ + event: 'agent_failed', role: agentName, error: payload.error || 'Agent failed', timestamp, + }), + diagnosis_ready: ({ payload }, timestamp) => payload.consensus + ? { event: 'diagnosis_ready', consensus: payload.consensus, timestamp } + : null, +}; + +export function translateAgentEventToNDJSON(agentEvent: AgentEvent): NDJSONEvent | null { + if (!agentEvent || !Object.hasOwn(agentToCouncil, agentEvent.type)) return null; + const translate = agentToCouncil[agentEvent.type]; + return translate?.(agentEvent, agentEvent.timestamp || utcIso()) ?? null; +} + +function failedProgressEvent(progress: SubagentProgress): AgentEvent { + const error = progress.result || progress.toolCall?.output || 'Agent failed'; + return { agentName: progress.agentName, type: 'agent_error', payload: { error } }; +} + +function progressPayload(progress: SubagentProgress): Pick { + if (progress.toolCall) return makeToolEvent(progress.toolCall); + const fallback = progress.state === 'completed' ? 'Completed' : 'Failed'; + return makeAgentEvent({}, { ...progress, result: progress.result || fallback }); +} + +/** Translates SubagentProgress into a KDM council event. */ +export function translateSubagentProgressToNDJSON(progress: SubagentProgress): NDJSONEvent | null { + if (!progress) return null; + if (progress.state === 'error' || progress.toolCall?.status === 'error') { + return translateAgentEventToNDJSON(failedProgressEvent(progress)); + } + return translateAgentEventToNDJSON({ ...progressPayload(progress), agentName: progress.agentName }); +} + +/** + * Stateful stream event translator handling chunk boundaries, line reassembly, + * and bidirectional conversion between NDJSON and SubagentProgress. + */ +export class EventTranslator { + private buffer = ''; + private decoder = new StringDecoder('utf8'); + + /** + * Ingests a raw stdout or network chunk, reassembles lines split across chunk boundaries, + * parses complete lines, and yields translated SubagentProgress items. + * + * @param chunk Raw string or Buffer chunk. + * @returns Array of translated SubagentProgress objects. + */ + public pushChunk(chunk: string | Buffer): SubagentProgress[] { + const text = typeof chunk === 'string' ? this.decoder.end() + chunk : this.decoder.write(chunk); + this.buffer += text; + + const lines = this.buffer.split(/\r?\n/); + // Keep incomplete trailing fragment in buffer + this.buffer = lines.pop() || ''; + + const results: SubagentProgress[] = []; + for (const line of lines) { + const trimmed = line.trim(); + if (!trimmed) continue; + const progress = this.translateLine(trimmed); + if (progress) { + results.push(progress); + } + } + return results; + } + + /** + * Flushes and processes any remaining line in buffer when stream ends. + */ + public flush(): SubagentProgress[] { + const remaining = (this.buffer + this.decoder.end()).trim(); + this.buffer = ''; + if (!remaining) return []; + const progress = this.translateLine(remaining); + return progress ? [progress] : []; + } + + /** + * Translates a single line string to SubagentProgress, returning null on corrupt/invalid input. + */ + public translateLine(line: string): SubagentProgress | null { + return translateNDJSONToSubagentProgress(line); + } + + /** + * Serializes an event or SubagentProgress into a single NDJSON line with trailing newline. + */ + public static serializeNDJSON(event: NDJSONEvent | AgentEvent | SubagentProgress): string { + let ndjson: NDJSONEvent | null = null; + if ('event' in event && typeof (event as any).event === 'string') { + ndjson = event as NDJSONEvent; + } else if ('type' in event && typeof (event as any).type === 'string') { + ndjson = translateAgentEventToNDJSON(event as AgentEvent); + } else if ('state' in event && typeof (event as any).state === 'string') { + ndjson = translateSubagentProgressToNDJSON(event as SubagentProgress); + } + + if (!ndjson) { + return ''; + } + + return JSON.stringify(ndjson) + '\n'; + } +} diff --git a/src/agent/index.ts b/src/agent/index.ts new file mode 100644 index 00000000..1153f87c --- /dev/null +++ b/src/agent/index.ts @@ -0,0 +1,14 @@ +/** + * KDM Agent Subsystem + * + * Exposes multi-agent coordination protocol, specialist registry, + * delegation tools, event streaming translator, and codebase investigator. + */ + +export * from './types.js'; +export * from './registry.js'; +export * from './agent-tool.js'; +export * from './event-schema.js'; +export * from './event-translator.js'; +export * from './investigator.js'; +export * from './python-bridge.js'; diff --git a/src/agent/investigator.ts b/src/agent/investigator.ts new file mode 100644 index 00000000..950f433a --- /dev/null +++ b/src/agent/investigator.ts @@ -0,0 +1,601 @@ +import { z } from 'zod'; +import fs from 'node:fs'; +import path from 'node:path'; +import { execFile } from 'node:child_process'; +import { promisify } from 'node:util'; +import { createTwoFilesPatch } from 'diff'; +import { isMap, isScalar, isSeq, parseAllDocuments, type YAMLMap } from 'yaml'; +import type { + AgentDefinition, + AgentContext, + CodebaseFindingItem, + CodebaseRelevantLocation, + CodebaseInvestigationReport, +} from './types.js'; + +const execFileAsync = promisify(execFile); + +// ─── Input & Output Schemas ────────────────────────────────────────────────── + +export const CodebaseInvestigatorInputSchema = z.object({ + objective: z.string().optional().describe('High-level goal or incident description'), + prompt: z.string().optional().describe('Delegation prompt string'), + workspaceRoot: z.string().optional().describe('Directory path of local workspace root'), + workspaceFiles: z + .record(z.string()) + .optional() + .describe('In-memory virtual file map for testing or isolated executions'), + liveClusterState: z + .object({ + podName: z.string().optional(), + workloadName: z.string().optional(), + namespace: z.string().optional(), + memoryLimit: z.string().optional(), + containerName: z.string().optional(), + secretKeys: z.record(z.array(z.string())).optional().describe('Observed key names by Secret name in the supplied namespace'), + cpuLimit: z.string().optional(), + exitCode: z.number().optional(), + errorLog: z.string().optional(), + }) + .optional(), +}); + +export type CodebaseInvestigatorInput = z.infer; + +export const CodebaseFindingItemSchema = z.object({ + file: z.string(), + issue: z.string(), + recommendation: z.string(), + patch: z.string().optional(), +}); + +export const CodebaseRelevantLocationSchema = z.object({ + FilePath: z.string(), + Reasoning: z.string(), + KeySymbols: z.array(z.string()), + LineNumber: z.number().optional(), + Snippet: z.string().optional(), +}); + +export const CodebaseInvestigationReportSchema = z.object({ + // gemini-cli compatibility fields + SummaryOfFindings: z.string(), + ExplorationTrace: z.array(z.string()), + RelevantLocations: z.array(CodebaseRelevantLocationSchema), + // KDM SRE compatibility fields + discoveredManifests: z.array(z.string()), + findings: z.array(CodebaseFindingItemSchema), + driftDetected: z.boolean(), +}); + +// ─── Constants & Utility Functions ─────────────────────────────────────────── + +const BINARY_EXTENSIONS = new Set([ + '.png', '.jpg', '.jpeg', '.gif', '.ico', '.svg', '.tar', '.gz', '.zip', + '.bin', '.exe', '.dll', '.so', '.dylib', '.jar', '.war', '.class', '.pyc', '.iso', '.pdf', +]); + +const IGNORED_DIRS = new Set([ + 'node_modules', '.git', 'dist', 'build', '.next', '.cache', '.agents', +]); + +export function parseMemoryBytes(memStr: string): number { + const match = memStr.trim().match(/^(\d+(?:\.\d+)?)\s*([KMGTP]i?|B)?$/i); + if (!match) return 0; + const powers = new Map([['K', 1], ['M', 2], ['G', 3], ['T', 4]]); + const unit = (match[2] ?? 'B')[0].toUpperCase(); + return Number(match[1]) * 1024 ** (powers.get(unit) ?? 0); +} + +const K8S_QUANTITY_POWERS = new Map([['K', 1], ['M', 2], ['G', 3], ['T', 4], ['P', 5]]); + +function computeQuantityMultiplier(unitChar?: string, binaryFlag?: string): number { + if (!unitChar) return 1; + if (unitChar === 'm' && !binaryFlag) return 0.001; + const base = binaryFlag ? 1024 : 1000; + return base ** (K8S_QUANTITY_POWERS.get(unitChar.toUpperCase()) ?? 0); +} + +export function parseKubernetesQuantityBytes(memStr: string): number { + const match = memStr.trim().match(/^(\d+(?:\.\d+)?)\s*([kKmMgGtTpP])?(i)?(?:B)?$/); + if (!match) return 0; + return Number(match[1]) * computeQuantityMultiplier(match[2], match[3]); +} + +export function isBinaryFile(filename: string): boolean { + const lower = filename.toLowerCase(); + for (const ext of BINARY_EXTENSIONS) { + if (lower.endsWith(ext)) return true; + } + return false; +} + +export function isManifestFile(filename: string): boolean { + return !isBinaryFile(filename) && /\.ya?ml$|Dockerfile|\.dockerfile$/.test(path.basename(filename)); +} + +function getManifestContainers(document: YAMLMap): YAMLMap[] { + const containers = [ + ['spec', 'containers'], + ['spec', 'template', 'spec', 'containers'], + ['spec', 'jobTemplate', 'spec', 'template', 'spec', 'containers'], + ].map((keys) => document.getIn(keys, true)).find(isSeq); + return containers?.items.filter(isMap) ?? []; +} + +type LiveState = CodebaseInvestigatorInput['liveClusterState']; + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +async function readManifest(target: { filename: string; relative: string; trace: string[] }) { + try { + return await fs.promises.readFile(target.filename, 'utf8'); + } catch (error) { + target.trace.push(`Read error skipping file ${target.relative}: ${errorMessage(error)}`); + return undefined; + } +} + +function selectTargetWorkloadName(ctx: { root: YAMLMap; liveState: NonNullable }): string | undefined { + if (ctx.root.get('kind') === 'Pod') { + return ctx.liveState.podName ?? ctx.liveState.workloadName; + } + return ctx.liveState.workloadName ?? ctx.liveState.podName; +} + +function matchesWorkloadIdentity(ctx: { root: YAMLMap; liveState: NonNullable }): boolean { + const { root, liveState } = ctx; + const target = selectTargetWorkloadName(ctx); + if (target && target !== root.getIn(['metadata', 'name'])) return false; + if (liveState.namespace) { + const manifestNs = root.getIn(['metadata', 'namespace']) ?? 'default'; + if (liveState.namespace !== manifestNs) return false; + } + return true; +} + +function getWorkloadMemory(ctx: { + root: YAMLMap; + container: YAMLMap; + count: number; + liveState: LiveState; +}) { + if (!ctx.liveState?.memoryLimit) return undefined; + if (!matchesWorkloadIdentity({ root: ctx.root, liveState: ctx.liveState })) return undefined; + if (ctx.liveState.containerName) { + return ctx.liveState.containerName === ctx.container.get('name') ? ctx.liveState.memoryLimit : undefined; + } + return ctx.count === 1 ? ctx.liveState.memoryLimit : undefined; +} + +function emptyWorkspaceReport(trace: string[]): CodebaseInvestigationReport { + return { + SummaryOfFindings: 'No relevant configuration or manifest files discovered in workspace.', + ExplorationTrace: trace, + RelevantLocations: [], + discoveredManifests: [], + findings: [ + { + file: 'none', + issue: 'No relevant configuration or manifest files discovered in workspace', + recommendation: 'Verify workspace directory contains Helm charts or manifests', + }, + ], + driftDetected: false, + }; +} + +function buildJvmPatch(ctx: { + filePath: string; + content: string; + memory: unknown; + recommendedLimitMi: number; + manifestLimit?: string; +}): string | undefined { + const range = isScalar(ctx.memory) ? ctx.memory.range : undefined; + if (!range) return undefined; + if (parseKubernetesQuantityBytes(ctx.manifestLimit ?? '') >= ctx.recommendedLimitMi * 1024 * 1024) return undefined; + const patched = ctx.content.slice(0, range[0]) + `${ctx.recommendedLimitMi}Mi` + ctx.content.slice(range[1]); + return createTwoFilesPatch(ctx.filePath, `${ctx.filePath}.patched`, ctx.content, patched); +} + +function buildHeapFinding(ctx: { + filePath: string; + heapStr: string; + liveLimit: string; + targetLimitStr: string; + patch?: string; +}) { + return { + finding: { + file: ctx.filePath, + issue: `Configured JVM heap (-Xmx${ctx.heapStr}) exceeds container cgroup memory limit (${ctx.liveLimit}).`, + recommendation: `Increase the container memory limit to ${ctx.targetLimitStr} or lower the JVM heap to leave room for non-heap memory.`, + patch: ctx.patch, + }, + location: { + FilePath: ctx.filePath, + Reasoning: `Specifies JVM heap (-Xmx${ctx.heapStr}) exceeding cgroup limit (${ctx.liveLimit})`, + KeySymbols: ['JAVA_OPTS', '-Xmx', 'memory'], + }, + }; +} + +function checkMissingSecretRef(ctx: { + ref: YAMLMap; + filePath: string; + namespace: string; + secretKeys: Record; +}) { + const name = ctx.ref.get('name'); + const key = ctx.ref.get('key'); + if (typeof name !== 'string' || typeof key !== 'string') return null; + if (ctx.ref.get('optional') === true) return null; + if (!Object.hasOwn(ctx.secretKeys, name) || ctx.secretKeys[name].includes(key)) return null; + return { + finding: { + file: ctx.filePath, + issue: `Secret ${name} in namespace ${ctx.namespace} does not provide the referenced key ${key}.`, + recommendation: `Add the expected key ${key} or update secretKeyRef to the intended key in ${name}.`, + }, + location: { + FilePath: ctx.filePath, + Reasoning: `Requests missing Secret key ${key}`, + KeySymbols: ['secretKeyRef', name, key], + }, + }; +} + +function extractContainerSecretRefs(container: YAMLMap): YAMLMap[] { + const env = container.getIn(['env'], true); + if (!isSeq(env)) return []; + return env.items + .filter((entry): entry is YAMLMap => isMap(entry)) + .map((entry) => entry.getIn(['valueFrom', 'secretKeyRef'], true)) + .filter((ref): ref is YAMLMap => isMap(ref)); +} + +function collectSecretRefs(document: YAMLMap): YAMLMap[] { + return getManifestContainers(document).flatMap(extractContainerSecretRefs); +} + +function shouldEnrichGitHistory(ctx: { + input: CodebaseInvestigatorInput; + findings: CodebaseFindingItem[]; +}): boolean { + if (!ctx.input.workspaceRoot || !ctx.findings.length) return false; + return ctx.findings[0].file !== 'none'; +} + +function resolveDelegatedInput(ctx: { + input: CodebaseInvestigatorInput; + context?: AgentContext; +}): CodebaseInvestigatorInput { + const { input, context } = ctx; + if (input.workspaceRoot || input.workspaceFiles) return input; + if (!context || !context.cwd) return input; + return { ...input, workspaceRoot: context.cwd }; +} + +function sliceContainerContent(ctx: { content: string; container?: YAMLMap }): string { + const range = ctx.container ? ctx.container.range : undefined; + return range ? ctx.content.slice(range[0], range[1]) : ctx.content; +} + +function readContainerHeapSpec(ctx: { content: string; container?: YAMLMap }) { + const jvmMatch = sliceContainerContent(ctx).match(/-Xmx([0-9]+[kmgKMG]?)/); + if (!jvmMatch) return null; + const memory = ctx.container ? ctx.container.getIn(['resources', 'limits', 'memory'], true) : undefined; + const manifestLimit = isScalar(memory) ? String(memory.value) : undefined; + return { heapStr: jvmMatch[1], memory, manifestLimit }; +} + +function computeRecommendedLimitMi(ctx: { heapBytes: number; manifestLimit?: string }): number { + const desiredBytes = Math.max(ctx.heapBytes * 1.33, parseKubernetesQuantityBytes(ctx.manifestLimit ?? '')); + return Math.max(1024, Math.ceil(desiredBytes / (1024 * 1024))); +} + +// ─── CodebaseInvestigatorAgent Implementation ──────────────────────────────── + +export class CodebaseInvestigatorAgent { + static readonly NAME = 'CodebaseInvestigatorAgent'; + static readonly name = 'CodebaseInvestigatorAgent'; + static readonly DISPLAY_NAME = 'Codebase Investigator Agent'; + static readonly DESCRIPTION = + 'Specialized agent that inspects local workspace manifests (Helm charts, Dockerfiles, YAML manifests, code files) during incidents to trace errors, detect configuration drift, and generate remediation patches.'; + + /** + * Main execution method. Supports both real workspace filesystem and in-memory virtual files. + */ + static async run(input: CodebaseInvestigatorInput): Promise { + const trace: string[] = []; + const fileEntries = await this.resolveFiles({ input, trace }); + const discoveredManifests = fileEntries.manifestPaths; + + trace.push(`Discovered ${discoveredManifests.length} manifest files in workspace`); + if (discoveredManifests.length === 0) { + return emptyWorkspaceReport(trace); + } + + const { findings, relevantLocations } = this.inspectAllManifests({ + discoveredManifests, + contents: fileEntries.contents, + liveState: input.liveClusterState, + trace, + }); + + if (shouldEnrichGitHistory({ input, findings })) { + await this.enrichWithGitHistory({ + file: findings[0].file, + rootDir: input.workspaceRoot!, + trace, + }); + } + + const driftDetected = findings.length > 0; + const summary = driftDetected + ? `Identified ${findings.length} configuration drift / resource discrepancies across workspace manifests.` + : 'All inspected workspace manifests align with expected configurations.'; + + return { + SummaryOfFindings: summary, + ExplorationTrace: trace, + RelevantLocations: relevantLocations, + discoveredManifests, + findings, + driftDetected, + }; + } + + private static inspectAllManifests(ctx: { + discoveredManifests: string[]; + contents: Record; + liveState: LiveState; + trace: string[]; + }) { + const relevantLocations: CodebaseRelevantLocation[] = []; + const findings: CodebaseFindingItem[] = []; + const results = ctx.discoveredManifests.flatMap((file) => + this.inspectManifest({ + file, + content: ctx.contents[file], + liveState: ctx.liveState, + trace: ctx.trace, + }) + ); + for (const result of results) { + findings.push(result.finding); + relevantLocations.push(result.location); + } + return { findings, relevantLocations }; + } + + private static inspectManifest(ctx: { + file: string; + content: string; + liveState: LiveState; + trace: string[]; + }) { + if (!ctx.content) return []; + if (!/\.ya?ml$/.test(ctx.file)) { + const finding = this.checkJvmHeapLimit({ + filePath: ctx.file, + content: ctx.content, + observedLimit: ctx.liveState?.memoryLimit, + }); + return finding ? [finding] : []; + } + + const documents = parseAllDocuments(ctx.content); + if (documents.some((doc) => doc.errors.length)) { + ctx.trace.push(`Skipping syntactically invalid manifest: ${ctx.file}`); + return []; + } + return documents.flatMap(({ contents }) => + isMap(contents) + ? this.inspectYaml({ file: ctx.file, content: ctx.content, document: contents, liveState: ctx.liveState }) + : [] + ); + } + + private static inspectYaml(ctx: { + file: string; + content: string; + document: YAMLMap; + liveState: LiveState; + }) { + const isValuesFile = /^values(?:[-.][\w-]+)?\.ya?ml$/i.test(path.basename(ctx.file)); + const containers = getManifestContainers(ctx.document); + const jvmFindings = isValuesFile + ? [this.checkJvmHeapLimit({ filePath: ctx.file, content: ctx.content, container: ctx.document })] + : containers.map((container) => + this.checkJvmHeapLimit({ + filePath: ctx.file, + content: ctx.content, + observedLimit: getWorkloadMemory({ + root: ctx.document, + container, + count: containers.length, + liveState: ctx.liveState, + }), + container, + }) + ); + const secretFindings = this.checkSecretKeyReferences({ + filePath: ctx.file, + document: ctx.document, + liveState: ctx.liveState, + }); + return [...jvmFindings.filter((finding) => finding !== null), ...secretFindings]; + } + + /** Compares a manifest's JVM heap with its container limit and proposes a scoped patch. */ + private static checkJvmHeapLimit(ctx: { + filePath: string; + content: string; + observedLimit?: string; + container?: YAMLMap; + }) { + const heapSpec = readContainerHeapSpec({ content: ctx.content, container: ctx.container }); + if (!heapSpec) return null; + + const liveLimit = ctx.observedLimit || heapSpec.manifestLimit; + if (!liveLimit) return null; + + const heapBytes = parseMemoryBytes(heapSpec.heapStr); + const limitBytes = parseKubernetesQuantityBytes(liveLimit); + if (limitBytes <= 0) return null; + if (heapBytes <= limitBytes) return null; + + const recommendedLimitMi = computeRecommendedLimitMi({ + heapBytes, + manifestLimit: heapSpec.manifestLimit, + }); + const targetLimitStr = `${recommendedLimitMi}Mi`; + const patch = buildJvmPatch({ + filePath: ctx.filePath, + content: ctx.content, + memory: heapSpec.memory, + recommendedLimitMi, + manifestLimit: heapSpec.manifestLimit, + }); + return buildHeapFinding({ + filePath: ctx.filePath, + heapStr: heapSpec.heapStr, + liveLimit, + targetLimitStr, + patch, + }); + } + + /** + * Compares manifest references to observed Secret key names without reading values. + */ + private static checkSecretKeyReferences(ctx: { + filePath: string; + document: YAMLMap; + liveState?: LiveState; + }) { + const namespace = String(ctx.document.getIn(['metadata', 'namespace']) ?? ctx.liveState?.namespace ?? 'default'); + const secretKeys = ctx.liveState?.secretKeys; + if (!secretKeys || namespace !== (ctx.liveState?.namespace ?? 'default')) return []; + + return collectSecretRefs(ctx.document) + .map((ref) => checkMissingSecretRef({ ref, filePath: ctx.filePath, namespace, secretKeys })) + .filter((item) => item !== null); + } + + /** + * Discovers manifests while enforcing boundary guards: symlink cycle prevention, + * binary file skipping, directory exclusions, and EACCES error handling. + */ + private static async resolveFiles(ctx: { + input: CodebaseInvestigatorInput; + trace: string[]; + }): Promise<{ manifestPaths: string[]; contents: Record }> { + if (ctx.input.workspaceFiles) { + const paths = Object.keys(ctx.input.workspaceFiles); + return { manifestPaths: paths.filter(isManifestFile), contents: ctx.input.workspaceFiles }; + } + + const rootDir = ctx.input.workspaceRoot || process.cwd(); + const manifestPaths: string[] = []; + const contents: Record = {}; + await this.scanDirectory({ directory: rootDir, rootDir, manifestPaths, contents, trace: ctx.trace }); + return { manifestPaths, contents }; + } + + private static async scanDirectory(ctx: { + directory: string; + rootDir: string; + manifestPaths: string[]; + contents: Record; + trace: string[]; + }): Promise { + const entries = await fs.promises.readdir(ctx.directory, { withFileTypes: true }).catch((error: unknown) => { + ctx.trace.push(`Read error on ${ctx.directory}: ${errorMessage(error)}`); + return []; + }); + for (const entry of entries) { + await this.processEntry({ ...ctx, entry }); + } + } + + private static async processEntry(ctx: { + entry: fs.Dirent; + directory: string; + rootDir: string; + manifestPaths: string[]; + contents: Record; + trace: string[]; + }): Promise { + const filename = path.join(ctx.directory, ctx.entry.name); + const relative = path.relative(ctx.rootDir, filename); + if (ctx.entry.isSymbolicLink()) { + ctx.trace.push(`Skipping symbolic link: ${relative}`); + return; + } + if (ctx.entry.isDirectory()) { + await this.scanChildDirectoryIfIncluded(ctx); + return; + } + if (!ctx.entry.isFile() || !isManifestFile(ctx.entry.name)) return; + const content = await readManifest({ filename, relative, trace: ctx.trace }); + if (content === undefined) return; + ctx.manifestPaths.push(relative); + ctx.contents[relative] = content; + } + + private static async scanChildDirectoryIfIncluded(ctx: { + entry: fs.Dirent; + directory: string; + rootDir: string; + manifestPaths: string[]; + contents: Record; + trace: string[]; + }): Promise { + if (IGNORED_DIRS.has(ctx.entry.name)) return; + await this.scanDirectory({ + directory: path.join(ctx.directory, ctx.entry.name), + rootDir: ctx.rootDir, + manifestPaths: ctx.manifestPaths, + contents: ctx.contents, + trace: ctx.trace, + }); + } + + private static async enrichWithGitHistory(ctx: { + file: string; + rootDir: string; + trace: string[]; + }) { + try { + const { stdout } = await execFileAsync('git', ['log', '-n', '3', '--oneline', ctx.file], { + cwd: ctx.rootDir, + timeout: 2000, + }); + if (stdout.trim()) { + ctx.trace.push(`Recent git commits for ${ctx.file}:\n${stdout.trim()}`); + } + } catch { + // Git unavailable or file untracked — proceed cleanly + } + } + + /** + * Factory returning standard AgentDefinition for AgentRegistry registration. + */ + static toDefinition(): AgentDefinition { + return { + name: this.NAME, + description: this.DESCRIPTION, + inputSchema: CodebaseInvestigatorInputSchema, + outputSchema: CodebaseInvestigationReportSchema, + run: async (input: CodebaseInvestigatorInput, context?: AgentContext) => { + return this.run(resolveDelegatedInput({ input, context })); + }, + }; + } +} diff --git a/src/agent/registry.ts b/src/agent/registry.ts new file mode 100644 index 00000000..4ec01f00 --- /dev/null +++ b/src/agent/registry.ts @@ -0,0 +1,105 @@ +import type { AgentDefinition } from './types.js'; + +function assertAgentName(agent: AgentDefinition): void { + if (typeof agent.name !== 'string') { + throw new Error('Agent name must be defined'); + } + if (!agent.name.trim()) { + throw new Error('Agent name must be defined'); + } +} + +function assertAgentSchemas(agent: AgentDefinition): void { + if (!agent.inputSchema || !agent.outputSchema) { + throw new Error(`Agent '${agent.name}' must define inputSchema and outputSchema`); + } +} + +function assertRunnable(agent: AgentDefinition): void { + if (typeof agent.run !== 'function') { + throw new Error(`Agent '${agent.name}' must define an executable run() function`); + } +} + +function validateAgentDefinition(agent: AgentDefinition): void { + if (!agent || typeof agent !== 'object') { + throw new Error('Agent definition must be a valid object'); + } + assertAgentName(agent); + assertAgentSchemas(agent); + assertRunnable(agent); +} + +/** + * AgentRegistry — Registry for discovering, registering, and retrieving + * specialist AI agents (local, bridged, or council) in KDM CLI. + * + * Conforms strictly to PROJECT.md § Interface Contracts. + */ +export class AgentRegistry { + private readonly agents = new Map(); + + /** + * Registers a specialist agent definition in the registry. + */ + register(agent: AgentDefinition): void { + validateAgentDefinition(agent); + this.agents.set(agent.name, agent); + } + + /** + * Registers multiple agents in bulk. + */ + registerAll(agents: AgentDefinition[]): void { + for (const agent of agents) { + this.register(agent); + } + } + + /** + * Retrieves a registered agent by name. + */ + get(name: string): AgentDefinition | undefined { + return this.agents.get(name); + } + + /** + * Checks whether an agent is registered by name. + */ + has(name: string): boolean { + return this.agents.has(name); + } + + /** + * Lists all registered agents. + */ + list(): AgentDefinition[] { + return Array.from(this.agents.values()); + } + + /** + * Returns names of all registered agents. + */ + getNames(): string[] { + return Array.from(this.agents.keys()); + } + + /** + * Unregisters an agent by name. + */ + unregister(name: string): boolean { + return this.agents.delete(name); + } + + /** + * Clears all registered agents. + */ + clear(): void { + this.agents.clear(); + } +} + +/** + * Singleton default AgentRegistry instance for KDM CLI. + */ +export const defaultAgentRegistry = new AgentRegistry(); diff --git a/src/agent/types.ts b/src/agent/types.ts index 3644a9b8..2778597b 100644 --- a/src/agent/types.ts +++ b/src/agent/types.ts @@ -2,6 +2,8 @@ * Types and interfaces for the Multi-Agent Collaborative Analysis system. */ +import type { z } from 'zod'; + /** * Roles for agents participating in workload failure triaging. */ @@ -97,3 +99,148 @@ export type NDJSONEvent = | { event: 'agent_failed'; role: string; error: string; timestamp: string } | { event: 'diagnosis_ready'; consensus: ConsensusDiagnosis; timestamp: string } | { event: 'error'; message: string; fatal: boolean; timestamp: string }; + +// ─── Milestone 3: Multi-Agent Coordination Protocol Types ──────────────────── + +/** + * Execution context provided to registered subagents. + */ +export interface AgentContext { + cwd?: string; + namespace?: string; + clusterContext?: string; + signal?: AbortSignal; + depth?: number; + maxDepth?: number; + dryRun?: boolean; + auditTrail?: any; + registry?: any; + aiClient?: any; + toolRegistry?: any; + [key: string]: unknown; +} + +/** + * Standard agent definition registered in AgentRegistry. + * Conforms to PROJECT.md § Interface Contracts. + */ +export interface AgentDefinition { + name: string; + description: string; + inputSchema: z.ZodType; + outputSchema: z.ZodType; + run: (input: TInput, context?: AgentContext) => Promise; + type?: 'local' | 'remote' | 'specialist' | 'council'; + metadata?: Record; +} + +/** + * Type alias for local in-process agent definition. + */ +export type LocalAgentDefinition = AgentDefinition; + +/** + * Unified subagent progress representation consumed by terminal UI and event bridges. + * Conforms to PROJECT.md § Interface Contracts. + */ +export interface SubagentProgress { + agentName: string; + state: 'running' | 'completed' | 'error' | 'cancelled'; + thought?: string; + toolCall?: { + name: string; + args: Record; + status: 'running' | 'success' | 'error'; + output?: string; + }; + result?: string; +} + +/** + * Event type discriminators for gemini-cli agent coordination. + */ +export type AgentEventType = + | 'agent_start' + | 'thought' + | 'tool_call' + | 'tool_result' + | 'agent_complete' + | 'agent_error' + | 'agent_cancelled' + | 'diagnosis_ready'; + +/** + * Unified gemini-cli agent event protocol envelope. + */ +export interface AgentEvent { + id?: string; + agentName: string; + type: AgentEventType; + timestamp?: string; + payload: { + message?: string; + thought?: string; + tool?: string; + args?: Record; + output?: string; + durationMs?: number; + result?: string; + summary?: string; + error?: string; + consensus?: ConsensusDiagnosis; + }; +} + +/** + * Parameters for delegate_to_agent tool. + */ +export interface DelegateToAgentParams { + agent_name: string; + prompt: string; + depth?: number; + input?: Record; + context?: Record; +} + +/** + * Finding item produced by codebase investigation. + */ +export interface CodebaseFindingItem { + file: string; + issue: string; + recommendation: string; + patch?: string; +} + +/** + * Location citation in codebase investigation (gemini-cli format). + */ +export interface CodebaseRelevantLocation { + FilePath: string; + Reasoning: string; + KeySymbols: string[]; + LineNumber?: number; + Snippet?: string; +} + +/** + * KDM SRE finding report from codebase investigation. + */ +export interface CodebaseFinding { + discoveredManifests: string[]; + findings: CodebaseFindingItem[]; + driftDetected?: boolean; +} + +/** + * Comprehensive dual-schema report from CodebaseInvestigatorAgent + * supporting both gemini-cli and KDM SRE schemas. + */ +export interface CodebaseInvestigationReport { + SummaryOfFindings: string; + ExplorationTrace: string[]; + RelevantLocations: CodebaseRelevantLocation[]; + discoveredManifests: string[]; + findings: CodebaseFindingItem[]; + driftDetected: boolean; +} diff --git a/src/ai/factory.ts b/src/ai/factory.ts index 6834675b..d6ca36cb 100644 --- a/src/ai/factory.ts +++ b/src/ai/factory.ts @@ -7,6 +7,7 @@ import { NoopAIClient } from './noop'; import { AzureOpenAIClient } from './azure-openai'; import { CohereAIClient } from './cohere'; import { GoogleGeminiAIClient } from './google-gemini'; +import { GoogleGenAIClient } from './google-genai'; import { GoogleVertexAIClient } from './google-vertex'; import { AmazonBedrockAIClient } from './amazon-bedrock'; import { HuggingFaceAIClient } from './huggingface'; @@ -27,7 +28,9 @@ const CLIENT_MAPPING: Record AIClient> = { cohere: CohereAIClient, 'google-gemini': GoogleGeminiAIClient, googlegemini: GoogleGeminiAIClient, - gemini: GoogleGeminiAIClient, + 'google-genai': GoogleGenAIClient, + googlegenai: GoogleGenAIClient, + gemini: GoogleGenAIClient, 'google-vertex': GoogleVertexAIClient, googlevertex: GoogleVertexAIClient, vertex: GoogleVertexAIClient, @@ -45,24 +48,37 @@ const CLIENT_MAPPING: Record AIClient> = { }; /** - * Instantiates and configures the appropriate AIClient based on the backend name. - * Looks up stored configuration credentials. + * Looks up stored provider settings, including compatible Gemini aliases. * @param backendName The name of the AI provider backend (e.g. 'openai', 'ollama'). - * @returns Instantiated and configured AIClient. */ -export async function createAIClient(backendName: string): Promise { +export function resolveAIProviderConfig(backendName: string) { const aiConfig = getAIConfig(); - const providerConfig = aiConfig.providers.find( - (p) => p.name.toLowerCase() === backendName.toLowerCase(), + const lower = backendName.toLowerCase(); + + let providerConfig = aiConfig.providers.find( + (p) => p.name.toLowerCase() === lower, ); + if (!providerConfig && ['gemini', 'google-genai', 'googlegenai'].includes(lower)) { + providerConfig = aiConfig.providers.find( + (p) => + p.name.toLowerCase() === 'google-genai' || + p.name.toLowerCase() === 'googlegenai' || + p.name.toLowerCase() === 'gemini' || + p.name.toLowerCase() === 'google-gemini', + ); + } + return providerConfig; +} + +export async function createAIClient(backendName: string, model?: string, headers?: Record): Promise { const ClientClass = CLIENT_MAPPING[backendName.toLowerCase()]; if (!ClientClass) { throw new Error(`Unsupported AI provider: ${backendName}`); } const client = new ClientClass(); - const activeConfig = providerConfig || { name: backendName, model: '' }; - await client.configure(activeConfig); + const activeConfig = resolveAIProviderConfig(backendName) || { name: backendName, model: '' }; + await client.configure({ ...activeConfig, model: model || activeConfig.model, customHeaders: { ...activeConfig.customHeaders, ...headers } }); return client; } diff --git a/src/ai/gemini-session.ts b/src/ai/gemini-session.ts new file mode 100644 index 00000000..e5ef1928 --- /dev/null +++ b/src/ai/gemini-session.ts @@ -0,0 +1,209 @@ +import type { GenerateContentResponse, Part } from '@google/genai'; +import { + FunctionCallPart, + GeminiSessionOptions, + SendMessageOptions, + SessionMessageResponse, + StreamChunk, + ThinkingConfig, +} from './types'; + +export type { + FunctionCallPart, + GeminiSessionOptions, + SendMessageOptions, + SessionMessageResponse, + StreamChunk, + ThinkingConfig, +}; + +export function normalizeTools(tools?: any[]): any[] | undefined { + if (!tools || tools.length === 0) return undefined; + return tools.every((tool) => typeof tool?.name === 'string') + ? [{ functionDeclarations: tools }] + : tools; +} + +export type ContentPart = Part; + +export interface SessionContent { + role: 'user' | 'model'; + parts: ContentPart[]; +} + +function extractChunkParts(chunk: GenerateContentResponse): ContentPart[] { + const candidate = chunk.candidates?.[0]; + const parts: ContentPart[] = [...(candidate?.content?.parts ?? [])]; + if (!parts.length && chunk.text) { + parts.push({ text: chunk.text }); + } + if (!parts.some((part) => part.functionCall) && chunk.functionCalls) { + parts.push(...chunk.functionCalls.map((functionCall) => ({ functionCall }))); + } + return parts; +} + +function toFunctionCallPart(part: ContentPart): FunctionCallPart | null { + if (!part.functionCall) return null; + const { name = '', args = {}, id } = part.functionCall; + return { name, args, id }; +} + +function collectPartsDelta(parts: ContentPart[]) { + const textParts: string[] = []; + const thoughts: string[] = []; + const calls: FunctionCallPart[] = []; + + for (const part of parts) { + if (part.text) { + (part.thought ? thoughts : textParts).push(part.text); + } + const call = toFunctionCallPart(part); + if (call) calls.push(call); + } + return { textParts, thoughts, calls }; +} + +export function parseGeminiChunk(chunk: GenerateContentResponse) { + const parts = extractChunkParts(chunk); + const { textParts, thoughts, calls } = collectPartsDelta(parts); + const text = textParts.join(''); + const thought = thoughts.join(''); + const event: StreamChunk = { + text: text || undefined, + thought: thought || undefined, + isThought: Boolean(thought), + functionCalls: calls.length ? calls : undefined, + finishReason: chunk.candidates?.[0]?.finishReason, + parts: parts.length ? parts : undefined, + }; + return { parts, calls, text, textParts, thoughts, event }; +} + +function notifyChunkDelta(delta: ReturnType, options?: SendMessageOptions): void { + if (!options) return; + if (options.onText) delta.textParts.forEach((part) => options.onText?.(part)); + if (options.onThought) delta.thoughts.forEach((part) => options.onThought?.(part)); +} + +export class GeminiSession { + private client: any; + private model: string; + private history: SessionContent[] = []; + private systemInstruction?: string; + private temperature: number; + private thinkingConfig?: ThinkingConfig; + private tools?: any[]; + private toolHandler?: (name: string, args: Record) => Promise>; + private maxToolRoundtrips: number; + + constructor(client: any, options?: GeminiSessionOptions) { + const opts = options ?? {}; + this.client = client; + this.model = opts.model ?? 'gemini-2.0-flash'; + this.systemInstruction = opts.systemInstruction; + this.temperature = opts.temperature ?? 0.7; + this.thinkingConfig = opts.thinkingConfig; + this.tools = normalizeTools(opts.tools); + this.toolHandler = opts.toolHandler; + this.maxToolRoundtrips = opts.maxToolRoundtrips ?? 10; + } + + getHistory(): SessionContent[] { + return JSON.parse(JSON.stringify(this.history)); + } + + setHistory(history: SessionContent[]): void { + this.history = JSON.parse(JSON.stringify(history)); + } + + clearHistory(): void { + this.history = []; + } + + async sendMessage(message: string, options?: SendMessageOptions): Promise { + const turn = this.streamTurn(message, options); + let next = await turn.next(); + while (!next.done) next = await turn.next(); + return next.value; + } + + sendMessageStream(message: string, options?: SendMessageOptions): AsyncIterable { + return this.streamTurn(message, options); + } + + private async *streamTurn( + message: string, + options?: SendMessageOptions + ): AsyncGenerator { + this.history.push({ role: 'user', parts: [{ text: message }] }); + let text = ''; + const thoughts: string[] = []; + let functionCalls: FunctionCallPart[] = []; + + for (let round = 0; round < this.maxToolRoundtrips; round++) { + text = ''; + functionCalls = []; + const parts: ContentPart[] = []; + const stream = await this.openStream(options); + + for await (const chunk of stream) { + const delta = parseGeminiChunk(chunk); + parts.push(...delta.parts); + functionCalls.push(...delta.calls); + text += delta.text; + thoughts.push(...delta.thoughts); + notifyChunkDelta(delta, options); + yield delta.event; + } + + this.history.push({ role: 'model', parts }); + if (!functionCalls.length || !this.toolHandler) break; + const responses = await this.runTools(this.toolHandler, functionCalls, options); + this.history.push({ role: 'user', parts: responses }); + } + + return { text, thoughts, functionCalls, history: this.getHistory() }; + } + + private openStream(options?: SendMessageOptions): Promise> { + const opts = options ?? {}; + return this.client.models.generateContentStream({ + model: this.model, + contents: this.history, + config: { + systemInstruction: this.systemInstruction, + temperature: this.temperature, + thinkingConfig: opts.thinkingConfig ?? this.thinkingConfig, + tools: this.tools, + abortSignal: opts.abortSignal, + }, + }); + } + + private async runTools( + handler: NonNullable, + calls: FunctionCallPart[], + options?: SendMessageOptions + ): Promise { + const responses: ContentPart[] = []; + for (const call of calls) { + options?.onToolCall?.(call); + const result = await this.invokeSingleTool(handler, call); + options?.onToolResult?.(call.name, result); + responses.push({ functionResponse: { name: call.name, response: result, id: call.id } }); + } + return responses; + } + + private async invokeSingleTool( + handler: NonNullable, + call: FunctionCallPart + ): Promise> { + try { + return await handler(call.name, call.args); + } catch (error) { + return { error: error instanceof Error ? error.message : String(error) }; + } + } +} diff --git a/src/ai/google-gemini.ts b/src/ai/google-gemini.ts index 261de355..8caa9ac7 100644 --- a/src/ai/google-gemini.ts +++ b/src/ai/google-gemini.ts @@ -52,4 +52,30 @@ export class GoogleGeminiAIClient implements AIClient { const data = (await response.json()) as any; return data.candidates?.[0]?.content?.parts?.[0]?.text ?? ''; } + + /** + * Applies sliding window truncation to input exceeding limit to avoid token exhaustion. + * @param input Raw log or prompt string. + * @param limit Maximum character limit (default 100,000). + */ + truncatePrompt(input: string, limit = 100_000): { text: string; truncated: boolean } { + if (input.length <= limit) return { text: input, truncated: false }; + const slice = input.slice(-limit); + return { + text: `[... Truncated earlier log entries ...]\n` + slice, + truncated: true, + }; + } + + /** + * Safely parses tool call JSON payload from model response, handling truncation or syntax errors. + */ + safeParseToolCall(raw: string): { success: boolean; data?: any; error?: string } { + try { + const parsed = JSON.parse(raw); + return { success: true, data: parsed }; + } catch (err: any) { + return { success: false, error: `Truncated function call JSON: ${err.message}` }; + } + } } diff --git a/src/ai/google-genai.ts b/src/ai/google-genai.ts new file mode 100644 index 00000000..8e89330b --- /dev/null +++ b/src/ai/google-genai.ts @@ -0,0 +1,236 @@ +import { GoogleGenAI, type GoogleGenAIOptions } from '@google/genai'; +import { AIProviderConfig } from '../config/schema'; +import { + AIClient, + GeminiSessionOptions, + GenerateContentOptions, + ModernAIClient, + StreamChunk, + StructuredOutputOptions, + ThinkingConfig, +} from './types'; +import { GeminiSession, normalizeTools, parseGeminiChunk } from './gemini-session'; + +export { normalizeTools }; + +const OPTION_KEYS = ['schema', 'validator', 'model', 'temperature', 'systemInstruction'] as const; + +function resolveApiKey(config: AIProviderConfig): string | undefined { + return ( + config.password || + process.env.GEMINI_API_KEY || + process.env.GOOGLE_GENAI_API_KEY || + process.env.GOOGLE_API_KEY + ); +} + +function buildClientOptions( + apiKey: string, + baseUrl?: string, + customHeaders?: Record +): GoogleGenAIOptions { + const options: GoogleGenAIOptions = { apiKey }; + if (baseUrl || customHeaders) { + options.httpOptions = { baseUrl, headers: customHeaders }; + } + return options; +} + +function readCandidateParts(response: any): any[] { + const candidates = response.candidates; + if (!Array.isArray(candidates) || !candidates.length) return []; + const content = candidates[0].content; + return Array.isArray(content?.parts) ? content.parts : []; +} + +function collectResponseText(response: any): string { + return readCandidateParts(response) + .filter((part: any) => !part.thought && Boolean(part.text)) + .map((part: any) => part.text) + .join(''); +} + +function extractText(response: any): string { + if (response.text !== undefined && response.text !== null) { + return response.text; + } + return collectResponseText(response); +} + +function isStructuredOptions(input: unknown): input is StructuredOutputOptions { + if (input === null || typeof input !== 'object') return false; + return OPTION_KEYS.some((key) => Object.hasOwn(input, key)); +} + +function parseJsonPayload(rawText: string): unknown { + if (!rawText.trim()) { + throw new Error('Google GenAI returned empty response for structured output request'); + } + try { + return JSON.parse(rawText); + } catch (err: any) { + throw new Error(`Failed to parse structured JSON output from Gemini: ${err.message}. Response was: ${rawText}`); + } +} + +function validateParsedOutput(parsed: unknown, validator: StructuredOutputOptions['validator']): T { + if (!validator) return parsed as T; + if (typeof (validator as any).parse === 'function') { + return (validator as any).parse(parsed); + } + return (validator as (data: unknown) => T)(parsed); +} + +function emitChunkCallbacks( + delta: ReturnType, + options: GenerateContentOptions +): void { + const { onText, onThought, onFunctionCall } = options; + if (onText) delta.textParts.forEach((text) => onText(text)); + if (onThought) delta.thoughts.forEach((thought) => onThought(thought)); + if (onFunctionCall) delta.calls.forEach((call) => onFunctionCall(call)); +} + +export class GoogleGenAIClient implements ModernAIClient, AIClient { + readonly name = 'google-genai'; + private client?: any; + private apiKey = ''; + private model = 'gemini-2.0-flash'; + private temperature = 0.7; + private topP?: number; + private topK?: number; + private maxOutputTokens?: number; + private baseUrl?: string; + private customHeaders?: Record; + private thinkingConfig?: ThinkingConfig; + + constructor(clientInstance?: any) { + if (clientInstance) { + this.client = clientInstance; + } + } + + setClient(client: any): void { + this.client = client; + } + + private requireClient(): any { + if (!this.client) { + throw new Error('GoogleGenAIClient is not configured. Call configure() before use.'); + } + return this.client; + } + + async configure(config: AIProviderConfig): Promise { + const key = resolveApiKey(config); + if (!key && !this.client) { + throw new Error('API key is required for Google GenAI provider (password field in AIProviderConfig)'); + } + + this.apiKey = key ?? ''; + this.model = config.model || 'gemini-2.0-flash'; + this.temperature = config.temperature ?? 0.7; + this.topP = config.topP; + this.topK = config.topK; + this.maxOutputTokens = config.maxTokens; + this.baseUrl = config.baseUrl ? config.baseUrl.replace(/\/+$/, '') : undefined; + this.customHeaders = config.customHeaders; + + if (!this.client) { + this.client = new GoogleGenAI(buildClientOptions(this.apiKey, this.baseUrl, this.customHeaders)); + } + } + + async getCompletion(prompt: string): Promise { + const client = this.requireClient(); + const response = await client.models.generateContent({ + model: this.model, + contents: prompt, + config: { + temperature: this.temperature, + topP: this.topP, + topK: this.topK, + maxOutputTokens: this.maxOutputTokens, + }, + }); + return extractText(response); + } + + private buildStreamRequest(promptOrParts: string | any[], options: GenerateContentOptions) { + const contents = + typeof promptOrParts === 'string' + ? [{ role: 'user', parts: [{ text: promptOrParts }] }] + : promptOrParts; + + return { + model: options.model ?? this.model, + contents, + config: { + temperature: options.temperature ?? this.temperature, + topP: options.topP ?? this.topP, + topK: options.topK ?? this.topK, + maxOutputTokens: options.maxOutputTokens ?? this.maxOutputTokens, + systemInstruction: options.systemInstruction, + thinkingConfig: options.thinkingConfig ?? this.thinkingConfig, + tools: normalizeTools(options.tools), + responseMimeType: options.responseMimeType, + responseSchema: options.responseSchema, + abortSignal: options.abortSignal, + }, + }; + } + + async *generateContentStream( + promptOrParts: string | any[], + options?: GenerateContentOptions + ): AsyncIterable { + const client = this.requireClient(); + const opts = options ?? {}; + const stream = await client.models.generateContentStream(this.buildStreamRequest(promptOrParts, opts)); + + for await (const chunk of stream) { + const delta = parseGeminiChunk(chunk); + emitChunkCallbacks(delta, opts); + yield delta.event; + } + } + + createSession(options?: GeminiSessionOptions): GeminiSession { + const client = this.requireClient(); + const opts = options ?? {}; + return new GeminiSession(client, { + ...opts, + model: opts.model ?? this.model, + temperature: opts.temperature ?? this.temperature, + thinkingConfig: opts.thinkingConfig ?? this.thinkingConfig, + }); + } + + async getStructuredOutput( + prompt: string, + schemaOrOptions: unknown | StructuredOutputOptions + ): Promise { + const client = this.requireClient(); + const options: StructuredOutputOptions = isStructuredOptions(schemaOrOptions) + ? schemaOrOptions + : { schema: schemaOrOptions }; + + const response = await client.models.generateContent({ + model: options.model ?? this.model, + contents: prompt, + config: { + temperature: options.temperature ?? 0.1, + systemInstruction: options.systemInstruction, + responseMimeType: 'application/json', + responseSchema: options.schema, + }, + }); + + const parsed = parseJsonPayload(extractText(response)); + return validateParsedOutput(parsed, options.validator); + } + + async close(): Promise { + this.client = undefined; + } +} diff --git a/src/ai/types.ts b/src/ai/types.ts index 7a31da1b..3715f0cc 100644 --- a/src/ai/types.ts +++ b/src/ai/types.ts @@ -26,3 +26,90 @@ export interface AIClient { */ close?(): Promise; } + +export interface FunctionCallPart { + name: string; + args: Record; + id?: string; +} + +export interface StreamChunk { + text?: string; + thought?: string; + isThought?: boolean; + functionCalls?: FunctionCallPart[]; + finishReason?: string; + parts?: any[]; +} + +export interface StreamCallbacks { + onText?: (delta: string) => void; + onThought?: (thoughtDelta: string) => void; + onFunctionCall?: (functionCall: FunctionCallPart) => void; + onError?: (error: Error) => void; +} + +export interface ThinkingConfig { + includeThoughts?: boolean; + thinkingBudget?: number; +} + +export interface GenerateContentOptions extends StreamCallbacks { + model?: string; + temperature?: number; + topP?: number; + topK?: number; + maxOutputTokens?: number; + systemInstruction?: string; + thinkingConfig?: ThinkingConfig; + tools?: any[]; // Tool[] or FunctionDeclaration[] + responseSchema?: unknown; + responseMimeType?: string; + abortSignal?: AbortSignal; +} + +export interface StructuredOutputOptions { + model?: string; + schema?: unknown; + systemInstruction?: string; + temperature?: number; + validator?: ((data: unknown) => T) | { parse: (data: unknown) => T }; +} + +export interface GeminiSessionOptions { + model?: string; + systemInstruction?: string; + temperature?: number; + thinkingConfig?: ThinkingConfig; + tools?: any[]; + toolHandler?: (name: string, args: Record) => Promise>; + maxToolRoundtrips?: number; +} + +export interface SendMessageOptions extends StreamCallbacks { + thinkingConfig?: ThinkingConfig; + onToolCall?: (toolCall: FunctionCallPart) => void; + onToolResult?: (name: string, result: Record) => void; + abortSignal?: AbortSignal; +} + +export interface SessionMessageResponse { + text: string; + thoughts: string[]; + functionCalls: FunctionCallPart[]; + history: any[]; +} + +export interface ModernAIClient extends AIClient { + generateContentStream( + promptOrParts: string | any[], + options?: GenerateContentOptions + ): AsyncIterable; + + createSession(options?: GeminiSessionOptions): any; // GeminiSession + + getStructuredOutput( + prompt: string, + schemaOrOptions: unknown | StructuredOutputOptions + ): Promise; +} diff --git a/src/analysis/__tests__/analysis-baseline.test.ts b/src/analysis/__tests__/analysis-baseline.test.ts index ed574b0c..35462691 100644 --- a/src/analysis/__tests__/analysis-baseline.test.ts +++ b/src/analysis/__tests__/analysis-baseline.test.ts @@ -77,13 +77,15 @@ vi.mock('../../kubernetes/resources', () => ({ const mockGetCompletion = vi.fn(); vi.mock('../../ai/factory', () => ({ + resolveAIProviderConfig: vi.fn(), createAIClient: vi.fn(async () => ({ getCompletion: mockGetCompletion, model: 'test-model', })), })); -vi.mock('../../agent/python-bridge', () => ({ +vi.mock('../../agent/python-bridge', async importOriginal => ({ + ...await importOriginal(), runAgentCouncilProcess: vi.fn(), runPythonAgentCouncil: vi.fn(), isPythonAgentAvailable: vi.fn(async () => false), diff --git a/src/analysis/analysis.ts b/src/analysis/analysis.ts index 193aeb69..f8ff1af3 100644 --- a/src/analysis/analysis.ts +++ b/src/analysis/analysis.ts @@ -3,7 +3,7 @@ import { registry } from '../analyzers'; import { measureDuration } from './stats'; import { getActiveFilters, getAIConfig, getCacheConfig, getConfig } from '../config/store'; import type { Analyzer, AnalyzerResult } from '../analyzers/types'; -import { createAIClient } from '../ai/factory'; +import { createAIClient, resolveAIProviderConfig } from '../ai/factory'; import { buildPrompt } from '../ai/prompts'; import { anonymize, deanonymize } from '../utils/text'; import { createCacheProvider } from '../cache'; @@ -12,6 +12,7 @@ import { runPythonAgentCouncil, runAgentCouncilProcess, isPythonAgentAvailable, + resolveCouncilTimeoutMs, } from '../agent/python-bridge'; import type { ConsensusDiagnosis, AgentProgressEvent, NDJSONEvent } from '../agent/types'; import { @@ -277,6 +278,27 @@ function applyAnonymization( return shouldAnonymize ? deanonymize(text, mapping) : text; } +function restoreConsensusNames(consensus: ConsensusDiagnosis, mapping: ReturnType['mapping']): ConsensusDiagnosis { + if (mapping.length === 0) return consensus; + const restore = (text: string) => deanonymize(text, mapping); + return { + ...consensus, + rootCause: restore(consensus.rootCause), + findings: consensus.findings.map(finding => ({ + ...finding, + statusText: restore(finding.statusText), + summary: finding.summary && restore(finding.summary), + evidence: finding.evidence?.map(restore), + })), + bestSolution: { + ...consensus.bestSolution, + actionTitle: restore(consensus.bestSolution.actionTitle), + steps: consensus.bestSolution.steps.map(restore), + commandToRun: consensus.bestSolution.commandToRun && restore(consensus.bestSolution.commandToRun), + }, + }; +} + async function attemptPrimaryCouncil( params: ExplainSingleParams, promptText: string, @@ -297,10 +319,10 @@ async function attemptPrimaryCouncil( async function attemptPrimaryClient( backend: string, - prompt: string + prompt: string, + client: Awaited>, ): Promise { try { - const client = await createAIClient(backend); const rawResponse = await client.getCompletion(prompt); if (rawResponse) { return { success: true, response: rawResponse }; @@ -316,12 +338,13 @@ async function executePrimaryStep( params: ExplainSingleParams, promptText: string, prompt: string, - model: string + model: string, + client: Awaited>, ): Promise { if (params.backend.toLowerCase() === 'ollama') { return attemptPrimaryCouncil(params, promptText, model); } - return attemptPrimaryClient(params.backend, prompt); + return attemptPrimaryClient(params.backend, prompt, client); } async function executeFallbackSteps( @@ -373,8 +396,8 @@ export async function explainSingleResult(params: ExplainSingleParams): Promise< analyzerName: params.result.kind, }); - const client = await createAIClient(params.backend); - const model = params.model || ((client as any).model ?? ''); + const client = await createAIClient(params.backend, params.model, params.customHeaders); + const model = params.model || resolveAIProviderConfig(params.backend)?.model || ''; const cacheKey = await buildCacheKey({ provider: params.backend, @@ -389,7 +412,7 @@ export async function explainSingleResult(params: ExplainSingleParams): Promise< return; } - const primary = await executePrimaryStep(params, promptText, prompt, model); + const primary = await executePrimaryStep(params, promptText, prompt, model, client); if (primary.success && primary.response) { params.result.details = applyAnonymization(primary.response, mapping, params.shouldAnonymize); if (!params.noCache) { @@ -482,7 +505,7 @@ async function runSingleAnalyzer(params: RunSingleParams): Promise { params.stats.push({ analyzer: params.analyzer.name, durationMs }); } - params.results.push(...analyzerResults); + params.results.push(...analyzerResults.filter(result => !params.options.resourceName || result.name === params.options.resourceName)); } catch (err: any) { params.errors.push(`Analyzer ${params.analyzer.name} failed: ${err?.message || String(err)}`); } @@ -576,55 +599,48 @@ async function executeCouncilForResults( results: AnalyzerResult[], options: AnalysisOptions, ): Promise { - const primaryResult = results.find((result) => result.errors.length > 0) || results[0]; - const failureText = results - .flatMap((r) => r.errors.map((e) => e.text)) - .join('\n') || (options.targetResource ? `Workload ${options.targetResource} failure` : options.labelSelector ? `Workload matching selector ${options.labelSelector} failure` : 'Cluster workload failure'); - - const targetKind = primaryResult?.kind || (options.targetResource?.includes('/') ? options.targetResource.split('/')[0] : 'Workload'); - const targetName = primaryResult?.name || options.resourceName || options.labelSelector || 'cluster'; - - const targetContext = { - namespace: primaryResult?.namespace || options.namespace, - kind: targetKind, - name: targetName, - }; - - try { - const baseUrl = resolveOllamaBaseUrl(); - const dependencies = await checkCouncilDependencies(baseUrl); - if (!dependencies.canRunCouncil) { - throw new Error(dependencies.degradationReason || 'Council dependencies are unavailable'); - } + const failures = results.filter(result => result.errors.length > 0); + if (!failures.length || options.signal?.aborted) return; - const runner = runAgentCouncilProcess || runPythonAgentCouncil; - const consensus = await runner({ - failureText, - context: targetContext, - model: options.model, - baseUrl, - timeoutMs: options.councilTimeoutMs, - }); + const baseUrl = resolveOllamaBaseUrl(); + const deps = await checkCouncilDependencies(baseUrl); + if (!deps.canRunCouncil) { + await applyCouncilFallbacks(failures, options, deps.degradationReason || 'Council unavailable'); + return; + } - if (primaryResult) { - (primaryResult as any).consensus = consensus; - primaryResult.details = formatConsensusExplanation(consensus); - primaryResult.fallbackStep = 'council'; - } else { - results.push({ - kind: targetContext.kind, - name: targetContext.name, - namespace: targetContext.namespace || 'default', - errors: [{ text: failureText }], - details: formatConsensusExplanation(consensus), - consensus, - fallbackStep: 'council', - } as any); + const model = options.model || getAIConfig().providers.find(p => p.name.toLowerCase() === 'ollama')?.model; + const deadline = performance.now() + resolveCouncilTimeoutMs(options.councilTimeoutMs); + const pendingFallbacks: AnalyzerResult[] = []; + for (const [index, result] of failures.entries()) { + if (options.signal?.aborted) return; + const remainingMs = Math.floor(deadline - performance.now()); + if (remainingMs <= 0) { + pendingFallbacks.push(...failures.slice(index)); + break; } - } catch (err) { - const degradationReason = (err as Error).message; - logger.warn(`Multi-agent council bridge failed: ${degradationReason}. Falling back to diagnostics.`); - await applyCouncilFallbacks(results, options, degradationReason); + const failureText = result.errors.map(error => error.text).join('\n'); + const { promptText, mapping } = preparePromptMapping(failureText, options.anonymize); + try { + const consensus = await runAgentCouncilProcess({ + failureText: promptText, + context: options.anonymize ? { kind: result.kind } : { + kind: result.kind, name: result.name, namespace: result.namespace, + }, + model, baseUrl, timeoutMs: remainingMs, + }); + result.consensus = restoreConsensusNames(consensus, mapping); + result.details = formatConsensusExplanation(result.consensus); + result.fallbackStep = 'council'; + } catch (error) { + const reason = error instanceof Error ? error.message : String(error); + logger.warn('Multi-agent council bridge failed: ' + reason); + result.fallbackReason = reason; + pendingFallbacks.push(result); + } + } + if (!options.signal?.aborted) { + await applyCouncilFallbacks(pendingFallbacks, options, 'Council time budget exhausted'); } } @@ -637,7 +653,7 @@ async function applyCouncilFallbacks( const backend = resolveBackend(options); for (const result of results) { if (result.errors.length > 0) { - await applyCouncilFallbackForResult(result, options, backend, degradationReason); + await applyCouncilFallbackForResult(result, options, backend, result.fallbackReason ?? degradationReason); } } } diff --git a/src/analysis/fallback.ts b/src/analysis/fallback.ts index a1659219..70324ab8 100644 --- a/src/analysis/fallback.ts +++ b/src/analysis/fallback.ts @@ -68,8 +68,8 @@ export function applyRuleEngineFallback( if (!match) return null; const notice = ctx.degradationReason || 'Local AI unavailable'; - logger.info(`Notice: ${notice}.`); - logger.info('Running in Deterministic Rule Mode (zero LLM overhead)...'); + logger.warn(`Notice: ${notice}.`); + logger.warn('Running in Deterministic Rule Mode (zero LLM overhead)...'); const formattedDetails = ruleEngine.formatMatch(match, notice); diff --git a/src/analyzers/types.ts b/src/analyzers/types.ts index 71b5dd23..18b98aee 100644 --- a/src/analyzers/types.ts +++ b/src/analyzers/types.ts @@ -19,6 +19,7 @@ export interface AnalyzerResult { parentObject?: string; errors: Failure[]; details?: string; + consensus?: import('../agent/types').ConsensusDiagnosis; fallbackBadge?: string; fallbackReason?: string; fallbackStep?: 'council' | 'rule_engine' | 'legacy_ai' | 'raw_summary'; diff --git a/src/commands/analyze.ts b/src/commands/analyze.ts index 235ef12e..bbddbaaf 100644 --- a/src/commands/analyze.ts +++ b/src/commands/analyze.ts @@ -81,7 +81,7 @@ const buildAnalysisOptions = (options: any, signal: AbortSignal): AnalysisOption language: options.language, anonymize: Boolean(options.anonymize), customHeaders: options.customHeaders, - noCache: Boolean(options.noCache), + noCache: options.cache === false, councilTimeoutMs: options.councilTimeout, exportAudit: options.exportAudit, multiAgent: options.multiAgent ? Boolean(options.multiAgent) : undefined, @@ -159,7 +159,11 @@ async function handleExportAudit( }; await exportIncidentAudit(exportPath, session); - logger.success(`Incident audit exported to ${exportPath}`); + if (runOpts.output === 'json') { + console.error(chalk.green(`✔ Incident audit exported to ${exportPath}`)); + } else { + logger.success(`Incident audit exported to ${exportPath}`); + } } /** @@ -235,12 +239,12 @@ async function handleAnalyze(resourceOrOptions: any, optionsOrCommand?: any): Pr output = parseOutput(options.output); const runOpts = buildAnalysisOptions(options, abortController.signal); - if (output === 'json') { + if (!runOpts.interactive) { const result = await runAnalysis(runOpts); if (options.exportAudit) { await handleExportAudit(options.exportAudit, runOpts, result); } - printAnalysisResult(result, 'json'); + printAnalysisResult(result, output); return; } diff --git a/src/commands/copilot.tsx b/src/commands/copilot.tsx new file mode 100644 index 00000000..837680f6 --- /dev/null +++ b/src/commands/copilot.tsx @@ -0,0 +1,44 @@ +/** + * Copilot Command — KDM CLI + * Launches the interactive Gemini + Multi-Agent SRE Copilot Shell. + */ + +import { Command, InvalidArgumentError } from 'commander'; +import { render } from 'ink'; +import { CopilotShell } from '../ui/CopilotShell.js'; + +function parseTab(input: string) { + if (!/^[1-4]$/.test(input)) throw new InvalidArgumentError('Choose a tab from 1 through 4.'); + return Number(input); +} + +function canStartCopilot() { + const inCI = !/^(?:false|0)?$/i.test(process.env.CI ?? '') || process.env.GITHUB_ACTIONS === 'true'; + return Boolean(!inCI && process.stdin.isTTY && process.stdout.isTTY); +} + +export const registerCopilotCommand = (program: Command) => { + program + .command('copilot [resource]') + .alias('agent') + .alias('chat') + .description('Interactive AI SRE Copilot Shell with Gemini & Multi-Agent Council') + .option('-t, --tab ', 'Initial tab (1: Monitor, 2: Agents, 3: Diffs, 4: Settings)', parseTab, 1) + .action(async (resource, options) => { + if (!canStartCopilot()) { + program.error('kdm copilot requires an interactive terminal and cannot run in CI.'); + } + // Clear terminal screen before launching the shell + process.stdout.write('\x1Bc'); + + const appInstance = render( + appInstance.unmount()} + /> + ); + + await appInstance.waitUntilExit(); + }); +}; diff --git a/src/commands/root.ts b/src/commands/root.ts index 57b28517..1c456c3e 100644 --- a/src/commands/root.ts +++ b/src/commands/root.ts @@ -14,7 +14,7 @@ import { registerAuthCommand } from './auth'; import { registerCacheCommand } from './cache'; import { registerServeCommand } from './serve'; import { registerCustomAnalyzerCommand } from './custom-analyzer'; -import { logger } from '../utils/logger'; +import { registerCopilotCommand } from './copilot'; import { showWelcomeBanner } from '../ui/banner'; import { createSpinner } from '../ui/spinner'; import { checkForUpdates, getInstalledVersion } from '../utils/version-check'; @@ -39,6 +39,7 @@ registerAuthCommand(program); registerCacheCommand(program); registerServeCommand(program); registerCustomAnalyzerCommand(program); +registerCopilotCommand(program); // Register integration analyzers registerIntegrations(); diff --git a/src/remediation/executor.ts b/src/remediation/executor.ts index a24355a6..0a31864e 100644 --- a/src/remediation/executor.ts +++ b/src/remediation/executor.ts @@ -36,6 +36,7 @@ export interface ExecutionOptions { rollbackCommand?: string; cwd?: string; env?: NodeJS.ProcessEnv; + stdin?: string; execFileFn?: ( file: string, args: string[], @@ -252,11 +253,14 @@ function recordAuditEntry( * @returns Promise resolving to ExecutionResult with stdout, stderr, exit code, and duration. */ export async function executeRemediationCommand( - commandStr: string, + command: string | readonly [string, ...string[]], options: ExecutionOptions = {} ): Promise { const startTime = Date.now(); - const { file, args } = splitCommand(commandStr); + const commandStr = typeof command === 'string' ? command : command.join(' '); + const { file, args } = typeof command === 'string' + ? splitCommand(command) + : { file: command[0], args: command.slice(1) }; const rollback = options.rollbackCommand; if (!file) { @@ -279,14 +283,21 @@ export async function executeRemediationCommand( } const timeout = options.timeoutMs ?? DEFAULT_TIMEOUT_MS; - const execFn = options.execFileFn ?? execFileAsync; - try { - const { stdout, stderr } = await execFn(file, args, { + const processOptions = { timeout, cwd: options.cwd, env: options.env, + }; + const run = options.execFileFn ?? (() => { + const execution = execFileAsync(file, args, processOptions); + if (options.stdin !== undefined) { + execution.child.stdin?.on('error', () => {}); + execution.child.stdin?.end(options.stdin); + } + return execution; }); + const { stdout, stderr } = await run(file, args, processOptions); const result = createResult({ success: true, exitCode: 0, diff --git a/src/tools/declarative-tool.ts b/src/tools/declarative-tool.ts new file mode 100644 index 00000000..64d6dee8 --- /dev/null +++ b/src/tools/declarative-tool.ts @@ -0,0 +1,177 @@ +/** + * Declarative Tool Abstraction — KDM v4.0.0 + * ========================================= + * Base declarative tool interfaces, parameter schema validation with Zod, + * safety classification, and conversion to @google/genai FunctionDeclaration. + */ + +import { z } from 'zod'; +import { Type, type FunctionDeclaration, type Schema } from '@google/genai'; + +export type ToolSafetyLevel = 'read_only' | 'mutating'; +export type ToolRiskLevel = 'low' | 'medium' | 'high'; + +export interface ToolExecutionContext { + signal?: AbortSignal; + dryRun?: boolean; + namespace?: string; + approveMutation?: (name: string, input: unknown) => Promise; + auditTrail?: any; + [key: string]: unknown; +} + +export interface DeclarativeToolDefinition { + name: string; + description: string; + safetyLevel?: ToolSafetyLevel; + safety?: ToolSafetyLevel; // Harness compatibility + riskLevel?: ToolRiskLevel; + schema?: z.ZodType; + parameters?: z.ZodType; // Harness compatibility + execute: (input: TInput, context?: ToolExecutionContext) => Promise; +} + +/** + * Converts a Zod schema into a @google/genai OpenAPI 3.03 Schema object. + */ +export function zodToGenAiSchema(schema: z.ZodTypeAny): Schema { + const value = schemaForType(schema); + return schema.description ? { ...value, description: schema.description } : value; +} + +function schemaForType(schema: z.ZodTypeAny): Schema { + if (schema instanceof z.ZodOptional) return zodToGenAiSchema(schema.unwrap()); + if (schema instanceof z.ZodNullable) return { ...zodToGenAiSchema(schema.unwrap()), nullable: true }; + if (schema instanceof z.ZodDefault) return defaultSchema(schema); + if (schema instanceof z.ZodEffects) return zodToGenAiSchema(schema.innerType()); + return schemaForValue(schema); +} + +function defaultSchema(schema: z.ZodDefault): Schema { + const inner = zodToGenAiSchema(schema.removeDefault()); + try { + return { ...inner, default: schema._def.defaultValue() }; + } catch { + return inner; + } +} + +function nativeEnumSchema(enumObj: Record): Schema { + const values = Object.entries(enumObj) + .filter(([key]) => Number.isNaN(Number(key))) + .map(([, val]) => val); + const stringValues = values.filter((v): v is string => typeof v === 'string'); + const numberValues = values.filter((v): v is number => typeof v === 'number'); + if (stringValues.length > 0 && numberValues.length === 0) { + return { type: Type.STRING, enum: stringValues }; + } + if (numberValues.length > 0 && stringValues.length === 0) { + const type = numberValues.every(Number.isInteger) ? Type.INTEGER : Type.NUMBER; + return { type, format: 'enum', enum: numberValues.map(String) }; + } + throw new Error('Unsupported native enum schema: mixed or empty enum values'); +} + +function schemaForValue(schema: z.ZodTypeAny): Schema { + if (schema instanceof z.ZodObject) return objectSchema(schema.shape); + if (schema instanceof z.ZodArray) return { type: Type.ARRAY, items: zodToGenAiSchema(schema.element) }; + if (schema instanceof z.ZodNumber) return { type: schema.isInt ? Type.INTEGER : Type.NUMBER }; + if (schema instanceof z.ZodBoolean) return { type: Type.BOOLEAN }; + if (schema instanceof z.ZodEnum) return { type: Type.STRING, enum: schema.options }; + if (schema instanceof z.ZodNativeEnum) return nativeEnumSchema(schema.enum); + return { type: Type.STRING }; +} + +function objectSchema(shape: z.ZodRawShape): Schema { + const fields = Object.entries(shape); + const properties = Object.fromEntries(fields.map(([name, field]) => [name, zodToGenAiSchema(field)])); + const required = fields.filter(([, field]) => requiresInput(field)).map(([name]) => name); + return { type: Type.OBJECT, properties, ...(required.length ? { required } : {}) }; +} + +function requiresInput(schema: z.ZodTypeAny): boolean { + if (schema instanceof z.ZodOptional || schema instanceof z.ZodDefault) return false; + if (schema instanceof z.ZodNullable) return requiresInput(schema.unwrap()); + if (schema instanceof z.ZodEffects) return requiresInput(schema.innerType()); + return true; +} + +/** + * Base abstract class for declarative tools. + */ +export abstract class BaseDeclarativeTool { + abstract readonly name: string; + abstract readonly description: string; + readonly safetyLevel: ToolSafetyLevel = 'read_only'; + readonly riskLevel: ToolRiskLevel = 'low'; + abstract readonly schema: z.ZodType; + + /** Getter alias for harness compatibility */ + get safety(): ToolSafetyLevel { + return this.safetyLevel; + } + + /** Getter alias for harness compatibility */ + get parameters(): z.ZodType { + return this.schema; + } + + abstract execute(input: TInput, context?: ToolExecutionContext): Promise; + + /** + * Validates raw input arguments against the tool's Zod schema. + */ + validate(rawArgs: unknown): TInput { + return this.schema.parse(rawArgs); + } + + /** + * Converts the tool's parameter schema to @google/genai FunctionDeclaration format. + */ + toGeminiToolDeclaration(): FunctionDeclaration { + return { + name: this.name, + description: this.description, + parameters: zodToGenAiSchema(this.schema), + }; + } +} + +/** + * Concrete DeclarativeTool implementation supporting object-based initialization. + */ +export class DeclarativeTool extends BaseDeclarativeTool { + readonly name: string; + readonly description: string; + readonly safetyLevel: ToolSafetyLevel; + readonly riskLevel: ToolRiskLevel; + readonly schema: z.ZodType; + private readonly executeFn: (input: TInput, context?: ToolExecutionContext) => Promise; + + constructor(def: DeclarativeToolDefinition) { + super(); + this.name = def.name; + this.description = def.description; + this.safetyLevel = def.safetyLevel ?? def.safety ?? 'read_only'; + this.riskLevel = def.riskLevel ?? (this.safetyLevel === 'mutating' ? 'high' : 'low'); + const s = def.schema ?? def.parameters; + if (!s) { + throw new Error(`Tool '${def.name}' must have a schema or parameters defined.`); + } + this.schema = s; + this.executeFn = def.execute; + } + + execute(input: TInput, context?: ToolExecutionContext): Promise { + return this.executeFn(input, context); + } +} + +/** + * Convenience factory function to create a DeclarativeTool. + */ +export function createDeclarativeTool( + def: DeclarativeToolDefinition +): DeclarativeTool { + return new DeclarativeTool(def); +} diff --git a/src/tools/docker-tools.ts b/src/tools/docker-tools.ts new file mode 100644 index 00000000..714f3b40 --- /dev/null +++ b/src/tools/docker-tools.ts @@ -0,0 +1,261 @@ +/** + * Declarative Docker Tools — KDM v4.0.0 + * ===================================== + * Host container monitoring, inspection, diagnostic, and remediation tools + * conforming to BaseDeclarativeTool with safety gating. + */ + +import { z } from 'zod'; +import { DeclarativeTool } from './declarative-tool'; +import { getDockerClient } from '../docker/client'; +import { executeRemediationCommand } from '../remediation/executor'; + +const containerReference = z.string().regex(/^[a-z0-9][a-z0-9_.-]*$/i, 'Expected a Docker container ID or name'); + +function isValidStreamByte(byte: number): boolean { + return byte === 1 || byte === 2; +} + +function readFramePayload(buffer: Buffer, offset: number): { payload: Buffer; nextOffset: number } { + const start = offset + 8; + if (start > buffer.length) throw new Error('Invalid Docker log frame header'); + if (!isValidStreamByte(buffer[offset])) throw new Error('Invalid Docker log frame header'); + const end = start + buffer.readUInt32BE(offset + 4); + if (end > buffer.length) throw new Error('Incomplete Docker log frame'); + return { payload: buffer.subarray(start, end), nextOffset: end }; +} + +function decodeLogFrames(buffer: Buffer): string { + const payloads: Buffer[] = []; + for (let offset = 0; offset < buffer.length;) { + const frame = readFramePayload(buffer, offset); + payloads.push(frame.payload); + offset = frame.nextOffset; + } + return Buffer.concat(payloads).toString('utf8'); +} + +function formatContainerRow(c: any) { + const names: string[] = c.Names ?? []; + const firstName = names[0] ?? ''; + return { + id: c.Id.substring(0, 12), + name: firstName.replace('/', '') || 'unknown', + image: c.Image, + state: c.State, + status: c.Status, + created: c.Created, + ports: c.Ports, + }; +} + +function formatContainerState(state: any) { + return { + state: state.Status, + status: state.Status, + exitCode: state.ExitCode, + oomKilled: state.OOMKilled, + restarting: state.Restarting, + startedAt: state.StartedAt, + finishedAt: state.FinishedAt, + }; +} + +function resolveContainerName({ rawName, fallback }: { rawName?: string; fallback: string }): string { + if (!rawName) return fallback; + return rawName.replace('/', '') || fallback; +} + +function formatContainerInspection({ info, containerId }: { info: any; containerId: string }) { + const state = info.State ?? {}; + const config = info.Config ?? {}; + return { + containerId: info.Id ? info.Id.substring(0, 12) : containerId, + name: resolveContainerName({ rawName: info.Name, fallback: containerId }), + image: config.Image, + ...formatContainerState(state), + env: config.Env, + mounts: info.Mounts, + }; +} + +async function readContainerLogsViaSdk(params: { + containerId: string; + tail: number; + stdout: boolean; + stderr: boolean; + timestamps: boolean; +}): Promise { + const container = getDockerClient().getContainer(params.containerId); + const info = await container.inspect(); + const logsBuf = await container.logs({ + stdout: params.stdout, + stderr: params.stderr, + tail: params.tail, + timestamps: params.timestamps, + }); + return info.Config?.Tty === false ? decodeLogFrames(logsBuf) : String(logsBuf); +} + +function formatContainerLogStreams(ctx: { stdout: boolean; stderr: boolean; output: { stdout: string; stderr: string } }): string { + const streams: string[] = []; + if (ctx.stdout && ctx.output.stdout) streams.push(ctx.output.stdout); + if (ctx.stderr && ctx.output.stderr) streams.push(ctx.output.stderr); + return streams.join('\n'); +} + +async function readContainerLogsViaCli(params: { + containerId: string; + tail: number; + stdout: boolean; + stderr: boolean; + timestamps: boolean; +}): Promise { + const tsArgs = params.timestamps ? ['--timestamps'] : []; + const cmdResult = await executeRemediationCommand([ + 'docker', 'logs', '--tail', String(params.tail), ...tsArgs, params.containerId, + ]); + if (!cmdResult.success) { + throw new Error(`Failed to retrieve logs for ${params.containerId}: ${cmdResult.stderr}`); + } + return formatContainerLogStreams({ stdout: params.stdout, stderr: params.stderr, output: cmdResult }); +} + +function filterContainersByStatus(ctx: { containers: any[]; status?: string }) { + if (!ctx.status || ctx.status === 'all') return ctx.containers; + return ctx.containers.filter((c) => String(c.State ?? '').toLowerCase() === ctx.status); +} + +function buildContainerLogQuery(params: { + containerId: string; + tail?: number; + stdout?: boolean; + stderr?: boolean; + timestamps?: boolean; +}) { + return { + containerId: params.containerId, + tail: params.tail ?? 100, + stdout: params.stdout !== false, + stderr: params.stderr !== false, + timestamps: params.timestamps ?? false, + }; +} + +async function fetchContainerLogsWithFallback(query: { + containerId: string; + tail: number; + stdout: boolean; + stderr: boolean; + timestamps: boolean; +}): Promise { + try { + return await readContainerLogsViaSdk(query); + } catch { + return readContainerLogsViaCli(query); + } +} + +// ─── 1. docker_list_containers ────────────────────────────────────────────── + +export const dockerListContainersTool = new DeclarativeTool({ + name: 'docker_list_containers', + description: 'List Docker containers on the host with optional status filtering (all, running, exited, restarting).', + safety: 'read_only', + riskLevel: 'low', + parameters: z.object({ + all: z.boolean().optional().default(true).describe('Include stopped containers (default: true)'), + status: z.enum(['all', 'running', 'exited', 'restarting', 'paused']).optional().default('all').describe('Filter containers by state'), + limit: z.number().int().positive().optional().describe('Maximum number of containers to return'), + }), + execute: async ({ all, status, limit }) => { + const rawContainers = await getDockerClient().listContainers({ all: all ?? true }); + const filtered = filterContainersByStatus({ containers: rawContainers, status }); + const containers = filtered.slice(0, limit).map(formatContainerRow); + return { count: containers.length, containers }; + }, +}); + +// ─── 2. docker_inspect_container ──────────────────────────────────────────── + +export const dockerInspectContainerTool = new DeclarativeTool({ + name: 'docker_inspect_container', + description: 'Inspect detailed configuration, state, exit code, health, and network settings of a Docker container.', + safety: 'read_only', + riskLevel: 'low', + parameters: z.object({ + containerId: containerReference.describe('Docker container ID or container name'), + }), + execute: async ({ containerId }) => { + const container = getDockerClient().getContainer(containerReference.parse(containerId)); + const info = await container.inspect(); + return formatContainerInspection({ info, containerId }); + }, +}); + +// ─── 3. docker_get_logs ───────────────────────────────────────────────────── + +export const dockerGetLogsTool = new DeclarativeTool({ + name: 'docker_get_logs', + description: 'Retrieve stdout and stderr logs from a specified Docker container.', + safety: 'read_only', + riskLevel: 'low', + parameters: z.object({ + containerId: containerReference.describe('Docker container ID or name'), + tail: z.number().int().positive().optional().default(100).describe('Number of lines from end of log (default: 100)'), + stdout: z.boolean().optional().default(true).describe('Include stdout'), + stderr: z.boolean().optional().default(true).describe('Include stderr'), + timestamps: z.boolean().optional().default(false).describe('Include timestamps'), + }), + execute: async ({ containerId, tail, stdout, stderr, timestamps }) => { + containerReference.parse(containerId); + const query = buildContainerLogQuery({ containerId, tail, stdout, stderr, timestamps }); + const output = await fetchContainerLogsWithFallback(query); + + const lines = output.split('\n').filter((l) => l.trim().length > 0); + return { + containerId, + tail, + linesCount: lines.length, + logs: output, + lines, + }; + }, +}); + +// ─── 4. docker_restart_container (Mutating) ───────────────────────────────── + +async function restartViaSdkOrCli(containerId: string, timeoutSeconds: number): Promise { + try { + const container = getDockerClient().getContainer(containerId); + await container.restart({ t: timeoutSeconds }); + } catch { + const cmd = ['docker', 'restart', '-t', String(timeoutSeconds), containerId] as const; + const result = await executeRemediationCommand(cmd); + if (!result.success) { + throw new Error(`Failed to restart container ${containerId}: ${result.stderr}`); + } + } +} + +export const dockerRestartContainerTool = new DeclarativeTool({ + name: 'docker_restart_container', + description: 'Restart a running or stopped Docker container. This is a mutating operation.', + safety: 'mutating', + riskLevel: 'medium', + parameters: z.object({ + containerId: containerReference.describe('Docker container ID or name to restart'), + timeoutSeconds: z.number().int().min(0).optional().default(10).describe('Seconds to wait before killing the container'), + }), + execute: async ({ containerId, timeoutSeconds }, context) => { + containerReference.parse(containerId); + if (context?.dryRun) throw new Error('Docker restart does not support dry run.'); + await restartViaSdkOrCli(containerId, timeoutSeconds ?? 10); + + return { + success: true, + containerId, + status: 'Restarted successfully', + }; + }, +}); diff --git a/src/tools/index.ts b/src/tools/index.ts new file mode 100644 index 00000000..54f07bdd --- /dev/null +++ b/src/tools/index.ts @@ -0,0 +1,10 @@ +/** + * Declarative Cluster Tools — KDM v4.0.0 + * ===================================== + * Public module exports for tools, registry, and schemas. + */ + +export * from './declarative-tool'; +export * from './k8s-tools'; +export * from './docker-tools'; +export * from './tool-registry'; diff --git a/src/tools/k8s-tools.ts b/src/tools/k8s-tools.ts new file mode 100644 index 00000000..cb184864 --- /dev/null +++ b/src/tools/k8s-tools.ts @@ -0,0 +1,599 @@ +/** + * Declarative Kubernetes Tools — KDM v4.0.0 + * ========================================= + * Cluster monitoring, inspection, diagnostic, and remediation tools + * conforming to BaseDeclarativeTool with safety gating. + */ + +import { z } from 'zod'; +import { loadAllYaml } from '@kubernetes/client-node'; +import { DeclarativeTool } from './declarative-tool'; +import { + listPods, + listNodes, + listServices, + listDeployments, + listStatefulSets, + listDaemonSets, + listJobs, + listCronJobs, + listIngresses, + listPersistentVolumeClaims, + listConfigMaps, + listEvents, + listHPAs, + type KubernetesResourceOptions, +} from '../kubernetes/resources'; +import { getK8sApi } from '../kubernetes/client'; +import { executeRemediationCommand } from '../remediation/executor'; + +const resourceName = z.string().regex(/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/, 'Expected a Kubernetes resource name'); +const resourceKind = z.string().regex(/^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$/i, 'Expected a Kubernetes resource kind'); +const resourceReference = z.string().refine((reference) => { + const parts = reference.split('/'); + if (parts.length !== 2) return false; + return resourceKind.safeParse(parts[0]).success && resourceName.safeParse(parts[1]).success; +}, 'Expected a Kubernetes resource in kind/name format'); + +interface ListedResource { + metadata?: { name?: string; namespace?: string; creationTimestamp?: Date }; + status?: unknown; +} + +const RESOURCE_QUERIES: Record Promise> = { + pod: (o) => listPods(o), + node: (o) => listNodes(o), + service: (o) => listServices(o), + deployment: (o) => listDeployments(o), + statefulset: (o) => listStatefulSets(o), + daemonset: (o) => listDaemonSets(o), + job: (o) => listJobs(o), + cronjob: (o) => listCronJobs(o), + ingress: (o) => listIngresses(o), + pvc: (o) => listPersistentVolumeClaims(o), + configmap: (o) => listConfigMaps(o), + event: (o) => listEvents(o), + hpa: (o) => listHPAs(o), +}; + +function summarizeResource({ item, namespace }: { item: ListedResource; namespace?: string }) { + const metadata = item.metadata ?? {}; + const status = item.status; + const hasPhase = status !== null && typeof status === 'object' && 'phase' in status; + const phase = hasPhase ? (status as { phase?: unknown }).phase : undefined; + return { + name: metadata.name ?? 'unknown', + namespace: metadata.namespace ?? namespace ?? 'default', + status: phase ?? status ?? 'active', + creationTimestamp: metadata.creationTimestamp, + raw: item, + }; +} + +function isValidDocumentEntry(doc: unknown): boolean { + return doc !== null && typeof doc === 'object'; +} + +function assertValidManifestYaml({ manifest }: { manifest: string }): void { + try { + const documents = loadAllYaml(manifest); + if (!documents.length) { + throw new Error('Expected a manifest or patch object'); + } + if (!documents.every(isValidDocumentEntry)) { + throw new Error('Expected a manifest or patch object'); + } + } catch (error) { + throw new Error('YAML syntax error: invalid Kubernetes manifest or patch', { cause: error }); + } +} + +function runManifestKubectl(params: { + manifest: string; + namespace: string; + resource?: string; + dryRun?: boolean; +}) { + const dryRunArgs = params.dryRun ? ['--dry-run=server'] : []; + if (params.resource) { + return executeRemediationCommand([ + 'kubectl', 'patch', resourceReference.parse(params.resource), '-n', params.namespace, '--patch', params.manifest, ...dryRunArgs, + ]); + } + return executeRemediationCommand(['kubectl', 'apply', '-n', params.namespace, '-f', '-', ...dryRunArgs], { + stdin: params.manifest, + }); +} + +async function applyManifest(params: { + manifest: string; + namespace: string; + resource?: string; + dryRun?: boolean; +}) { + assertValidManifestYaml({ manifest: params.manifest }); + const dryRun = params.dryRun ?? false; + const result = await runManifestKubectl({ ...params, dryRun }); + const action = params.resource ? 'patch' : 'apply'; + if (!result.success) { + throw new Error(`Failed to ${action} ${params.resource ?? 'manifest'}: ${result.stderr}`); + } + return { + success: true, + appliedTo: `${params.namespace}/${params.resource ?? 'manifest'}`, + dryRun, + status: params.resource ? 'Patched successfully' : 'Applied successfully', + output: result.stdout, + }; +} + +type ApiReader = (ctx: { api: ReturnType; name: string; namespace: string }) => Promise; + +const API_READERS = new Map([ + ['pod', ({ api, name, namespace }) => api.readNamespacedPod({ name, namespace })], + ['pods', ({ api, name, namespace }) => api.readNamespacedPod({ name, namespace })], + ['node', ({ api, name }) => api.readNode({ name })], + ['nodes', ({ api, name }) => api.readNode({ name })], + ['service', ({ api, name, namespace }) => api.readNamespacedService({ name, namespace })], + ['services', ({ api, name, namespace }) => api.readNamespacedService({ name, namespace })], +]); + +async function readResourceViaApi({ kind, name, ns }: { kind: string; name: string; ns: string }): Promise { + const reader = API_READERS.get(kind.toLowerCase()); + if (!reader) return null; + try { + return await reader({ api: getK8sApi(), name, namespace: ns }); + } catch { + return null; + } +} + +async function describeResourceViaCli({ kind, name, ns }: { kind: string; name: string; ns: string }) { + resourceKind.parse(kind); + resourceName.parse(name); + const cmdResult = await executeRemediationCommand(['kubectl', 'describe', kind.toLowerCase(), name, '-n', ns]); + if (cmdResult.success) { + return { kind, name, namespace: ns, found: true, description: cmdResult.stdout }; + } + if (!/not\s*found/i.test(cmdResult.stderr)) { + throw new Error(`Failed to describe ${kind}/${name}: ${cmdResult.stderr}`); + } + return null; +} + +async function fetchRelatedEvents({ name, ns }: { name: string; ns: string }) { + try { + const events = await listEvents({ namespace: ns }); + return events + .filter((e) => e.involvedObject?.name === name) + .map((e) => ({ + type: e.type, + reason: e.reason, + message: e.message, + lastTimestamp: e.lastTimestamp, + })); + } catch { + return []; + } +} + +async function readPodLogsViaApi(params: { + name: string; + ns: string; + container?: string; + tailLines: number; + previous: boolean; +}): Promise { + const res = await getK8sApi().readNamespacedPodLog({ + name: params.name, + namespace: params.ns, + container: params.container, + tailLines: params.tailLines, + previous: params.previous, + }); + return typeof res === 'string' ? res : String(res ?? ''); +} + +async function readPodLogsViaCli(params: { + name: string; + ns: string; + container?: string; + tailLines: number; + previous: boolean; +}): Promise { + resourceName.parse(params.name); + const contArgs = params.container ? ['-c', resourceName.parse(params.container)] : []; + const prevArgs = params.previous ? ['--previous'] : []; + const cmdResult = await executeRemediationCommand([ + 'kubectl', 'logs', params.name, '-n', params.ns, ...contArgs, ...prevArgs, `--tail=${params.tailLines}`, + ]); + if (!cmdResult.success) { + throw new Error(`Failed to retrieve logs for ${params.ns}/${params.name}: ${cmdResult.stderr}`); + } + return cmdResult.stdout; +} + +function eventTimestampMs(event: { lastTimestamp?: unknown; eventTime?: unknown }): number { + const raw = (event.lastTimestamp ?? event.eventTime ?? 0) as string | number | Date; + return new Date(raw).getTime(); +} + +function matchesEventFilters(ctx: { event: any; resourceNameFilter?: string; typeFilter?: string }): boolean { + const { event, resourceNameFilter, typeFilter } = ctx; + if (resourceNameFilter) { + const involved = event.involvedObject; + if (!involved || involved.name !== resourceNameFilter) return false; + } + if (typeFilter && typeFilter !== 'All') { + return event.type === typeFilter; + } + return true; +} + +function filterAndSortEvents(params: { + rawEvents: any[]; + resourceNameFilter?: string; + typeFilter?: string; + limit?: number; +}) { + const filtered = params.rawEvents.filter((event) => + matchesEventFilters({ + event, + resourceNameFilter: params.resourceNameFilter, + typeFilter: params.typeFilter, + }) + ); + const sorted = [...filtered].sort((a, b) => eventTimestampMs(b) - eventTimestampMs(a)); + return params.limit && sorted.length > params.limit ? sorted.slice(0, params.limit) : sorted; +} + +function formatClusterEvent({ event }: { event: any }) { + const involved = event.involvedObject ?? {}; + const metadata = event.metadata ?? {}; + return { + type: event.type, + reason: event.reason, + message: event.message, + involvedResource: `${involved.kind}/${involved.name}`, + namespace: metadata.namespace ?? 'default', + count: event.count ?? 1, + lastTimestamp: event.lastTimestamp, + }; +} + +function assertDeletableResource({ kind, name }: { kind: string; name: string }): void { + const baseKind = kind.split('.')[0]; + if (!['namespace', 'namespaces', 'ns'].includes(baseKind)) return; + if (['kube-system', 'default', 'production'].includes(name)) { + throw new Error(`Policy violation: deletion of protected namespace '${name}' is permanently blocked.`); + } +} + +function isNotFoundStatusError({ error }: { error: unknown }): boolean { + if (!error || typeof error !== 'object') return false; + if (!('code' in error)) return false; + return (error as { code?: unknown }).code === 404; +} + +function getTerminatedState(statusEntry: any) { + const state = statusEntry ? statusEntry.state : undefined; + if (state && state.terminated) return state.terminated; + const lastState = statusEntry ? statusEntry.lastState : undefined; + return lastState ? lastState.terminated : undefined; +} + +function findTerminatedEntry(statuses: any[]) { + return statuses.find((s) => Boolean(getTerminatedState(s))); +} + +function findTargetContainer({ spec, targetName }: { spec: any; targetName?: string }) { + const containers: any[] = spec && spec.containers ? spec.containers : []; + return containers.find((item) => item.name === targetName) ?? containers[0]; +} + +function extractContainerMemoryLimit(container: any): unknown { + const resources = container ? container.resources : undefined; + const limits = resources ? resources.limits : undefined; + return limits ? limits.memory : undefined; +} + +function extractPodDiagnostics({ pod, name, namespace }: { pod: any; name: string; namespace: string }) { + const statusObj = pod.status ?? {}; + const metadata = pod.metadata ?? {}; + const spec = pod.spec ?? {}; + const statuses: any[] = statusObj.containerStatuses ?? []; + const terminated = findTerminatedEntry(statuses); + const terminatedState = getTerminatedState(terminated); + const container = findTargetContainer({ spec, targetName: terminated ? terminated.name : undefined }); + const restartCount = statuses.reduce((total: number, s: any) => total + s.restartCount, 0); + + return { + pod: metadata.name ?? name, + namespace: metadata.namespace ?? namespace, + found: true, + phase: statusObj.phase, + exitCode: terminatedState ? terminatedState.exitCode : undefined, + restartCount, + node: spec.nodeName, + memoryLimit: extractContainerMemoryLimit(container), + }; +} + +function summarizeListedPod(pod: any) { + const statusObj = pod.status ?? {}; + const metadata = pod.metadata ?? {}; + const statuses: any[] = statusObj.containerStatuses ?? []; + return { + name: metadata.name ?? 'unknown', + status: statusObj.phase ?? 'Unknown', + restarts: statuses.reduce((total: number, s: any) => total + s.restartCount, 0), + }; +} + +async function fetchPodLogsWithFallback(query: { + name: string; + ns: string; + container?: string; + tailLines: number; + previous: boolean; +}): Promise { + try { + return await readPodLogsViaApi(query); + } catch { + return readPodLogsViaCli(query); + } +} + +function buildDeleteCommandArgs(params: { + kind: string; + name: string; + namespace?: string; + gracePeriodSeconds?: number; + dryRun?: boolean; +}) { + const graceArgs = params.gracePeriodSeconds !== undefined ? [`--grace-period=${params.gracePeriodSeconds}`] : []; + const dryRunArgs = params.dryRun ? ['--dry-run=server'] : []; + return ['kubectl', 'delete', params.kind, params.name, '-n', params.namespace ?? 'default', ...graceArgs, ...dryRunArgs] as const; +} + +async function readPodSafe({ name, namespace }: { name: string; namespace: string }) { + try { + return await getK8sApi().readNamespacedPod({ name, namespace }); + } catch (error) { + if (isNotFoundStatusError({ error })) return undefined; + throw error; + } +} + +// ─── 1. k8s_get_resources ─────────────────────────────────────────────────── + +export const k8sGetResourcesTool = new DeclarativeTool({ + name: 'k8s_get_resources', + description: 'Retrieve Kubernetes resources of a specified kind (pods, nodes, services, deployments, etc.) in a namespace with optional label selector filtering.', + safety: 'read_only', + riskLevel: 'low', + parameters: z.object({ + kind: z.enum([ + 'pod', 'pods', + 'node', 'nodes', + 'service', 'services', + 'deployment', 'deployments', + 'statefulset', 'statefulsets', + 'daemonset', 'daemonsets', + 'job', 'jobs', + 'cronjob', 'cronjobs', + 'ingress', 'ingresses', + 'pvc', 'pvcs', + 'configmap', 'configmaps', + 'event', 'events', + 'hpa', 'hpas', + ]).describe('Kubernetes resource kind to retrieve'), + namespace: z.string().optional().describe('Target namespace (omit for all namespaces)'), + labelSelector: z.string().optional().describe('Kubernetes label selector (e.g. app=frontend)'), + limit: z.number().int().positive().optional().describe('Maximum number of items to return'), + }), + execute: async ({ kind, namespace, labelSelector, limit }) => { + const normalized = kind === 'ingresses' ? 'ingress' : kind; + const query = RESOURCE_QUERIES[normalized] ?? RESOURCE_QUERIES[normalized.replace(/s$/, '')]; + if (!query) throw new Error(`Unsupported resource kind: ${kind}`); + const resources = await query({ namespace, labelSelector }); + const items = resources.slice(0, limit).map((item) => summarizeResource({ item, namespace })); + return { kind, namespace: namespace ?? 'all', count: items.length, items }; + }, +}); + +// ─── 2. k8s_describe_resource ─────────────────────────────────────────────── + +export const k8sDescribeResourceTool = new DeclarativeTool({ + name: 'k8s_describe_resource', + description: 'Describe a specific Kubernetes resource in detail, including metadata, spec, status, and recent events.', + safety: 'read_only', + riskLevel: 'low', + parameters: z.object({ + kind: resourceKind.describe('Resource kind (e.g. pod, deployment, service, node)'), + name: resourceName.describe('Name of the resource to describe'), + namespace: z.string().optional().default('default').describe('Namespace of the resource (default: "default")'), + }), + execute: async ({ kind, name, namespace }) => { + const ns = namespace ?? 'default'; + const resourceDetails = await readResourceViaApi({ kind, name, ns }); + if (!resourceDetails) { + const cliResult = await describeResourceViaCli({ kind, name, ns }); + if (cliResult) return cliResult; + } + + const events = await fetchRelatedEvents({ name, ns }); + if (!resourceDetails) { + return { + kind, + name, + namespace: ns, + found: false, + description: `Resource ${kind}/${name} in namespace ${ns} not found`, + events: [], + }; + } + + return { kind, name, namespace: ns, found: true, resource: resourceDetails, events }; + }, +}); + +// ─── 3. k8s_get_logs ──────────────────────────────────────────────────────── + +export const k8sGetLogsTool = new DeclarativeTool({ + name: 'k8s_get_logs', + description: 'Retrieve container logs from a Kubernetes pod with options for container selection, previous instance, and line limit.', + safety: 'read_only', + riskLevel: 'low', + parameters: z.object({ + name: z.string().min(1, 'Pod name is required').describe('Name of the pod'), + namespace: z.string().default('default').describe('Namespace of the pod (default: "default")'), + container: z.string().optional().describe('Specific container name if multi-container pod'), + tailLines: z.number().int().positive().optional().default(100).describe('Number of lines to retrieve (default: 100)'), + previous: z.boolean().optional().default(false).describe('Retrieve logs for previous terminated container'), + }), + execute: async ({ name, namespace, container, tailLines, previous }) => { + const ns = namespace ?? 'default'; + const query = { name, ns, container, tailLines: tailLines ?? 100, previous: previous ?? false }; + const logs = await fetchPodLogsWithFallback(query); + + const lines = logs.split('\n').filter((l) => l.trim().length > 0); + return { pod: name, namespace: ns, container, tailLines, previous, linesCount: lines.length, logs, lines }; + }, +}); + +// ─── 4. k8s_get_events ────────────────────────────────────────────────────── + +export const k8sGetEventsTool = new DeclarativeTool({ + name: 'k8s_get_events', + description: 'Retrieve Kubernetes cluster events filtered by namespace, resource name, or type (Warning/Normal).', + safety: 'read_only', + riskLevel: 'low', + parameters: z.object({ + namespace: z.string().optional().describe('Namespace to query (omit for all namespaces)'), + resourceName: z.string().optional().describe('Filter events by involved resource name'), + type: z.enum(['Normal', 'Warning', 'All']).optional().default('All').describe('Filter by event type'), + limit: z.number().int().positive().optional().default(50).describe('Maximum number of events to return'), + }), + execute: async ({ namespace, resourceName: targetName, type, limit }) => { + const rawEvents = await listEvents({ namespace }); + const filtered = filterAndSortEvents({ rawEvents, resourceNameFilter: targetName, typeFilter: type, limit }); + return { + namespace: namespace ?? 'all', + count: filtered.length, + events: filtered.map((event) => formatClusterEvent({ event })), + }; + }, +}); + +// ─── 5. k8s_apply_manifest (Mutating) ─────────────────────────────────────── + +export const k8sApplyManifestTool = new DeclarativeTool({ + name: 'k8s_apply_manifest', + description: 'Apply or patch a Kubernetes manifest or configuration to the cluster. This is a mutating operation.', + safety: 'mutating', + riskLevel: 'high', + parameters: z.object({ + manifest: z.string().min(1, 'Manifest YAML/JSON or patch payload is required').describe('Manifest content or patch payload'), + namespace: z.string().optional().default('default').describe('Target namespace (default: "default")'), + resource: z.string().optional().describe('Target resource identifier (e.g. "deployment/payment-service")'), + dryRun: z.boolean().optional().default(false).describe('Perform server-side dry run without persisting changes'), + }), + execute: async ({ manifest, namespace, resource, dryRun }, context) => + applyManifest({ + manifest, + namespace: namespace ?? 'default', + resource, + dryRun: Boolean(dryRun || context?.dryRun), + }), +}); + +// ─── 6. k8s_delete_resource (Mutating) ─────────────────────────────────────── + +export const k8sDeleteResourceTool = new DeclarativeTool({ + name: 'k8s_delete_resource', + description: 'Delete a Kubernetes resource by kind and name. This is a mutating operation that removes cluster state.', + safety: 'mutating', + riskLevel: 'high', + parameters: z.object({ + kind: resourceKind.describe('Kubernetes resource kind (e.g. pod, deployment, service)'), + name: resourceName.describe('Name of the resource to delete'), + namespace: z.string().optional().default('default').describe('Namespace of the resource (default: "default")'), + gracePeriodSeconds: z.number().int().min(0).optional().describe('Grace period in seconds'), + }), + execute: async ({ kind, name, namespace, gracePeriodSeconds }, context) => { + const parsedKind = resourceKind.parse(kind).toLowerCase(); + resourceName.parse(name); + assertDeletableResource({ kind: parsedKind, name }); + + const dryRun = Boolean(context && context.dryRun); + const cmd = buildDeleteCommandArgs({ kind: parsedKind, name, namespace, gracePeriodSeconds, dryRun }); + const result = await executeRemediationCommand(cmd); + + if (!result.success) { + throw new Error(`Failed to delete ${kind}/${name}: ${result.stderr}`); + } + + return { + success: true, + deleted: `${kind}/${name}`, + namespace, + status: dryRun ? 'Deletion validated by server' : 'Resource deleted successfully', + output: result.stdout, + }; + }, +}); + +// ─── Compatibility Aliases (Directly matching E2E Harness) ─────────────────── + +export const k8sGetPodTool = new DeclarativeTool({ + name: 'k8s_get_pod', + description: 'Inspect status, exit codes, and restart counts of a Kubernetes pod', + safety: 'read_only', + riskLevel: 'low', + parameters: z.object({ + name: z.string().min(1, 'Pod name is required'), + namespace: z.string().default('default'), + }), + execute: async ({ name, namespace = 'default' }) => { + const pod = await readPodSafe({ name, namespace }); + if (!pod) return { pod: name, namespace, found: false }; + return extractPodDiagnostics({ pod, name, namespace }); + }, +}); + +export const k8sListPodsTool = new DeclarativeTool({ + name: 'k8s_list_pods', + description: 'List pods in a specified namespace', + safety: 'read_only', + riskLevel: 'low', + parameters: z.object({ + namespace: z.string().default('default'), + }), + execute: async ({ namespace }) => { + const pods = await listPods({ namespace }); + return { + namespace, + pods: pods.map(summarizeListedPod), + }; + }, +}); + +export const k8sApplyPatchTool = new DeclarativeTool({ + name: 'k8s_apply_patch', + description: 'Apply an approved YAML manifest patch to a Kubernetes resource', + safety: 'mutating', + riskLevel: 'high', + parameters: z.object({ + resource: z.string().min(1), + namespace: z.string().default('default'), + patch: z.string().min(1, 'Patch payload is required'), + }), + execute: async ({ resource, namespace, patch }, context) => + applyManifest({ + manifest: patch, + namespace: namespace ?? 'default', + resource, + dryRun: Boolean(context && context.dryRun), + }), +}); diff --git a/src/tools/tool-registry.ts b/src/tools/tool-registry.ts new file mode 100644 index 00000000..7869e5a7 --- /dev/null +++ b/src/tools/tool-registry.ts @@ -0,0 +1,161 @@ +/** + * Tool Registry — KDM v4.0.0 + * ========================== + * Discovery, registration, safety filtering, and execution dispatch + * of declarative tools with @google/genai tool declaration integration. + */ + +import type { FunctionDeclaration, Tool } from '@google/genai'; +import { + BaseDeclarativeTool, + type ToolSafetyLevel, + type ToolRiskLevel, + type ToolExecutionContext, +} from './declarative-tool'; +import { + k8sGetResourcesTool, + k8sDescribeResourceTool, + k8sGetLogsTool, + k8sGetEventsTool, + k8sApplyManifestTool, + k8sDeleteResourceTool, + k8sGetPodTool, + k8sListPodsTool, + k8sApplyPatchTool, +} from './k8s-tools'; +import { + dockerListContainersTool, + dockerInspectContainerTool, + dockerGetLogsTool, + dockerRestartContainerTool, +} from './docker-tools'; + +export class ToolRegistry { + private readonly tools = new Map(); + + /** + * Registers a single declarative tool in the registry. + */ + register(tool: BaseDeclarativeTool): void { + this.tools.set(tool.name, tool); + } + + /** + * Registers multiple declarative tools in bulk. + */ + registerAll(tools: BaseDeclarativeTool[]): void { + for (const tool of tools) { + this.register(tool); + } + } + + /** + * Retrieves a tool by name. + */ + get(name: string): BaseDeclarativeTool | undefined { + return this.tools.get(name); + } + + /** + * Checks whether a tool with the specified name is registered. + */ + has(name: string): boolean { + return this.tools.has(name); + } + + /** + * Lists all registered tools. + */ + list(): BaseDeclarativeTool[] { + return Array.from(this.tools.values()); + } + + /** + * Filters tools by safety level ('read_only' | 'mutating'). + */ + filterBySafety(safety: ToolSafetyLevel): BaseDeclarativeTool[] { + return this.list().filter((t) => t.safetyLevel === safety || t.safety === safety); + } + + /** + * Filters tools by risk level ('low' | 'medium' | 'high'). + */ + filterByRisk(riskLevel: ToolRiskLevel): BaseDeclarativeTool[] { + return this.list().filter((t) => t.riskLevel === riskLevel); + } + + /** + * Converts all registered tools into @google/genai FunctionDeclaration array. + */ + getDeclarations(): FunctionDeclaration[] { + return this.list().map((tool) => tool.toGeminiToolDeclaration()); + } + + /** + * Alias for getDeclarations() matching SCOPE.md interface contract. + */ + getGeminiTools(): FunctionDeclaration[] { + return this.getDeclarations(); + } + + /** + * Converts all registered tools into @google/genai Tool array for model configuration. + */ + toGeminiTools(): Tool[] { + return [ + { + functionDeclarations: this.getDeclarations(), + }, + ]; + } + + /** + * Validates arguments against the tool schema and executes the tool. + * Throws Error if tool not found, or ZodError if validation fails. + */ + async invoke(name: string, rawArgs: unknown, context?: ToolExecutionContext): Promise { + const tool = this.get(name); + if (!tool) { + throw new Error(`Declarative tool '${name}' not found.`); + } + + // Parameter schema validation before execution + const validated = tool.validate(rawArgs); + if (tool.safetyLevel === 'mutating' && !(await context?.approveMutation?.(name, validated))) { + throw new Error(`Tool '${name}' requires explicit approval.`); + } + return await tool.execute(validated, context); + } + + /** + * Alias for invoke() matching standard dispatch convention. + */ + async execute(name: string, rawArgs: unknown, context?: ToolExecutionContext): Promise { + return this.invoke(name, rawArgs, context); + } +} + +/** + * Compatibility alias for DeclarativeToolRegistry expected by tests and harness. + */ +export class DeclarativeToolRegistry extends ToolRegistry {} + +/** + * Default pre-configured singleton registry with all standard K8s and Docker tools. + */ +export const defaultToolRegistry = new ToolRegistry(); +defaultToolRegistry.registerAll([ + k8sGetResourcesTool, + k8sDescribeResourceTool, + k8sGetLogsTool, + k8sGetEventsTool, + k8sApplyManifestTool, + k8sDeleteResourceTool, + k8sGetPodTool, + k8sListPodsTool, + k8sApplyPatchTool, + dockerListContainersTool, + dockerInspectContainerTool, + dockerGetLogsTool, + dockerRestartContainerTool, +]); diff --git a/src/ui/AppContainer.tsx b/src/ui/AppContainer.tsx new file mode 100644 index 00000000..0e3b16b6 --- /dev/null +++ b/src/ui/AppContainer.tsx @@ -0,0 +1,110 @@ +/** + * AppContainer — KDM Copilot Shell v4.0.0 + * Unified interactive workspace container with multi-tab header, responsive layout, + * and signal handling. + */ + +import React, { useEffect, useState } from 'react'; +import { Box, Text, useInput, type Key } from 'ink'; + +export interface AppContainerProps { + children?: React.ReactNode; + activeTab?: number; + onExit?: () => void; + bannerError?: string | null; + registerSignalHandlers?: boolean; + onSignal?: (signal: string) => void; + title?: string; + version?: string; + onTabChange?: (tab: number) => void; +} + +const tabs = ['Monitor', 'Agents', 'Diffs', 'Settings']; + +function wantsExit(ctx: { input: string; key: Key; activeTab: number }): boolean { + const lower = ctx.input.toLowerCase(); + if (ctx.input === '\u0003') return true; + if (ctx.key.ctrl && lower === 'c') return true; + return ctx.activeTab !== 1 && lower === 'q'; +} + +function isTabShortcut(ctx: { activeTab: number; key: Key; input: string }): boolean { + if (!/^[1-4]$/.test(ctx.input)) return false; + return ctx.activeTab !== 1 || Boolean(ctx.key.meta); +} + +function useSigtermHandler({ registerSignalHandlers, onExit, onSignal }: AppContainerProps) { + useEffect(() => { + if (!registerSignalHandlers) return; + const handleSigterm = () => { + onSignal?.('SIGTERM'); + onExit?.(); + }; + process.on('SIGTERM', handleSigterm); + return () => { + process.removeListener('SIGTERM', handleSigterm); + }; + }, [registerSignalHandlers, onExit, onSignal]); +} + +export const AppContainer: React.FC = ({ + children, + activeTab: initialTab = 1, + onExit, + bannerError, + registerSignalHandlers = false, + onSignal, + title = 'KDM Copilot Shell', + version = 'v4.0.0', + onTabChange, +}) => { + const [activeTab, setActiveTab] = useState(initialTab); + + useEffect(() => { + setActiveTab(initialTab); + }, [initialTab]); + + useInput((input, key) => { + if (wantsExit({ input, key, activeTab })) { + onExit?.(); + return; + } + if (isTabShortcut({ activeTab, key, input })) { + const nextTab = parseInt(input, 10); + setActiveTab(nextTab); + onTabChange?.(nextTab); + } + }); + + useSigtermHandler({ registerSignalHandlers, onExit, onSignal }); + + return ( + + + + {' '} + {title} {version} + + + {tabs.map((label, index) => ( + + [Alt+{index + 1}: {label}]{' '} + + ))} + + + + {bannerError ? ( + + ⚠ {bannerError} + + ) : null} + + + {children} + + + ); +}; + +export const AppContainerView = AppContainer; diff --git a/src/ui/CopilotShell.tsx b/src/ui/CopilotShell.tsx new file mode 100644 index 00000000..e518d29e --- /dev/null +++ b/src/ui/CopilotShell.tsx @@ -0,0 +1,316 @@ +import React, { useEffect, useRef, useState } from 'react'; +import { Box, Text } from 'ink'; +import { AppContainer } from './AppContainer.js'; +import { Composer, DEFAULT_SLASH_COMMANDS } from './components/Composer.js'; +import { ThinkingMessage } from './components/ThinkingMessage.js'; +import { SubagentProgressDisplay, type SubagentProgress } from './components/SubagentProgressDisplay.js'; +import { DiffRenderer } from './components/DiffRenderer.js'; +import { defaultAgentRegistry } from '../agent/registry.js'; +import { CodebaseInvestigatorAgent, CodebaseInvestigationReportSchema } from '../agent/investigator.js'; +import { checkDockerConnection } from '../docker/client.js'; +import { checkK8sConnection } from '../kubernetes/client.js'; +import { WatchDashboard } from './WatchDashboard.js'; +import { createAIClient } from '../ai/factory.js'; +import { getRunningContainers } from '../docker/containers.js'; +import { getRunningPods } from '../kubernetes/pods.js'; +import { runAnalysis, resolveBackend } from '../analysis/analysis.js'; +import { registry } from '../analyzers/index.js'; +import { formatTextOutput } from '../analysis/output.js'; +import { dockerInspectContainerTool } from '../tools/docker-tools.js'; + +export type TroubleshootTarget = + | { kind: 'Pod'; name: string; namespace: string } + | { kind: 'Container'; name: string; id: string }; + +export interface ChatMessage { + id: string; + role: 'user' | 'assistant' | 'system'; + content: string; + thought?: string; + timestamp: Date; +} + +export interface CopilotShellProps { + onExit?: () => void; + initialTab?: number; + initialPrompt?: string; + targetResource?: string | TroubleshootTarget; +} + +interface WorkloadTarget { + kind: string; + name: string; + namespace?: string; + containerId?: string; +} + +interface PromptContext { + prompt: string; + args: string[]; + backend: string; + target?: string | TroubleshootTarget; +} + +interface PromptResponse { + text: string; + diff?: string; +} + +async function complete(req: { backend: string; prompt: string }): Promise { + const client = await createAIClient(req.backend); + try { + const reply = await client.getCompletion(req.prompt); + if (!reply?.trim()) throw new Error('Provider returned an empty response'); + return reply; + } finally { + await client.close?.(); + } +} + +function readTarget(props: { input?: string | TroubleshootTarget }): WorkloadTarget | undefined { + const { input } = props; + if (!input) return undefined; + if (typeof input === 'object') { + return input.kind === 'Container' ? { ...input, containerId: input.id } : input; + } + const [prefix, name] = input.split('/', 2); + return name ? { kind: prefix, name } : { kind: 'Pod', name: prefix }; +} + +async function inspectContainer(req: { target: WorkloadTarget; backend: string }): Promise { + const containerId = req.target.containerId ?? req.target.name; + const { state, exitCode, oomKilled, restarting } = await dockerInspectContainerTool.execute({ containerId }); + const diagnostic = JSON.stringify({ state, exitCode, oomKilled, restarting }); + return complete({ + backend: req.backend, + prompt: `Explain these Docker container diagnostics and suggest next steps: ${diagnostic}`, + }); +} + +async function runAnalyzerForTarget(target?: WorkloadTarget): Promise { + const kind = target?.kind.toLowerCase(); + const filter = kind ? registry.list().find((analyzer) => analyzer.name.toLowerCase() === kind) : undefined; + if (target && !filter) throw new Error(`Unknown workload kind: ${target.kind}`); + const result = await runAnalysis({ + multiAgent: true, + explain: true, + resourceName: target?.name, + namespace: target?.namespace, + filters: filter ? [filter.name] : undefined, + }); + return formatTextOutput(result); +} + +async function analyzeTarget(context: PromptContext): Promise { + const target = readTarget({ input: context.args[0] || context.target }); + if (target?.kind.toLowerCase() === 'container') { + return inspectContainer({ target, backend: context.backend }); + } + return runAnalyzerForTarget(target); +} + +async function listPods(context: PromptContext): Promise { + const pods = await getRunningPods(); + const { args } = context; + const matches = pods.filter((pod) => !args.length || (args[0] === '-n' && pod.namespace === args[1])); + return matches.map((pod) => `${pod.namespace}/${pod.name} ${pod.status}`).join('\n') || 'No matching pods.'; +} + +async function listContainers(): Promise { + const containers = await getRunningContainers(); + return containers.map((container) => `${container.name} ${container.status}`).join('\n') || 'No containers.'; +} + +async function checkHealth(): Promise { + const [docker, kube] = await Promise.all([checkDockerConnection(), checkK8sConnection()]); + return `Docker connected: ${docker}\nKubernetes connected: ${kube}`; +} + +async function investigate(context: PromptContext): Promise { + const agent = defaultAgentRegistry.get(CodebaseInvestigatorAgent.NAME); + if (!agent) throw new Error('Investigator unavailable'); + const raw = await agent.run({ objective: context.args.join(' ') || 'Inspect local manifests' }); + const result = CodebaseInvestigationReportSchema.parse(raw); + return { text: JSON.stringify(result, null, 2), diff: result.findings.find((finding) => finding.patch)?.patch }; +} + +const diagnostics = new Map Promise>([ + ['/analyze', analyzeTarget], + ['/pods', listPods], + ['/containers', listContainers], + ['/health', checkHealth], +]); + +async function answerPrompt(req: { command: string; context: PromptContext }): Promise { + if (req.command === '/investigate') return investigate(req.context); + const diagnostic = diagnostics.get(req.command); + if (diagnostic) return { text: await diagnostic(req.context) }; + const target = readTarget({ input: req.context.target }); + const prompt = target ? `Workload: ${target.name}\n${req.context.prompt}` : req.context.prompt; + return { text: await complete({ backend: req.context.backend, prompt }) }; +} + +function buildMessage(entry: { role: ChatMessage['role']; content: string }): ChatMessage { + return { id: `${Date.now()}-${entry.role}`, timestamp: new Date(), role: entry.role, content: entry.content }; +} + +function buildGreeting(props: { target?: string | TroubleshootTarget }): ChatMessage { + const name = typeof props.target === 'string' ? props.target : props.target?.name; + return buildMessage({ + role: 'system', + content: name + ? `SRE Copilot for ${name}. Type /help or press Alt+2 to see agent tasks.` + : 'Welcome to KDM Copilot. Type /help or ask a Kubernetes or Docker troubleshooting question.', + }); +} + +function useCopilotSession(props: CopilotShellProps) { + const [messages, setMessages] = useState(() => [buildGreeting({ target: props.targetResource })]); + const [progress, setProgress] = useState(); + const [diff, setDiff] = useState(); + const [draft, setDraft] = useState(''); + const running = useRef(false); + + const appendMessage = (entry: { role: ChatMessage['role']; content: string }) => { + const next = buildMessage(entry); + setMessages((previous) => [...previous, next]); + }; + + async function runPrompt(submission: { text: string }) { + const prompt = submission.text.trim(); + if (!prompt || running.current) return; + running.current = true; + const [command, ...args] = prompt.split(/\s+/); + const backend = resolveBackend({}); + const agentName = command.startsWith('/') ? command.slice(1) : backend; + appendMessage({ role: 'user', content: prompt }); + setProgress({ agentName, state: 'running' }); + try { + const response = await answerPrompt({ command, context: { args, prompt, backend, target: props.targetResource } }); + appendMessage({ role: 'assistant', content: response.text }); + if (command === '/investigate') setDiff(response.diff); + setProgress({ agentName, state: 'completed' }); + } catch (error) { + const result = error instanceof Error ? error.message : String(error); + appendMessage({ role: 'assistant', content: result }); + setProgress({ agentName, state: 'error', result }); + } finally { + running.current = false; + } + } + + useEffect(() => { + if (!defaultAgentRegistry.has(CodebaseInvestigatorAgent.NAME)) { + defaultAgentRegistry.register(CodebaseInvestigatorAgent.toDefinition()); + } + }, []); + + useEffect(() => { + setMessages([buildGreeting({ target: props.targetResource })]); + }, [props.targetResource]); + + const showHelp = () => { + appendMessage({ role: 'user', content: '/help' }); + appendMessage({ + role: 'assistant', + content: DEFAULT_SLASH_COMMANDS.map((item) => `${item.command} ${item.description}`).join('\n'), + }); + }; + + return { messages, progress, diff, draft, setDraft, runPrompt, showHelp, clearMessages: () => setMessages([]) }; +} + +const messageStyles = { + user: { color: 'green', label: '❯ User:' }, + system: { color: 'yellow', label: 'ℹ System:' }, + assistant: { color: 'cyan', label: '🤖 Copilot:' }, +}; + +function Conversation({ session, onSubmit }: { + session: ReturnType; + onSubmit: (input: string) => void; +}) { + const { messages, progress } = session; + const thinking = progress?.state === 'running'; + return ( + + + {messages.slice(-8).map((entry) => ( + + {messageStyles[entry.role].label} + {entry.content} + + ))} + {thinking && } + + + + ); +} + +function buildTabPanels(ctx: { + session: ReturnType; + onSubmit: (input: string) => void; +}) { + return [ + , + + Specialist Agents + + , + + Manifest Diff + + , + + AI Provider Configuration + Chat provider: {resolveBackend({})} + Analysis council: Ollama + Subagents Registered: {defaultAgentRegistry.list().length} + , + ]; +} + +export const CopilotShell: React.FC = (props) => { + const [tab, setTab] = useState(props.initialTab ?? 1); + const [watching, setWatching] = useState(false); + const session = useCopilotSession(props); + const handledInitialPrompt = useRef(undefined); + + const shortcuts = new Map void>([ + ['/quit', () => props.onExit?.()], + ['/exit', () => props.onExit?.()], + ['/clear', session.clearMessages], + ['/help', session.showHelp], + ['/watch', () => setWatching(true)], + ['/diff', () => setTab(3)], + ]); + + function submit(input: string) { + const shortcut = shortcuts.get(input.trim()); + if (shortcut) return shortcut(); + void session.runPrompt({ text: input }); + } + + useEffect(() => { + const initial = props.initialPrompt; + if (initial && initial !== handledInitialPrompt.current) { + handledInitialPrompt.current = initial; + submit(initial); + } + }, [props.initialPrompt]); + + if (watching) { + const closeWatch = () => setWatching(false); + return ; + } + + const panels = buildTabPanels({ session, onSubmit: submit }); + return {panels[tab - 1]}; +}; diff --git a/src/ui/InitialDashboard.tsx b/src/ui/InitialDashboard.tsx index ed17f196..a562cfe4 100644 --- a/src/ui/InitialDashboard.tsx +++ b/src/ui/InitialDashboard.tsx @@ -11,6 +11,7 @@ import { LogsDashboard } from './LogsDashboard'; import { AuthDashboard } from './AuthDashboard'; import { CacheDashboard } from './CacheDashboard'; import { CustomAnalyzerDashboard } from './CustomAnalyzerDashboard'; +import { CopilotShell } from './CopilotShell'; import { getConfig, setConfigValue } from '../config/store'; import { createCustomAnalyzer, type CustomAnalyzerConfig } from '../analyzers/custom'; import { registry } from '../analyzers'; @@ -96,6 +97,14 @@ const MENU_ACTIONS: MenuAction[] = [ description: 'Collaborative multi-agent council (Runtime, Config, Resource, SRE Synthesizer) triaging failures', args: ['analyze', '--explain', '--backend', 'ollama'], }, + { + id: 'copilot', + key: 'g', + name: 'Gemini Copilot Shell', + cmd: 'kdm copilot', + description: 'Interactive SRE workspace with Gemini AI, slash commands & agent tree', + args: ['copilot'], + }, { id: 'watch', key: 'w', @@ -403,6 +412,7 @@ export const SUB_SCREENS: Record< onExit={onExit} /> ), + copilot: (onBack, onExit) => , watch: (onBack, onExit) => , health: (onBack, onExit) => , logs: (onBack, onExit) => , diff --git a/src/ui/WatchDashboard.tsx b/src/ui/WatchDashboard.tsx index f993afcd..8db1c638 100644 --- a/src/ui/WatchDashboard.tsx +++ b/src/ui/WatchDashboard.tsx @@ -8,6 +8,7 @@ import { createAIClient } from '../ai/factory'; import { getAIConfig } from '../config/store'; import chalk from 'chalk'; import { triggerBack, triggerExit } from './navigation-utils'; +import { CopilotShell, type TroubleshootTarget } from './CopilotShell'; const StatusBadge = ({ status, type }: { status: string, type: 'pod' | 'container' }) => { const isRunning = type === 'pod' ? status === 'Running' : status === 'running'; @@ -54,6 +55,7 @@ export const WatchDashboard: React.FC = ({ onBack, onExit } const [aiDiagnosis, setAiDiagnosis] = useState(null); const [runningAi, setRunningAi] = useState(false); + const [troubleshootResource, setTroubleshootResource] = useState(null); const [actionMessage, setActionMessage] = useState(null); const [confirmRestart, setConfirmRestart] = useState(false); @@ -305,6 +307,12 @@ export const WatchDashboard: React.FC = ({ onBack, onExit } void fetchSelectedLogs(selectedResource); return; } + if (lowerInput === 't') { + setTroubleshootResource('namespace' in selectedResource + ? { kind: 'Pod', name: selectedResource.name, namespace: selectedResource.namespace } + : { kind: 'Container', name: selectedResource.name, id: selectedResource.id }); + return; + } if (lowerInput === 'a') { void runAiAnalysis(selectedResource); return; @@ -314,7 +322,7 @@ export const WatchDashboard: React.FC = ({ onBack, onExit } return; } } - }); + }, { isActive: !troubleshootResource }); const isCompact = columns < 80; const layoutDirection = isCompact ? 'column' : 'row'; @@ -322,6 +330,15 @@ export const WatchDashboard: React.FC = ({ onBack, onExit } const availableWidth = isCompact ? (columns - 8) : (Math.floor(columns / 2) - 8); const maxNameLength = Math.max(10, availableWidth - 14); + if (troubleshootResource) { + return ( + setTroubleshootResource(null)} + /> + ); + } + // Render Log Streaming Overlay if (showLogs) { return ( @@ -508,7 +525,7 @@ export const WatchDashboard: React.FC = ({ onBack, onExit } {/* Footer / Shortcuts */} - [L] Logs [A] AI Analysis [R] Restart [TAB] Switch Focus [Esc/B] Back [Q] Quit + [L] Logs [T] Troubleshoot [A] AI Analysis [R] Restart [TAB] Switch Focus [Esc/B] Back [Q] Quit ); diff --git a/src/ui/components/Composer.tsx b/src/ui/components/Composer.tsx new file mode 100644 index 00000000..57ea034f --- /dev/null +++ b/src/ui/components/Composer.tsx @@ -0,0 +1,283 @@ +import React, { useState, useRef, useEffect, type FC } from 'react'; +import { Box, Text, useInput, type Key } from 'ink'; + +export interface SlashCommandDefinition { + command: string; + description: string; + usage?: string; +} + +export const DEFAULT_SLASH_COMMANDS: SlashCommandDefinition[] = [ + { command: '/pods', description: 'Inspect Kubernetes pods in namespace', usage: '/pods [-n ]' }, + { command: '/containers', description: 'Inspect Docker containers', usage: '/containers [--all]' }, + { command: '/watch', description: 'Launch live cluster monitoring dashboard', usage: '/watch' }, + { command: '/analyze', description: 'Run multi-agent automated root cause analysis', usage: '/analyze [pod-name]' }, + { command: '/investigate', description: 'Inspect local workspace manifests' }, + { command: '/diff', description: 'View pending remediation changes' }, + { command: '/health', description: 'Check Docker and Kubernetes connectivity', usage: '/health' }, + { command: '/help', description: 'Display available slash commands', usage: '/help' }, + { command: '/clear', description: 'Clear terminal screen', usage: '/clear' }, + { command: '/quit', description: 'Exit shell', usage: '/quit' }, + { command: '/exit', description: 'Exit shell', usage: '/exit' }, +]; + +/** + * Parses slash command string into command name and arguments. + */ +export function parseSlashCommand(input: string): { + isSlash: boolean; + command: string; + args: string[]; + raw: string; +} | null { + const trimmed = input.trim(); + if (!trimmed.startsWith('/')) return null; + const parts = trimmed.split(/\s+/); + return { + isSlash: true, + command: parts[0], + args: parts.slice(1), + raw: trimmed, + }; +} + +/** + * Validates whether a command is a registered slash command. + */ +export function executeSlashCommand( + cmd: string, + allowedCommands?: string[] +): { success: boolean; error?: string } { + const valid = allowedCommands ?? DEFAULT_SLASH_COMMANDS.map((c) => c.command); + if (!valid.includes(cmd)) { + return { + success: false, + error: `Unknown command '${cmd}'. Type /help for available commands.`, + }; + } + return { success: true }; +} + +export interface ComposerProps { + onSubmit: (prompt: string) => void; + onChange?: (value: string) => void; + onSlashCommand?: (command: string, args: string[]) => void; + history?: string[]; + placeholder?: string; + disabled?: boolean; + isFocused?: boolean; + initialValue?: string; + commands?: SlashCommandDefinition[]; + slashCommands?: Array; + maxBufferLength?: number; + terminalWidth?: number; +} + +interface KeyEvent { + input: string; + key: Key; +} + +function isSlashPrefix(state: { buffer: string }): boolean { + return state.buffer.startsWith('/') && !state.buffer.includes(' '); +} + +function isNewline(event: KeyEvent): boolean { + return event.key.return ? Boolean(event.key.shift || event.key.meta) : event.input === '\n'; +} + +function isPrintable(event: KeyEvent): boolean { + return Boolean(event.input) && !event.key.ctrl && !event.key.meta; +} + +function normalizeCommands( + commands?: SlashCommandDefinition[], + propSlashCommands?: ComposerProps['slashCommands'] +): SlashCommandDefinition[] { + if (commands) return commands; + if (!propSlashCommands) return DEFAULT_SLASH_COMMANDS; + return propSlashCommands.map((c) => + 'command' in c ? c : { command: c.name, description: c.description, usage: c.usage } + ); +} + +/** + * Composer component: + * Interactive multiline command prompt with history traversal (Up/Down), + * slash command autocompletion on '/' (/pods, /containers, /watch, /analyze, /health, /help, /clear, /quit), + * Tab completion, Escape dismissal, debounce lock, and newline insertion (Shift+Enter / Alt+Enter). + */ +export const Composer: FC = ({ + onSubmit, + onChange, + onSlashCommand, + history = [], + placeholder = 'Type a prompt or / command...', + disabled = false, + isFocused = true, + initialValue = '', + commands, + slashCommands: propSlashCommands, + maxBufferLength = 10000, + terminalWidth, +}) => { + const [buffer, renderBuffer] = useState(initialValue); + const inputBuffer = useRef(initialValue); + const draftBuffer = useRef(''); + const historyIndex = useRef(-1); + const [showAutocomplete, setShowAutocomplete] = useState(false); + const [autocompleteIndex, setAutocompleteIndex] = useState(0); + const [errorMessage, setErrorMessage] = useState(null); + const isSubmittingRef = useRef(false); + + const setBuffer = (next: { value: string }) => { + inputBuffer.current = next.value; + renderBuffer(next.value); + if (onChange) onChange(next.value); + }; + + const allCommands = normalizeCommands(commands, propSlashCommands); + const registeredCommandNames = allCommands.map((c) => c.command); + const filteredCommands = isSlashPrefix({ buffer }) + ? allCommands.filter((c) => c.command.startsWith(buffer.trim())) + : []; + + useEffect(() => { + if (filteredCommands.length === 0 || autocompleteIndex >= filteredCommands.length) { + setAutocompleteIndex(0); + } + }, [filteredCommands.length, autocompleteIndex]); + + const menuOpen = showAutocomplete && filteredCommands.length > 0; + + function completeCommand(): boolean { + const selected = filteredCommands[autocompleteIndex] ?? filteredCommands[0]; + if (!menuOpen || !selected) return false; + setBuffer({ value: selected.command + ' ' }); + setShowAutocomplete(false); + return true; + } + + function submit() { + if (completeCommand() || isSubmittingRef.current) return; + const trimmed = inputBuffer.current.trim(); + if (!trimmed) return; + const parsed = parseSlashCommand(trimmed); + if (parsed) { + const validation = executeSlashCommand(parsed.command, registeredCommandNames); + if (!validation.success) { + setErrorMessage(validation.error ?? 'Unknown command'); + return; + } + onSlashCommand?.(parsed.command, parsed.args); + } + isSubmittingRef.current = true; + onSubmit(trimmed); + setBuffer({ value: '' }); + draftBuffer.current = ''; + historyIndex.current = -1; + setShowAutocomplete(false); + setErrorMessage(null); + setTimeout(() => { isSubmittingRef.current = false; }, 50); + } + + function navigateHistory(direction: -1 | 1) { + const index = historyIndex.current; + if (!history.length || (direction === 1 && index === -1)) return; + if (index === -1) draftBuffer.current = inputBuffer.current; + const current = index === -1 ? history.length : Math.min(index, history.length - 1); + const next = Math.max(0, current + direction); + if (next >= history.length) { + historyIndex.current = -1; + setBuffer({ value: draftBuffer.current }); + return; + } + historyIndex.current = next; + setBuffer({ value: history[next] }); + } + + function navigate(direction: -1 | 1) { + if (menuOpen) { + const count = filteredCommands.length; + setAutocompleteIndex((index) => (index + direction + count) % count); + return; + } + navigateHistory(direction); + } + + function append(edit: { text: string; suggest: boolean }) { + const next = (inputBuffer.current + edit.text).slice(0, maxBufferLength); + setBuffer({ value: next }); + setShowAutocomplete(edit.suggest && isSlashPrefix({ buffer: next })); + setErrorMessage(null); + } + + useInput((input, key) => { + const event = { input, key }; + if (isNewline(event)) return append({ text: '\n', suggest: false }); + if (key.return || /^\r+$/.test(input)) return submit(); + if (key.tab) { + completeCommand(); + return; + } + if (key.escape) { + setShowAutocomplete(false); + setErrorMessage(null); + return; + } + if (key.upArrow) return navigate(-1); + if (key.downArrow) return navigate(1); + if (key.backspace || key.delete) { + const next = inputBuffer.current.slice(0, -1); + setBuffer({ value: next }); + setShowAutocomplete(isSlashPrefix({ buffer: next })); + setErrorMessage(null); + return; + } + if (isPrintable(event)) append({ text: input, suggest: true }); + }, { isActive: isFocused && !disabled }); + + const safeTerminalWidth = terminalWidth ? Math.max(0, Math.floor(terminalWidth)) : undefined; + + return ( + + {menuOpen ? ( + + Available Commands: + {filteredCommands.map((item, idx) => ( + + + {idx === autocompleteIndex ? '▶ ' : ' '} + {item.command} + + {item.description} + + ))} + + ) : null} + + + + ❯{' '} + + {buffer.length > 0 ? buffer : {placeholder}} + + + {errorMessage ? ( + + {errorMessage} + + ) : null} + + + Enter: Send · Shift+Enter: Newline · Up/Down: History · /: Commands + + + ); +}; diff --git a/src/ui/components/DiffRenderer.tsx b/src/ui/components/DiffRenderer.tsx new file mode 100644 index 00000000..27147e80 --- /dev/null +++ b/src/ui/components/DiffRenderer.tsx @@ -0,0 +1,201 @@ +import React, { useMemo, type FC } from 'react'; +import { Box, Text } from 'ink'; +import { createTwoFilesPatch } from 'diff'; + +export interface DiffLine { + type: 'add' | 'del' | 'context' | 'hunk' | 'header' | 'other'; + oldLine?: number; + newLine?: number; + content: string; +} + +export interface DiffRendererProps { + diff?: string; + diffContent?: string; + oldContent?: string; + newContent?: string; + filePath?: string; + filename?: string; + maxLines?: number; + showLineNumbers?: boolean; + terminalWidth?: number; + availableTerminalHeight?: number; + disableColor?: boolean; + disableTruncation?: boolean; +} + +const hunkHeaderRegex = /^@@ -(\d+),?\d* \+(\d+),?\d* @@/; + +interface DiffParseState { + oldLine: number; + newLine: number; + inHunk: boolean; +} + +function classifyBodyDiffLine(line: string, state: DiffParseState): DiffLine { + if (line.startsWith('+') && !line.startsWith('+++')) { + state.newLine++; + return { type: 'add', newLine: state.newLine, content: line }; + } + if (line.startsWith('-') && !line.startsWith('---')) { + state.oldLine++; + return { type: 'del', oldLine: state.oldLine, content: line }; + } + if (line.startsWith(' ')) { + state.oldLine++; + state.newLine++; + return { type: 'context', oldLine: state.oldLine, newLine: state.newLine, content: line }; + } + return { type: 'other', content: line }; +} + +function parseSingleDiffLine(line: string, state: DiffParseState): DiffLine { + const hunkMatch = line.match(hunkHeaderRegex); + if (hunkMatch) { + state.oldLine = parseInt(hunkMatch[1], 10) - 1; + state.newLine = parseInt(hunkMatch[2], 10) - 1; + state.inHunk = true; + return { type: 'hunk', content: line }; + } + if (!state.inHunk) return { type: 'header', content: line }; + return classifyBodyDiffLine(line, state); +} + +/** + * Parses unified diff strings and tracks old/new line numbers. + */ +export function parseDiffWithLineNumbers(diffText: string): DiffLine[] { + const state: DiffParseState = { oldLine: 0, newLine: 0, inHunk: false }; + return diffText.split(/\r?\n/).map((line) => parseSingleDiffLine(line, state)); +} + +const diffColors: Record = { '+': 'green', '-': 'red', '@@': 'cyan', '---': 'yellow', '+++': 'yellow' }; + +function diffLineColor(line: string) { + return diffColors[line.slice(0, 3)] ?? diffColors[line.slice(0, 2)] ?? diffColors[line[0]]; +} + +function DiffDisplayLine({ line, color, parsed, width }: { line: string; color?: string; parsed?: DiffLine; width: number }) { + if (!parsed) return {line}; + const number = parsed.newLine ?? parsed.oldLine ?? ''; + return ( + + {String(number).padStart(width)} + {line} + + ); +} + +function resolveDiff({ diff, diffContent, oldContent, newContent, filePath }: DiffRendererProps): string { + if (diff !== undefined) return diff; + if (diffContent !== undefined) return diffContent; + if (oldContent === undefined || newContent === undefined) return ''; + if (oldContent === newContent) return ''; + const name = filePath || 'manifest.yaml'; + return createTwoFilesPatch(name, `${name}.patched`, oldContent, newContent); +} + +function normalizeRawDiff(rawDiff: string): string { + // Decode transport-escaped single-line diffs without corrupting literal '\n' inside multiline diffs. + if (rawDiff.includes('\n')) return rawDiff.trim(); + return rawDiff.replace(/\\n/g, '\n').trim(); +} + +function computeGutterWidth(parsedLines: DiffLine[], showLineNumbers: boolean): number { + if (!showLineNumbers) return 3; + const maxLineNum = parsedLines.reduce((max, item) => { + const lineNum = Math.max(item.oldLine || 0, item.newLine || 0); + return Math.max(max, lineNum); + }, 0); + return maxLineNum > 0 ? maxLineNum.toString().length + 1 : 3; +} + +function resolveSafeWidth(terminalWidth?: number): number | undefined { + return terminalWidth ? Math.max(0, Math.floor(terminalWidth)) : undefined; +} + +function computeDisplaySlice(ctx: { normalizedDiff: string; maxLines: number; disableTruncation: boolean }) { + const rawLines = ctx.normalizedDiff.split('\n'); + const displayLines = rawLines.slice(0, ctx.disableTruncation ? rawLines.length : ctx.maxLines); + return { displayLines, remainingCount: rawLines.length - displayLines.length }; +} + +function DiffHeaderRow({ fileLabel }: { fileLabel?: string }) { + return ( + + ── Manifest Unified Diff ─────────────────── + {fileLabel ? File: {fileLabel} : null} + + ); +} + +function DiffEmptyBanner({ width }: { width?: number }) { + return ( + + No configuration differences detected. + + ); +} + +/** + * DiffRenderer component: + * Unified color-coded diff viewer for Kubernetes manifests and Dockerfile changes. + * Color codes additions (green), deletions (red), hunk headers (cyan), and file headers (yellow). + * Handles line numbers, empty diffs, line truncation, and terminal width safety. + */ +export const DiffRenderer: FC = ({ + diff, + diffContent, + oldContent, + newContent, + filePath, + filename, + maxLines = 50, + showLineNumbers = false, + terminalWidth, + disableColor = false, + disableTruncation = false, +}) => { + const fileLabel = filePath || filename; + const rawDiff = useMemo( + () => resolveDiff({ diff, diffContent, oldContent, newContent, filePath: fileLabel }), + [diff, diffContent, oldContent, newContent, fileLabel] + ); + + const safeTerminalWidth = resolveSafeWidth(terminalWidth); + const normalizedDiff = normalizeRawDiff(rawDiff); + const { displayLines, remainingCount } = computeDisplaySlice({ + normalizedDiff, + maxLines, + disableTruncation, + }); + + const parsedLines = useMemo( + () => (showLineNumbers ? parseDiffWithLineNumbers(normalizedDiff) : []), + [showLineNumbers, normalizedDiff] + ); + const gutterWidth = useMemo( + () => computeGutterWidth(parsedLines, showLineNumbers), + [parsedLines, showLineNumbers] + ); + + if (!normalizedDiff) return ; + + return ( + + + + {displayLines.map((line, index) => ( + + ))} + + {remainingCount > 0 ? ... and {remainingCount} more lines : null} + + ); +}; diff --git a/src/ui/components/SubagentProgressDisplay.tsx b/src/ui/components/SubagentProgressDisplay.tsx new file mode 100644 index 00000000..edb05273 --- /dev/null +++ b/src/ui/components/SubagentProgressDisplay.tsx @@ -0,0 +1,268 @@ +import React, { useState, type FC } from 'react'; +import { Box, Text, useInput } from 'ink'; +import { ThinkingMessage } from './ThinkingMessage.js'; +import { InkSpinner } from './InkSpinner.js'; +import { getAgentDisplayName, getAgentIcon } from '../council-state.js'; + +export interface SubagentProgress { + agentName: string; + state: 'running' | 'completed' | 'error' | 'cancelled'; + thought?: string; + toolCall?: { + name: string; + args: Record; + status: 'running' | 'success' | 'error'; + output?: string; + }; + result?: string; +} + +export interface SubagentActivityItem { + id: string; + type: 'thought' | 'tool_call'; + content?: string; + displayName?: string; + description?: string; + args?: Record | string; + status?: 'running' | 'completed' | 'error' | 'cancelled'; +} + +export interface SubagentProgressDisplayProps { + progress?: SubagentProgress; + subagents?: SubagentProgress[]; + activeAgentName?: string; + initiallyExpanded?: boolean; + isExpanded?: boolean; + onToggleExpand?: () => void; + interactive?: boolean; + borderStyle?: 'round' | 'single' | 'double'; + title?: string; + terminalWidth?: number; + availableTerminalHeight?: number; + historyOverrides?: SubagentActivityItem[]; +} + +function serializeArgValue(key: string, value: unknown): string { + if (typeof value === 'string') return `${key}="${value}"`; + if (typeof value === 'bigint') return `${key}=${value.toString()}n`; + try { + return `${key}=${JSON.stringify(value)}`; + } catch { + return `${key}=[Complex]`; + } +} + +function truncateToolText(text: string): string { + return text.length > 60 ? `${text.slice(0, 60)}...` : text; +} + +function formatObjectToolArgs(args: Record): string { + try { + const entries = Object.entries(args); + if (entries.length === 0) return ''; + return truncateToolText(entries.map(([k, v]) => serializeArgValue(k, v)).join(', ')); + } catch { + return String(args).slice(0, 60); + } +} + +/** + * Formats tool call arguments cleanly into key="val" pairs, truncated to max 60 chars. + */ +export function formatToolArgs(args: Record | string | undefined): string { + if (!args) return ''; + if (typeof args !== 'string') return formatObjectToolArgs(args); + try { + return formatToolArgs(JSON.parse(args)); + } catch { + return truncateToolText(args); + } +} + +const statusStyles = { + running: { color: 'cyan', icon: }, + completed: { color: 'green', icon: ✔ }, + error: { color: 'red', icon: ✖ }, + cancelled: { color: 'yellow', icon: ℹ }, +}; + +const statusMessages: Record string> = { + running: (agent) => agent.thought || `Running subagent ${agent.agentName}...`, + completed: (agent) => agent.result || `Subagent ${agent.agentName} completed.`, + error: (agent) => `Subagent ${agent.agentName} failed: ${agent.result || 'Unknown error'}`, + cancelled: (agent) => `Subagent ${agent.agentName} was cancelled.`, +}; + +const toolIcons = { + running: , + success: ✔ , + error: ✖ , +}; + +function ToolOutputPreview({ expanded, output }: { expanded: boolean; output?: string }) { + if (!expanded || !output) return null; + return ( + + Output: {output} + + ); +} + +function ToolProgress({ tool, name, expanded, cancelled }: { + tool: NonNullable; + name: string; + expanded: boolean; + cancelled: boolean; +}) { + return ( + + + ⚡ Active Tool: + [{name}] + {toolIcons[tool.status]} + {tool.name} + {tool.output ? ({tool.output}) : null} + + + → + {tool.name}({formatToolArgs(tool.args)}) + + + + ); +} + +function canShowCardResult(agent: SubagentProgress, expanded: boolean): boolean { + if (!expanded || !agent.result) return false; + return agent.state !== 'error'; +} + +function CardResult({ agent, expanded }: { agent: SubagentProgress; expanded: boolean }) { + if (!canShowCardResult(agent, expanded)) return null; + return ( + + Result: {agent.result} + + ); +} + +function AgentThoughtRow({ thought, expanded, width }: { thought?: string; expanded: boolean; width?: number }) { + if (!thought) return null; + return ( + + + + ); +} + +function AgentToolRow({ tool, name, expanded, cancelled }: { + tool?: SubagentProgress['toolCall']; + name: string; + expanded: boolean; + cancelled: boolean; +}) { + if (!tool) return null; + return ; +} + +function AgentProgressCard({ agent, expanded, width }: { agent: SubagentProgress; expanded: boolean; width?: number }) { + const displayName = getAgentDisplayName(agent.agentName) || agent.agentName; + const style = statusStyles[agent.state]; + const cancelled = agent.state === 'cancelled'; + + return ( + + + + {style.icon} + {getAgentIcon(agent.agentName)} + {displayName}: + {statusMessages[agent.state](agent)} + + + + + + ); +} + +function ActivityHistory({ entries }: { entries: SubagentActivityItem[] }) { + return <>{entries.map((item) => ( + + [{item.type}] + {item.displayName || item.id}: + {item.content || formatToolArgs(item.args)} + + ))}; +} + +function countAgentStates(agents: SubagentProgress[]) { + const tally = { running: 0, completed: 0, error: 0, cancelled: 0 }; + for (const agent of agents) tally[agent.state]++; + return tally; +} + +function formatStateSuffix(label: string, count: number): string { + return count ? `, ${count} ${label}` : ''; +} + +function AgentProgressHeader({ agents, title, expanded }: { agents: SubagentProgress[]; title: string; expanded: boolean }) { + const tally = countAgentStates(agents); + const failures = formatStateSuffix('failed', tally.error); + const cancellations = formatStateSuffix('cancelled', tally.cancelled); + return ( + + + {title} ({agents.length} agents: {tally.running} running, {tally.completed} completed{failures}{cancellations}) + + (ctrl+o to {expanded ? 'collapse' : 'expand'}) + + ); +} + +function resolveAgents(progress?: SubagentProgress, subagents?: SubagentProgress[]): SubagentProgress[] { + if (progress) return [progress]; + return subagents ?? []; +} + +function resolveSafeWidth(terminalWidth?: number): number | undefined { + return terminalWidth ? Math.max(0, Math.floor(terminalWidth)) : undefined; +} + +function resolveBorderColor(agents: SubagentProgress[]): 'red' | 'cyan' { + return agents.some((agent) => agent.state === 'error') ? 'red' : 'cyan'; +} + +export const SubagentProgressDisplay: FC = ({ + progress, + subagents, + initiallyExpanded = false, + isExpanded: controlledExpanded, + onToggleExpand, + interactive = true, + borderStyle = 'round', + title = '🤖 Active Multi-Agent Observability', + terminalWidth, + historyOverrides = [], +}) => { + const [internalExpanded, setInternalExpanded] = useState(initiallyExpanded); + const expanded = controlledExpanded ?? internalExpanded; + const toggleExpand = onToggleExpand ?? (() => setInternalExpanded((previous) => !previous)); + + useInput((input, key) => { + if (key.ctrl && input.toLowerCase() === 'o') toggleExpand(); + }, { isActive: interactive }); + + const agents = resolveAgents(progress, subagents); + if (!agents.length && !historyOverrides.length) return null; + + return ( + + + + {agents.map((agent) => )} + + + + ); +}; diff --git a/src/ui/components/ThinkingMessage.tsx b/src/ui/components/ThinkingMessage.tsx new file mode 100644 index 00000000..aa1a4b31 --- /dev/null +++ b/src/ui/components/ThinkingMessage.tsx @@ -0,0 +1,141 @@ +import React, { useMemo, type FC } from 'react'; +import { Box, Text } from 'ink'; + +export interface ThoughtSummary { + subject?: string; + description?: string; +} + +export interface ThinkingMessageProps { + thought?: string | ThoughtSummary; + compact?: boolean; + maxPreviewLength?: number; + terminalWidth?: number; + isFirstThinking?: boolean; +} + +/** + * Strips raw ANSI escape sequences from strings. + */ +export function stripAnsi(text: string): string { + return text.replace(/\u001b\[[0-9;?]*[a-zA-Z]/g, ''); +} + +/** + * Normalizes escaped newlines (e.g. literal '\n') into real newline characters. + */ +export function normalizeEscapedNewlines(text?: string): string { + if (!text) return ''; + return text.replace(/\\n/g, '\n'); +} + +/** + * Checks whether text is whitespace or repetitive progress dot noise (e.g. '...'). + */ +export function isNoise(text: string): boolean { + const trimmed = text.trim(); + return !trimmed || /^[.\s…]+$/.test(trimmed); +} + +/** + * Compacts long text with an ellipsis and [+more] suffix. + */ +export function compactPreview(text: string, maxLen = 120): string { + if (text.length <= maxLen) return text; + return text.substring(0, maxLen) + '... [+more]'; +} + +/** + * Normalizes thought input into sanitized, noise-filtered lines. + */ +function normalizeThoughtLines( + thought?: string | ThoughtSummary, + compact = false, + maxPreviewLength?: number +): string[] { + if (!thought) return []; + + const previewLength = maxPreviewLength ?? (compact ? 120 : 1500); + const [subject, ...description] = thoughtSegments(thought, previewLength); + const descLines = description.map(line => line.trim()).filter(line => !isNoise(line)); + const maxLines = compact ? 3 : 50; + const lines = isNoise(subject) ? [] : [subject.trim()]; + lines.push(...descLines.slice(0, maxLines)); + if (descLines.length > maxLines) lines.push('... [+more]'); + return lines; +} + +function thoughtSegments(thought: string | ThoughtSummary, previewLength: number): string[] { + const clean = (text = '') => normalizeEscapedNewlines(stripAnsi(text)); + if (typeof thought === 'string') return compactPreview(clean(thought), previewLength).split('\n'); + return [clean(thought.subject), ...clean(thought.description).split('\n')]; +} + +/** + * ThinkingMessage component: + * Renders model or agent reasoning bubbles with 💭 icon, left vertical rule (│), + * noise filtering, newline normalization, and compact preview options. + */ +export const ThinkingMessage: FC = ({ + thought, + compact = false, + maxPreviewLength, + terminalWidth, + isFirstThinking = false, +}) => { + const fullLines = useMemo( + () => normalizeThoughtLines(thought, compact, maxPreviewLength), + [thought, compact, maxPreviewLength] + ); + + if (fullLines.length === 0) { + return null; + } + + const displayThought = fullLines.join(' '); + + if (compact) { + return ( + + 💭 + + {displayThought} + + + ); + } + + return ( + + {isFirstThinking ? ( + + 💭 Thinking... + + ) : null} + + + + 💭 + + {fullLines[0]} + + + {fullLines.slice(1).map((line, index) => ( + + {line} + + ))} + + + ); +}; diff --git a/src/ui/components/ToolConfirmationQueue.tsx b/src/ui/components/ToolConfirmationQueue.tsx new file mode 100644 index 00000000..4b88225b --- /dev/null +++ b/src/ui/components/ToolConfirmationQueue.tsx @@ -0,0 +1,285 @@ +import React, { useState, useRef, useEffect, type FC } from 'react'; +import { Box, Text, useInput, type Key } from 'ink'; +import { DiffRenderer } from './DiffRenderer.js'; +import { formatToolArgs } from './SubagentProgressDisplay.js'; + +export interface ConfirmationRequest { + id: string; + toolName: string; + args: Record; + diff?: string; + riskLevel: 'low' | 'medium' | 'high'; + prompt: string; + timestamp?: number; +} + +export type ConfirmationDecision = 'ALLOW' | 'DENY' | 'EDIT'; + +export interface ToolConfirmationQueueProps { + request?: ConfirmationRequest; + requests?: ConfirmationRequest[]; + queue?: ConfirmationRequest[]; + currentIndex?: number; + onDecision: ( + decision: ConfirmationDecision, + request: ConfirmationRequest, + editedArgs?: Record + ) => void; + onResolve?: (id: string, decision: ConfirmationDecision) => void; + onAbort?: () => void; + interactive?: boolean; + terminalWidth?: number; + availableTerminalHeight?: number; +} + +const DESTRUCTIVE_PATTERNS = [ + /\brm\s+(?:.*?\s+)?(-[a-z0-9]*r[a-z0-9]*f[a-z0-9]*|-[a-z0-9]*f[a-z0-9]*r[a-z0-9]*|-[a-z0-9]*r[a-z0-9]*\s+-[a-z0-9]*f[a-z0-9]*|-[a-z0-9]*f[a-z0-9]*\s+-[a-z0-9]*r[a-z0-9]*|--recursive\s+--force|--force\s+--recursive)(?:\s+.*?)*\s+\//i, + /\bkubectl\s+delete\s+(namespaces?|ns)\s+(kube-system|default|production)\b/i, + /mkfs/i, + /dd\s+if=/i, +]; + +const RISK_COLORS: Record = { + high: 'red', + medium: 'yellow', + low: 'green', +}; + +/** + * Evaluates safety policy against dangerous or destructive cluster mutations. + */ +export function evaluateSafetyPolicy(command: string): { allowed: boolean; violation?: string } { + for (const pattern of DESTRUCTIVE_PATTERNS) { + if (pattern.test(command)) { + return { + allowed: false, + violation: `Destructive command permanently blocked by safety policy: ${command}`, + }; + } + } + return { allowed: true }; +} + +function extractCommandString(currentRequest?: ConfirmationRequest): string { + if (!currentRequest) return ''; + const { args, toolName } = currentRequest; + const candidates = [args.command, args.cmd, args.script, args.raw, toolName]; + return String(candidates.find(Boolean) ?? toolName); +} + +function isDenyKey(lower: string, key: Key): boolean { + if (lower === 'n') return true; + return Boolean(key.escape || key.return); +} + +function resolveSafeWidth(terminalWidth?: number): number | undefined { + return terminalWidth ? Math.max(0, Math.floor(terminalWidth)) : undefined; +} + +function resolveAllRequests({ queue, requests, request }: Pick) { + if (queue) return queue; + if (requests) return requests; + return request ? [request] : []; +} + +function dispatchAllowedKeyAction(ctx: { + lower: string; + currentRequest: ConfirmationRequest; + onDecision: (target: ConfirmationRequest, decision: ConfirmationDecision) => void; +}) { + if (ctx.lower === 'y') ctx.onDecision(ctx.currentRequest, 'ALLOW'); + if (ctx.lower === 'e') ctx.onDecision(ctx.currentRequest, 'EDIT'); +} + +function handleQueueKeyInput(ctx: { + input: string; + key: Key; + policyAllowed: boolean; + currentRequest: ConfirmationRequest; + onAbort?: () => void; + onDecision: (target: ConfirmationRequest, decision: ConfirmationDecision) => void; +}) { + const lower = ctx.input.toLowerCase(); + if (ctx.key.ctrl && lower === 'c') { + ctx.onAbort?.(); + ctx.onDecision(ctx.currentRequest, 'DENY'); + return; + } + if (isDenyKey(lower, ctx.key)) { + ctx.onDecision(ctx.currentRequest, 'DENY'); + return; + } + if (ctx.policyAllowed) { + dispatchAllowedKeyAction({ lower, currentRequest: ctx.currentRequest, onDecision: ctx.onDecision }); + } +} + +function EmptyConfirmationCard({ width }: { width?: number }) { + return ( + + No pending confirmations. + + ); +} + +function PolicyBlockedCard({ violation, width }: { violation?: string; width?: number }) { + return ( + + ⛔ POLICY VIOLATION: COMMAND BLOCKED + {violation} + + + Execution prohibited by automated safety gate. Press [n],{' '} + [Enter], or [Esc] to dismiss. + + + + ); +} + +function ConfirmationDiffSection({ diff, width }: { diff?: string; width?: number }) { + if (!diff) return null; + return ( + + + + ); +} + +function ConfirmationCard({ request, index, total, width }: { + request: ConfirmationRequest; + index: number; + total: number; + width?: number; +}) { + const riskColor = RISK_COLORS[request.riskLevel]; + const riskBadge = `[${request.riskLevel.toUpperCase()} RISK ACTION REQUIRED]`; + + return ( + + + {riskBadge} + Queue: {index + 1} of {total} (ID: {request.id}) + + + + + Tool: + {request.toolName} + + + Args: + {formatToolArgs(request.args)} + + + + + {request.prompt} + + + + + + + Press [y] to Approve, [n] to Deny,{' '} + [e] to Edit + + + + ); +} + +function nextQueueIndex(prev: number, decidingId: string, list: ConfirmationRequest[]): number { + const next = list[prev]?.id === decidingId ? prev + 1 : prev; + return Math.min(next, Math.max(0, list.length - 1)); +} + +function renderQueueView(ctx: { + currentRequest?: ConfirmationRequest; + policy: { allowed: boolean; violation?: string }; + internalIndex: number; + total: number; + width?: number; +}) { + if (!ctx.currentRequest) return ; + if (!ctx.policy.allowed) return ; + return ( + + ); +} + +/** + * ToolConfirmationQueue component: + * Interactive confirmation queue gating mutating/dangerous cluster operations with + * risk safety badges (low, medium, high), safety policy checks, embedded diffs, + * and keyboard approval ([y] Approve, [n] Deny, [e] Edit). + */ +export const ToolConfirmationQueue: FC = ({ + request, + requests, + queue, + currentIndex = 0, + onDecision, + onResolve, + onAbort, + interactive = true, + terminalWidth, +}) => { + const allRequests = resolveAllRequests({ queue, requests, request }); + const allRequestsRef = useRef(allRequests); + allRequestsRef.current = allRequests; + const [internalIndex, setInternalIndex] = useState(currentIndex); + const currentRequest = allRequests[internalIndex]; + const handledRef = useRef(false); + + useEffect(() => { + setInternalIndex((prev) => Math.min(prev, Math.max(0, allRequests.length - 1))); + }, [allRequests.length]); + + useEffect(() => { + handledRef.current = false; + }, [currentRequest?.id]); + + const policy = evaluateSafetyPolicy(extractCommandString(currentRequest)); + + const applyDecision = (target: ConfirmationRequest, decision: ConfirmationDecision) => { + handledRef.current = true; + onDecision(decision, target); + onResolve?.(target.id, decision); + + if (internalIndex + 1 < allRequests.length) { + setTimeout(() => { + setInternalIndex((prev) => nextQueueIndex(prev, target.id, allRequestsRef.current)); + handledRef.current = false; + }, 30); + } + }; + + useInput((input, key) => { + if (!interactive || handledRef.current) return; + if (!currentRequest) return; + handleQueueKeyInput({ + input, + key, + policyAllowed: policy.allowed, + currentRequest, + onAbort, + onDecision: applyDecision, + }); + }); + + return renderQueueView({ + currentRequest, + policy, + internalIndex, + total: allRequests.length, + width: resolveSafeWidth(terminalWidth), + }); +}; + +export const ToolConfirmationQueueView = ToolConfirmationQueue; diff --git a/src/ui/components/index.ts b/src/ui/components/index.ts new file mode 100644 index 00000000..7b225d93 --- /dev/null +++ b/src/ui/components/index.ts @@ -0,0 +1,10 @@ +export * from './ActiveToolPanel.js'; +export * from './AgentCard.js'; +export * from './ConsensusDiagnosisView.js'; +export * from './InkSpinner.js'; +export * from './ThinkingMessage.js'; +export * from './SubagentProgressDisplay.js'; +export * from './DiffRenderer.js'; +export * from './ToolConfirmationQueue.js'; +export * from './Composer.js'; +export * from '../AppContainer.js'; diff --git a/src/ui/contexts/StreamingContext.tsx b/src/ui/contexts/StreamingContext.tsx new file mode 100644 index 00000000..0323be9f --- /dev/null +++ b/src/ui/contexts/StreamingContext.tsx @@ -0,0 +1,324 @@ +import React, { createContext, useContext, useReducer, useMemo, useRef, type FC, type ReactNode } from 'react'; +import type { NDJSONEvent, SubagentProgress } from '../../agent/types.js'; +import { translateNDJSONToSubagentProgress } from '../../agent/event-translator.js'; + +export type { SubagentProgress } from '../../agent/types.js'; + +export interface ActiveToolCall { + id: string; + agentName: string; + toolName: string; + args: Record; + status: 'running' | 'success' | 'error'; + startTime: number; + durationMs?: number; + output?: string; +} + +export interface StreamingState { + subagents: Record; + subagentOrder: string[]; + streamingThoughts: Record; + activeTools: ActiveToolCall[]; + isStreaming: boolean; + streamError: string | null; +} + +export interface StreamingActions { + updateSubagentProgress: (progress: SubagentProgress) => void; + appendSubagentProgress: (progress: SubagentProgress) => void; + appendThought: (agentName: string, chunk: string) => void; + setThought: (agentName: string, thought: string) => void; + setStreamingThought: (thought: string) => void; + startToolCall: (params: { + agentName: string; + toolName: string; + args: Record; + }) => string; + finishToolCall: (params: { + id?: string; + agentName?: string; + toolName: string; + status: 'success' | 'error'; + output?: string; + durationMs?: number; + }) => void; + setActiveTool: (tool: ActiveToolCall | null) => void; + clearStream: () => void; + clearStreaming: () => void; + setStreaming: (isStreaming: boolean) => void; + setStreamError: (error: string | null) => void; + processNDJSON: (event: NDJSONEvent) => void; +} + +export interface StreamingContextValue extends StreamingActions { + state: StreamingState; + actions: StreamingActions; + subagents: SubagentProgress[]; + subagentsMap: Record; + subagentOrder: string[]; + activeThought: string; + streamingThoughts: Record; + activeTool: ActiveToolCall | null; + activeTools: ActiveToolCall[]; + isStreaming: boolean; + streamError: string | null; +} + +type FinishToolPayload = { + id?: string; + agentName?: string; + toolName: string; + status: 'success' | 'error'; + output?: string; + durationMs?: number; + finishedAt: number; +}; + +type StreamingAction = + | { type: 'UPDATE_SUBAGENT_PROGRESS'; payload: SubagentProgress } + | { type: 'APPEND_THOUGHT'; payload: { agentName: string; chunk: string } } + | { type: 'SET_THOUGHT'; payload: { agentName: string; thought: string } } + | { type: 'SET_GLOBAL_THOUGHT'; payload: string } + | { type: 'START_TOOL_CALL'; payload: ActiveToolCall } + | { type: 'FINISH_TOOL_CALL'; payload: FinishToolPayload } + | { type: 'SET_ACTIVE_TOOL'; payload: ActiveToolCall | null } + | { type: 'CLEAR_STREAM' } + | { type: 'SET_STREAMING'; payload: boolean } + | { type: 'SET_STREAM_ERROR'; payload: string | null }; + +const initialStreamingState: StreamingState = { + subagents: {}, + subagentOrder: [], + streamingThoughts: {}, + activeTools: [], + isStreaming: false, + streamError: null, +}; + +function shouldPreserveToolArgs(prev: SubagentProgress | undefined, next: SubagentProgress): boolean { + if (!next.toolCall || !prev?.toolCall) return false; + if (next.toolCall.status === 'running') return false; + return prev.toolCall.name === next.toolCall.name; +} + +function mergeToolCallArgs(prev: SubagentProgress | undefined, next: SubagentProgress): SubagentProgress { + if (!shouldPreserveToolArgs(prev, next)) return next; + const nextTool = next.toolCall!; + if (Object.keys(nextTool.args).length > 0) return next; + return { ...next, toolCall: { ...nextTool, args: prev!.toolCall!.args } }; +} + +function applySubagentUpdate(state: StreamingState, progress: SubagentProgress): StreamingState { + const order = state.subagentOrder.includes(progress.agentName) + ? state.subagentOrder + : [...state.subagentOrder, progress.agentName]; + const existing = state.subagents[progress.agentName]; + const merged = mergeToolCallArgs(existing, progress); + const currentThoughts = state.streamingThoughts[progress.agentName] || ''; + const updatedThoughts = progress.thought !== undefined ? progress.thought : currentThoughts; + + return { + ...state, + subagents: { ...state.subagents, [progress.agentName]: { ...existing, ...merged } }, + subagentOrder: order, + streamingThoughts: { ...state.streamingThoughts, [progress.agentName]: updatedThoughts }, + isStreaming: progress.state === 'running' ? true : state.isStreaming, + }; +} + +function reduceAgentProgress(state: StreamingState, action: StreamingAction): StreamingState | undefined { + if (action.type === 'UPDATE_SUBAGENT_PROGRESS') { + return applySubagentUpdate(state, action.payload); + } + if (action.type === 'APPEND_THOUGHT') { + const { agentName, chunk } = action.payload; + const existing = state.streamingThoughts[agentName] || ''; + return { ...state, streamingThoughts: { ...state.streamingThoughts, [agentName]: existing + chunk } }; + } + if (action.type === 'SET_THOUGHT') { + const { agentName, thought } = action.payload; + return { ...state, streamingThoughts: { ...state.streamingThoughts, [agentName]: thought } }; + } + if (action.type === 'SET_GLOBAL_THOUGHT') { + return { ...state, streamingThoughts: { ...state.streamingThoughts, _global: action.payload } }; + } + return undefined; +} + +function isAnyAgentToolMatch(tool: ActiveToolCall, payload: FinishToolPayload): boolean { + if (tool.toolName !== payload.toolName) return false; + return !payload.agentName || tool.agentName === payload.agentName; +} + +function isRunningToolMatch(tool: ActiveToolCall, payload: FinishToolPayload): boolean { + return tool.status === 'running' && isAnyAgentToolMatch(tool, payload); +} + +function findLastIndex(items: T[], predicate: (item: T) => boolean): number { + for (let idx = items.length - 1; idx >= 0; idx--) { + if (predicate(items[idx])) return idx; + } + return -1; +} + +function findToolCallIndex(tools: ActiveToolCall[], payload: FinishToolPayload): number { + if (payload.id) { + return tools.findIndex((t) => t.id === payload.id); + } + const runningIdx = findLastIndex(tools, (t) => isRunningToolMatch(t, payload)); + if (runningIdx >= 0) return runningIdx; + return findLastIndex(tools, (t) => isAnyAgentToolMatch(t, payload)); +} + +function applyFinishToolCall(tools: ActiveToolCall[], payload: FinishToolPayload): ActiveToolCall[] { + const targetIdx = findToolCallIndex(tools, payload); + if (targetIdx < 0) return tools; + return tools.map((tool, idx) => + idx === targetIdx + ? { + ...tool, + status: payload.status, + output: payload.output, + durationMs: payload.durationMs ?? (payload.finishedAt - tool.startTime), + } + : tool + ); +} + +function reduceActiveTools(state: StreamingState, action: StreamingAction): StreamingState | undefined { + if (action.type === 'START_TOOL_CALL') { + return { + ...state, + activeTools: [...state.activeTools.filter((t) => t.id !== action.payload.id), action.payload], + }; + } + if (action.type === 'FINISH_TOOL_CALL') { + return { ...state, activeTools: applyFinishToolCall(state.activeTools, action.payload) }; + } + if (action.type === 'SET_ACTIVE_TOOL') { + const payload = action.payload; + if (!payload) return { ...state, activeTools: [] }; + return { ...state, activeTools: [...state.activeTools.filter((t) => t.id !== payload.id), payload] }; + } + return undefined; +} + +function streamingReducer(state: StreamingState, action: StreamingAction): StreamingState { + const updated = reduceAgentProgress(state, action) ?? reduceActiveTools(state, action); + if (updated) return updated; + if (action.type === 'CLEAR_STREAM') return initialStreamingState; + if (action.type === 'SET_STREAMING') return { ...state, isStreaming: action.payload }; + if (action.type === 'SET_STREAM_ERROR') return { ...state, streamError: action.payload, isStreaming: false }; + return state; +} + +export const StreamingContext = createContext(null); + +function recordCouncilProgress( + event: NDJSONEvent, + dispatch: React.Dispatch, + nextId: () => string +) { + const progress = translateNDJSONToSubagentProgress(event); + if (!progress) return; + dispatch({ type: 'UPDATE_SUBAGENT_PROGRESS', payload: progress }); + if (event.event === 'agent_tool_call') { + dispatch({ + type: 'START_TOOL_CALL', + payload: { + id: nextId(), + agentName: event.role, + toolName: event.tool, + args: event.args, + status: 'running', + startTime: Date.now(), + }, + }); + } + if (event.event === 'agent_tool_result') { + dispatch({ + type: 'FINISH_TOOL_CALL', + payload: { + agentName: event.role, + toolName: event.tool, + status: 'success', + durationMs: event.durationMs, + output: progress.toolCall?.output, + finishedAt: Date.now(), + }, + }); + } +} + +export interface StreamingProviderProps { + children: ReactNode; + initialState?: Partial; +} + +export const StreamingProvider: FC = ({ children, initialState }) => { + const [state, dispatch] = useReducer(streamingReducer, { + ...initialStreamingState, + ...initialState, + }); + const idCounter = useRef(0); + + const actions = useMemo(() => { + const nextToolId = (prefix: string) => `${prefix}-${Date.now()}-${++idCounter.current}`; + return { + updateSubagentProgress: (progress) => dispatch({ type: 'UPDATE_SUBAGENT_PROGRESS', payload: progress }), + appendSubagentProgress: (progress) => dispatch({ type: 'UPDATE_SUBAGENT_PROGRESS', payload: progress }), + appendThought: (agentName, chunk) => dispatch({ type: 'APPEND_THOUGHT', payload: { agentName, chunk } }), + setThought: (agentName, thought) => dispatch({ type: 'SET_THOUGHT', payload: { agentName, thought } }), + setStreamingThought: (thought) => dispatch({ type: 'SET_GLOBAL_THOUGHT', payload: thought }), + startToolCall: ({ agentName, toolName, args }) => { + const id = nextToolId('tool'); + dispatch({ + type: 'START_TOOL_CALL', + payload: { id, agentName, toolName, args, status: 'running', startTime: Date.now() }, + }); + return id; + }, + finishToolCall: (params) => + dispatch({ type: 'FINISH_TOOL_CALL', payload: { ...params, finishedAt: Date.now() } }), + setActiveTool: (tool) => dispatch({ type: 'SET_ACTIVE_TOOL', payload: tool }), + clearStream: () => dispatch({ type: 'CLEAR_STREAM' }), + clearStreaming: () => dispatch({ type: 'CLEAR_STREAM' }), + setStreaming: (isStreaming) => dispatch({ type: 'SET_STREAMING', payload: isStreaming }), + setStreamError: (error) => dispatch({ type: 'SET_STREAM_ERROR', payload: error }), + processNDJSON: (event) => recordCouncilProgress(event, dispatch, () => nextToolId('ndjson')), + }; + }, []); + + const contextValue = useMemo(() => { + const subagentsList = state.subagentOrder.map((name) => state.subagents[name]); + const lastAgent = state.subagentOrder[state.subagentOrder.length - 1]; + const activeThought = state.streamingThoughts._global || (lastAgent ? state.streamingThoughts[lastAgent] || '' : ''); + const activeTool = state.activeTools.length > 0 ? state.activeTools[state.activeTools.length - 1] : null; + + return { + state, + actions, + subagents: subagentsList, + subagentsMap: state.subagents, + subagentOrder: state.subagentOrder, + activeThought, + streamingThoughts: state.streamingThoughts, + activeTool, + activeTools: state.activeTools, + isStreaming: state.isStreaming, + streamError: state.streamError, + ...actions, + }; + }, [state, actions]); + + return {children}; +}; + +export function useStreaming(): StreamingContextValue { + const ctx = useContext(StreamingContext); + if (!ctx) { + throw new Error('useStreaming must be used within a StreamingProvider'); + } + return ctx; +} diff --git a/src/ui/contexts/UIStateContext.tsx b/src/ui/contexts/UIStateContext.tsx new file mode 100644 index 00000000..f6f50c37 --- /dev/null +++ b/src/ui/contexts/UIStateContext.tsx @@ -0,0 +1,321 @@ +import React, { createContext, useContext, useReducer, useMemo, useRef, type FC, type ReactNode } from 'react'; + +export type ActiveDialog = 'none' | 'confirmation' | 'help' | 'settings' | 'dialog'; + +export type FocusedComponent = + | 'composer' + | 'confirmationQueue' + | 'subagentProgress' + | 'dashboard' + | 'dialog'; + +export interface ConfirmationRequest { + id: string; + toolName: string; + args: Record; + diff?: string; + riskLevel: 'low' | 'medium' | 'high'; + prompt: string; + timestamp?: number; +} + +export type ConfirmationDecision = 'ALLOW' | 'DENY' | 'EDIT'; + +export interface UIState { + activeDialog: ActiveDialog; + confirmationQueue: ConfirmationRequest[]; + expandedCards: Record; + focusedComponent: FocusedComponent; + activeTab: number; + terminalDimensions: { + columns: number; + rows: number; + }; +} + +export interface UIStateActions { + setActiveDialog: (dialog: ActiveDialog) => void; + closeDialog: () => void; + enqueueConfirmation: (request: ConfirmationRequest) => void; + resolveConfirmation: (id: string, decision: ConfirmationDecision) => void; + toggleCardExpansion: (cardId: string) => void; + setCardExpanded: (cardId: string, expanded: boolean) => void; + expandAllCards: () => void; + collapseAllCards: () => void; + setFocusedComponent: (component: FocusedComponent) => void; + setActiveTab: (tab: number) => void; + setTerminalDimensions: (dims: { columns: number; rows: number }) => void; + openConfirmation: (req: ConfirmationRequest) => void; + closeConfirmation: () => void; + toggleHelp: () => void; +} + +export interface UIStateContextValue { + state: UIState; + actions: UIStateActions; + activeDialog: ActiveDialog; + confirmationQueue: ConfirmationRequest[]; + expandedCards: Record; + focusedComponent: FocusedComponent; + activeTab: number; + terminalDimensions: { columns: number; rows: number }; + activeConfirmation: ConfirmationRequest | null; + isHelpOpen: boolean; + setActiveDialog: (dialog: ActiveDialog) => void; + closeDialog: () => void; + enqueueConfirmation: (request: ConfirmationRequest) => void; + resolveConfirmation: (id: string, decision: ConfirmationDecision) => void; + toggleCardExpansion: (cardId: string) => void; + setCardExpanded: (cardId: string, expanded: boolean) => void; + expandAllCards: () => void; + collapseAllCards: () => void; + setFocusedComponent: (component: FocusedComponent) => void; + setActiveTab: (tab: number) => void; + setTerminalDimensions: (dims: { columns: number; rows: number }) => void; + openConfirmation: (req: ConfirmationRequest) => void; + closeConfirmation: () => void; + toggleHelp: () => void; +} + +type UIStateAction = + | { type: 'SET_ACTIVE_DIALOG'; payload: ActiveDialog } + | { type: 'CLOSE_DIALOG' } + | { type: 'ENQUEUE_CONFIRMATION'; payload: ConfirmationRequest } + | { type: 'RESOLVE_CONFIRMATION'; payload: { id: string; decision: ConfirmationDecision } } + | { type: 'TOGGLE_CARD_EXPANSION'; payload: string } + | { type: 'SET_CARD_EXPANDED'; payload: { cardId: string; expanded: boolean } } + | { type: 'EXPAND_ALL_CARDS' } + | { type: 'COLLAPSE_ALL_CARDS' } + | { type: 'SET_FOCUSED_COMPONENT'; payload: FocusedComponent } + | { type: 'SET_ACTIVE_TAB'; payload: number } + | { type: 'SET_TERMINAL_DIMENSIONS'; payload: { columns: number; rows: number } }; + +const initialUIState: UIState = { + activeDialog: 'none', + confirmationQueue: [], + expandedCards: {}, + focusedComponent: 'composer', + activeTab: 1, + terminalDimensions: { + columns: typeof process !== 'undefined' && process.stdout?.columns ? process.stdout.columns : 120, + rows: typeof process !== 'undefined' && process.stdout?.rows ? process.stdout.rows : 40, + }, +}; + +function reduceEnqueueConfirmation(state: UIState, request: ConfirmationRequest): UIState { + const exists = state.confirmationQueue.some((r) => r.id === request.id); + const queue = exists ? state.confirmationQueue : [...state.confirmationQueue, request]; + return { + ...state, + confirmationQueue: queue, + activeDialog: 'confirmation', + focusedComponent: 'confirmationQueue', + }; +} + +function reduceResolveConfirmation({ state, id }: { state: UIState; id: string }): UIState { + const remaining = state.confirmationQueue.filter((r) => r.id !== id); + const stillHasPending = remaining.length > 0; + return { + ...state, + confirmationQueue: remaining, + activeDialog: stillHasPending ? 'confirmation' : 'none', + focusedComponent: stillHasPending ? 'confirmationQueue' : 'composer', + }; +} + +function reduceSetActiveDialog({ state, payload }: { state: UIState; payload: ActiveDialog }): UIState { + return { + ...state, + activeDialog: payload, + focusedComponent: payload === 'none' ? 'composer' : 'dialog', + }; +} + +function reduceCloseDialog({ state }: { state: UIState }): UIState { + return { + ...state, + activeDialog: 'none', + focusedComponent: state.confirmationQueue.length > 0 ? 'confirmationQueue' : 'composer', + }; +} + +function reduceDialogs(state: UIState, action: UIStateAction): UIState | undefined { + if (action.type === 'SET_ACTIVE_DIALOG') { + return reduceSetActiveDialog({ state, payload: action.payload }); + } + if (action.type === 'CLOSE_DIALOG') { + return reduceCloseDialog({ state }); + } + if (action.type === 'ENQUEUE_CONFIRMATION') { + return reduceEnqueueConfirmation(state, action.payload); + } + if (action.type === 'RESOLVE_CONFIRMATION') { + return reduceResolveConfirmation({ state, id: action.payload.id }); + } + return undefined; +} + +function expandAllCardMap({ expandedCards }: { expandedCards: Record }): Record { + const next: Record = {}; + for (const key of Object.keys(expandedCards)) next[key] = true; + return next; +} + +function reduceCardExpansion(state: UIState, action: UIStateAction): UIState | undefined { + switch (action.type) { + case 'TOGGLE_CARD_EXPANSION': + return { + ...state, + expandedCards: { ...state.expandedCards, [action.payload]: !state.expandedCards[action.payload] }, + }; + case 'SET_CARD_EXPANDED': + return { + ...state, + expandedCards: { ...state.expandedCards, [action.payload.cardId]: action.payload.expanded }, + }; + case 'EXPAND_ALL_CARDS': + return { ...state, expandedCards: expandAllCardMap({ expandedCards: state.expandedCards }) }; + case 'COLLAPSE_ALL_CARDS': + return { ...state, expandedCards: {} }; + default: + return undefined; + } +} + +function uiStateReducer(state: UIState, action: UIStateAction): UIState { + const updated = reduceDialogs(state, action) ?? reduceCardExpansion(state, action); + if (updated) return updated; + if (action.type === 'SET_FOCUSED_COMPONENT') return { ...state, focusedComponent: action.payload }; + if (action.type === 'SET_ACTIVE_TAB') return { ...state, activeTab: action.payload }; + if (action.type === 'SET_TERMINAL_DIMENSIONS') return { ...state, terminalDimensions: action.payload }; + return state; +} + +export const UIStateContext = createContext(null); + +export interface UIStateProviderProps { + children: ReactNode; + initialState?: Partial; + onDecision?: (id: string, decision: ConfirmationDecision) => void; +} + +function createPendingRefs(initialState?: Partial) { + const initialQueue = initialState?.confirmationQueue ?? []; + return { + ids: new Set(initialQueue.map((r) => r.id)), + queue: [...initialQueue], + }; +} + +function enqueuePendingTracking(ctx: { + pendingIdsRef: React.MutableRefObject>; + pendingQueueRef: React.MutableRefObject; + request: ConfirmationRequest; + dispatch: React.Dispatch; +}) { + if (!ctx.pendingIdsRef.current.has(ctx.request.id)) { + ctx.pendingIdsRef.current.add(ctx.request.id); + ctx.pendingQueueRef.current = [...ctx.pendingQueueRef.current, ctx.request]; + } + ctx.dispatch({ type: 'ENQUEUE_CONFIRMATION', payload: ctx.request }); +} + +function resolvePendingTracking(ctx: { + pendingIdsRef: React.MutableRefObject>; + pendingQueueRef: React.MutableRefObject; + onDecisionRef: React.MutableRefObject<((id: string, decision: ConfirmationDecision) => void) | undefined>; + id: string; + decision: ConfirmationDecision; + dispatch: React.Dispatch; +}) { + if (ctx.pendingIdsRef.current.has(ctx.id)) { + ctx.pendingIdsRef.current.delete(ctx.id); + ctx.pendingQueueRef.current = ctx.pendingQueueRef.current.filter((r) => r.id !== ctx.id); + ctx.onDecisionRef.current?.(ctx.id, ctx.decision); + } + ctx.dispatch({ type: 'RESOLVE_CONFIRMATION', payload: { id: ctx.id, decision: ctx.decision } }); +} + +function buildUIContextValue(ctx: { state: UIState; actions: UIStateActions }): UIStateContextValue { + const activeConfirmation = ctx.state.confirmationQueue.length > 0 ? ctx.state.confirmationQueue[0] : null; + return { + state: ctx.state, + actions: ctx.actions, + activeDialog: ctx.state.activeDialog, + confirmationQueue: ctx.state.confirmationQueue, + expandedCards: ctx.state.expandedCards, + focusedComponent: ctx.state.focusedComponent, + activeTab: ctx.state.activeTab, + terminalDimensions: ctx.state.terminalDimensions, + activeConfirmation, + isHelpOpen: ctx.state.activeDialog === 'help', + ...ctx.actions, + }; +} + +export const UIStateProvider: FC = ({ + children, + initialState, + onDecision, +}) => { + const [state, dispatch] = useReducer(uiStateReducer, { + ...initialUIState, + ...initialState, + }); + + // Track pending confirmation IDs synchronously so repeated calls in one render tick publish at most once. + const initialRefs = useMemo(() => createPendingRefs(initialState), []); + const pendingIdsRef = useRef>(initialRefs.ids); + const pendingQueueRef = useRef(initialRefs.queue); + const onDecisionRef = useRef(onDecision); + onDecisionRef.current = onDecision; + + const actions = useMemo(() => { + const enqueue = (request: ConfirmationRequest) => + enqueuePendingTracking({ pendingIdsRef, pendingQueueRef, request, dispatch }); + + const resolve = (id: string, decision: ConfirmationDecision) => + resolvePendingTracking({ pendingIdsRef, pendingQueueRef, onDecisionRef, id, decision, dispatch }); + + return { + setActiveDialog: (dialog) => dispatch({ type: 'SET_ACTIVE_DIALOG', payload: dialog }), + closeDialog: () => dispatch({ type: 'CLOSE_DIALOG' }), + enqueueConfirmation: enqueue, + resolveConfirmation: resolve, + toggleCardExpansion: (cardId) => dispatch({ type: 'TOGGLE_CARD_EXPANSION', payload: cardId }), + setCardExpanded: (cardId, expanded) => dispatch({ type: 'SET_CARD_EXPANDED', payload: { cardId, expanded } }), + expandAllCards: () => dispatch({ type: 'EXPAND_ALL_CARDS' }), + collapseAllCards: () => dispatch({ type: 'COLLAPSE_ALL_CARDS' }), + setFocusedComponent: (component) => dispatch({ type: 'SET_FOCUSED_COMPONENT', payload: component }), + setActiveTab: (tab) => dispatch({ type: 'SET_ACTIVE_TAB', payload: tab }), + setTerminalDimensions: (dims) => dispatch({ type: 'SET_TERMINAL_DIMENSIONS', payload: dims }), + openConfirmation: enqueue, + closeConfirmation: () => { + const current = pendingQueueRef.current[0]; + if (current) resolve(current.id, 'DENY'); + else dispatch({ type: 'CLOSE_DIALOG' }); + }, + toggleHelp: () => + dispatch({ + type: 'SET_ACTIVE_DIALOG', + payload: state.activeDialog === 'help' ? 'none' : 'help', + }), + }; + }, [state.activeDialog]); + + const contextValue = useMemo( + () => buildUIContextValue({ state, actions }), + [state, actions] + ); + + return {children}; +}; + +export function useUIState(): UIStateContextValue { + const ctx = useContext(UIStateContext); + if (!ctx) { + throw new Error('useUIState must be used within a UIStateProvider'); + } + return ctx; +} diff --git a/src/ui/contexts/index.ts b/src/ui/contexts/index.ts new file mode 100644 index 00000000..9849c93e --- /dev/null +++ b/src/ui/contexts/index.ts @@ -0,0 +1,2 @@ +export * from './UIStateContext.js'; +export * from './StreamingContext.js'; diff --git a/src/utils/logger.ts b/src/utils/logger.ts index 73f74c13..507936db 100644 --- a/src/utils/logger.ts +++ b/src/utils/logger.ts @@ -3,7 +3,7 @@ import chalk from 'chalk'; export const logger = { info: (message: string) => console.log(chalk.blue(message)), success: (message: string) => console.log(chalk.green(`✔ ${message}`)), - warn: (message: string) => console.log(chalk.yellow(`⚠ ${message}`)), + warn: (message: string) => console.error(chalk.yellow(`⚠ ${message}`)), error: (message: string, error?: unknown) => { console.error(chalk.red(`✖ ${message}`)); if (error) { diff --git a/src/utils/text.ts b/src/utils/text.ts index 681ccf11..a03a494e 100644 --- a/src/utils/text.ts +++ b/src/utils/text.ts @@ -54,9 +54,6 @@ export function anonymize(text: string): AnonymizeResult { * @returns Text with original names restored. */ export function deanonymize(text: string, mapping: AnonymizeMapping[]): string { - let result = text; - for (const entry of mapping) { - result = result.split(entry.placeholder).join(entry.original); - } - return result; + const originals = new Map(mapping.map(entry => [entry.placeholder, entry.original])); + return text.replace(/MASKED_\d+/g, placeholder => originals.get(placeholder) ?? placeholder); } diff --git a/tsconfig.json b/tsconfig.json index d696e23a..68845a62 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -14,5 +14,12 @@ "jsx": "react-jsx" }, "include": ["src/**/*"], - "exclude": ["node_modules", "dist", "**/*.test.ts"] + "exclude": [ + "node_modules", + "dist", + "**/*.test.ts", + "**/*.test.tsx", + "src/__tests__/**", + "src/**/__tests__/**" + ] }