code-guardian-ai 0.0.0-stage → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/.env.example +24 -0
  2. package/LICENSE +21 -0
  3. package/README.md +774 -2
  4. package/bin/cli.js +2 -0
  5. package/dist/build-manifest.json +136 -0
  6. package/dist/cli/commands/check.js +56 -0
  7. package/dist/cli/commands/doctor.js +55 -0
  8. package/dist/cli/commands/find.js +31 -0
  9. package/dist/cli/commands/init-files.js +13 -0
  10. package/dist/cli/commands/init.js +50 -0
  11. package/dist/cli/commands/optimize.js +53 -0
  12. package/dist/cli/commands/scan.js +47 -0
  13. package/dist/cli/index.js +62 -0
  14. package/dist/cli/output.js +4 -0
  15. package/dist/context.js +11 -0
  16. package/dist/core/ast/analysis.js +455 -0
  17. package/dist/core/ast/cached-info.js +46 -0
  18. package/dist/core/ast/discovery.js +485 -0
  19. package/dist/core/ast/extract-js.js +531 -0
  20. package/dist/core/ast/extract-py.js +298 -0
  21. package/dist/core/ast/graph.js +92 -0
  22. package/dist/core/ast/health.js +338 -0
  23. package/dist/core/ast/indexer.js +286 -0
  24. package/dist/core/ast/packages.js +343 -0
  25. package/dist/core/ast/parser.js +91 -0
  26. package/dist/core/ast/report.js +154 -0
  27. package/dist/core/ast/resolver.js +392 -0
  28. package/dist/core/ast/rules.js +37 -0
  29. package/dist/core/ast/scope-js.js +191 -0
  30. package/dist/core/ast/shared-index.js +131 -0
  31. package/dist/core/ast/tsconfig.js +301 -0
  32. package/dist/core/ast/types.js +1 -0
  33. package/dist/core/ast/util.js +156 -0
  34. package/dist/core/git/git.js +430 -0
  35. package/dist/core/llm/policy.js +35 -0
  36. package/dist/core/llm/provider.js +199 -0
  37. package/dist/core/prompt/compressor.js +118 -0
  38. package/dist/core/prompt/criteria.js +36 -0
  39. package/dist/core/prompt/find.js +47 -0
  40. package/dist/core/prompt/guidelines.js +22 -0
  41. package/dist/core/prompt/model-output.js +178 -0
  42. package/dist/core/prompt/refiner.js +194 -0
  43. package/dist/core/prompt/relevance.js +265 -0
  44. package/dist/core/prompt/untrusted.js +57 -0
  45. package/dist/core/security/masker.js +330 -0
  46. package/dist/core/security/outbound.js +40 -0
  47. package/dist/core/security/safe-file.js +396 -0
  48. package/dist/core/security/sandbox.js +181 -0
  49. package/dist/core/validation/baseline.js +121 -0
  50. package/dist/core/validation/delta.js +243 -0
  51. package/dist/core/validation/policy.js +123 -0
  52. package/dist/db/cache-key.js +221 -0
  53. package/dist/db/client.js +563 -0
  54. package/dist/db/schema-check.js +149 -0
  55. package/dist/db/schema.js +36 -0
  56. package/dist/db/windows-acl.js +150 -0
  57. package/dist/index.js +55 -0
  58. package/dist/mcp/server.js +20 -0
  59. package/dist/mcp/tools/find-reusable.js +22 -0
  60. package/dist/mcp/tools/get-context.js +39 -0
  61. package/dist/mcp/tools/optimize-prompt.js +31 -0
  62. package/dist/mcp/tools/result.js +31 -0
  63. package/dist/mcp/tools/validate-rules.js +28 -0
  64. package/dist/utils/config.js +117 -0
  65. package/dist/utils/errors.js +9 -0
  66. package/dist/utils/logger.js +19 -0
  67. package/dist/utils/pace.js +19 -0
  68. package/dist/utils/text.js +22 -0
  69. package/dist/utils/tokens.js +14 -0
  70. package/package.json +69 -4
