@aiready/agent-grounding 0.1.5 → 0.1.8

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.
@@ -1,6 +1,6 @@
1
1
 
2
2
  
3
- > @aiready/agent-grounding@0.1.5 build /Users/pengcao/projects/aiready/packages/agent-grounding
3
+ > @aiready/agent-grounding@0.1.8 build /Users/pengcao/projects/aiready/packages/agent-grounding
4
4
  > tsup src/index.ts src/cli.ts --format cjs,esm --dts
5
5
 
6
6
  CLI Building entry: src/cli.ts, src/index.ts
@@ -9,15 +9,15 @@
9
9
  CLI Target: es2020
10
10
  CJS Build start
11
11
  ESM Build start
12
+ CJS dist/cli.js 16.22 KB
13
+ CJS dist/index.js 10.75 KB
14
+ CJS ⚡️ Build success in 267ms
12
15
  ESM dist/index.mjs 154.00 B
13
- ESM dist/chunk-OOB3JMXQ.mjs 10.37 KB
14
- ESM dist/cli.mjs 5.04 KB
15
- ESM ⚡️ Build success in 1612ms
16
- CJS dist/index.js 11.62 KB
17
- CJS dist/cli.js 16.99 KB
18
- CJS ⚡️ Build success in 1620ms
16
+ ESM dist/cli.mjs 5.16 KB
17
+ ESM dist/chunk-NXIMJNCK.mjs 9.55 KB
18
+ ESM ⚡️ Build success in 266ms
19
19
  DTS Build start
20
- DTS ⚡️ Build success in 69473ms
20
+ DTS ⚡️ Build success in 10475ms
21
21
  DTS dist/cli.d.ts 20.00 B
22
22
  DTS dist/index.d.ts 2.34 KB
23
23
  DTS dist/cli.d.mts 20.00 B
@@ -0,0 +1,5 @@
1
+
2
+ 
3
+ > @aiready/agent-grounding@0.1.6 lint /Users/pengcao/projects/aiready/packages/agent-grounding
4
+ > eslint src
5
+
@@ -1,17 +1,17 @@
1
1
 
2
2
  
3
- > @aiready/agent-grounding@0.1.5 test /Users/pengcao/projects/aiready/packages/agent-grounding
3
+ > @aiready/agent-grounding@0.1.8 test /Users/pengcao/projects/aiready/packages/agent-grounding
4
4
  > vitest run
5
5
 
