code-guardian-ai 0.0.0-stage → 0.3.0
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.
- package/.env.example +24 -0
- package/LICENSE +21 -0
- package/README.md +774 -2
- package/bin/cli.js +2 -0
- package/dist/build-manifest.json +136 -0
- package/dist/cli/commands/check.js +56 -0
- package/dist/cli/commands/doctor.js +55 -0
- package/dist/cli/commands/find.js +31 -0
- package/dist/cli/commands/init-files.js +13 -0
- package/dist/cli/commands/init.js +50 -0
- package/dist/cli/commands/optimize.js +53 -0
- package/dist/cli/commands/scan.js +47 -0
- package/dist/cli/index.js +62 -0
- package/dist/cli/output.js +4 -0
- package/dist/context.js +11 -0
- package/dist/core/ast/analysis.js +455 -0
- package/dist/core/ast/cached-info.js +46 -0
- package/dist/core/ast/discovery.js +485 -0
- package/dist/core/ast/extract-js.js +531 -0
- package/dist/core/ast/extract-py.js +298 -0
- package/dist/core/ast/graph.js +92 -0
- package/dist/core/ast/health.js +338 -0
- package/dist/core/ast/indexer.js +286 -0
- package/dist/core/ast/packages.js +343 -0
- package/dist/core/ast/parser.js +91 -0
- package/dist/core/ast/report.js +154 -0
- package/dist/core/ast/resolver.js +392 -0
- package/dist/core/ast/rules.js +37 -0
- package/dist/core/ast/scope-js.js +191 -0
- package/dist/core/ast/shared-index.js +131 -0
- package/dist/core/ast/tsconfig.js +301 -0
- package/dist/core/ast/types.js +1 -0
- package/dist/core/ast/util.js +156 -0
- package/dist/core/git/git.js +430 -0
- package/dist/core/llm/policy.js +35 -0
- package/dist/core/llm/provider.js +199 -0
- package/dist/core/prompt/compressor.js +118 -0
- package/dist/core/prompt/criteria.js +36 -0
- package/dist/core/prompt/find.js +47 -0
- package/dist/core/prompt/guidelines.js +22 -0
- package/dist/core/prompt/model-output.js +178 -0
- package/dist/core/prompt/refiner.js +194 -0
- package/dist/core/prompt/relevance.js +265 -0
- package/dist/core/prompt/untrusted.js +57 -0
- package/dist/core/security/masker.js +330 -0
- package/dist/core/security/outbound.js +40 -0
- package/dist/core/security/safe-file.js +396 -0
- package/dist/core/security/sandbox.js +181 -0
- package/dist/core/validation/baseline.js +121 -0
- package/dist/core/validation/delta.js +243 -0
- package/dist/core/validation/policy.js +123 -0
- package/dist/db/cache-key.js +221 -0
- package/dist/db/client.js +563 -0
- package/dist/db/schema-check.js +149 -0
- package/dist/db/schema.js +36 -0
- package/dist/db/windows-acl.js +150 -0
- package/dist/index.js +55 -0
- package/dist/mcp/server.js +20 -0
- package/dist/mcp/tools/find-reusable.js +22 -0
- package/dist/mcp/tools/get-context.js +39 -0
- package/dist/mcp/tools/optimize-prompt.js +31 -0
- package/dist/mcp/tools/result.js +31 -0
- package/dist/mcp/tools/validate-rules.js +28 -0
- package/dist/utils/config.js +117 -0
- package/dist/utils/errors.js +9 -0
- package/dist/utils/logger.js +19 -0
- package/dist/utils/pace.js +19 -0
- package/dist/utils/text.js +22 -0
- package/dist/utils/tokens.js +14 -0
- package/package.json +69 -4
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { CACHE_VERSION, schema } from './schema.js';
|
|
2
|
+
// Structural validation of cache.db, done with SQLite's own introspection (sqlite_master, table_list, table_xinfo, index_list,
|
|
3
|
+
// index_info, foreign_key_list) and not by column names alone. cache.db can be shipped by a repository, so a database is only
|
|
4
|
+
// trusted for cache operations when its objects are exactly the ones schema.ts creates: ordinary tables of the expected shape,
|
|
5
|
+
// the one index the primary key implies, and nothing else (no virtual tables, views, triggers, extra indexes, statistics tables,
|
|
6
|
+
// generated or hidden columns, foreign keys, CHECK / DEFAULT / COLLATE clauses, WITHOUT ROWID or STRICT tables).
|
|
7
|
+
//
|
|
8
|
+
// Versions. CACHE_VERSION is the current layout. 5 is the oldest layout this code migrates (CHANGELOG: cache versions 5 and 6; 7 added
|
|
9
|
+
// the `usage_archive` table, which a migration simply creates): the `files` table of an older version is dropped and rebuilt, and its
|
|
10
|
+
// `usage` statistics are kept after they pass the same checks. Version 0 is a database
|
|
11
|
+
// that has never been written (it must hold no objects at all). Any other version (older ones nothing here can vouch for, and
|
|
12
|
+
// versions from a newer release) is not trusted and is replaced like a corrupted file.
|
|
13
|
+
export const OLDEST_MIGRATABLE_VERSION = 5;
|
|
14
|
+
const col = (name, type, notnull, pk = 0) => ({ name, type, notnull, pk });
|
|
15
|
+
const TABLES = {
|
|
16
|
+
files: {
|
|
17
|
+
columns: [col('path', 'TEXT', 0, 1), col('hash', 'TEXT', 1), col('size', 'INTEGER', 1), col('mtime_ms', 'INTEGER', 1), col('info', 'TEXT', 1)],
|
|
18
|
+
autoIndex: 'path',
|
|
19
|
+
autoIncrement: false,
|
|
20
|
+
},
|
|
21
|
+
usage: {
|
|
22
|
+
columns: [col('id', 'INTEGER', 0, 1), col('at', 'INTEGER', 1), col('tool', 'TEXT', 1), col('raw_tokens', 'INTEGER', 1), col('sent_tokens', 'INTEGER', 1)],
|
|
23
|
+
autoIndex: null,
|
|
24
|
+
autoIncrement: true,
|
|
25
|
+
},
|
|
26
|
+
// One row (id 1): the totals of usage rows that were trimmed away. An INTEGER PRIMARY KEY is the rowid itself, so it has no index.
|
|
27
|
+
usage_archive: {
|
|
28
|
+
columns: [col('id', 'INTEGER', 0, 1), col('calls', 'INTEGER', 1), col('raw_tokens', 'INTEGER', 1), col('sent_tokens', 'INTEGER', 1)],
|
|
29
|
+
autoIndex: null,
|
|
30
|
+
autoIncrement: false,
|
|
31
|
+
},
|
|
32
|
+
};
|
|
33
|
+
// SQLite keeps the CREATE statement as it was written (minus IF NOT EXISTS), so a whitespace- and case-insensitive comparison with
|
|
34
|
+
// the statements of schema.ts catches every clause the pragmas cannot show (CHECK, DEFAULT, COLLATE, ON CONFLICT, GENERATED ...).
|
|
35
|
+
const squash = (sql) => sql.replace(/\s+/g, '').replace(/ifnotexists/gi, '').toLowerCase();
|
|
36
|
+
const EXPECTED_SQL = new Map(schema
|
|
37
|
+
.split(';')
|
|
38
|
+
.map((s) => s.trim())
|
|
39
|
+
.filter(Boolean)
|
|
40
|
+
.map((statement) => [/^\s*CREATE TABLE (?:IF NOT EXISTS )?(\w+)/i.exec(statement)[1].toLowerCase(), squash(statement)]));
|
|
41
|
+
// At most this many entries in sqlite_master are read: a real cache has five. More is refused without reading further.
|
|
42
|
+
const MAX_OBJECTS = 16;
|
|
43
|
+
function tableProblem(db, name, master) {
|
|
44
|
+
const spec = TABLES[name];
|
|
45
|
+
const what = `the ${name} table`;
|
|
46
|
+
if (master.type !== 'table' || master.tbl_name !== name || typeof master.sql !== 'string')
|
|
47
|
+
return `${what} is not an ordinary table`;
|
|
48
|
+
if (/^\s*CREATE\s+VIRTUAL/i.test(master.sql))
|
|
49
|
+
return `${what} is a virtual table`;
|
|
50
|
+
if (squash(master.sql) !== EXPECTED_SQL.get(name))
|
|
51
|
+
return `${what} was declared differently from the supported schema`;
|
|
52
|
+
const listed = db.prepare('PRAGMA main.table_list').all().find((t) => t.name === name);
|
|
53
|
+
if (!listed || listed.type !== 'table' || listed.wr !== 0 || listed.strict !== 0)
|
|
54
|
+
return `${what} is not a plain rowid table`;
|
|
55
|
+
const found = db.prepare(`PRAGMA main.table_xinfo(${name})`).all();
|
|
56
|
+
if (found.length !== spec.columns.length)
|
|
57
|
+
return `${what} has ${found.length} columns, expected ${spec.columns.length}`;
|
|
58
|
+
for (const [i, want] of spec.columns.entries()) {
|
|
59
|
+
const got = found[i];
|
|
60
|
+
if (got.name !== want.name)
|
|
61
|
+
return `${what} has column ${got.name} where ${want.name} is expected`;
|
|
62
|
+
if (got.type.toUpperCase() !== want.type)
|
|
63
|
+
return `${what}: column ${want.name} has type ${got.type || '(none)'}, expected ${want.type}`;
|
|
64
|
+
if (got.notnull !== want.notnull)
|
|
65
|
+
return `${what}: column ${want.name} has the wrong nullability`;
|
|
66
|
+
if (got.pk !== want.pk)
|
|
67
|
+
return `${what}: column ${want.name} has the wrong primary key membership`;
|
|
68
|
+
if (got.dflt_value !== null)
|
|
69
|
+
return `${what}: column ${want.name} has a default value`;
|
|
70
|
+
if (got.hidden !== 0)
|
|
71
|
+
return `${what}: column ${want.name} is hidden or generated`;
|
|
72
|
+
}
|
|
73
|
+
const indexes = db.prepare(`PRAGMA main.index_list(${name})`).all();
|
|
74
|
+
if (spec.autoIndex === null) {
|
|
75
|
+
if (indexes.length > 0)
|
|
76
|
+
return `${what} has an index`;
|
|
77
|
+
}
|
|
78
|
+
else {
|
|
79
|
+
if (indexes.length !== 1)
|
|
80
|
+
return `${what} has ${indexes.length} indexes, expected only its primary key`;
|
|
81
|
+
const [index] = indexes;
|
|
82
|
+
if (index.origin !== 'pk' || index.unique !== 1 || index.partial !== 0)
|
|
83
|
+
return `${what} has an index that is not its plain primary key`;
|
|
84
|
+
const columns = db.prepare(`PRAGMA main.index_info(${JSON.stringify(index.name)})`).all().map((c) => c.name);
|
|
85
|
+
if (columns.join(',') !== spec.autoIndex)
|
|
86
|
+
return `${what}: the primary key covers ${columns.join(',')}`;
|
|
87
|
+
}
|
|
88
|
+
if (db.prepare(`PRAGMA main.foreign_key_list(${name})`).all().length > 0)
|
|
89
|
+
return `${what} has a foreign key`;
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
// Counts of rows in sqlite_sequence are bounded by the number of AUTOINCREMENT tables; anything else in it is not ours.
|
|
93
|
+
function sequenceProblem(db, master) {
|
|
94
|
+
if (master.type !== 'table' || master.sql === null || squash(master.sql) !== 'createtablesqlite_sequence(name,seq)')
|
|
95
|
+
return 'sqlite_sequence is not the table SQLite creates';
|
|
96
|
+
const rows = db.prepare('SELECT name FROM sqlite_sequence LIMIT 3').all();
|
|
97
|
+
return rows.length > 1 || rows.some((r) => r.name !== 'usage') ? 'sqlite_sequence holds entries that are not ours' : null;
|
|
98
|
+
}
|
|
99
|
+
// null when the database matches what `version` promises, otherwise the first difference. Read-only: it runs before anything is
|
|
100
|
+
// created, dropped or migrated, so nothing is ever executed against a structure that has not been looked at. `state` says what
|
|
101
|
+
// the caller has to do next.
|
|
102
|
+
export function inspectSchema(db, version) {
|
|
103
|
+
const refuse = (problem) => ({ state: null, problem });
|
|
104
|
+
const objects = db.prepare('SELECT type, name, tbl_name, sql FROM sqlite_master LIMIT ?').all(MAX_OBJECTS + 1);
|
|
105
|
+
if (objects.length > MAX_OBJECTS)
|
|
106
|
+
return refuse('it holds more schema objects than a cache ever does');
|
|
107
|
+
if (version === 0)
|
|
108
|
+
return objects.length === 0 ? { state: 'fresh', problem: null } : refuse('it has content but no schema version');
|
|
109
|
+
if (!Number.isInteger(version) || version < OLDEST_MIGRATABLE_VERSION || version > CACHE_VERSION)
|
|
110
|
+
return refuse(`schema version ${version} is not supported (supported: ${OLDEST_MIGRATABLE_VERSION} to ${CACHE_VERSION})`);
|
|
111
|
+
const current = version === CACHE_VERSION;
|
|
112
|
+
// First pass, names and kinds only, before any pragma is run: a pragma that lists tables resolves every one of them, and a
|
|
113
|
+
// virtual table of a module this process does not have would make it fail. Only the expected names, of the expected kind, are
|
|
114
|
+
// let through: indexes other than the primary key's automatic one, views, triggers, virtual tables and tables of any other name
|
|
115
|
+
// (sqlite_stat1, shadow tables, ...) are refused here.
|
|
116
|
+
const seen = new Set();
|
|
117
|
+
for (const object of objects) {
|
|
118
|
+
if (seen.has(object.name))
|
|
119
|
+
return refuse(`${object.name} appears twice`);
|
|
120
|
+
seen.add(object.name);
|
|
121
|
+
const named = object.name === 'files' || object.name === 'usage' || object.name === 'usage_archive';
|
|
122
|
+
if (named && (object.type !== 'table' || typeof object.sql !== 'string'))
|
|
123
|
+
return refuse(`the ${object.name} table is not an ordinary table`);
|
|
124
|
+
if (named && /^\s*CREATE\s+VIRTUAL/i.test(object.sql))
|
|
125
|
+
return refuse(`the ${object.name} table is a virtual table`);
|
|
126
|
+
const sequence = object.name === 'sqlite_sequence' && object.type === 'table';
|
|
127
|
+
const autoIndex = object.type === 'index' && object.sql === null && object.tbl_name === 'files' && /^sqlite_autoindex_files_\d+$/.test(object.name);
|
|
128
|
+
if (!named && !sequence && !autoIndex)
|
|
129
|
+
return refuse(`it contains an unexpected ${object.type} (${object.name.slice(0, 60)})`);
|
|
130
|
+
}
|
|
131
|
+
// Second pass, the details. The `files` table of an older version is dropped, not read: being an ordinary table is enough.
|
|
132
|
+
for (const object of objects) {
|
|
133
|
+
if (object.name === 'usage' || object.name === 'usage_archive' || (object.name === 'files' && current)) {
|
|
134
|
+
const problem = tableProblem(db, object.name, object);
|
|
135
|
+
if (problem)
|
|
136
|
+
return refuse(problem);
|
|
137
|
+
}
|
|
138
|
+
else if (object.name === 'sqlite_sequence') {
|
|
139
|
+
const problem = sequenceProblem(db, object);
|
|
140
|
+
if (problem)
|
|
141
|
+
return refuse(problem);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return { state: current ? 'current' : 'migrate', problem: null };
|
|
145
|
+
}
|
|
146
|
+
// After the schema was created or migrated, the whole structure is checked once more against the current version.
|
|
147
|
+
export function currentSchemaProblem(db) {
|
|
148
|
+
return inspectSchema(db, CACHE_VERSION).problem;
|
|
149
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// `hash` (sha256 of the file bytes) is the only validity check; size and mtime are recorded for diagnostics.
|
|
2
|
+
// Bump when the shape of the extracted file info changes; the file cache is rebuilt on mismatch.
|
|
3
|
+
export const CACHE_VERSION = 7;
|
|
4
|
+
export const CACHE_LIMITS = {
|
|
5
|
+
maxDbBytes: 128 * 1024 * 1024,
|
|
6
|
+
maxRows: 20_000,
|
|
7
|
+
maxInfoBytes: 4 * 1024 * 1024,
|
|
8
|
+
maxPathBytes: 4096,
|
|
9
|
+
maxLoadBytes: 64 * 1024 * 1024,
|
|
10
|
+
maxUsageRows: 100_000,
|
|
11
|
+
maxUsageTokens: 1_000_000_000,
|
|
12
|
+
};
|
|
13
|
+
export const schema = `
|
|
14
|
+
CREATE TABLE IF NOT EXISTS files (
|
|
15
|
+
path TEXT PRIMARY KEY,
|
|
16
|
+
hash TEXT NOT NULL,
|
|
17
|
+
size INTEGER NOT NULL,
|
|
18
|
+
mtime_ms INTEGER NOT NULL,
|
|
19
|
+
info TEXT NOT NULL
|
|
20
|
+
);
|
|
21
|
+
|
|
22
|
+
CREATE TABLE IF NOT EXISTS usage (
|
|
23
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
24
|
+
at INTEGER NOT NULL,
|
|
25
|
+
tool TEXT NOT NULL,
|
|
26
|
+
raw_tokens INTEGER NOT NULL,
|
|
27
|
+
sent_tokens INTEGER NOT NULL
|
|
28
|
+
);
|
|
29
|
+
|
|
30
|
+
CREATE TABLE IF NOT EXISTS usage_archive (
|
|
31
|
+
id INTEGER PRIMARY KEY,
|
|
32
|
+
calls INTEGER NOT NULL,
|
|
33
|
+
raw_tokens INTEGER NOT NULL,
|
|
34
|
+
sent_tokens INTEGER NOT NULL
|
|
35
|
+
);
|
|
36
|
+
`;
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
// Windows has no owner/mode bits that mean anything: a file's protection is its ACL. The machine key is only secret and
|
|
5
|
+
// unmodifiable if nobody but the current user (and the accounts that can take over the machine anyway) can read or change it,
|
|
6
|
+
// so on Windows the key directory and the key file are checked against their actual ACLs instead of against POSIX modes.
|
|
7
|
+
// The ACL is read through .NET's DirectorySecurity and FileSecurity APIs as an SDDL string, which uses SIDs, so the check
|
|
8
|
+
// does not depend on the language of the account names. Anything that cannot be read or parsed is refused: the caller
|
|
9
|
+
// then keeps the cache in memory, as it does for every other unsafe key location.
|
|
10
|
+
// The principals that may hold access: the current user, the local SYSTEM account and the Administrators group (who can take
|
|
11
|
+
// ownership of any file anyway), and the CREATOR OWNER / OWNER RIGHTS placeholders, which stand for the owner.
|
|
12
|
+
const SYSTEM = 'S-1-5-18';
|
|
13
|
+
const ADMINISTRATORS = 'S-1-5-32-544';
|
|
14
|
+
const ALIASES = { SY: SYSTEM, BA: ADMINISTRATORS, CO: 'S-1-3-0', OW: 'S-1-3-4' };
|
|
15
|
+
const sid = (token) => ALIASES[token] ?? token;
|
|
16
|
+
const SDDL = /^O:(S-1-[\d-]+|[A-Z]{2})(?:G:(?:S-1-[\d-]+|[A-Z]{2}))?(D:[A-Z]*(?:\([^()]*\))*)(?:S:.*)?$/;
|
|
17
|
+
const ALLOW = new Set(['A', 'OA', 'XA', 'ZA']);
|
|
18
|
+
const DENY = new Set(['D', 'OD', 'XD']);
|
|
19
|
+
// null when the ACL gives nobody but trusted principals any access, otherwise what is wrong with it.
|
|
20
|
+
export function aclProblem(sddl, userSid, what, localAdminSid) {
|
|
21
|
+
const match = SDDL.exec(sddl.trim());
|
|
22
|
+
if (!match)
|
|
23
|
+
return `${what} has an access control list that could not be read (no owner or no DACL)`;
|
|
24
|
+
const trusted = new Set([
|
|
25
|
+
userSid.toUpperCase(),
|
|
26
|
+
SYSTEM,
|
|
27
|
+
ADMINISTRATORS,
|
|
28
|
+
'S-1-3-0',
|
|
29
|
+
'S-1-3-4',
|
|
30
|
+
]);
|
|
31
|
+
const owner = (match[1] === 'LA' ? localAdminSid : sid(match[1]))?.toUpperCase();
|
|
32
|
+
if (!owner || (owner !== userSid.toUpperCase() && owner !== SYSTEM && owner !== ADMINISTRATORS)) {
|
|
33
|
+
return `${what} is not owned by the current user (owner ${match[1]})`;
|
|
34
|
+
}
|
|
35
|
+
// A NULL DACL (everyone has full access) has no D: section at all and was refused by the pattern above.
|
|
36
|
+
const aces = [...match[2].matchAll(/\(([^()]*)\)/g)].map((m) => m[1]);
|
|
37
|
+
for (const ace of aces) {
|
|
38
|
+
const fields = ace.split(';');
|
|
39
|
+
if (fields.length < 6)
|
|
40
|
+
return `${what} has an access control entry that could not be read`;
|
|
41
|
+
const [type, flags, , , , trustee] = fields;
|
|
42
|
+
if (DENY.has(type))
|
|
43
|
+
continue;
|
|
44
|
+
if (!ALLOW.has(type))
|
|
45
|
+
return `${what} has an access control entry of an unexpected type (${type})`;
|
|
46
|
+
// Inherit-only entries apply to children, not to this object.
|
|
47
|
+
if (/IO/.test(flags))
|
|
48
|
+
continue;
|
|
49
|
+
const trusteeSid = trustee === 'LA'
|
|
50
|
+
? localAdminSid?.toUpperCase()
|
|
51
|
+
: sid(trustee).toUpperCase();
|
|
52
|
+
if (!trusteeSid) {
|
|
53
|
+
return `${what} is accessible to other users (LA could not be resolved)`;
|
|
54
|
+
}
|
|
55
|
+
if (!trusted.has(trusteeSid)) {
|
|
56
|
+
return `${what} is accessible to other users (${trustee})`;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
const system32 = (name) => path.join(process.env.SystemRoot ?? process.env.windir ?? 'C:\\Windows', 'System32', name);
|
|
62
|
+
const run = (file, args, env = process.env) => {
|
|
63
|
+
if (!fs.existsSync(file))
|
|
64
|
+
throw new Error(`${path.basename(file)} is not available`);
|
|
65
|
+
return execFileSync(file, args, { encoding: 'utf8', timeout: 20_000, windowsHide: true, maxBuffer: 1 << 20, stdio: ['ignore', 'pipe', 'pipe'], env });
|
|
66
|
+
};
|
|
67
|
+
let userSid;
|
|
68
|
+
export function currentUserSid() {
|
|
69
|
+
if (userSid)
|
|
70
|
+
return userSid;
|
|
71
|
+
const found = /"(S-1-[\d-]+)"/.exec(run(system32('whoami.exe'), ['/user', '/fo', 'csv', '/nh']));
|
|
72
|
+
if (!found)
|
|
73
|
+
throw new Error('the current user could not be identified');
|
|
74
|
+
return (userSid = found[1]);
|
|
75
|
+
}
|
|
76
|
+
let localAdministratorSid;
|
|
77
|
+
export function currentLocalAdministratorSid() {
|
|
78
|
+
if (localAdministratorSid)
|
|
79
|
+
return localAdministratorSid;
|
|
80
|
+
const script = [
|
|
81
|
+
"$ErrorActionPreference = 'Stop'",
|
|
82
|
+
"$accounts = @(Get-CimInstance Win32_UserAccount -Filter \"LocalAccount=True\" | Where-Object { $_.SID -match '-500$' })",
|
|
83
|
+
"if ($accounts.Count -ne 1) { throw 'the local Administrator account could not be identified uniquely' }",
|
|
84
|
+
"$accounts[0].SID",
|
|
85
|
+
].join('; ');
|
|
86
|
+
const output = run(system32(path.join('WindowsPowerShell', 'v1.0', 'powershell.exe')), ['-NoProfile', '-NonInteractive', '-Command', script]).trim();
|
|
87
|
+
if (!/^S-1-5-21-(?:\d+-){2}\d+-500$/.test(output)) {
|
|
88
|
+
throw new Error('the local Administrator SID could not be verified');
|
|
89
|
+
}
|
|
90
|
+
localAdministratorSid = output.toUpperCase();
|
|
91
|
+
return localAdministratorSid;
|
|
92
|
+
}
|
|
93
|
+
// One SDDL string per path, in order. Paths travel in an environment variable, never inside the script text.
|
|
94
|
+
export function readSddls(paths) {
|
|
95
|
+
const script = [
|
|
96
|
+
"$ErrorActionPreference = 'Stop'",
|
|
97
|
+
"$sections = [System.Security.AccessControl.AccessControlSections]::Owner -bor [System.Security.AccessControl.AccessControlSections]::Access",
|
|
98
|
+
'$payload = ConvertFrom-Json -InputObject $env:GUARDIAN_ACL_PATHS',
|
|
99
|
+
'foreach ($p in $payload.paths) {',
|
|
100
|
+
' $attributes = [System.IO.File]::GetAttributes($p)',
|
|
101
|
+
' if (($attributes -band [System.IO.FileAttributes]::Directory) -ne 0) {',
|
|
102
|
+
' $acl = [System.Security.AccessControl.DirectorySecurity]::new($p, $sections)',
|
|
103
|
+
' } else {',
|
|
104
|
+
' $acl = [System.Security.AccessControl.FileSecurity]::new($p, $sections)',
|
|
105
|
+
' }',
|
|
106
|
+
' $acl.GetSecurityDescriptorSddlForm($sections)',
|
|
107
|
+
'}',
|
|
108
|
+
].join('; ');
|
|
109
|
+
const out = run(system32(path.join('WindowsPowerShell', 'v1.0', 'powershell.exe')), ['-NoProfile', '-NonInteractive', '-Command', script], {
|
|
110
|
+
...process.env,
|
|
111
|
+
GUARDIAN_ACL_PATHS: JSON.stringify({ paths }),
|
|
112
|
+
});
|
|
113
|
+
const lines = out.split(/\r?\n/).filter((line) => line.trim() !== '');
|
|
114
|
+
if (lines.length !== paths.length) {
|
|
115
|
+
throw new Error('the access control lists could not be read');
|
|
116
|
+
}
|
|
117
|
+
return lines;
|
|
118
|
+
}
|
|
119
|
+
// null when every target is private to the current user, otherwise the first problem. A failure to inspect is a problem too.
|
|
120
|
+
export const checkWindowsAcls = (targets) => {
|
|
121
|
+
try {
|
|
122
|
+
const user = currentUserSid();
|
|
123
|
+
let localAdmin;
|
|
124
|
+
try {
|
|
125
|
+
localAdmin = currentLocalAdministratorSid();
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
// ACLs containing LA will be refused if its SID cannot be resolved.
|
|
129
|
+
}
|
|
130
|
+
const sddls = readSddls(targets.map((t) => t.path));
|
|
131
|
+
for (let i = 0; i < targets.length; i++) {
|
|
132
|
+
const problem = aclProblem(sddls[i], user, targets[i].what, localAdmin);
|
|
133
|
+
if (problem)
|
|
134
|
+
return problem;
|
|
135
|
+
}
|
|
136
|
+
return null;
|
|
137
|
+
}
|
|
138
|
+
catch (err) {
|
|
139
|
+
const message = err instanceof Error ? err.message.split('\n')[0] : String(err);
|
|
140
|
+
const stderr = typeof err === 'object' && err !== null && 'stderr' in err
|
|
141
|
+
? typeof err.stderr === 'string'
|
|
142
|
+
? err.stderr
|
|
143
|
+
: Buffer.isBuffer(err.stderr)
|
|
144
|
+
? err.stderr.toString('utf8')
|
|
145
|
+
: ''
|
|
146
|
+
: '';
|
|
147
|
+
const detail = stderr.trim().replace(/\s+/g, ' ').slice(0, 500);
|
|
148
|
+
return `the permissions of ${targets.map((t) => t.what).join(' and ')} could not be verified (${message}${detail ? `; stderr: ${detail}` : ''})`;
|
|
149
|
+
}
|
|
150
|
+
};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
3
|
+
import { createContext } from './context.js';
|
|
4
|
+
import { closeDb } from './db/client.js';
|
|
5
|
+
import { terminateGitChildren } from './core/git/git.js';
|
|
6
|
+
import { createServer } from './mcp/server.js';
|
|
7
|
+
import { errorCode } from './utils/errors.js';
|
|
8
|
+
import { log } from './utils/logger.js';
|
|
9
|
+
const { version } = createRequire(import.meta.url)('../package.json');
|
|
10
|
+
export async function startServer(rootArg) {
|
|
11
|
+
const ctx = createContext(rootArg);
|
|
12
|
+
const server = createServer(ctx, version);
|
|
13
|
+
let closing = false;
|
|
14
|
+
const shutdown = () => {
|
|
15
|
+
if (closing)
|
|
16
|
+
return;
|
|
17
|
+
closing = true;
|
|
18
|
+
// Running git processes would otherwise outlive the server: their timeout and cancellation signal die with it.
|
|
19
|
+
terminateGitChildren();
|
|
20
|
+
try {
|
|
21
|
+
closeDb(ctx.db);
|
|
22
|
+
}
|
|
23
|
+
catch (err) {
|
|
24
|
+
log.error('Closing the cache failed:', err);
|
|
25
|
+
}
|
|
26
|
+
process.exit(0);
|
|
27
|
+
};
|
|
28
|
+
process.on('SIGINT', shutdown);
|
|
29
|
+
process.on('SIGTERM', shutdown);
|
|
30
|
+
process.stdin.on('close', shutdown);
|
|
31
|
+
process.stdout.on('error', (err) => (errorCode(err) === 'EPIPE' ? shutdown() : log.error(err)));
|
|
32
|
+
// After an uncaught exception or an unhandled rejection the process state is unknown (a half-finished write, a stuck
|
|
33
|
+
// request). Log it, close the cache and exit non-zero instead of serving further requests from that state; the MCP client
|
|
34
|
+
// restarts the server. Tool errors are handled per request and never reach here.
|
|
35
|
+
const fatal = (what) => (reason) => {
|
|
36
|
+
log.error(`${what}:`, reason);
|
|
37
|
+
terminateGitChildren();
|
|
38
|
+
if (!closing) {
|
|
39
|
+
closing = true;
|
|
40
|
+
try {
|
|
41
|
+
closeDb(ctx.db);
|
|
42
|
+
}
|
|
43
|
+
catch (err) {
|
|
44
|
+
log.error('Closing the cache failed:', err);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
process.exit(1);
|
|
48
|
+
};
|
|
49
|
+
process.on('unhandledRejection', fatal('Unhandled rejection'));
|
|
50
|
+
process.on('uncaughtException', fatal('Uncaught exception'));
|
|
51
|
+
server.server.onerror = (err) => log.error('Protocol error:', err);
|
|
52
|
+
server.server.onclose = shutdown;
|
|
53
|
+
await server.connect(new StdioServerTransport());
|
|
54
|
+
log.info(`MCP server ready, workspace: ${ctx.root}`);
|
|
55
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
2
|
+
import { registerFindReusable } from './tools/find-reusable.js';
|
|
3
|
+
import { registerGetContext } from './tools/get-context.js';
|
|
4
|
+
import { registerOptimizePrompt } from './tools/optimize-prompt.js';
|
|
5
|
+
import { registerValidateRules } from './tools/validate-rules.js';
|
|
6
|
+
// MCP is pull-based: the client decides whether and when to call these tools. Nothing here intercepts a prompt,
|
|
7
|
+
// so the instructions below only work if the assistant follows them.
|
|
8
|
+
const instructions = [
|
|
9
|
+
'GuardStack AI helps keep generated code consistent with the existing codebase.',
|
|
10
|
+
'Before writing code, call find_reusable_code for each helper you are about to write, or optimize_prompt for the whole task.',
|
|
11
|
+
'Reuse what they list instead of writing new functions. After your changes, call validate_rules.',
|
|
12
|
+
].join(' ');
|
|
13
|
+
export function createServer(ctx, version) {
|
|
14
|
+
const server = new McpServer({ name: 'codeguardian', version }, { instructions });
|
|
15
|
+
registerGetContext(server, ctx);
|
|
16
|
+
registerValidateRules(server, ctx);
|
|
17
|
+
registerOptimizePrompt(server, ctx);
|
|
18
|
+
registerFindReusable(server, ctx);
|
|
19
|
+
return server;
|
|
20
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { analyzeProject } from '../../core/ast/analysis.js';
|
|
3
|
+
import { indexShared } from '../../core/ast/shared-index.js';
|
|
4
|
+
import { findReusable, renderFind } from '../../core/prompt/find.js';
|
|
5
|
+
import { indexNotes, reply } from './result.js';
|
|
6
|
+
const inputSchema = {
|
|
7
|
+
query: z.string().min(1).max(2000).describe('What you are about to write, in plain words or with identifiers, e.g. "format a date for display".'),
|
|
8
|
+
limit: z.number().int().min(1).max(20).optional().describe('Maximum number of candidates (default 8).'),
|
|
9
|
+
};
|
|
10
|
+
export function registerFindReusable(server, ctx) {
|
|
11
|
+
server.registerTool('find_reusable_code', {
|
|
12
|
+
title: 'Find reusable code',
|
|
13
|
+
description: 'Looks up existing functions and classes in this workspace that match what you are about to write, with the reason each one matched. ' +
|
|
14
|
+
'Runs locally and never contacts a model. Says so plainly when nothing matches, so do not invent a helper in that case.',
|
|
15
|
+
inputSchema,
|
|
16
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
17
|
+
}, ({ query, limit }, extra) => reply(async () => {
|
|
18
|
+
const project = await indexShared(ctx, extra.signal);
|
|
19
|
+
const { graph } = analyzeProject(project, ctx.config);
|
|
20
|
+
return [renderFind(findReusable(project, graph, query, limit ?? 8)), ...indexNotes(project, ctx)].join('\n\n');
|
|
21
|
+
}));
|
|
22
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { analyzeProject } from '../../core/ast/analysis.js';
|
|
3
|
+
import { indexShared } from '../../core/ast/shared-index.js';
|
|
4
|
+
import { buildContext } from '../../core/prompt/compressor.js';
|
|
5
|
+
import { resolveInside, toRelative } from '../../core/security/sandbox.js';
|
|
6
|
+
import { recordUsage } from '../../db/client.js';
|
|
7
|
+
import { describeTokens } from '../../utils/tokens.js';
|
|
8
|
+
import { indexNotes, reply } from './result.js';
|
|
9
|
+
const inputSchema = {
|
|
10
|
+
query: z.string().max(500).optional().describe('What you are about to build. Files and symbols related to it are listed first.'),
|
|
11
|
+
paths: z.array(z.string().max(300)).max(20).optional().describe('Limit the map to these files or folders (relative to the workspace).'),
|
|
12
|
+
max_tokens: z.number().int().min(500).max(16000).optional().describe('Size budget for the map.'),
|
|
13
|
+
};
|
|
14
|
+
export function registerGetContext(server, ctx) {
|
|
15
|
+
server.registerTool('get_codebase_context', {
|
|
16
|
+
title: 'Get codebase context',
|
|
17
|
+
description: 'Returns a compact map of the files, exported functions, classes and types that already exist in this workspace. ' +
|
|
18
|
+
'Call it before writing new code so existing helpers are reused instead of duplicated.',
|
|
19
|
+
inputSchema,
|
|
20
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
21
|
+
}, ({ query, paths, max_tokens }, extra) => reply(async () => {
|
|
22
|
+
const project = await indexShared(ctx, extra.signal);
|
|
23
|
+
const { graph } = analyzeProject(project, ctx.config);
|
|
24
|
+
const scopes = (paths ?? []).map((p) => toRelative(ctx.root, resolveInside(ctx.root, p)));
|
|
25
|
+
const built = buildContext(project, graph, { query, paths: scopes, budgetTokens: max_tokens ?? ctx.config.contextTokens });
|
|
26
|
+
recordUsage(ctx.db, 'get_codebase_context', built.baselineTokens, built.sentTokens);
|
|
27
|
+
const notes = [
|
|
28
|
+
describeTokens({ sent: built.sentTokens, baseline: built.baselineTokens, baselineFiles: built.includedFiles, truncated: built.truncated }),
|
|
29
|
+
];
|
|
30
|
+
if (built.omittedFiles > 0)
|
|
31
|
+
notes.push(`${built.omittedFiles} file(s) did not fit the budget.`);
|
|
32
|
+
if (built.symbolsDropped > 0)
|
|
33
|
+
notes.push(`${built.symbolsDropped} export(s) were cut from partially listed files.`);
|
|
34
|
+
if (built.redactions > 0)
|
|
35
|
+
notes.push(`${built.redactions} secret(s) were redacted.`);
|
|
36
|
+
notes.push(...indexNotes(project, ctx));
|
|
37
|
+
return `${built.text}\n\n${notes.join(' ')}`;
|
|
38
|
+
}));
|
|
39
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { analyzeProject } from '../../core/ast/analysis.js';
|
|
3
|
+
import { indexShared } from '../../core/ast/shared-index.js';
|
|
4
|
+
import { resolvePolicy } from '../../core/llm/policy.js';
|
|
5
|
+
import { MAX_PROMPT_CHARS, describeLlm, refinePrompt } from '../../core/prompt/refiner.js';
|
|
6
|
+
import { InputError } from '../../utils/errors.js';
|
|
7
|
+
import { describeTokens } from '../../utils/tokens.js';
|
|
8
|
+
import { indexNotes, reply } from './result.js';
|
|
9
|
+
const inputSchema = {
|
|
10
|
+
prompt: z.string().min(1).max(MAX_PROMPT_CHARS).describe('The developer request to turn into a precise, codebase-aware task.'),
|
|
11
|
+
};
|
|
12
|
+
export function registerOptimizePrompt(server, ctx) {
|
|
13
|
+
server.registerTool('optimize_prompt', {
|
|
14
|
+
title: 'Optimize prompt',
|
|
15
|
+
description: 'Adds codebase context to a coding request: the existing functions and modules to reuse, constraints against duplication and bloat, ' +
|
|
16
|
+
'and the acceptance criteria found in the request. The original request is kept verbatim. Call it first for any request that adds or changes code.',
|
|
17
|
+
inputSchema,
|
|
18
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: true },
|
|
19
|
+
}, ({ prompt }, extra) => reply(async () => {
|
|
20
|
+
if (!prompt.trim())
|
|
21
|
+
throw new InputError('The prompt is empty');
|
|
22
|
+
const project = await indexShared(ctx, extra.signal);
|
|
23
|
+
const { graph } = analyzeProject(project, ctx.config);
|
|
24
|
+
const refined = await refinePrompt(ctx, project, graph, prompt, resolvePolicy(ctx.config), { signal: extra.signal });
|
|
25
|
+
const notes = [describeTokens({ sent: refined.sentTokens, baseline: refined.baselineTokens, baselineFiles: refined.baselineFiles, truncated: false })];
|
|
26
|
+
notes.push(describeLlm(refined), ...indexNotes(project, ctx));
|
|
27
|
+
if (refined.redactions > 0)
|
|
28
|
+
notes.push(`${refined.redactions} secret(s) were redacted.`);
|
|
29
|
+
return `${refined.text}\n\n${notes.join(' ')}`;
|
|
30
|
+
}));
|
|
31
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { describeCoverage } from '../../core/ast/report.js';
|
|
2
|
+
import { maskSecrets } from '../../core/security/masker.js';
|
|
3
|
+
import { InputError, errorMessage } from '../../utils/errors.js';
|
|
4
|
+
import { log } from '../../utils/logger.js';
|
|
5
|
+
import { isAbort } from '../../utils/pace.js';
|
|
6
|
+
const INTERNAL_MESSAGE = 'GuardStack AI could not complete this request. Details were written to the server log.';
|
|
7
|
+
function failure(err) {
|
|
8
|
+
const known = err instanceof InputError;
|
|
9
|
+
// A cancelled request is not a fault: the client asked to stop, and indexing kept what it had already cached.
|
|
10
|
+
if (isAbort(err))
|
|
11
|
+
return { isError: true, content: [{ type: 'text', text: JSON.stringify({ error: { code: 'cancelled', message: 'The request was cancelled.' } }) }] };
|
|
12
|
+
if (!known)
|
|
13
|
+
log.error(err instanceof Error ? (err.stack ?? err.message) : String(err));
|
|
14
|
+
const error = {
|
|
15
|
+
code: known ? err.code : 'internal_error',
|
|
16
|
+
message: maskSecrets(known ? errorMessage(err) : INTERNAL_MESSAGE).text,
|
|
17
|
+
};
|
|
18
|
+
return { isError: true, content: [{ type: 'text', text: JSON.stringify({ error }) }] };
|
|
19
|
+
}
|
|
20
|
+
// Every byte returned to an MCP client leaves through here, so masking here covers all tools.
|
|
21
|
+
export async function reply(work) {
|
|
22
|
+
try {
|
|
23
|
+
return { content: [{ type: 'text', text: maskSecrets(await work()).text }] };
|
|
24
|
+
}
|
|
25
|
+
catch (err) {
|
|
26
|
+
return failure(err);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
export function indexNotes(project, ctx) {
|
|
30
|
+
return project.complete ? [] : [describeCoverage(project, ctx.config.maxFiles)];
|
|
31
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { indexShared } from '../../core/ast/shared-index.js';
|
|
3
|
+
import { renderValidation } from '../../core/ast/report.js';
|
|
4
|
+
import { resolveInside, toRelative } from '../../core/security/sandbox.js';
|
|
5
|
+
import { validateProject } from '../../core/validation/delta.js';
|
|
6
|
+
import { indexNotes, reply } from './result.js';
|
|
7
|
+
const inputSchema = {
|
|
8
|
+
paths: z.array(z.string().max(300)).max(20).optional().describe('Only report findings in these files or folders (relative to the workspace).'),
|
|
9
|
+
base: z.string().max(200).optional().describe('Git ref to compare against, for example main. Defaults to HEAD, so staged, unstaged and untracked changes are checked.'),
|
|
10
|
+
include_existing: z.boolean().optional().describe('Also list findings that were already there before your changes.'),
|
|
11
|
+
};
|
|
12
|
+
export function registerValidateRules(server, ctx) {
|
|
13
|
+
server.registerTool('validate_rules', {
|
|
14
|
+
title: 'Validate your changes',
|
|
15
|
+
description: 'Checks what you just changed in git for duplicate functions, circular dependencies, unused imports, orphan files, unused exports and suppressed type or lint errors ' +
|
|
16
|
+
'(@ts-ignore, eslint-disable, any, # noqa, # type: ignore). Only problems introduced by your changes are reported; pre-existing ones are counted, not listed. ' +
|
|
17
|
+
'Outside a git repository the whole workspace is checked. Call it after making changes.',
|
|
18
|
+
inputSchema,
|
|
19
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
20
|
+
}, ({ paths, base, include_existing }, extra) => reply(async () => {
|
|
21
|
+
const project = await indexShared(ctx, extra.signal);
|
|
22
|
+
const scopes = (paths ?? []).map((p) => toRelative(ctx.root, resolveInside(ctx.root, p))).filter(Boolean);
|
|
23
|
+
const { validation } = await validateProject(ctx, project, { base, signal: extra.signal });
|
|
24
|
+
const body = renderValidation(validation, { includeExisting: include_existing, scopes });
|
|
25
|
+
const notes = indexNotes(project, ctx);
|
|
26
|
+
return notes.length > 0 ? `${body}\n\n${notes.join(' ')}` : body;
|
|
27
|
+
}));
|
|
28
|
+
}
|