package/bin/cli.js ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import '../dist/cli/index.js';
@@ -0,0 +1,136 @@
1
+ {
2
+ "version": 2,
3
+ "tsconfig": "e902c20d6ddc0f7582ac8ff3ca99b4ef1b645c907612e07b52d0c8736c60bffe",
4
+ "sources": {
5
+ "src/cli/commands/check.ts": "f62b08d9e697dd0a3df95f58cbadcfffa946f977854ccdc9af24fa565560fff5",
6
+ "src/cli/commands/doctor.ts": "c865deb5b3c16903219176926517ec0a8fa53489453dfe492bf7249c13357f16",
7
+ "src/cli/commands/find.ts": "83fd66ec190dd758b4bf2e3802cdc0341e891e2a76579c4a9a4555a887814823",
8
+ "src/cli/commands/init-files.ts": "1d99c3c4ad1bbf9903158138957b4a675f9151146a54db09cfd011e3c95c3b41",
9
+ "src/cli/commands/init.ts": "7fd7a4e0bc597ebcb60594b14fc7d511526b0c66c3b7f3a648d42e40130e8e56",
10
+ "src/cli/commands/optimize.ts": "55e0a5bcfe9436ccfecd81fa840a1c32b71ad6a605b025ed9dfda5f76600d77e",
11
+ "src/cli/commands/scan.ts": "bd2309efaf8bbf47a63f60418ce183c4df7cc4d168681857b227995d561a5818",
12
+ "src/cli/index.ts": "d9560503817235cce4d5e6f3d3de98395d3df5edfadad7b1625983d879917b86",
13
+ "src/cli/output.ts": "7232fd101a75677355f478958651fb0a35ae4f068049b11857fe8d55af9a65e1",
14
+ "src/context.ts": "003d06254f88464e96f59111665b1d8e370f2cd03967cb51288403e144444b38",
15
+ "src/core/ast/analysis.ts": "470dbea4000e7af91d2b55571b4f1ed6e2a0cc4276c67b4a9f99c501f961ddb3",
16
+ "src/core/ast/cached-info.ts": "debae96fa29c39f43100f6c0f8f0ef9be0782557140971a2710781d7b3513103",
17
+ "src/core/ast/discovery.ts": "648c3a8e45491d3ea9e0a16eae5e14a962e995f1a9042bc05d80d22e61823861",
18
+ "src/core/ast/extract-js.ts": "cd566df143e4ca5d42b83b8f3826032f94b947f9038232f96b7adec84915c4a2",
19
+ "src/core/ast/extract-py.ts": "74bc15949cb8e77c58f4facd5dbc792e15297ad0d611db37596a202a03ff3579",
20
+ "src/core/ast/graph.ts": "ff81fe47f391c363400d4e4516f417eeafeebb5f623a9d3995dc16cbb6ce284d",
21
+ "src/core/ast/health.ts": "5ae91dcd88f2f30935cb908884708b2e393d07e54bafd9989833715ceb856b51",
22
+ "src/core/ast/indexer.ts": "aa1876d968f04073b3fb751b291958f37132aafe6f6ceecfb37defd2b24fc490",
23
+ "src/core/ast/packages.ts": "874f15abb89aae8ce93864f87beb42d1ead886e1f9330145f5f4e00ad11b5c19",
24
+ "src/core/ast/parser.ts": "05d08b58abb51894d73e1620bc15db7167c5805c30ce12569dbfe833399e431e",
25
+ "src/core/ast/report.ts": "5eb5cc8bc0048bb28fc2e2dfe2295a08e33ecfc366098b8a463a0458f6714777",
26
+ "src/core/ast/resolver.ts": "6ba97974ce981c4f13d36639da61a97a7eb5b213de321fa9ebea608ac281e842",
27
+ "src/core/ast/rules.ts": "ff99f0d582544bac8fbbc00274151d0c0fc3a0c919430abe5d8bef15bed0419f",
28
+ "src/core/ast/scope-js.ts": "a461d3a7c1a854612e3651e1015b042afdb9d8e2b51d465936e914b525bf865a",
29
+ "src/core/ast/shared-index.ts": "23d5f77d60c49f7a71842395769b50a0aaec349bc89d46b836e8e2634ed8481f",
30
+ "src/core/ast/tsconfig.ts": "cfd0f379fd9ec00d303705ac6b597d2516fa13d80b7ee69d35687dc02d8cc20c",
31
+ "src/core/ast/types.ts": "fb027bffa4c0969ade4ca880e106c9f31e221f3e60a4e0417f865c3f4dd7bc3f",
32
+ "src/core/ast/util.ts": "ab1a7cb1111c86ae813994fad390ef76401a414e274ebf169314611eb506d2e8",
33
+ "src/core/git/git.ts": "87e2aded00ab3e73ffe0d34f4ea9923452ab797336422c32fefb089cdfcf902c",
34
+ "src/core/llm/policy.ts": "4f69e7e73778fe642ffbfb36a671f42e801dca15c050a6a354e9d6d2495c3dbc",
35
+ "src/core/llm/provider.ts": "f975507f0d42c7275d5258ab20ab4e0bd2ce60377b967c4642908a47275546db",
36
+ "src/core/prompt/compressor.ts": "f5a6f1b8a8139e2092c8fc6c6f64647469f1532b41f0f6979aaab33d6398fd5f",
37
+ "src/core/prompt/criteria.ts": "c71bb07fb620824043c12a1175fd6445bd5dc0610b1d5ad651b93ddab9ad98f9",
38
+ "src/core/prompt/find.ts": "1ca9a60f32fe19b82a378819040ca4789a486b617df1d97397fa7d9cbe71e734",
39
+ "src/core/prompt/guidelines.ts": "46a4e51dfaa531cde5ee103a08a50979658cea540fc964f600d2c43b1d85a74c",
40
+ "src/core/prompt/model-output.ts": "8958a4cfbe46262f9c42e62e43616a8a5d80359bbdc1a09192a58a36572cfabd",
41
+ "src/core/prompt/refiner.ts": "261fcf503a69b0a78b7347a0d61f586a867b782ce55fa098a874212bd93db44c",
42
+ "src/core/prompt/relevance.ts": "4fe0a65a4ffc1c6a39a935cc5ca55009c01e0fde0bfba56c72158951b6104308",
43
+ "src/core/prompt/untrusted.ts": "9ff20292fb07cc9345ced489f6d4288f16357e6996de0ec15149a1c2c82d0444",
44
+ "src/core/security/masker.ts": "4e732f97d5b3b1c03e35507238f62921740a3459e862fcbadc1208298a8e482e",
45
+ "src/core/security/outbound.ts": "86b1f5943c9ad7ff1351536492f3aa30751dbefcbd300b31874e7619ceb8b671",
46
+ "src/core/security/safe-file.ts": "2147226806ca7e6a11fb74adbb4e086e7fd5738d88c6a55ee86fc94abf9fd9b9",
47
+ "src/core/security/sandbox.ts": "ad372fc22e3a43a0ae3d35975a5abeea03318a3b9d7313fbafc4d48b78bf8998",
48
+ "src/core/validation/baseline.ts": "0b18ba067c33d849208f4689fe9dcb285ca80d3c4a17930f30263a9e5f6e2b02",
49
+ "src/core/validation/delta.ts": "aeb6c05084ce03f5f36a970082982e858b7e1e1ff3adead82b1e50481d6736e0",
50
+ "src/core/validation/policy.ts": "dc1d1a9edf1e8c397532f1f0984c9472351d3fc89750a701e7c214483d7198d8",
51
+ "src/db/cache-key.ts": "49599415ff4ef0cc1067d69cc90d03f8dc2164780bec11e35c4f311778af2ab3",
52
+ "src/db/client.ts": "bc98dae6710ca08b278d035d604bad25dc51f0acb2ce80fa49a65ef1e255b633",
53
+ "src/db/schema-check.ts": "51b91374c8bd08a6874fb2a08c4b6cb44285aa916b4cef96fab39ba7adb9ee92",
54
+ "src/db/schema.ts": "acc3059acede1df88ea951779986837c39d2dc0925622e439e4a14d013680f40",
55
+ "src/db/windows-acl.ts": "adb027f382055e1425571a004eb887237f6bc2e23434e871968199dea3a016cd",
56
+ "src/index.ts": "ca417dd062bf5e1aa5ca2139b261c443c7e5ac5c3e744b18ae868a4ab23d3fd3",
57
+ "src/mcp/server.ts": "50e9c3246e6ff788588141a7b19b78f1d6bbc688c782e2b37e6120cea957d761",
58
+ "src/mcp/tools/find-reusable.ts": "ce11f81306a8aa621876dd0046348bea74903fde2328c87cd34629aac246e989",
59
+ "src/mcp/tools/get-context.ts": "4cecb27a039c688c8864911a71d2a02255dd60ad319613b41bfa0caae2e443fb",
60
+ "src/mcp/tools/optimize-prompt.ts": "ab54c659603365d38ad0b0078fe19f5d88b7200fed1279cce986a63142f9a162",
61
+ "src/mcp/tools/result.ts": "a1f838b79fc8753305d0f8c00773a50c4063d8a4809023f14da8b522a4d37a6c",
62
+ "src/mcp/tools/validate-rules.ts": "026bdea2fe179f90d81f7fc86cc82df40c2c1a62ce6da103aaa7b73c293498ce",
63
+ "src/utils/config.ts": "12faea26935ee33d70773190d57ec79c69bf63f72ed83292e3995a66cbac52db",
64
+ "src/utils/errors.ts": "add451a13e2cba9bd2898cc21ca5bef1863bacfb9634dc1705f93d81d20a9463",
65
+ "src/utils/logger.ts": "75cd9e99f569a6ead6cd24d5f1cb505a62557c60ca10981d961c617e09012426",
66
+ "src/utils/pace.ts": "1048d247debb0fc26860cc548bfe8baacc18165f6955812ad9b2bce696203405",
67
+ "src/utils/text.ts": "50c667f616100a91566c0f2121af72aeb913ecf316bc5831f1363b080dcac469",
68
+ "src/utils/tokens.ts": "c45214edab417514c4aa9a62467ff9b5d24305803bf1b19088f450e2dd520528"
69
+ },
70
+ "outputs": {
71
+ "dist/cli/commands/check.js": "ca5a58c84f6ae7dabba93800abca6f57965f2466156f24b6a831f2551f4ad569",
72
+ "dist/cli/commands/doctor.js": "d224811a7f6bbf4f72644331f1f9daf6656a0ccdbed4174577049f6225f1885b",
73
+ "dist/cli/commands/find.js": "752ff8b3debcc4f3906db038382883db8cddaba827b87e2ce79200fe9cdf5a6d",
74
+ "dist/cli/commands/init-files.js": "1d71ba38e42315c690f449d9bb8b5bd34b462f1d167e97eeb73461594f788251",
75
+ "dist/cli/commands/init.js": "99b576771951895bde3bc75b767cc9fdc31800890b77bc7d2edc02e608970c39",
76
+ "dist/cli/commands/optimize.js": "70e289c46e93dfae1a0f725c4427aa5c7ab9c62e03b80011934e5e66e13d8a5d",
77
+ "dist/cli/commands/scan.js": "a425a34299fe42adf0cbbc8be2dafec642a7f475095109ff383368228edae294",
78
+ "dist/cli/index.js": "41cdc0231416e27013c06b8237c156e920b101ef0a9723620fa1c7ed5843311b",
79
+ "dist/cli/output.js": "b464676e8b4f8c27c46d2b4b08fa9875285f61ce2b39f40677ae52579c4f7644",
80
+ "dist/context.js": "42b91275cdc473683f3adcf6604a1c059c24ac38d4305a898f11fcb0d234ab54",
81
+ "dist/core/ast/analysis.js": "533deb380ae6427f5ea2edf7d6bf6e41a8384e1a40b41b78c783a7ceed86bfc0",
82
+ "dist/core/ast/cached-info.js": "13c03044ece314fbfea9c11d62d1c5b3a46906aa4c1ee5b6bf7d81509d0f8f39",
83
+ "dist/core/ast/discovery.js": "fba2a83715eadec1b47cc7e4270dfdcbfe77fc0a4b911763e08be507695f1224",
84
+ "dist/core/ast/extract-js.js": "596a2655d40e7962ed55837fe01d16bd84659884a8272852b1dbdec979acd86e",
85
+ "dist/core/ast/extract-py.js": "fe6d847bb1c70715f709be5424c29ecc833a03b81bbd9fd1e8c1572788e40ded",
86
+ "dist/core/ast/graph.js": "4fe63915119d627b20a9858fc771a610d17df19655dd9f9375f74d299f1b07f2",
87
+ "dist/core/ast/health.js": "af579e860f18c623d516154c27a6514ff2d143e6f42bae2c2e0b0af0f9612e8b",
88
+ "dist/core/ast/indexer.js": "0091d931b7d79f38148c138fff1a71297d5d55c780df283cf887b12a7fc9a4fd",
89
+ "dist/core/ast/packages.js": "c4a66951199c6ef8d4685c5e663098abb3625a1dd2c6748a4fe04d690b9249ff",
90
+ "dist/core/ast/parser.js": "da54f7daac274b3374db7efa74780b9e45a6a8fbb4ddfd987ebe1ede47ee555c",
91
+ "dist/core/ast/report.js": "5a3c10ebae11c13be04f0eef5401b031a426aa22eba7664b48a430726e005c1f",
92
+ "dist/core/ast/resolver.js": "04a31bf94435929c0c21bb40931a5c96c523b0f5077d2c824446330a13498199",
93
+ "dist/core/ast/rules.js": "93cde1273ef272635ab3b010b4ef86ce74bd6a8d55307ec4a8423feb09514bd3",
94
+ "dist/core/ast/scope-js.js": "b4eec746e6772479da66f6f653534f2b4401ccfd85560a2c62e22b66ea000e8a",
95
+ "dist/core/ast/shared-index.js": "f710bbaa8b3394054ae9a9d189d0218c23bb496a9aaf680058073737136045bd",
96
+ "dist/core/ast/tsconfig.js": "e2da641dafdd9429abd6bc89f7a4bb1d2229cc2a2ec7d8a7a2d5cb06c5b9e979",
97
+ "dist/core/ast/types.js": "8e609bb71c20b858c77f0e9f90bb1319db8477b13f9f965f1a1e18524bf50881",
98
+ "dist/core/ast/util.js": "cdc348344a15b4b63e1792d99a49cbb09ab9530cc55fdf342f468dfbc57735bf",
99
+ "dist/core/git/git.js": "c64a14de280b9516224d28a284a64bfdd1721742900607f24d4c8925ff3065e0",
100
+ "dist/core/llm/policy.js": "57bf521f34719439821d8748eb3226c6a8767c7410334b01a0baa88625948787",
101
+ "dist/core/llm/provider.js": "6f51d52491b6ceb0ea08a155eecf1f2a74354e5d5470974fcd53e8a0e9e85c9c",
102
+ "dist/core/prompt/compressor.js": "1120705dee04e1741ef8045d10ecd2db737c19aca3627d4d33893110ca1b9ffe",
103
+ "dist/core/prompt/criteria.js": "fd7bc490b3e0f604fd19ca5f35277dbe92ee94ac90b6516e1e0a99a7574b89b4",
104
+ "dist/core/prompt/find.js": "762f0b00d5e4a1bc26fbb3816a743679619c5964d0bfef67c9f4427d9621d0d9",
105
+ "dist/core/prompt/guidelines.js": "66561994a162b4f373a17e432c46e30d5c45c05310c9edd422c83092b1e3ea3b",
106
+ "dist/core/prompt/model-output.js": "77413c49843cef282ba031fd6c45fe1a27bbe88194fe0d8c5a74958e99ca12b2",
107
+ "dist/core/prompt/refiner.js": "2ac4a93d8b2d8d2ff37ec807928ba1846f9eb8bdce1a352820dfda7068c2b085",
108
+ "dist/core/prompt/relevance.js": "4895609905a1517d7f81fd20a841b354df0143d77dbea4ad46d8272ed4a9fc79",
109
+ "dist/core/prompt/untrusted.js": "9cfd10000e751cc36fae2fa6446bc00cc1acc77b56fd4e09f090af170c5706d1",
110
+ "dist/core/security/masker.js": "3c28845e28ae4417997826d46d7394b6ec5b1ac47eb66a1124432b725e9e8e4d",
111
+ "dist/core/security/outbound.js": "802d34e8b85203094fb7ef8193a4572712ce7c2ef2f9a3b02631efe79157d83a",
112
+ "dist/core/security/safe-file.js": "e4c2dc078d469745e937b01a7cf8ec1e09274c9717634c7a7bf73baf39aa1df5",
113
+ "dist/core/security/sandbox.js": "ea7beb73e525e64710c29cc065493ee55ace2f77ecc1e8f6a01911bc91f32f6a",
114
+ "dist/core/validation/baseline.js": "9796bdee4708eba078aa5615e706826d51dc3ffb816650d8131164c79c26156e",
115
+ "dist/core/validation/delta.js": "eb4294dcf85bf21df36985342f31a31c87cb1af27f885b0f7b27638f0c34ef9c",
116
+ "dist/core/validation/policy.js": "38c036cabdb8b02f595c6cbfbbf8178760e2c11c653c6ae1702df4f8e59a7ace",
117
+ "dist/db/cache-key.js": "1d8b72a07f300adfa24aca89d198eb3a63f54e3b58011d44b10f535b3b192bd0",
118
+ "dist/db/client.js": "715476c4a77caae7bc272a2846e3daf4ff42327cdab04f80857e8012cb540067",
119
+ "dist/db/schema-check.js": "036c8276c4a308bb959246e5467d678300fd090afe6469ca4082404c50cc69f6",
120
+ "dist/db/schema.js": "1c3cfec35f214a586961e23508c039679c4800e1131c1ca20b5be23038c80a99",
121
+ "dist/db/windows-acl.js": "fc2a590e965393a428c109746da7dadd9d32be70091280db4dff2ac85a8bd4e0",
122
+ "dist/index.js": "016dd09ecc2c1c35b6aa72218d2ad7bc5cff308585acd998f0b7d13dfe405bae",
123
+ "dist/mcp/server.js": "4415fb6405dcd56c5856a4a434886cd4d68684ddab39fd9960d8073349437127",
124
+ "dist/mcp/tools/find-reusable.js": "ef430eff772a86a39eb3b8dc99397377d56c7ea62f6c79b8a53d37b92bd025d9",
125
+ "dist/mcp/tools/get-context.js": "2f9dda568a3bbcbc0cb346ea147ebf9594b7f40a5138012c9819d6a4091e9f3f",
126
+ "dist/mcp/tools/optimize-prompt.js": "0a2a13391cb7c8cf659a6cccbf526b7082d5530976951e0fac5494865954d67d",
127
+ "dist/mcp/tools/result.js": "32f74f14dcc7a5b8b8c64b9461dc2569dd6336bdd737a15bc6e3261d87aadc29",
128
+ "dist/mcp/tools/validate-rules.js": "414e236e3d2471a4fdc7ca5a357a8c28f230d614d83813a3cf65f2d469018e14",
129
+ "dist/utils/config.js": "099def080993b312a19701ddf61f311bab6f26ea558dd2e4227a1baf3606da09",
130
+ "dist/utils/errors.js": "b7f58da21a12ddbf13d28691c696f33080d5d3f3eb7ba26e54c2f7293e9723e1",
131
+ "dist/utils/logger.js": "38198f3d83bfad5381c6a62d0ce5f8ef40ef3ccd460aad67bb0180d2abbfe598",
132
+ "dist/utils/pace.js": "302474e8af17ff62336e2bb0be73829282c7ba7e93a9dd01cfe009f798f47fc5",
133
+ "dist/utils/text.js": "2b858e099e7d10abab36ab57acc2ffd703654d3762015ea07addee2683f0e747",
134
+ "dist/utils/tokens.js": "92a3b7f6e23eb0d37b68abf0e76b751b8f604be2a197adff5c96dde9e9f1a970"
135
+ }
136
+ }
@@ -0,0 +1,56 @@
1
+ import { createContext } from '../../context.js';
2
+ import { err as printError, out } from '../output.js';
3
+ import { indexProject } from '../../core/ast/indexer.js';
4
+ import { describeCoverage, renderValidation } from '../../core/ast/report.js';
5
+ import { validateProject } from '../../core/validation/delta.js';
6
+ import { closeDb } from '../../db/client.js';
7
+ const RANK = { high: 0, medium: 1, low: 2 };
8
+ // What to do when the change weakens the project's own analysis configuration (rules off or lowered, ignore patterns,
9
+ // exceptions, entry points, files no longer analysed):
10
+ // warn report it prominently; the exit code is not affected (default, the historical behaviour)
11
+ // fail exit 1
12
+ // approve the caller accepts the weakening explicitly: it is still reported, and the exit code is not affected
13
+ // The choice is made by whoever runs the command (a CI job), never by a file in the repository being checked.
14
+ export const CONFIG_POLICIES = ['warn', 'fail', 'approve'];
15
+ // Exit code 1 means the check failed one of the requested conditions; 0 means none was triggered. Usage and runtime
16
+ // errors exit 2 (see src/cli/index.ts). Without --fail-on, --fail-on-partial and --config-policy fail, the exit code is
17
+ // 0 whatever was found, as before.
18
+ export async function check(opts) {
19
+ if (opts.failOn && !(opts.failOn in RANK))
20
+ throw new Error('--fail-on must be high, medium or low');
21
+ const policy = (opts.configPolicy ?? 'warn');
22
+ if (!CONFIG_POLICIES.includes(policy))
23
+ throw new Error('--config-policy must be warn, fail or approve');
24
+ const ctx = createContext(opts.root);
25
+ try {
26
+ const project = await indexProject(ctx);
27
+ const { validation } = await validateProject(ctx, project, { base: opts.base });
28
+ const failures = [];
29
+ const limit = opts.failOn;
30
+ if (limit && validation.introduced.some((f) => RANK[f.severity] <= RANK[limit]))
31
+ failures.push(`a new finding is at least ${limit} severity (--fail-on ${limit})`);
32
+ if (opts.failOnPartial && validation.partial)
33
+ failures.push('the validation is partial, so it cannot be treated as a definitive pass (--fail-on-partial)');
34
+ if (policy === 'fail' && validation.configDowngrades.length > 0)
35
+ failures.push('the change weakens the analysis configuration (--config-policy fail)');
36
+ if (opts.json) {
37
+ out(JSON.stringify({ complete: project.complete, configProblems: project.configProblems, ...validation, configPolicy: policy, failures }, null, 2));
38
+ }
39
+ else {
40
+ out(renderValidation(validation, { includeExisting: opts.all }));
41
+ if (!project.complete)
42
+ out(`\n${describeCoverage(project, ctx.config.maxFiles)}`);
43
+ if (policy === 'approve' && validation.configDowngrades.length > 0)
44
+ out('\nThe configuration downgrade above was approved with --config-policy approve.');
45
+ out(`\nValidation: ${validation.partial ? 'PARTIAL (provisional, see the reasons above)' : 'COMPLETE'}.`);
46
+ }
47
+ // The reasons go to stderr so that --json output stays machine-readable.
48
+ for (const reason of failures)
49
+ printError(`Check failed: ${reason}.`);
50
+ if (failures.length > 0)
51
+ process.exitCode = 1;
52
+ }
53
+ finally {
54
+ closeDb(ctx.db);
55
+ }
56
+ }
@@ -0,0 +1,55 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { out } from '../output.js';
3
+ import os from 'node:os';
4
+ import { promisify } from 'node:util';
5
+ import { resolvePolicy, describePolicy } from '../../core/llm/policy.js';
6
+ import { loadEnv } from '../../utils/config.js';
7
+ import { errorMessage } from '../../utils/errors.js';
8
+ const run = promisify(execFile);
9
+ async function sqlite() {
10
+ const { default: Database } = await import('better-sqlite3');
11
+ const db = new Database(':memory:');
12
+ try {
13
+ return `SQLite ${db.prepare('select sqlite_version() as v').get().v}`;
14
+ }
15
+ finally {
16
+ db.close();
17
+ }
18
+ }
19
+ async function treeSitter() {
20
+ const { loadLanguages, parseFile } = await import('../../core/ast/parser.js');
21
+ await loadLanguages(['typescript', 'tsx', 'javascript', 'python']);
22
+ const info = parseFile('probe.ts', 'typescript', 'export const probe = 1;\n');
23
+ if (!info || info.symbols.length !== 1)
24
+ throw new Error('parser returned no symbols');
25
+ return 'grammars load and parse';
26
+ }
27
+ async function git() {
28
+ const { stdout } = await run('git', ['--version']);
29
+ return stdout.trim();
30
+ }
31
+ async function attempt(name, required, work) {
32
+ try {
33
+ return { name, ok: true, detail: await work(), required };
34
+ }
35
+ catch (err) {
36
+ return { name, ok: false, detail: errorMessage(err), required };
37
+ }
38
+ }
39
+ export async function doctor() {
40
+ loadEnv();
41
+ const major = Number(process.versions.node.split('.')[0]);
42
+ const checks = [
43
+ { name: 'Node.js', ok: major >= 22, detail: `${process.version} on ${os.platform()}-${os.arch()}${major >= 22 ? '' : ' (22 or newer is required)'}`, required: true },
44
+ await attempt('better-sqlite3', true, sqlite),
45
+ await attempt('tree-sitter', true, treeSitter),
46
+ await attempt('git', false, git),
47
+ ];
48
+ for (const c of checks)
49
+ out(`${c.ok ? 'ok ' : c.required ? 'FAIL' : 'warn'} ${c.name}: ${c.detail}`);
50
+ out(`\n${describePolicy(resolvePolicy({ llm: true }))}`);
51
+ if (checks.some((c) => c.required && !c.ok))
52
+ process.exitCode = 1;
53
+ else if (!checks[3].ok)
54
+ out('git is missing: validate_rules and check will fall back to scanning the whole workspace.');
55
+ }
@@ -0,0 +1,31 @@
1
+ import { createContext } from '../../context.js';
2
+ import { analyzeProject } from '../../core/ast/analysis.js';
3
+ import { indexProject } from '../../core/ast/indexer.js';
4
+ import { describeCoverage } from '../../core/ast/report.js';
5
+ import { findReusable, renderFind } from '../../core/prompt/find.js';
6
+ import { closeDb } from '../../db/client.js';
7
+ import { InputError } from '../../utils/errors.js';
8
+ import { out } from '../output.js';
9
+ export async function find(query, opts) {
10
+ if (!query.trim())
11
+ throw new InputError('Describe what you are looking for, e.g. guardian find "format a date"');
12
+ const limit = opts.limit === undefined ? 8 : Number(opts.limit);
13
+ if (!Number.isInteger(limit) || limit < 1 || limit > 50)
14
+ throw new InputError('--limit must be a whole number from 1 to 50');
15
+ const ctx = createContext(opts.root);
16
+ try {
17
+ const project = await indexProject(ctx);
18
+ const { graph } = analyzeProject(project, ctx.config);
19
+ const result = findReusable(project, graph, query, limit);
20
+ if (opts.json) {
21
+ out(JSON.stringify({ complete: project.complete, configProblems: project.configProblems, ...result }, null, 2));
22
+ return;
23
+ }
24
+ out(renderFind(result));
25
+ if (!project.complete)
26
+ out(`\n${describeCoverage(project, ctx.config.maxFiles)}`);
27
+ }
28
+ finally {
29
+ closeDb(ctx.db);
30
+ }
31
+ }
@@ -0,0 +1,13 @@
1
+ import { appendToRegularFile, createFileExclusive } from '../../core/security/safe-file.js';
2
+ const MAX_GITIGNORE_BYTES = 1024 * 1024;
3
+ const GUARDIAN_ENTRY = /^\/?\.guardian\/?$/m;
4
+ // Both writers refuse symlinks and non-regular files (UnsafeFileError) and never modify anything outside `root`.
5
+ export function ensureGitignore(root) {
6
+ if (createFileExclusive(root, '.gitignore', '.guardian/\n'))
7
+ return;
8
+ appendToRegularFile(root, '.gitignore', MAX_GITIGNORE_BYTES, (current) => GUARDIAN_ENTRY.test(current) ? null : `${current && !current.endsWith('\n') ? '\n' : ''}.guardian/\n`);
9
+ }
10
+ // An existing config is never rewritten.
11
+ export function ensureConfig(root, fileName) {
12
+ createFileExclusive(root, fileName, `${JSON.stringify({ ignore: [], llm: true }, null, 2)}\n`);
13
+ }
@@ -0,0 +1,50 @@
1
+ import { out, err as err_ } from '../output.js';
2
+ import path from 'node:path';
3
+ import { prepareStateDir } from '../../db/client.js';
4
+ import { UnsafeFileError } from '../../core/security/safe-file.js';
5
+ import { resolveWorkspaceRoot } from '../../core/security/sandbox.js';
6
+ import { configFileName, loadEnv, packageRoot } from '../../utils/config.js';
7
+ import { describePolicy, resolvePolicy } from '../../core/llm/policy.js';
8
+ import { loadConfig } from '../../utils/config.js';
9
+ import { errorCode, errorMessage } from '../../utils/errors.js';
10
+ import { ensureConfig, ensureGitignore } from './init-files.js';
11
+ const NUDGE = 'Before writing or changing code, call the GuardStack AI tool optimize_prompt with the task and follow its "Reuse existing code" list. ' +
12
+ 'After making changes, call validate_rules and fix what it reports.';
13
+ function attempt(label, work) {
14
+ try {
15
+ work();
16
+ return true;
17
+ }
18
+ catch (err) {
19
+ if (err instanceof UnsafeFileError) {
20
+ // A link or special file where a plain file belongs: report it, leave it untouched and fail the command.
21
+ err_(`Refusing to ${label}: ${err.message}. The file was left untouched; remove it or replace it with a regular file.`);
22
+ process.exitCode = 2;
23
+ return false;
24
+ }
25
+ err_(`Could not ${label}: ${errorCode(err) ?? errorMessage(err)}`);
26
+ return false;
27
+ }
28
+ }
29
+ export function init(rootArg) {
30
+ loadEnv();
31
+ const root = resolveWorkspaceRoot(rootArg ?? process.env.GUARDIAN_ROOT ?? process.cwd());
32
+ out(`Workspace: ${root}`);
33
+ const cacheReady = prepareStateDir(root) !== null;
34
+ out(`Cache: ${cacheReady ? '.guardian/ ready' : 'unavailable, an in-memory cache will be used'}`);
35
+ if (attempt(`create ${configFileName}`, () => ensureConfig(root, configFileName)))
36
+ out(`Config: ${configFileName} ready`);
37
+ attempt('update .gitignore', () => ensureGitignore(root));
38
+ out(`Gemini key: ${process.env.GEMINI_API_KEY ? 'set' : 'not set'}`);
39
+ out(`Groq key: ${process.env.GROQ_API_KEY ? 'set' : 'not set'}`);
40
+ out(`\nPrivacy: ${describePolicy(resolvePolicy(loadConfig(root)))}`);
41
+ out(' To allow the optional external step, set GUARDIAN_LLM=on and add a key. Run "guardian optimize --dry-run" to see exactly what would be sent.');
42
+ const cli = path.join(packageRoot, 'bin', 'cli.js');
43
+ const mcpConfig = { mcpServers: { codeguardian: { command: 'node', args: [cli, 'serve', '--root', root] } } };
44
+ out('\nClaude Code:');
45
+ out(` claude mcp add codeguardian -- node ${cli} serve`);
46
+ out('\nClaude Desktop / Cursor (add to the MCP servers config):');
47
+ out(JSON.stringify(mcpConfig, null, 2));
48
+ out('\nAdd this to CLAUDE.md or .cursorrules so the assistant actually calls the tools:');
49
+ out(` ${NUDGE}`);
50
+ }
@@ -0,0 +1,53 @@
1
+ import { createContext } from '../../context.js';
2
+ import { out, err } from '../output.js';
3
+ import { analyzeProject } from '../../core/ast/analysis.js';
4
+ import { indexProject } from '../../core/ast/indexer.js';
5
+ import { resolvePolicy } from '../../core/llm/policy.js';
6
+ import { describeLlm, refinePrompt } from '../../core/prompt/refiner.js';
7
+ import { closeDb } from '../../db/client.js';
8
+ import { describeTokens } from '../../utils/tokens.js';
9
+ const MAX_STDIN_BYTES = 64 * 1024;
10
+ async function readStdin() {
11
+ const chunks = [];
12
+ let size = 0;
13
+ for await (const chunk of process.stdin) {
14
+ size += chunk.length;
15
+ if (size > MAX_STDIN_BYTES)
16
+ throw new Error('Prompt on stdin is too large');
17
+ chunks.push(chunk);
18
+ }
19
+ return Buffer.concat(chunks).toString('utf8');
20
+ }
21
+ export async function optimize(promptArg, opts) {
22
+ if (!promptArg && process.stdin.isTTY)
23
+ throw new Error('Pass the prompt as an argument or pipe it on stdin');
24
+ const prompt = (promptArg ?? (await readStdin())).trim();
25
+ if (!prompt)
26
+ throw new Error('The prompt is empty');
27
+ const ctx = createContext(opts.root);
28
+ try {
29
+ const project = await indexProject(ctx);
30
+ const { graph } = analyzeProject(project, ctx.config);
31
+ const policy = resolvePolicy(ctx.config, { disabled: !opts.llm });
32
+ const refined = await refinePrompt(ctx, project, graph, prompt, policy, { dryRun: opts.dryRun });
33
+ if (opts.dryRun) {
34
+ if (refined.payload) {
35
+ out('--- system ---\n' + refined.payload.system + '\n--- message (secrets already masked) ---\n' + refined.payload.prompt);
36
+ err(`\n${refined.dryRunRedactions} secret(s) were redacted from this payload.`);
37
+ }
38
+ else {
39
+ out('Nothing would be sent: fully local mode.');
40
+ }
41
+ err(describeLlm(refined));
42
+ return;
43
+ }
44
+ out(refined.text);
45
+ err(`\n${describeTokens({ sent: refined.sentTokens, baseline: refined.baselineTokens, baselineFiles: refined.baselineFiles, truncated: false })}`);
46
+ err(describeLlm(refined));
47
+ if (refined.redactions > 0)
48
+ err(`${refined.redactions} secret(s) were redacted.`);
49
+ }
50
+ finally {
51
+ closeDb(ctx.db);
52
+ }
53
+ }
@@ -0,0 +1,47 @@
1
+ import { createContext } from '../../context.js';
2
+ import { out } from '../output.js';
3
+ import { analyzeProject } from '../../core/ast/analysis.js';
4
+ import { indexProject } from '../../core/ast/indexer.js';
5
+ import { describeCoverage, renderFindings } from '../../core/ast/report.js';
6
+ import { closeDb, lifetimeUsage } from '../../db/client.js';
7
+ export async function scan(opts) {
8
+ const ctx = createContext(opts.root);
9
+ try {
10
+ const project = await indexProject(ctx);
11
+ const { graph, findings, cycles, unresolved, unsupported } = analyzeProject(project, ctx.config);
12
+ if (opts.json) {
13
+ const report = {
14
+ complete: project.complete,
15
+ configProblems: project.configProblems,
16
+ files: project.files.length,
17
+ eligible: project.eligible,
18
+ truncated: project.truncated,
19
+ skipped: project.skipped,
20
+ parseIssues: project.parseIssues,
21
+ stopped: project.stopped ?? null,
22
+ unindexed: project.unindexed,
23
+ graph,
24
+ cycles,
25
+ unresolved,
26
+ unsupported,
27
+ findings,
28
+ };
29
+ out(JSON.stringify(report, null, 2));
30
+ return;
31
+ }
32
+ const exported = project.files.reduce((n, f) => n + f.symbols.filter((s) => s.exportName).length, 0);
33
+ out(`Scanned ${project.files.length} files, ${exported} exported symbols, ${graph.links.length} import links, ${cycles.length} cycle(s).`);
34
+ out(describeCoverage(project, ctx.config.maxFiles));
35
+ out(`\n${renderFindings(findings, 15, opts.explain)}`);
36
+ if (unsupported.length > 0) {
37
+ out(`\n${unsupported.length} import(s) use aliases or built packages this tool cannot resolve (for example ${unsupported[0].spec}); they were not counted as broken. List them with scan --json.`);
38
+ }
39
+ const usage = lifetimeUsage(ctx.db);
40
+ if (usage.calls > 0) {
41
+ out(`\nEstimated tokens across ${usage.calls} tool calls: ~${usage.sent} sent vs ~${usage.raw} for reading the referenced files in full.`);
42
+ }
43
+ }
44
+ finally {
45
+ closeDb(ctx.db);
46
+ }
47
+ }
@@ -0,0 +1,62 @@
1
+ import { createRequire } from 'node:module';
2
+ import { Command } from 'commander';
3
+ import { maskSecrets } from '../core/security/masker.js';
4
+ const { version } = createRequire(import.meta.url)('../../package.json');
5
+ // Commands load lazily so that "guardian doctor" can still report when a native module fails to load.
6
+ const program = new Command()
7
+ .name('guardian')
8
+ .description('Keeps AI coding assistants inside your codebase\'s real structure')
9
+ .version(version)
10
+ .option('-r, --root <dir>', 'workspace root (default: current directory)');
11
+ const root = () => program.opts().root;
12
+ program
13
+ .command('init')
14
+ .description('set up the workspace and print MCP client config')
15
+ .action(async () => (await import('./commands/init.js')).init(root()));
16
+ program
17
+ .command('serve')
18
+ .description('start the MCP server on stdio')
19
+ .action(async () => (await import('../index.js')).startServer(root()));
20
+ program
21
+ .command('doctor')
22
+ .description('check that native modules, parsers and git work on this machine')
23
+ .action(async () => (await import('./commands/doctor.js')).doctor());
24
+ program
25
+ .command('scan')
26
+ .description('find duplicates, cycles, unused imports, orphan files, unused exports and suppressed checks')
27
+ .option('--json', 'print the full report with the dependency graph as JSON')
28
+ .option('--explain', 'show the evidence and a recommended action under each finding')
29
+ .action(async (opts) => (await import('./commands/scan.js')).scan({ root: root(), ...opts }));
30
+ program
31
+ .command('check')
32
+ .description('report only the problems introduced by your uncommitted git changes')
33
+ .option('--base <ref>', 'compare against this git ref instead of HEAD')
34
+ .option('--all', 'also list pre-existing findings')
35
+ .option('--json', 'print the result as JSON')
36
+ .option('--fail-on <severity>', 'exit with code 1 if a new finding is at least this severe (high, medium, low)')
37
+ .option('--fail-on-partial', 'exit with code 1 if the validation is partial (not every changed file or the base configuration could be compared)')
38
+ .option('--config-policy <policy>', 'when the change weakens the analysis configuration: warn (report, default), fail (exit 1) or approve (accept explicitly)')
39
+ .action(async (opts) => (await import('./commands/check.js')).check({ root: root(), ...opts }));
40
+ program
41
+ .command('find <query...>')
42
+ .description('look up existing code that could be reused for a task (local, no model)')
43
+ .option('--json', 'print the result as JSON')
44
+ .option('--limit <n>', 'maximum number of candidates (1-50, default 8)')
45
+ .action(async (query, opts) => (await import('./commands/find.js')).find(query.join(' '), { root: root(), ...opts }));
46
+ program
47
+ .command('optimize [prompt]')
48
+ .description('add codebase context to a prompt (reads stdin if no prompt is given)')
49
+ .option('--no-llm', 'do not contact any external model')
50
+ .option('--dry-run', 'print the exact payload that would be sent externally, then exit without sending')
51
+ .action(async (prompt, opts) => (await import('./commands/optimize.js')).optimize(prompt, { root: root(), llm: opts.llm, dryRun: opts.dryRun }));
52
+ // Exit codes, the same on every platform: 0 success, 1 the check failed a requested condition (check --fail-on, --fail-on-partial,
53
+ // --config-policy fail; doctor), 2 usage or runtime error.
54
+ const usageExit = (err) => process.exit(err.exitCode === 0 ? 0 : 2);
55
+ program.exitOverride(usageExit);
56
+ for (const command of program.commands)
57
+ command.exitOverride(usageExit);
58
+ program.parseAsync().catch((err) => {
59
+ const message = err instanceof Error ? err.message : String(err);
60
+ console.error(`Error: ${maskSecrets(message).text}`);
61
+ process.exit(2);
62
+ });
@@ -0,0 +1,4 @@
1
+ import { maskSecrets } from '../core/security/masker.js';
2
+ // Every line the CLI prints goes through here, so terminal output is masked exactly like JSON output and tool replies.
3
+ export const out = (text = '') => console.log(maskSecrets(text).text);
4
+ export const err = (text = '') => console.error(maskSecrets(text).text);
@@ -0,0 +1,11 @@
1
+ import { configureMasking } from './core/security/masker.js';
2
+ import { resolveWorkspaceRoot } from './core/security/sandbox.js';
3
+ import { openDb } from './db/client.js';
4
+ import { loadConfig, loadEnv } from './utils/config.js';
5
+ export function createContext(rootArg) {
6
+ loadEnv();
7
+ const root = resolveWorkspaceRoot(rootArg ?? process.env.GUARDIAN_ROOT ?? process.cwd());
8
+ const config = loadConfig(root);
9
+ configureMasking({ patterns: config.maskPatterns, literals: config.maskLiterals });
10
+ return { root, config, db: openDb(root) };
11
+ }