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