6
6
  [?25l
7
7
   RUN  v4.0.18 /Users/pengcao/projects/aiready/packages/agent-grounding
8
8
 
9
- ✓ src/__tests__/analyzer.test.ts (3 tests) 1215ms
10
- ✓ should detect deep directories and vague file names  954ms
9
+ ✓ src/__tests__/analyzer.test.ts (3 tests) 719ms
10
+ ✓ should detect deep directories and vague file names  336ms
11
11
 
12
12
   Test Files  1 passed (1)
13
13
   Tests  3 passed (3)
14
-  Start at  14:38:43
15
-  Duration  21.71s (transform 4.66s, setup 0ms, import 16.23s, tests 1.21s, environment 0ms)
14
+  Start at  00:56:24
15
+  Duration  5.49s (transform 1.39s, setup 0ms, import 3.93s, tests 719ms, environment 0ms)
16
16
 
17
17
  [?25h
@@ -0,0 +1,336 @@
1
+ // src/analyzer.ts
2
+ import { readdirSync, statSync, existsSync, readFileSync } from "fs";
3
+ import { join, extname, basename } from "path";
4
+ import { parse } from "@typescript-eslint/typescript-estree";
5
+ import { calculateAgentGrounding } from "@aiready/core";
6
+ var VAGUE_FILE_NAMES = /* @__PURE__ */ new Set([
7
+ "utils",
8
+ "helpers",
9
+ "helper",
10
+ "misc",
11
+ "common",
12
+ "shared",
13
+ "tools",
14
+ "util",
15
+ "lib",
16
+ "libs",
17
+ "stuff",
18
+ "functions",
19
+ "methods",
20
+ "handlers",
21
+ "data",
22
+ "temp",
23
+ "tmp",
24
+ "test-utils",
25
+ "test-helpers",
26
+ "mocks"
27
+ ]);
28
+ var SUPPORTED_EXTENSIONS = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx"]);
29
+ var DEFAULT_EXCLUDES = [
30
+ "node_modules",
31
+ "dist",
32
+ ".git",
33
+ "coverage",
34
+ ".turbo",
35
+ "build"
36
+ ];
37
+ function collectEntries(dir, options, depth = 0, dirs = [], files = []) {
38
+ if (depth > (options.maxDepth ?? 20)) return { dirs, files };
39
+ const excludes = [...DEFAULT_EXCLUDES, ...options.exclude ?? []];
40
+ let entries;
41
+ try {
42
+ entries = readdirSync(dir);
43
+ } catch {
44
+ return { dirs, files };
45
+ }
46
+ for (const entry of entries) {
47
+ if (excludes.some((ex) => entry === ex || entry.includes(ex))) continue;
48
+ const full = join(dir, entry);
49
+ let stat;
50
+ try {
51
+ stat = statSync(full);
52
+ } catch {
53
+ continue;
54
+ }
55
+ if (stat.isDirectory()) {
56
+ dirs.push({ path: full, depth });
57
+ collectEntries(full, options, depth + 1, dirs, files);
58
+ } else if (stat.isFile() && SUPPORTED_EXTENSIONS.has(extname(full))) {
59
+ if (!options.include || options.include.some((p) => full.includes(p))) {
60
+ files.push(full);
61
+ }
62
+ }
63
+ }
64
+ return { dirs, files };
65
+ }
66
+ function analyzeFile(filePath) {
67
+ let code;
68
+ try {
69
+ code = readFileSync(filePath, "utf-8");
70
+ } catch {
71
+ return {
72
+ isBarrel: false,
73
+ exportedNames: [],
74
+ untypedExports: 0,
75
+ totalExports: 0,
76
+ domainTerms: []
77
+ };
78
+ }
79
+ let ast;
80
+ try {
81
+ ast = parse(code, {
82
+ jsx: filePath.endsWith(".tsx") || filePath.endsWith(".jsx"),
83
+ range: false,
84
+ loc: false
85
+ });
86
+ } catch {
87
+ return {
88
+ isBarrel: false,
89
+ exportedNames: [],
90
+ untypedExports: 0,
91
+ totalExports: 0,
92
+ domainTerms: []
93
+ };
94
+ }
95
+ let isBarrel = false;
96
+ const exportedNames = [];
97
+ let untypedExports = 0;
98
+ let totalExports = 0;
99
+ const domainTerms = [];
100
+ for (const node of ast.body) {
101
+ if (node.type === "ExportAllDeclaration") {
102
+ isBarrel = true;
103
+ continue;
104
+ }
105
+ if (node.type === "ExportNamedDeclaration") {
106
+ totalExports++;
107
+ const decl = node.declaration;
108
+ if (decl) {
109
+ const name = decl.id?.name ?? decl.declarations?.[0]?.id?.name;
110
+ if (name) {
111
+ exportedNames.push(name);
112
+ domainTerms.push(
113
+ ...name.replace(/([A-Z])/g, " $1").toLowerCase().split(/\s+/).filter(Boolean)
114
+ );
115
+ const hasType = decl.returnType != null || decl.declarations?.[0]?.id?.typeAnnotation != null || decl.typeParameters != null;
116
+ if (!hasType) untypedExports++;
117
+ }
118
+ } else if (node.specifiers && node.specifiers.length > 0) {
119
+ isBarrel = true;
120
+ }
121
+ }
122
+ if (node.type === "ExportDefaultDeclaration") {
123
+ totalExports++;
124
+ }
125
+ }
126
+ return { isBarrel, exportedNames, untypedExports, totalExports, domainTerms };
127
+ }
128
+ function detectInconsistentTerms(allTerms) {
129
+ const termFreq = /* @__PURE__ */ new Map();
130
+ for (const term of allTerms) {
131
+ if (term.length >= 3) {
132
+ termFreq.set(term, (termFreq.get(term) ?? 0) + 1);
133
+ }
134
+ }
135
+ const orphans = [...termFreq.values()].filter((count) => count === 1).length;
136
+ const common = [...termFreq.values()].filter((count) => count >= 3).length;
137
+ const vocabularySize = termFreq.size;
138
+ const inconsistent = Math.max(0, orphans - common * 2);
139
+ return { inconsistent, vocabularySize };
140
+ }
141
+ async function analyzeAgentGrounding(options) {
142
+ const rootDir = options.rootDir;
143
+ const maxRecommendedDepth = options.maxRecommendedDepth ?? 4;
144
+ const readmeStaleDays = options.readmeStaleDays ?? 90;
145
+ const { dirs, files } = collectEntries(rootDir, options);
146
+ const deepDirectories = dirs.filter(
147
+ (d) => d.depth > maxRecommendedDepth
148
+ ).length;
149
+ const additionalVague = new Set(
150
+ (options.additionalVagueNames ?? []).map((n) => n.toLowerCase())
151
+ );
152
+ let vagueFileNames = 0;
153
+ for (const f of files) {
154
+ const base = basename(f, extname(f)).toLowerCase();
155
+ if (VAGUE_FILE_NAMES.has(base) || additionalVague.has(base)) {
156
+ vagueFileNames++;
157
+ }
158
+ }
159
+ const readmePath = join(rootDir, "README.md");
160
+ const hasRootReadme = existsSync(readmePath);
161
+ let readmeIsFresh = false;
162
+ if (hasRootReadme) {
163
+ try {
164
+ const stat = statSync(readmePath);
165
+ const ageDays = (Date.now() - stat.mtimeMs) / (1e3 * 60 * 60 * 24);
166
+ readmeIsFresh = ageDays < readmeStaleDays;
167
+ } catch {
168
+ }
169
+ }
170
+ const allDomainTerms = [];
171
+ let barrelExports = 0;
172
+ let untypedExports = 0;
173
+ let totalExports = 0;
174
+ for (const f of files) {
175
+ const analysis = analyzeFile(f);
176
+ if (analysis.isBarrel) barrelExports++;
177
+ untypedExports += analysis.untypedExports;
178
+ totalExports += analysis.totalExports;
179
+ allDomainTerms.push(...analysis.domainTerms);
180
+ }
181
+ const {
182
+ inconsistent: inconsistentDomainTerms,
183
+ vocabularySize: domainVocabularySize
184
+ } = detectInconsistentTerms(allDomainTerms);
185
+ const groundingResult = calculateAgentGrounding({
186
+ deepDirectories,
187
+ totalDirectories: dirs.length,
188
+ vagueFileNames,
189
+ totalFiles: files.length,
190
+ hasRootReadme,
191
+ readmeIsFresh,
192
+ barrelExports,
193
+ untypedExports,
194
+ totalExports: Math.max(1, totalExports),
195
+ inconsistentDomainTerms,
196
+ domainVocabularySize: Math.max(1, domainVocabularySize)
197
+ });
198
+ const issues = [];
199
+ if (groundingResult.dimensions.structureClarityScore < 70) {
200
+ issues.push({
201
+ type: "agent-navigation-failure",
202
+ dimension: "structure-clarity",
203
+ severity: "major",
204
+ message: `${deepDirectories} directories exceed recommended depth of ${maxRecommendedDepth} \u2014 agents struggle to navigate deep trees.`,
205
+ location: { file: rootDir, line: 0 },
206
+ suggestion: `Flatten nested directories to ${maxRecommendedDepth} levels or fewer.`
207
+ });
208
+ }
209
+ if (groundingResult.dimensions.selfDocumentationScore < 70) {
210
+ issues.push({
211
+ type: "agent-navigation-failure",
212
+ dimension: "self-documentation",
213
+ severity: "major",
214
+ message: `${vagueFileNames} files use vague names (utils, helpers, misc) \u2014 an agent cannot determine their purpose from the name alone.`,
215
+ location: { file: rootDir, line: 0 },
216
+ suggestion: "Rename to domain-specific names: e.g., userAuthUtils \u2192 tokenValidator."
217
+ });
218
+ }
219
+ if (!hasRootReadme) {
220
+ issues.push({
221
+ type: "agent-navigation-failure",
222
+ dimension: "entry-point",
223
+ severity: "critical",
224
+ message: "No root README.md found \u2014 agents have no orientation document to start from.",
225
+ location: { file: join(rootDir, "README.md"), line: 0 },
226
+ suggestion: "Add a README.md explaining the project structure, entry points, and key conventions."
227
+ });
228
+ } else if (!readmeIsFresh) {
229
+ issues.push({
230
+ type: "agent-navigation-failure",
231
+ dimension: "entry-point",
232
+ severity: "minor",
233
+ message: `README.md is stale (>${readmeStaleDays} days without updates) \u2014 agents may be misled by outdated context.`,
234
+ location: { file: readmePath, line: 0 },
235
+ suggestion: "Update README.md to reflect the current codebase structure."
236
+ });
237
+ }
238
+ if (groundingResult.dimensions.apiClarityScore < 70) {
239
+ issues.push({
240
+ type: "agent-navigation-failure",
241
+ dimension: "api-clarity",
242
+ severity: "major",
243
+ message: `${untypedExports} of ${totalExports} public exports lack TypeScript type annotations \u2014 agents cannot infer the API contract.`,
244
+ location: { file: rootDir, line: 0 },
245
+ suggestion: "Add explicit return type and parameter annotations to all exported functions."
246
+ });
247
+ }
248
+ if (groundingResult.dimensions.domainConsistencyScore < 70) {
249
+ issues.push({
250
+ type: "agent-navigation-failure",
251
+ dimension: "domain-consistency",
252
+ severity: "major",
253
+ message: `${inconsistentDomainTerms} domain terms appear to be used inconsistently \u2014 agents get confused when one concept has multiple names.`,
254
+ location: { file: rootDir, line: 0 },
255
+ suggestion: "Establish a domain glossary and enforce one term per concept across the codebase."
256
+ });
257
+ }
258
+ return {
259
+ summary: {
260
+ filesAnalyzed: files.length,
261
+ directoriesAnalyzed: dirs.length,
262
+ score: groundingResult.score,
263
+ rating: groundingResult.rating,
264
+ dimensions: groundingResult.dimensions
265
+ },
266
+ issues,
267
+ rawData: {
268
+ deepDirectories,
269
+ totalDirectories: dirs.length,
270
+ vagueFileNames,
271
+ totalFiles: files.length,
272
+ hasRootReadme,
273
+ readmeIsFresh,
274
+ barrelExports,
275
+ untypedExports,
276
+ totalExports,
277
+ inconsistentDomainTerms,
278
+ domainVocabularySize
279
+ },
280
+ recommendations: groundingResult.recommendations
281
+ };
282
+ }
283
+
284
+ // src/scoring.ts
285
+ function calculateGroundingScore(report) {
286
+ const { summary, rawData, recommendations } = report;
287
+ const factors = [
288
+ {
289
+ name: "Structure Clarity",
290
+ impact: Math.round(summary.dimensions.structureClarityScore - 50),
291
+ description: `${rawData.deepDirectories} of ${rawData.totalDirectories} dirs exceed recommended depth`
292
+ },
293
+ {
294
+ name: "Self-Documentation",
295
+ impact: Math.round(summary.dimensions.selfDocumentationScore - 50),
296
+ description: `${rawData.vagueFileNames} of ${rawData.totalFiles} files have vague names`
297
+ },
298
+ {
299
+ name: "Entry Points",
300
+ impact: Math.round(summary.dimensions.entryPointScore - 50),
301
+ description: rawData.hasRootReadme ? rawData.readmeIsFresh ? "README present and fresh" : "README present but stale" : "No root README"
302
+ },
303
+ {
304
+ name: "API Clarity",
305
+ impact: Math.round(summary.dimensions.apiClarityScore - 50),
306
+ description: `${rawData.untypedExports} of ${rawData.totalExports} exports lack type annotations`
307
+ },
308
+ {
309
+ name: "Domain Consistency",
310
+ impact: Math.round(summary.dimensions.domainConsistencyScore - 50),
311
+ description: `${rawData.inconsistentDomainTerms} inconsistent domain terms detected`
312
+ }
313
+ ];
314
+ const recs = recommendations.map(
315
+ (action) => ({
316
+ action,
317
+ estimatedImpact: 6,
318
+ priority: summary.score < 50 ? "high" : "medium"
319
+ })
320
+ );
321
+ return {
322
+ toolName: "agent-grounding",
323
+ score: summary.score,
324
+ rawMetrics: {
325
+ ...rawData,
326
+ rating: summary.rating
327
+ },
328
+ factors,
329
+ recommendations: recs
330
+ };
331
+ }
332
+
333
+ export {
334
+ analyzeAgentGrounding,
335
+ calculateGroundingScore
336
+ };
@@ -0,0 +1,294 @@
1
+ // src/analyzer.ts
2
+ import {
3
+ scanEntries,
4
+ calculateAgentGrounding,
5
+ VAGUE_FILE_NAMES
6
+ } from "@aiready/core";
7
+ import { readFileSync, existsSync, statSync } from "fs";
8
+ import { join, extname, basename, relative } from "path";
9
+ import { parse } from "@typescript-eslint/typescript-estree";
10
+ function analyzeFile(filePath) {
11
+ let code;
12
+ try {
13
+ code = readFileSync(filePath, "utf-8");
14
+ } catch {
15
+ return {
16
+ isBarrel: false,
17
+ exportedNames: [],
18
+ untypedExports: 0,
19
+ totalExports: 0,
20
+ domainTerms: []
21
+ };
22
+ }
23
+ let ast;
24
+ try {
25
+ ast = parse(code, {
26
+ jsx: filePath.endsWith(".tsx") || filePath.endsWith(".jsx"),
27
+ range: false,
28
+ loc: false
29
+ });
30
+ } catch {
31
+ return {
32
+ isBarrel: false,
33
+ exportedNames: [],
34
+ untypedExports: 0,
35
+ totalExports: 0,
36
+ domainTerms: []
37
+ };
38
+ }
39
+ let isBarrel = false;
40
+ const exportedNames = [];
41
+ let untypedExports = 0;
42
+ let totalExports = 0;
43
+ const domainTerms = [];
44
+ for (const node of ast.body) {
45
+ if (node.type === "ExportAllDeclaration") {
46
+ isBarrel = true;
47
+ continue;
48
+ }
49
+ if (node.type === "ExportNamedDeclaration") {
50
+ totalExports++;
51
+ const decl = node.declaration;
52
+ if (decl) {
53
+ const name = decl.id?.name ?? decl.declarations?.[0]?.id?.name;
54
+ if (name) {
55
+ exportedNames.push(name);
56
+ domainTerms.push(
57
+ ...name.replace(/([A-Z])/g, " $1").toLowerCase().split(/\s+/).filter(Boolean)
58
+ );
59
+ const hasType = decl.returnType != null || decl.declarations?.[0]?.id?.typeAnnotation != null || decl.typeParameters != null;
60
+ if (!hasType) untypedExports++;
61
+ }
62
+ } else if (node.specifiers && node.specifiers.length > 0) {
63
+ isBarrel = true;
64
+ }
65
+ }
66
+ if (node.type === "ExportDefaultDeclaration") {
67
+ totalExports++;
68
+ }
69
+ }
70
+ return { isBarrel, exportedNames, untypedExports, totalExports, domainTerms };
71
+ }
72
+ function detectInconsistentTerms(allTerms) {
73
+ const termFreq = /* @__PURE__ */ new Map();
74
+ for (const term of allTerms) {
75
+ if (term.length >= 3) {
76
+ termFreq.set(term, (termFreq.get(term) ?? 0) + 1);
77
+ }
78
+ }
79
+ const orphans = [...termFreq.values()].filter((count) => count === 1).length;
80
+ const common = [...termFreq.values()].filter((count) => count >= 3).length;
81
+ const vocabularySize = termFreq.size;
82
+ const inconsistent = Math.max(0, orphans - common * 2);
83
+ return { inconsistent, vocabularySize };
84
+ }
85
+ async function analyzeAgentGrounding(options) {
86
+ const rootDir = options.rootDir;
87
+ const maxRecommendedDepth = options.maxRecommendedDepth ?? 4;
88
+ const readmeStaleDays = options.readmeStaleDays ?? 90;
89
+ const { files, dirs: rawDirs } = await scanEntries({
90
+ ...options,
91
+ include: options.include || ["**/*.{ts,tsx,js,jsx}"]
92
+ });
93
+ const dirs = rawDirs.map((d) => ({
94
+ path: d,
95
+ depth: relative(rootDir, d).split(/[/\\]/).filter(Boolean).length
96
+ }));
97
+ const deepDirectories = dirs.filter(
98
+ (d) => d.depth > maxRecommendedDepth
99
+ ).length;
100
+ const additionalVague = new Set(
101
+ (options.additionalVagueNames ?? []).map((n) => n.toLowerCase())
102
+ );
103
+ let vagueFileNames = 0;
104
+ for (const f of files) {
105
+ const base = basename(f, extname(f)).toLowerCase();
106
+ if (VAGUE_FILE_NAMES.has(base) || additionalVague.has(base)) {
107
+ vagueFileNames++;
108
+ }
109
+ }
110
+ const readmePath = join(rootDir, "README.md");
111
+ const hasRootReadme = existsSync(readmePath);
112
+ let readmeIsFresh = false;
113
+ if (hasRootReadme) {
114
+ try {
115
+ const stat = statSync(readmePath);
116
+ const ageDays = (Date.now() - stat.mtimeMs) / (1e3 * 60 * 60 * 24);
117
+ readmeIsFresh = ageDays < readmeStaleDays;
118
+ } catch {
119
+ }
120
+ }
121
+ const allDomainTerms = [];
122
+ let barrelExports = 0;
123
+ let untypedExports = 0;
124
+ let totalExports = 0;
125
+ let processed = 0;
126
+ for (const f of files) {
127
+ processed++;
128
+ options.onProgress?.(
129
+ processed,
130
+ files.length,
131
+ `agent-grounding: analyzing files`
132
+ );
133
+ const analysis = analyzeFile(f);
134
+ if (analysis.isBarrel) barrelExports++;
135
+ untypedExports += analysis.untypedExports;
136
+ totalExports += analysis.totalExports;
137
+ allDomainTerms.push(...analysis.domainTerms);
138
+ }
139
+ const {
140
+ inconsistent: inconsistentDomainTerms,
141
+ vocabularySize: domainVocabularySize
142
+ } = detectInconsistentTerms(allDomainTerms);
143
+ const groundingResult = calculateAgentGrounding({
144
+ deepDirectories,
145
+ totalDirectories: dirs.length,
146
+ vagueFileNames,
147
+ totalFiles: files.length,
148
+ hasRootReadme,
149
+ readmeIsFresh,
150
+ barrelExports,
151
+ untypedExports,
152
+ totalExports: Math.max(1, totalExports),
153
+ inconsistentDomainTerms,
154
+ domainVocabularySize: Math.max(1, domainVocabularySize)
155
+ });
156
+ const issues = [];
157
+ if (groundingResult.dimensions.structureClarityScore < 70) {
158
+ issues.push({
159
+ type: "agent-navigation-failure",
160
+ dimension: "structure-clarity",
161
+ severity: "major",
162
+ message: `${deepDirectories} directories exceed recommended depth of ${maxRecommendedDepth} \u2014 agents struggle to navigate deep trees.`,
163
+ location: { file: rootDir, line: 0 },
164
+ suggestion: `Flatten nested directories to ${maxRecommendedDepth} levels or fewer.`
165
+ });
166
+ }
167
+ if (groundingResult.dimensions.selfDocumentationScore < 70) {
168
+ issues.push({
169
+ type: "agent-navigation-failure",
170
+ dimension: "self-documentation",
171
+ severity: "major",
172
+ message: `${vagueFileNames} files use vague names (utils, helpers, misc) \u2014 an agent cannot determine their purpose from the name alone.`,
173
+ location: { file: rootDir, line: 0 },
174
+ suggestion: "Rename to domain-specific names: e.g., userAuthUtils \u2192 tokenValidator."
175
+ });
176
+ }
177
+ if (!hasRootReadme) {
178
+ issues.push({
179
+ type: "agent-navigation-failure",
180
+ dimension: "entry-point",
181
+ severity: "critical",
182
+ message: "No root README.md found \u2014 agents have no orientation document to start from.",
183
+ location: { file: join(rootDir, "README.md"), line: 0 },
184
+ suggestion: "Add a README.md explaining the project structure, entry points, and key conventions."
185
+ });
186
+ } else if (!readmeIsFresh) {
187
+ issues.push({
188
+ type: "agent-navigation-failure",
189
+ dimension: "entry-point",
190
+ severity: "minor",
191
+ message: `README.md is stale (>${readmeStaleDays} days without updates) \u2014 agents may be misled by outdated context.`,
192
+ location: { file: readmePath, line: 0 },
193
+ suggestion: "Update README.md to reflect the current codebase structure."
194
+ });
195
+ }
196
+ if (groundingResult.dimensions.apiClarityScore < 70) {
197
+ issues.push({
198
+ type: "agent-navigation-failure",
199
+ dimension: "api-clarity",
200
+ severity: "major",
201
+ message: `${untypedExports} of ${totalExports} public exports lack TypeScript type annotations \u2014 agents cannot infer the API contract.`,
202
+ location: { file: rootDir, line: 0 },
203
+ suggestion: "Add explicit return type and parameter annotations to all exported functions."
204
+ });
205
+ }
206
+ if (groundingResult.dimensions.domainConsistencyScore < 70) {
207
+ issues.push({
208
+ type: "agent-navigation-failure",
209
+ dimension: "domain-consistency",
210
+ severity: "major",
211
+ message: `${inconsistentDomainTerms} domain terms appear to be used inconsistently \u2014 agents get confused when one concept has multiple names.`,
212
+ location: { file: rootDir, line: 0 },
213
+ suggestion: "Establish a domain glossary and enforce one term per concept across the codebase."
214
+ });
215
+ }
216
+ return {
217
+ summary: {
218
+ filesAnalyzed: files.length,
219
+ directoriesAnalyzed: dirs.length,
220
+ score: groundingResult.score,
221
+ rating: groundingResult.rating,
222
+ dimensions: groundingResult.dimensions
223
+ },
224
+ issues,
225
+ rawData: {
226
+ deepDirectories,
227
+ totalDirectories: dirs.length,
228
+ vagueFileNames,
229
+ totalFiles: files.length,
230
+ hasRootReadme,
231
+ readmeIsFresh,
232
+ barrelExports,
233
+ untypedExports,
234
+ totalExports,
235
+ inconsistentDomainTerms,
236
+ domainVocabularySize
237
+ },
238
+ recommendations: groundingResult.recommendations
239
+ };
240
+ }
241
+
242
+ // src/scoring.ts
243
+ function calculateGroundingScore(report) {
244
+ const { summary, rawData, recommendations } = report;
245
+ const factors = [
246
+ {
247
+ name: "Structure Clarity",
248
+ impact: Math.round(summary.dimensions.structureClarityScore - 50),
249
+ description: `${rawData.deepDirectories} of ${rawData.totalDirectories} dirs exceed recommended depth`
250
+ },
251
+ {
252
+ name: "Self-Documentation",
253
+ impact: Math.round(summary.dimensions.selfDocumentationScore - 50),
254
+ description: `${rawData.vagueFileNames} of ${rawData.totalFiles} files have vague names`
255
+ },
256
+ {
257
+ name: "Entry Points",
258
+ impact: Math.round(summary.dimensions.entryPointScore - 50),
259
+ description: rawData.hasRootReadme ? rawData.readmeIsFresh ? "README present and fresh" : "README present but stale" : "No root README"
260
+ },
261
+ {
262
+ name: "API Clarity",
263
+ impact: Math.round(summary.dimensions.apiClarityScore - 50),
264
+ description: `${rawData.untypedExports} of ${rawData.totalExports} exports lack type annotations`
265
+ },
266
+ {
267
+ name: "Domain Consistency",
268
+ impact: Math.round(summary.dimensions.domainConsistencyScore - 50),
269
+ description: `${rawData.inconsistentDomainTerms} inconsistent domain terms detected`
270
+ }
271
+ ];
272
+ const recs = recommendations.map(
273
+ (action) => ({
274
+ action,
275
+ estimatedImpact: 6,
276
+ priority: summary.score < 50 ? "high" : "medium"
277
+ })
278
+ );
279
+ return {
280
+ toolName: "agent-grounding",
281
+ score: summary.score,
282
+ rawMetrics: {
283
+ ...rawData,
284
+ rating: summary.rating
285
+ },
286
+ factors,
287
+ recommendations: recs
288
+ };
289
+ }
290
+
291
+ export {
292
+ analyzeAgentGrounding,
293
+ calculateGroundingScore
294
+ };