akbo-cli 0.0.0-stage → 1.9.4

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 (66) hide show
  1. package/README.md +706 -2
  2. package/dist/catalog_store.d.ts +78 -0
  3. package/dist/catalog_store.js +375 -0
  4. package/dist/cleaner.d.ts +11 -0
  5. package/dist/cleaner.js +92 -0
  6. package/dist/cli.d.ts +2 -0
  7. package/dist/cli.js +1596 -0
  8. package/dist/extractors/base.d.ts +35 -0
  9. package/dist/extractors/base.js +17 -0
  10. package/dist/extractors/custom_extractor.d.ts +55 -0
  11. package/dist/extractors/custom_extractor.js +198 -0
  12. package/dist/extractors/dotnet_extractor.d.ts +11 -0
  13. package/dist/extractors/dotnet_extractor.js +579 -0
  14. package/dist/extractors/golang_extractor.d.ts +11 -0
  15. package/dist/extractors/golang_extractor.js +73 -0
  16. package/dist/extractors/index.d.ts +14 -0
  17. package/dist/extractors/index.js +30 -0
  18. package/dist/extractors/jvm_extractor.d.ts +11 -0
  19. package/dist/extractors/jvm_extractor.js +319 -0
  20. package/dist/extractors/node_extractor.d.ts +11 -0
  21. package/dist/extractors/node_extractor.js +306 -0
  22. package/dist/extractors/proto_graphql_extractor.d.ts +11 -0
  23. package/dist/extractors/proto_graphql_extractor.js +125 -0
  24. package/dist/extractors/python_extractor.d.ts +11 -0
  25. package/dist/extractors/python_extractor.js +298 -0
  26. package/dist/extractors/rust_extractor.d.ts +11 -0
  27. package/dist/extractors/rust_extractor.js +66 -0
  28. package/dist/graph_builder.d.ts +87 -0
  29. package/dist/graph_builder.js +1498 -0
  30. package/dist/harvester.d.ts +38 -0
  31. package/dist/harvester.js +461 -0
  32. package/dist/hook_generator.d.ts +26 -0
  33. package/dist/hook_generator.js +203 -0
  34. package/dist/importers/skill_importer.d.ts +43 -0
  35. package/dist/importers/skill_importer.js +470 -0
  36. package/dist/index.d.ts +17 -0
  37. package/dist/index.js +17 -0
  38. package/dist/indexer.d.ts +19 -0
  39. package/dist/indexer.js +108 -0
  40. package/dist/init_service.d.ts +37 -0
  41. package/dist/init_service.js +246 -0
  42. package/dist/mcp_server.d.ts +10 -0
  43. package/dist/mcp_server.js +632 -0
  44. package/dist/pool_resolver.d.ts +40 -0
  45. package/dist/pool_resolver.js +84 -0
  46. package/dist/provider.d.ts +135 -0
  47. package/dist/provider.js +880 -0
  48. package/dist/query_service.d.ts +33 -0
  49. package/dist/query_service.js +161 -0
  50. package/dist/schema_generator.d.ts +236 -0
  51. package/dist/schema_generator.js +264 -0
  52. package/dist/standards_loader.d.ts +7 -0
  53. package/dist/standards_loader.js +33 -0
  54. package/dist/types.d.ts +265 -0
  55. package/dist/types.js +105 -0
  56. package/dist/unit_synthesizer.d.ts +22 -0
  57. package/dist/unit_synthesizer.js +196 -0
  58. package/dist/validator.d.ts +13 -0
  59. package/dist/validator.js +152 -0
  60. package/dist/version.d.ts +6 -0
  61. package/dist/version.js +16 -0
  62. package/dist/watcher.d.ts +38 -0
  63. package/dist/watcher.js +132 -0
  64. package/package.json +56 -6
  65. package/schemas/index-schema.json +98 -0
  66. package/schemas/knowledge-unit.json +154 -0
