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
@@ -0,0 +1,117 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { z } from 'zod';
5
+ import { PROFILES, RULES } from '../core/ast/rules.js';
6
+ import { checkMaskPattern } from '../core/security/masker.js';
7
+ import { readOptionalInside } from '../core/security/sandbox.js';
8
+ import { log } from './logger.js';
9
+ export const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
10
+ export const configFileName = '.guardianrc';
11
+ // Trusted hard ceilings for the resource limits. .guardianrc comes from the repository being analysed, so it is untrusted input:
12
+ // it may lower a limit but can never raise it past these values, which live in the application and not in any workspace.
13
+ // A value above its ceiling is rejected like every other out-of-range setting (the whole file is refused, with the ceiling named).
14
+ // Every default is well below its ceiling, so a repository that sets nothing, or sets reasonable values, behaves as before.
15
+ export const RESOURCE_CEILINGS = Object.freeze({
16
+ maxFiles: 20_000,
17
+ maxFileKb: 1024,
18
+ // Lowered from 2,000,000: the entry count alone is not a memory limit (see maxDiscoveryMemoryMb). At 1,000,000 entries the smallest
19
+ // possible retained candidate (about 0.13 KB) still fits the memory ceiling, so the entry ceiling can be reached by an ordinary tree.
20
+ maxDiscoveryEntries: 1_000_000,
21
+ // Estimated memory discovery may hold (listing buffers, sort allowance, pending directories, candidates and result lists). When it
22
+ // would be exceeded, discovery stops and the scan is reported as PARTIAL with the reason 'memory-limit'.
23
+ maxDiscoveryMemoryMb: 256,
24
+ maxDiscoveryMs: 60_000,
25
+ maxIndexMs: 120_000,
26
+ });
27
+ const RESOURCE_DEFAULTS = { maxFiles: 5000, maxFileKb: 512, maxDiscoveryEntries: 500_000, maxDiscoveryMemoryMb: 128, maxDiscoveryMs: 20_000, maxIndexMs: 30_000 };
28
+ // The value a limit actually takes effect with. The schema already rejects anything out of range, but a Config can also be built
29
+ // without it (tests, embedding), so the indexer asks here instead of trusting the object: a value that is not a finite number falls
30
+ // back to the default, and one above the ceiling is cut to it. Values below the ceiling, including the negative deadlines the
31
+ // tests use to stop a scan at once, pass through unchanged.
32
+ export function effectiveLimit(config, name) {
33
+ const value = config[name];
34
+ if (typeof value !== 'number' || Number.isNaN(value))
35
+ return RESOURCE_DEFAULTS[name];
36
+ return Math.min(value, RESOURCE_CEILINGS[name]);
37
+ }
38
+ const schema = z.strictObject({
39
+ ignore: z.array(z.string().max(200)).max(100).default([]),
40
+ maxFiles: z.number().int().min(1).max(RESOURCE_CEILINGS.maxFiles).default(RESOURCE_DEFAULTS.maxFiles),
41
+ maxFileKb: z.number().int().min(1).max(RESOURCE_CEILINGS.maxFileKb).default(RESOURCE_DEFAULTS.maxFileKb),
42
+ // Resource limits for indexing. When one is hit the scan stops, says so, and is reported as partial; files already
43
+ // processed stay cached, so the next call continues from there.
44
+ // maxDiscoveryEntries caps the entries PROCESSED, in sorted order. It does not cap the entries READ: choosing the first N
45
+ // names of a directory in name order means reading that whole directory (the time limit bounds that), while memory is
46
+ // bounded separately, by what is retained. maxDiscoveryMs and maxIndexMs are cooperative: they are checked between units of
47
+ // work, so one file system call or one parse can overrun them (see README, "Resource limits").
48
+ maxDiscoveryEntries: z.number().int().min(100).max(RESOURCE_CEILINGS.maxDiscoveryEntries).default(RESOURCE_DEFAULTS.maxDiscoveryEntries),
49
+ maxDiscoveryMemoryMb: z.number().int().min(4).max(RESOURCE_CEILINGS.maxDiscoveryMemoryMb).default(RESOURCE_DEFAULTS.maxDiscoveryMemoryMb),
50
+ maxDiscoveryMs: z.number().int().min(100).max(RESOURCE_CEILINGS.maxDiscoveryMs).default(RESOURCE_DEFAULTS.maxDiscoveryMs),
51
+ maxIndexMs: z.number().int().min(100).max(RESOURCE_CEILINGS.maxIndexMs).default(RESOURCE_DEFAULTS.maxIndexMs),
52
+ contextTokens: z.number().int().min(500).max(32000).default(4000),
53
+ llm: z.boolean().default(true),
54
+ pythonRoots: z.array(z.string().max(200)).max(20).default(['', 'src']),
55
+ // Framework profile for entry points: 'auto' detects it from package.json dependencies, 'none' trusts only entryPoints.
56
+ profile: z.enum(PROFILES).default('auto'),
57
+ // Gitignore-style patterns for files loaded by something other than an import (plugins, routes, scripts, DI).
58
+ entryPoints: z.array(z.string().min(1).max(200)).max(100).default([]),
59
+ // Severity per rule, or 'off'.
60
+ rules: z.partialRecord(z.enum(RULES), z.enum(['off', 'low', 'medium', 'high'])).default({}),
61
+ // Project-specific exceptions: a finding of `rule` in files matching `path` (and mentioning `symbol`, if given) is not reported.
62
+ exceptions: z
63
+ .array(z.strictObject({ rule: z.enum(RULES), path: z.string().min(1).max(200), symbol: z.string().min(1).max(100).optional() }))
64
+ .max(200)
65
+ .default([]),
66
+ // Fail closed: refuse to send an external request whose content could not be verified as free of secrets.
67
+ strictOutbound: z.boolean().default(false),
68
+ maskPatterns: z
69
+ .array(z.strictObject({
70
+ name: z.string().regex(/^[\w-]{1,40}$/),
71
+ pattern: z.string().superRefine((value, ctx) => {
72
+ const problem = checkMaskPattern(value);
73
+ if (problem)
74
+ ctx.addIssue({ code: 'custom', message: `pattern ${problem}` });
75
+ }),
76
+ }))
77
+ .max(20)
78
+ .default([]),
79
+ maskLiterals: z.array(z.string().min(6).max(200)).max(50).default([]),
80
+ });
81
+ // Keys come from the tool's own .env, never from the workspace being analysed.
82
+ export function loadEnv() {
83
+ const file = process.env.GUARDIAN_ENV_FILE ?? path.join(packageRoot, '.env');
84
+ if (!fs.existsSync(file))
85
+ return;
86
+ try {
87
+ if (process.platform !== 'win32' && fs.statSync(file).mode & 0o077) {
88
+ log.warn(`${file} is readable by other users, run: chmod 600 "${file}"`);
89
+ }
90
+ process.loadEnvFile(file);
91
+ }
92
+ catch (err) {
93
+ log.warn(`Could not read ${file}: ${err instanceof Error ? err.message : err}`);
94
+ }
95
+ }
96
+ export function parseConfig(raw) {
97
+ const parsed = schema.safeParse(raw);
98
+ if (!parsed.success)
99
+ throw new Error(`Invalid ${configFileName}:\n${z.prettifyError(parsed.error)}`);
100
+ return parsed.data;
101
+ }
102
+ const MAX_CONFIG_BYTES = 64 * 1024;
103
+ export function parseConfigText(text) {
104
+ let raw;
105
+ try {
106
+ raw = JSON.parse(text);
107
+ }
108
+ catch {
109
+ throw new Error(`${configFileName} is not valid JSON`);
110
+ }
111
+ return parseConfig(raw);
112
+ }
113
+ // The workspace config goes through the same sandbox as every other workspace read.
114
+ export function loadConfig(root) {
115
+ const data = readOptionalInside(root, configFileName, MAX_CONFIG_BYTES, { rejectHardLinks: true });
116
+ return data === null ? parseConfig({}) : parseConfigText(data.toString('utf8'));
117
+ }
@@ -0,0 +1,9 @@
1
+ export class InputError extends Error {
2
+ code;
3
+ constructor(message, code = 'invalid_input') {
4
+ super(message);
5
+ this.code = code;
6
+ }
7
+ }
8
+ export const errorMessage = (err) => (err instanceof Error ? err.message : String(err));
9
+ export const errorCode = (err) => typeof err === 'object' && err !== null && 'code' in err ? String(err.code) : undefined;
@@ -0,0 +1,19 @@
1
+ import { maskSecrets } from '../core/security/masker.js';
2
+ const levels = { debug: 0, info: 1, warn: 2, error: 3 };
3
+ function threshold() {
4
+ const name = process.env.GUARDIAN_LOG;
5
+ return levels[name && name in levels ? name : 'warn'];
6
+ }
7
+ // stdout carries the MCP protocol, so every diagnostic line goes to stderr
8
+ function write(level, args) {
9
+ if (levels[level] < threshold())
10
+ return;
11
+ const line = args.map((a) => (a instanceof Error ? a.message : String(a))).join(' ');
12
+ process.stderr.write(`[guardian:${level}] ${maskSecrets(line).text}\n`);
13
+ }
14
+ export const log = {
15
+ debug: (...args) => write('debug', args),
16
+ info: (...args) => write('info', args),
17
+ warn: (...args) => write('warn', args),
18
+ error: (...args) => write('error', args),
19
+ };
@@ -0,0 +1,19 @@
1
+ import { performance } from 'node:perf_hooks';
2
+ export function createPacer(options = {}) {
3
+ const sliceMs = options.sliceMs ?? 10;
4
+ let sliceStart = performance.now();
5
+ let yielded = 0;
6
+ return {
7
+ async tick() {
8
+ options.signal?.throwIfAborted();
9
+ if (performance.now() - sliceStart < sliceMs)
10
+ return;
11
+ await new Promise((resolve) => setImmediate(resolve));
12
+ yielded++;
13
+ options.signal?.throwIfAborted();
14
+ sliceStart = performance.now();
15
+ },
16
+ yields: () => yielded,
17
+ };
18
+ }
19
+ export const isAbort = (err) => err instanceof Error && (err.name === 'AbortError' || err.name === 'TimeoutError');
@@ -0,0 +1,22 @@
1
+ // One definition of "text that is invisible or reorders what a reader sees while a model still reads it", used by every path that builds
2
+ // a prompt. Two groups, so that each path can pick what it needs:
3
+ // HIDDEN line and paragraph separators, zero-width space, bidirectional controls and isolates, word joiner and invisible operators,
4
+ // the byte order mark and the Unicode "tag" block (U+E0000 to U+E007F), which can carry an entire invisible sentence.
5
+ // JOINERS characters that are invisible but that emoji and some scripts need: zero-width non-joiner and joiner, variation selectors,
6
+ // soft hyphen, filler characters, annotation marks and the rest of the tag block.
7
+ // Text typed by the developer keeps its joiners (an emoji must survive); anything read from the repository loses both groups.
8
+ export const HIDDEN_CLASS = '\\u007f-\\u009f\\u061c\\u200b\\u200e\\u200f\\u2028\\u2029\\u202a-\\u202e\\u2060-\\u2069\\ufeff\\u{e0000}-\\u{e007f}';
9
+ export const JOINER_CLASS = '\\u00ad\\u034f\\u115f\\u1160\\u17b4\\u17b5\\u180b-\\u180f\\u200c\\u200d\\u206a-\\u206f\\u3164\\ufe00-\\ufe0f\\uffa0\\ufff9-\\ufffb\\u{e0080}-\\u{e0fff}';
10
+ const CONTROLS_CLASS = '\\u0000-\\u001f';
11
+ const SCRUBBED = new RegExp(`[${CONTROLS_CLASS}${HIDDEN_CLASS}]`, 'gu');
12
+ const EVERYTHING_INVISIBLE = new RegExp(`[${CONTROLS_CLASS}${HIDDEN_CLASS}${JOINER_CLASS}]`, 'gu');
13
+ const HIDDEN = new RegExp(`[${HIDDEN_CLASS}]`, 'gu');
14
+ // General-purpose scrub for text shown to a person or a model: controls and hidden text become '?'. Joiners are kept.
15
+ export const safe = (value) => value.replace(SCRUBBED, '?');
16
+ // The scrub for anything read from the repository (paths, names, signatures, comments) that goes into a prompt: every invisible
17
+ // character, joiners included, becomes '?'.
18
+ export const scrubRepositoryText = (value) => value.replace(EVERYTHING_INVISIBLE, '?');
19
+ // The same hidden set as `safe`, minus the ordinary controls: tabs and newlines in a developer's request are legitimate.
20
+ export const hasHiddenText = (value) => new RegExp(HIDDEN.source, 'u').test(value);
21
+ export const replaceHiddenText = (value, replacement) => value.replace(HIDDEN, replacement);
22
+ export const compareText = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
@@ -0,0 +1,14 @@
1
+ // Heuristic only: about four bytes per token. Every figure shown to a user is labelled "estimated".
2
+ export const tokensFromBytes = (bytes) => Math.ceil(bytes / 4);
3
+ export const estimateTokens = (text) => tokensFromBytes(Buffer.byteLength(text));
4
+ export function describeTokens(report) {
5
+ const { sent, baseline, baselineFiles, truncated } = report;
6
+ const cut = truncated ? ' Output was truncated to fit the token budget.' : '';
7
+ if (baselineFiles === 0)
8
+ return `~${sent} estimated tokens (no referenced files to compare against).${cut}`;
9
+ const files = `${baselineFiles} referenced file${baselineFiles === 1 ? '' : 's'}`;
10
+ if (baseline <= sent)
11
+ return `~${sent} estimated tokens, no saving compared with reading the ${files} in full (~${baseline}).${cut}`;
12
+ const pct = Math.round((1 - sent / baseline) * 100);
13
+ return `~${sent} estimated tokens instead of ~${baseline} for reading the ${files} in full (${pct}% fewer).${cut}`;
14
+ }
package/package.json CHANGED
@@ -1,6 +1,71 @@
1
1
  {
2
2
  "name": "code-guardian-ai",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.1",
4
+ "description": "Privacy-first local MCP server and CLI that helps AI coding assistants reuse existing code and validate code changes.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "bin": {
8
+ "guardian": "bin/cli.js"
9
+ },
10
+ "files": [
11
+ "bin",
12
+ "dist",
13
+ "LICENSE",
14
+ ".env.example",
15
+ "README.md"
16
+ ],
17
+ "engines": {
18
+ "node": ">=22"
19
+ },
20
+ "scripts": {
21
+ "build": "node scripts/dist-integrity.mjs clean && tsc && node scripts/dist-integrity.mjs write",
22
+ "dev": "tsx src/cli/index.ts",
23
+ "typecheck": "tsc --noEmit",
24
+ "verify:dist": "node scripts/dist-integrity.mjs verify",
25
+ "prepack": "node scripts/dist-integrity.mjs verify",
26
+ "test": "node --import tsx --test \"test/*.test.ts\"",
27
+ "doctor": "node bin/cli.js doctor",
28
+ "prepublishOnly": "npm run typecheck && npm test && npm run build && node scripts/pack-smoke.mjs",
29
+ "bench": "tsx bench/run.ts",
30
+ "bench:mcp": "tsx bench/mcp-latency.ts",
31
+ "pack:smoke": "npm run build && node scripts/pack-smoke.mjs"
32
+ },
33
+ "dependencies": {
34
+ "@ai-sdk/google": "^4.0.108",
35
+ "@ai-sdk/openai": "^4.0.105",
36
+ "@modelcontextprotocol/sdk": "^1.32.2",
37
+ "@vscode/tree-sitter-wasm": "^0.3.1",
38
+ "ai": "^7.0.157",
39
+ "better-sqlite3": "^13.0.3",
40
+ "commander": "^15.0.0",
41
+ "ignore": "^7.0.14",
42
+ "zod": "^4.6.7"
43
+ },
44
+ "devDependencies": {
45
+ "@types/better-sqlite3": "^9.6.0",
46
+ "@types/node": "^26.6.6",
47
+ "tsx": "^4.23.15",
48
+ "typescript": "^7.0.2"
49
+ },
50
+ "keywords": [
51
+ "mcp",
52
+ "model-context-protocol",
53
+ "mcp-server",
54
+ "code-analysis",
55
+ "static-analysis",
56
+ "developer-tools",
57
+ "code-search",
58
+ "typescript",
59
+ "javascript",
60
+ "python",
61
+ "cli"
62
+ ],
63
+ "homepage": "https://github.com/Ayush8092/GuardStack-AI#readme",
64
+ "repository": {
65
+ "type": "git",
66
+ "url": "https://github.com/Ayush8092/GuardStack-AI.git"
67
+ },
68
+ "bugs": {
69
+ "url": "https://github.com/Ayush8092/GuardStack-AI/issues"
70
+ }
71
+ }