@@ -0,0 +1,7 @@
1
+ import { type StandardsConfig } from './types.js';
2
+ export declare class StandardsLoader {
3
+ /**
4
+ * Loads and validates .akb/standards.yaml or .akb/standards.json if present.
5
+ */
6
+ static load(repoRoot: string, poolDir?: string): StandardsConfig | null;
7
+ }
@@ -0,0 +1,33 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import YAML from 'yaml';
4
+ import { StandardsConfigSchema } from './types.js';
5
+ export class StandardsLoader {
6
+ /**
7
+ * Loads and validates .akb/standards.yaml or .akb/standards.json if present.
8
+ */
9
+ static load(repoRoot, poolDir) {
10
+ const searchDirs = poolDir && poolDir !== repoRoot ? [poolDir, repoRoot] : [repoRoot];
11
+ const candidatePaths = [];
12
+ for (const dir of searchDirs) {
13
+ candidatePaths.push(path.join(dir, '.akb', 'standards.yaml'), path.join(dir, '.akb', 'standards.yml'), path.join(dir, '.akb', 'standards.json'));
14
+ }
15
+ const configPath = candidatePaths.find(p => fs.existsSync(p));
16
+ if (!configPath)
17
+ return null;
18
+ try {
19
+ const raw = fs.readFileSync(configPath, 'utf-8');
20
+ const parsed = configPath.endsWith('.json') ? JSON.parse(raw) : YAML.parse(raw);
21
+ if (!parsed)
22
+ return null;
23
+ const validated = StandardsConfigSchema.safeParse(parsed);
24
+ if (validated.success) {
25
+ return validated.data;
26
+ }
27
+ return null;
28
+ }
29
+ catch {
30
+ return null;
31
+ }
32
+ }
33
+ }
@@ -0,0 +1,265 @@
1
+ import { z } from 'zod';
2
+ export declare const SchemaTypeEnum: z.ZodEnum<{
3
+ prisma: "prisma";
4
+ sql: "sql";
5
+ rust_db: "rust_db";
6
+ python_models: "python_models";
7
+ typescript_types: "typescript_types";
8
+ drizzle: "drizzle";
9
+ typeorm: "typeorm";
10
+ gorm: "gorm";
11
+ graphql: "graphql";
12
+ efcore: "efcore";
13
+ edmx: "edmx";
14
+ protobuf: "protobuf";
15
+ fluentvalidation: "fluentvalidation";
16
+ dapper: "dapper";
17
+ wcf: "wcf";
18
+ jpa: "jpa";
19
+ sqlalchemy: "sqlalchemy";
20
+ }>;
21
+ export type SchemaType = z.infer<typeof SchemaTypeEnum>;
22
+ export interface ManifestSummary {
23
+ path: string;
24
+ type: 'npm' | 'cargo' | 'python' | 'go' | 'docker' | 'config' | 'dotnet' | 'maven' | 'gradle' | 'unknown';
25
+ contentSummary: Record<string, any>;
26
+ }
27
+ export interface RouteOrSignature {
28
+ file: string;
29
+ framework?: string;
30
+ method?: string;
31
+ identifier: string;
32
+ signature: string;
33
+ implements?: string[];
34
+ }
35
+ export interface SchemaSummary {
36
+ file: string;
37
+ type: SchemaType;
38
+ tablesOrModels: string[];
39
+ }
40
+ export interface TopologySummary {
41
+ totalFiles: number;
42
+ topLevelDirectories: string[];
43
+ keyDirectories: Record<string, string[]>;
44
+ entryPoints: string[];
45
+ }
46
+ export interface RepositorySkeleton {
47
+ timestamp: string;
48
+ repoPath: string;
49
+ topology: TopologySummary;
50
+ manifests: ManifestSummary[];
51
+ schemas: SchemaSummary[];
52
+ routesAndCommands: RouteOrSignature[];
53
+ scriptsAndWorkflows: {
54
+ packageScripts?: Record<string, string>;
55
+ githubWorkflows?: string[];
56
+ dockerServices?: string[];
57
+ };
58
+ }
59
+ export interface ProposedKnowledgeUnit {
60
+ id: string;
61
+ domain: 'architecture' | 'development' | 'product' | 'decisions' | 'security' | 'production' | string;
62
+ file: string;
63
+ title: string;
64
+ purpose: string;
65
+ targetFilesOrPatterns: string[];
66
+ }
67
+ export interface ProposedIndex {
68
+ system_name: string;
69
+ description: string;
70
+ domains: Record<string, ProposedKnowledgeUnit[]>;
71
+ }
72
+ export declare const AuthoritySchema: z.ZodDefault<z.ZodObject<{
73
+ level: z.ZodOptional<z.ZodDefault<z.ZodString>>;
74
+ confidence: z.ZodOptional<z.ZodDefault<z.ZodString>>;
75
+ }, z.core.$strip>>;
76
+ export declare const OwnerSchema: z.ZodDefault<z.ZodObject<{
77
+ team: z.ZodOptional<z.ZodDefault<z.ZodString>>;
78
+ }, z.core.$strip>>;
79
+ export declare const StandardKnowledgeUnitSchema: z.ZodObject<{
80
+ id: z.ZodString;
81
+ type: z.ZodUnion<[z.ZodEnum<{
82
+ architecture_standard: "architecture_standard";
83
+ development_standard: "development_standard";
84
+ product_rule: "product_rule";
85
+ security_standard: "security_standard";
86
+ }>, z.ZodString]>;
87
+ title: z.ZodString;
88
+ domain: z.ZodString;
89
+ status: z.ZodDefault<z.ZodEnum<{
90
+ approved: "approved";
91
+ draft: "draft";
92
+ deprecated: "deprecated";
93
+ accepted: "accepted";
94
+ proposed: "proposed";
95
+ locked: "locked";
96
+ }>>;
97
+ version: z.ZodDefault<z.ZodString>;
98
+ authority: z.ZodOptional<z.ZodDefault<z.ZodObject<{
99
+ level: z.ZodOptional<z.ZodDefault<z.ZodString>>;
100
+ confidence: z.ZodOptional<z.ZodDefault<z.ZodString>>;
101
+ }, z.core.$strip>>>;
102
+ owner: z.ZodOptional<z.ZodDefault<z.ZodObject<{
103
+ team: z.ZodOptional<z.ZodDefault<z.ZodString>>;
104
+ }, z.core.$strip>>>;
105
+ applies_to: z.ZodDefault<z.ZodArray<z.ZodString>>;
106
+ rule: z.ZodString;
107
+ do: z.ZodArray<z.ZodString>;
108
+ dont: z.ZodArray<z.ZodString>;
109
+ reason: z.ZodString;
110
+ related_items: z.ZodDefault<z.ZodArray<z.ZodString>>;
111
+ skill_file: z.ZodOptional<z.ZodString>;
112
+ reference_files: z.ZodOptional<z.ZodArray<z.ZodString>>;
113
+ workflow_gates: z.ZodOptional<z.ZodArray<z.ZodString>>;
114
+ }, z.core.$strip>;
115
+ export declare const DecisionKnowledgeUnitSchema: z.ZodObject<{
116
+ id: z.ZodString;
117
+ type: z.ZodUnion<[z.ZodLiteral<"architecture_decision">, z.ZodString]>;
118
+ title: z.ZodString;
119
+ domain: z.ZodDefault<z.ZodString>;
120
+ decision: z.ZodString;
121
+ context: z.ZodOptional<z.ZodString>;
122
+ status: z.ZodOptional<z.ZodEnum<{
123
+ approved: "approved";
124
+ draft: "draft";
125
+ deprecated: "deprecated";
126
+ accepted: "accepted";
127
+ proposed: "proposed";
128
+ locked: "locked";
129
+ }>>;
130
+ version: z.ZodOptional<z.ZodString>;
131
+ authority: z.ZodOptional<z.ZodDefault<z.ZodObject<{
132
+ level: z.ZodOptional<z.ZodDefault<z.ZodString>>;
133
+ confidence: z.ZodOptional<z.ZodDefault<z.ZodString>>;
134
+ }, z.core.$strip>>>;
135
+ owner: z.ZodOptional<z.ZodDefault<z.ZodObject<{
136
+ team: z.ZodOptional<z.ZodDefault<z.ZodString>>;
137
+ }, z.core.$strip>>>;
138
+ applies_to: z.ZodOptional<z.ZodArray<z.ZodString>>;
139
+ related_items: z.ZodDefault<z.ZodArray<z.ZodString>>;
140
+ skill_file: z.ZodOptional<z.ZodString>;
141
+ reference_files: z.ZodOptional<z.ZodArray<z.ZodString>>;
142
+ workflow_gates: z.ZodOptional<z.ZodArray<z.ZodString>>;
143
+ }, z.core.$strip>;
144
+ export declare const MasterIndexEntrySchema: z.ZodObject<{
145
+ id: z.ZodString;
146
+ file: z.ZodString;
147
+ title: z.ZodString;
148
+ purpose: z.ZodOptional<z.ZodString>;
149
+ }, z.core.$strip>;
150
+ export declare const DomainCatalogReferenceSchema: z.ZodObject<{
151
+ id: z.ZodString;
152
+ name: z.ZodOptional<z.ZodString>;
153
+ description: z.ZodOptional<z.ZodString>;
154
+ catalog: z.ZodString;
155
+ applies_to: z.ZodOptional<z.ZodUnion<[z.ZodArray<z.ZodString>, z.ZodString]>>;
156
+ }, z.core.$strip>;
157
+ export declare const MasterIndexSchema: z.ZodObject<{
158
+ system_name: z.ZodString;
159
+ repository_root: z.ZodOptional<z.ZodString>;
160
+ description: z.ZodOptional<z.ZodString>;
161
+ knowledge_units_count: z.ZodOptional<z.ZodNumber>;
162
+ last_updated: z.ZodOptional<z.ZodString>;
163
+ knowledge_units: z.ZodDefault<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodArray<z.ZodObject<{
164
+ id: z.ZodString;
165
+ file: z.ZodString;
166
+ title: z.ZodString;
167
+ purpose: z.ZodOptional<z.ZodString>;
168
+ }, z.core.$strip>>>>>;
169
+ domains: z.ZodOptional<z.ZodArray<z.ZodObject<{
170
+ id: z.ZodString;
171
+ name: z.ZodOptional<z.ZodString>;
172
+ description: z.ZodOptional<z.ZodString>;
173
+ catalog: z.ZodString;
174
+ applies_to: z.ZodOptional<z.ZodUnion<[z.ZodArray<z.ZodString>, z.ZodString]>>;
175
+ }, z.core.$strip>>>;
176
+ }, z.core.$strip>;
177
+ export type StandardKnowledgeUnit = z.infer<typeof StandardKnowledgeUnitSchema>;
178
+ export type DecisionKnowledgeUnit = z.infer<typeof DecisionKnowledgeUnitSchema>;
179
+ export type MasterIndex = z.infer<typeof MasterIndexSchema>;
180
+ export type MasterIndexEntry = z.infer<typeof MasterIndexEntrySchema>;
181
+ export type DomainCatalogReference = z.infer<typeof DomainCatalogReferenceSchema>;
182
+ export interface KnowledgeUnitContent {
183
+ id: string;
184
+ type: 'architecture_standard' | 'development_standard' | 'product_rule' | 'architecture_decision' | 'security_standard' | string;
185
+ title: string;
186
+ domain: string;
187
+ status: 'approved' | 'draft' | 'deprecated' | 'accepted' | 'proposed' | 'locked' | string;
188
+ version: string;
189
+ authority?: {
190
+ level?: 'official' | 'guideline' | 'experimental' | 'human_curated' | string;
191
+ confidence?: 'high' | 'medium' | 'low' | 'verified' | string;
192
+ };
193
+ owner?: {
194
+ team?: string;
195
+ };
196
+ applies_to: string[];
197
+ rule: string;
198
+ do: string[];
199
+ dont: string[];
200
+ reason: string;
201
+ related_items: string[];
202
+ skill_file?: string;
203
+ reference_files?: string[];
204
+ workflow_gates?: string[];
205
+ }
206
+ export type GraphNodeType = 'domain' | 'project' | 'endpoint' | 'message' | 'handler' | 'schema' | 'invariant';
207
+ export type GraphEdgeType = 'CONTAINS' | 'EXPOSES' | 'DISPATCHES' | 'HANDLES' | 'PERSISTS' | 'DEPENDS_ON' | 'CONSTRAINS' | 'RELATES_TO' | 'VALIDATES' | 'CONSUMES_EVENT' | 'CALLS_HTTP' | 'CALLS_GRPC' | 'CALLS_RPC' | 'IMPLEMENTS';
208
+ export interface GraphNode {
209
+ id: string;
210
+ type: GraphNodeType;
211
+ label: string;
212
+ file?: string;
213
+ domain?: string;
214
+ metadata?: Record<string, any>;
215
+ }
216
+ export interface GraphEdge {
217
+ source: string;
218
+ target: string;
219
+ type: GraphEdgeType;
220
+ metadata?: Record<string, any>;
221
+ }
222
+ export interface CodebaseKnowledgeGraph {
223
+ timestamp: string;
224
+ repoPath: string;
225
+ nodes: GraphNode[];
226
+ edges: GraphEdge[];
227
+ }
228
+ export interface GraphNeighborhood {
229
+ centerNode: GraphNode;
230
+ nodes: GraphNode[];
231
+ edges: GraphEdge[];
232
+ formattedContext: string;
233
+ activeInvariants?: KnowledgeUnitContent[];
234
+ deprecationWarnings?: string[];
235
+ }
236
+ export declare const CodeStandardPatternSchema: z.ZodObject<{
237
+ pattern: z.ZodString;
238
+ description: z.ZodOptional<z.ZodString>;
239
+ reason: z.ZodOptional<z.ZodString>;
240
+ appliesTo: z.ZodOptional<z.ZodString>;
241
+ deprecated: z.ZodOptional<z.ZodBoolean>;
242
+ migrationTarget: z.ZodOptional<z.ZodString>;
243
+ }, z.core.$strip>;
244
+ export type CodeStandardPattern = z.infer<typeof CodeStandardPatternSchema>;
245
+ export declare const StandardsConfigSchema: z.ZodObject<{
246
+ standards: z.ZodDefault<z.ZodObject<{
247
+ target_patterns: z.ZodDefault<z.ZodArray<z.ZodObject<{
248
+ pattern: z.ZodString;
249
+ description: z.ZodOptional<z.ZodString>;
250
+ reason: z.ZodOptional<z.ZodString>;
251
+ appliesTo: z.ZodOptional<z.ZodString>;
252
+ deprecated: z.ZodOptional<z.ZodBoolean>;
253
+ migrationTarget: z.ZodOptional<z.ZodString>;
254
+ }, z.core.$strip>>>;
255
+ deprecated_patterns: z.ZodDefault<z.ZodArray<z.ZodObject<{
256
+ pattern: z.ZodString;
257
+ description: z.ZodOptional<z.ZodString>;
258
+ reason: z.ZodOptional<z.ZodString>;
259
+ appliesTo: z.ZodOptional<z.ZodString>;
260
+ deprecated: z.ZodOptional<z.ZodBoolean>;
261
+ migrationTarget: z.ZodOptional<z.ZodString>;
262
+ }, z.core.$strip>>>;
263
+ }, z.core.$strip>>;
264
+ }, z.core.$strip>;
265
+ export type StandardsConfig = z.infer<typeof StandardsConfigSchema>;
package/dist/types.js ADDED
@@ -0,0 +1,105 @@
1
+ import { z } from 'zod';
2
+ export const SchemaTypeEnum = z.enum([
3
+ 'prisma',
4
+ 'sql',
5
+ 'rust_db',
6
+ 'python_models',
7
+ 'typescript_types',
8
+ 'drizzle',
9
+ 'typeorm',
10
+ 'gorm',
11
+ 'graphql',
12
+ 'efcore',
13
+ 'edmx',
14
+ 'protobuf',
15
+ 'fluentvalidation',
16
+ 'dapper',
17
+ 'wcf',
18
+ 'jpa',
19
+ 'sqlalchemy'
20
+ ]);
21
+ // Zod Schemas for Runtime Validation
22
+ export const AuthoritySchema = z.object({
23
+ level: z.string().default('official'),
24
+ confidence: z.string().default('high')
25
+ }).partial().default({});
26
+ export const OwnerSchema = z.object({
27
+ team: z.string().default('core_architecture')
28
+ }).partial().default({});
29
+ export const StandardKnowledgeUnitSchema = z.object({
30
+ id: z.string().min(1, 'Missing required field "id"'),
31
+ type: z.enum([
32
+ 'architecture_standard',
33
+ 'development_standard',
34
+ 'product_rule',
35
+ 'security_standard'
36
+ ]).or(z.string()),
37
+ title: z.string().min(1, 'Missing required field "title"'),
38
+ domain: z.string().min(1, 'Missing required field "domain"'),
39
+ status: z.enum(['approved', 'draft', 'deprecated', 'accepted', 'proposed', 'locked']).default('approved'),
40
+ version: z.string().default('1.0.0'),
41
+ authority: AuthoritySchema.optional(),
42
+ owner: OwnerSchema.optional(),
43
+ applies_to: z.array(z.string()).default([]),
44
+ rule: z.string().min(1, 'Missing required field "rule"'),
45
+ do: z.array(z.string()).min(1, '"do" list must contain at least one item'),
46
+ dont: z.array(z.string()).min(1, '"dont" list must contain at least one item'),
47
+ reason: z.string().min(1, 'Missing required field "reason"'),
48
+ related_items: z.array(z.string()).default([]),
49
+ skill_file: z.string().optional(),
50
+ reference_files: z.array(z.string()).optional(),
51
+ workflow_gates: z.array(z.string()).optional()
52
+ });
53
+ export const DecisionKnowledgeUnitSchema = z.object({
54
+ id: z.string().min(1, 'Missing required field "id"'),
55
+ type: z.literal('architecture_decision').or(z.string()),
56
+ title: z.string().min(1, 'Missing required field "title"'),
57
+ domain: z.string().default('decisions'),
58
+ decision: z.string().min(1, 'Decision missing required field "decision"'),
59
+ context: z.string().optional(),
60
+ status: z.enum(['approved', 'draft', 'deprecated', 'proposed', 'accepted', 'locked']).optional(),
61
+ version: z.string().optional(),
62
+ authority: AuthoritySchema.optional(),
63
+ owner: OwnerSchema.optional(),
64
+ applies_to: z.array(z.string()).optional(),
65
+ related_items: z.array(z.string()).default([]),
66
+ skill_file: z.string().optional(),
67
+ reference_files: z.array(z.string()).optional(),
68
+ workflow_gates: z.array(z.string()).optional()
69
+ });
70
+ export const MasterIndexEntrySchema = z.object({
71
+ id: z.string().min(1, 'Master index entry missing "id"'),
72
+ file: z.string().min(1, 'Master index entry missing "file"'),
73
+ title: z.string().min(1, 'Master index entry missing "title"'),
74
+ purpose: z.string().optional()
75
+ });
76
+ export const DomainCatalogReferenceSchema = z.object({
77
+ id: z.string().min(1, 'Domain catalog entry missing "id"'),
78
+ name: z.string().optional(),
79
+ description: z.string().optional(),
80
+ catalog: z.string().min(1, 'Domain catalog entry missing "catalog" path'),
81
+ applies_to: z.array(z.string()).or(z.string()).optional()
82
+ });
83
+ export const MasterIndexSchema = z.object({
84
+ system_name: z.string().min(1, 'Master index missing "system_name"'),
85
+ repository_root: z.string().optional(),
86
+ description: z.string().optional(),
87
+ knowledge_units_count: z.number().optional(),
88
+ last_updated: z.string().optional(),
89
+ knowledge_units: z.record(z.string(), z.array(MasterIndexEntrySchema)).optional().default({}),
90
+ domains: z.array(DomainCatalogReferenceSchema).optional()
91
+ });
92
+ export const CodeStandardPatternSchema = z.object({
93
+ pattern: z.string().min(1),
94
+ description: z.string().optional(),
95
+ reason: z.string().optional(),
96
+ appliesTo: z.string().optional(),
97
+ deprecated: z.boolean().optional(),
98
+ migrationTarget: z.string().optional()
99
+ });
100
+ export const StandardsConfigSchema = z.object({
101
+ standards: z.object({
102
+ target_patterns: z.array(CodeStandardPatternSchema).default([]),
103
+ deprecated_patterns: z.array(CodeStandardPatternSchema).default([])
104
+ }).default({ target_patterns: [], deprecated_patterns: [] })
105
+ });
@@ -0,0 +1,22 @@
1
+ import type { ProposedKnowledgeUnit, KnowledgeUnitContent } from './types.js';
2
+ import { type LLMProvider } from './provider.js';
3
+ export declare class UnitSynthesizer {
4
+ private provider;
5
+ client?: any;
6
+ private modelName;
7
+ private repoRoot;
8
+ private poolDir?;
9
+ private initialRetryDelay;
10
+ constructor(repoRoot: string, apiKeyOrProvider?: string | LLMProvider, modelName?: string, initialRetryDelay?: number, options?: {
11
+ forceCli?: boolean;
12
+ provider?: string;
13
+ baseUrl?: string;
14
+ apiKey?: string;
15
+ poolDir?: string;
16
+ });
17
+ get providerName(): string;
18
+ synthesizeUnit(unit: ProposedKnowledgeUnit): Promise<KnowledgeUnitContent>;
19
+ getFileRecencyScore(relPath: string): number;
20
+ private readTargetFiles;
21
+ private buildPrompt;
22
+ }
@@ -0,0 +1,196 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import child_process from 'node:child_process';
4
+ import { globby } from 'globby';
5
+ import { createLLMProvider, GeminiApiProvider } from './provider.js';
6
+ import { StandardsLoader } from './standards_loader.js';
7
+ export class UnitSynthesizer {
8
+ provider;
9
+ client;
10
+ modelName;
11
+ repoRoot;
12
+ poolDir;
13
+ initialRetryDelay;
14
+ constructor(repoRoot, apiKeyOrProvider, modelName = process.env.GEMINI_MODEL || 'gemini-3.5-flash', initialRetryDelay = 2000, options) {
15
+ this.repoRoot = path.resolve(repoRoot);
16
+ this.poolDir = options?.poolDir;
17
+ this.modelName = modelName;
18
+ this.initialRetryDelay = initialRetryDelay;
19
+ if (apiKeyOrProvider && typeof apiKeyOrProvider === 'object' && 'generateJson' in apiKeyOrProvider) {
20
+ this.provider = apiKeyOrProvider;
21
+ if ('client' in apiKeyOrProvider) {
22
+ this.client = apiKeyOrProvider.client;
23
+ }
24
+ }
25
+ else {
26
+ const explicitKey = typeof apiKeyOrProvider === 'string' ? apiKeyOrProvider : options?.apiKey;
27
+ const provider = createLLMProvider({
28
+ apiKey: explicitKey,
29
+ model: modelName,
30
+ forceCli: options?.forceCli,
31
+ provider: options?.provider,
32
+ baseUrl: options?.baseUrl,
33
+ initialRetryDelay
34
+ });
35
+ this.provider = provider;
36
+ if (provider instanceof GeminiApiProvider) {
37
+ this.client = provider.client;
38
+ }
39
+ }
40
+ }
41
+ get providerName() {
42
+ return this.provider.name;
43
+ }
44
+ async synthesizeUnit(unit) {
45
+ const fileSnippets = await this.readTargetFiles(unit.targetFilesOrPatterns);
46
+ const prompt = this.buildPrompt(unit, fileSnippets);
47
+ try {
48
+ const parsed = await this.provider.generateJson(prompt);
49
+ // Sanitize fields
50
+ parsed.id = unit.id;
51
+ parsed.domain = unit.domain;
52
+ parsed.status = parsed.status || 'approved';
53
+ parsed.version = parsed.version || '1.0.0';
54
+ return parsed;
55
+ }
56
+ catch (err) {
57
+ throw new Error(`Failed to parse unit ${unit.id} JSON: ${err.message}`);
58
+ }
59
+ }
60
+ getFileRecencyScore(relPath) {
61
+ const fullPath = path.join(this.repoRoot, relPath);
62
+ try {
63
+ const out = child_process.execSync(`git log -1 --format=%ct -- "${relPath}"`, {
64
+ cwd: this.repoRoot,
65
+ stdio: ['ignore', 'pipe', 'ignore'],
66
+ encoding: 'utf-8',
67
+ timeout: 2000
68
+ }).trim();
69
+ if (out && /^\d+$/.test(out)) {
70
+ return parseInt(out, 10) * 1000;
71
+ }
72
+ }
73
+ catch { }
74
+ try {
75
+ return fs.statSync(fullPath).mtimeMs;
76
+ }
77
+ catch {
78
+ return 0;
79
+ }
80
+ }
81
+ async readTargetFiles(patterns) {
82
+ const snippets = {};
83
+ for (const pattern of patterns) {
84
+ const matched = await globby(pattern, {
85
+ cwd: this.repoRoot,
86
+ onlyFiles: true,
87
+ dot: true
88
+ });
89
+ // Tier 1 (Fast in-memory sort): Score all files by mtimeMs (0 child processes)
90
+ const fastScored = matched
91
+ .map(relPath => {
92
+ const fullPath = path.join(this.repoRoot, relPath);
93
+ let mtime = 0;
94
+ try {
95
+ mtime = fs.statSync(fullPath).mtimeMs;
96
+ }
97
+ catch { }
98
+ return { relPath, mtime };
99
+ })
100
+ .sort((a, b) => b.mtime - a.mtime);
101
+ // Tier 2 (Targeted Git refinement): Check git commit timestamps only on top candidates (max 10)
102
+ const topCandidates = fastScored.slice(0, 10);
103
+ const sortedMatched = topCandidates
104
+ .map(item => ({ relPath: item.relPath, score: this.getFileRecencyScore(item.relPath) }))
105
+ .sort((a, b) => b.score - a.score)
106
+ .map(item => item.relPath);
107
+ for (const relPath of sortedMatched.slice(0, 3)) { // Read top 3 most recent files per pattern to reflect target conventions
108
+ const fullPath = path.join(this.repoRoot, relPath);
109
+ try {
110
+ const stats = fs.statSync(fullPath);
111
+ if (stats.size > 100 * 1024) {
112
+ // If file is > 100KB, read only first 300 lines
113
+ const content = fs.readFileSync(fullPath, 'utf-8').split('\n').slice(0, 300).join('\n');
114
+ snippets[relPath] = `${content}\n\n... [Truncated for brevity - ${stats.size} bytes total]`;
115
+ }
116
+ else {
117
+ snippets[relPath] = fs.readFileSync(fullPath, 'utf-8');
118
+ }
119
+ }
120
+ catch {
121
+ // Skip unreadable files
122
+ }
123
+ }
124
+ }
125
+ return snippets;
126
+ }
127
+ buildPrompt(unit, snippets) {
128
+ const filesContext = Object.entries(snippets)
129
+ .map(([filepath, content]) => `### FILE: ${filepath}\n\`\`\`\n${content}\n\`\`\``)
130
+ .join('\n\n');
131
+ const standards = StandardsLoader.load(this.repoRoot, this.poolDir);
132
+ let standardsContext = '';
133
+ if (standards) {
134
+ const targets = standards.standards.target_patterns;
135
+ const deprecated = standards.standards.deprecated_patterns;
136
+ if (targets.length > 0 || deprecated.length > 0) {
137
+ standardsContext = `
138
+ IMPORTANT ARCHITECTURAL STANDARDS GUIDELINES:
139
+ The repository author has defined explicit target modern standards and forbidden legacy anti-patterns:
140
+ ${targets.length > 0 ? `Target Patterns (MUST enforce in "do" array if relevant to this unit):\n${targets.map(t => `- Pattern "${t.pattern}": ${t.description || ''}`).join('\n')}` : ''}
141
+ ${deprecated.length > 0 ? `Deprecated / Legacy Anti-Patterns (MUST strictly prohibit in "dont" array if relevant to this unit):\n${deprecated.map(d => `- Pattern "${d.pattern}": ${d.reason || ''}`).join('\n')}` : ''}
142
+ `;
143
+ }
144
+ }
145
+ return `
146
+ You are the Chief Software Architect creating an Atomic Knowledge Base Unit for AI coding agents (Antigravity, Cursor, Claude Code).
147
+ AI agents will load and strictly follow this Knowledge Unit whenever working in this domain.
148
+
149
+ Knowledge Unit ID: ${unit.id}
150
+ Domain: ${unit.domain}
151
+ Title: ${unit.title}
152
+ Purpose: ${unit.purpose}
153
+
154
+ Here are the specific targeted code/config snippets extracted from the repository:
155
+ ${filesContext || 'No specific files found matching pattern. Rely on architectural conventions for this technology stack.'}
156
+ ${standardsContext}
157
+ TASK:
158
+ Extract non-negotiable architectural invariants, code conventions, do's, dont's, and reasoning.
159
+ Avoid trivial advice like "write clean code" or "add comments".
160
+ Focus on SPECIFIC technology constraints, library choices, safety rules, directory layouts, and error prevention invariants evident in the code.
161
+ If target patterns or deprecated patterns were specified above, strictly honor them by enforcing target patterns in "do" and prohibiting deprecated patterns in "dont".
162
+
163
+ Output STRICT JSON conforming to this schema:
164
+ {
165
+ "id": "${unit.id}",
166
+ "type": "architecture_standard" | "development_standard" | "product_rule" | "architecture_decision" | "security_standard",
167
+ "title": "${unit.title}",
168
+ "domain": "${unit.domain}",
169
+ "status": "approved",
170
+ "version": "1.0.0",
171
+ "authority": {
172
+ "level": "official",
173
+ "confidence": "high"
174
+ },
175
+ "owner": {
176
+ "team": "core_architecture"
177
+ },
178
+ "applies_to": [
179
+ "e.g. backend", "frontend", "api", "database", etc.
180
+ ],
181
+ "rule": "Single concise paragraph stating the non-negotiable overarching architectural rule.",
182
+ "do": [
183
+ "Concrete, highly actionable requirement 1",
184
+ "Concrete requirement 2",
185
+ "Concrete requirement 3"
186
+ ],
187
+ "dont": [
188
+ "Specific anti-pattern or prohibited behavior 1",
189
+ "Specific anti-pattern 2"
190
+ ],
191
+ "reason": "Clear explanation of WHY this rule is mandatory (e.g. performance, zero zombie processes, consistency, security).",
192
+ "related_items": []
193
+ }
194
+ `;
195
+ }
196
+ }
@@ -0,0 +1,13 @@
1
+ import { type PoolConfig } from './pool_resolver.js';
2
+ export interface ValidationResult {
3
+ valid: boolean;
4
+ errors: string[];
5
+ warnings: string[];
6
+ unitCount: number;
7
+ }
8
+ export declare class KnowledgeValidator {
9
+ private repoRoot;
10
+ poolConfig: PoolConfig;
11
+ constructor(repoRoot: string, poolDir?: string);
12
+ validate(): Promise<ValidationResult>;
13
+ }