akbo-cli 1.9.4 → 2.0.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.
@@ -0,0 +1,330 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { CatalogStore } from './catalog_store.js';
4
+ import { KnowledgePoolResolver } from './pool_resolver.js';
5
+ import { GraphBuilder } from './graph_builder.js';
6
+ import { createLLMProvider } from './provider.js';
7
+ export class DreamEngine {
8
+ targetDir;
9
+ poolDir;
10
+ constructor(targetDir = process.cwd(), poolDir) {
11
+ this.targetDir = path.resolve(targetDir);
12
+ this.poolDir = poolDir;
13
+ }
14
+ /**
15
+ * Consolidates recorded observations and error traces out-of-band into durable knowledge units or staged proposals.
16
+ */
17
+ async dream(options) {
18
+ const targetDir = path.resolve(options.targetDir || this.targetDir);
19
+ const poolConfig = KnowledgePoolResolver.resolve(targetDir, { explicitPoolDir: options.poolDir || this.poolDir });
20
+ const poolDir = poolConfig.poolDir;
21
+ const result = {
22
+ observationsProcessed: 0,
23
+ unitsCreated: [],
24
+ unitsUpdated: [],
25
+ proposalsStaged: [],
26
+ errors: []
27
+ };
28
+ // 1. Gather recorded observations
29
+ const allObservations = CatalogStore.listObservations({ targetDir, poolDir });
30
+ const cutoffTime = options.sinceHours ? Date.now() - options.sinceHours * 60 * 60 * 1000 : 0;
31
+ const eligibleObservations = allObservations.filter(obs => {
32
+ const isRecorded = !obs.status || obs.status === 'recorded';
33
+ const obsTime = obs.timestamp ? new Date(obs.timestamp).getTime() : 0;
34
+ return isRecorded && (cutoffTime === 0 || obsTime >= cutoffTime);
35
+ });
36
+ // 2. Gather transcript errors if available
37
+ const transcriptErrors = [];
38
+ const candidateTranscriptFiles = [
39
+ ...(options.transcriptFiles || []),
40
+ path.join(targetDir, '.system_generated', 'logs', 'transcript.jsonl')
41
+ ];
42
+ for (const tf of candidateTranscriptFiles) {
43
+ if (fs.existsSync(tf)) {
44
+ try {
45
+ const content = fs.readFileSync(tf, 'utf-8');
46
+ const lines = content.split('\n').filter(l => l.trim().length > 0);
47
+ for (const line of lines) {
48
+ try {
49
+ const entry = JSON.parse(line);
50
+ if (entry.status === 'ERROR' || (entry.content && typeof entry.content === 'string' && entry.content.includes('Error:'))) {
51
+ const snippet = entry.content ? entry.content.slice(0, 300) : entry.status;
52
+ transcriptErrors.push(`[${entry.type || 'STEP'}] ${snippet}`);
53
+ }
54
+ }
55
+ catch { }
56
+ }
57
+ }
58
+ catch (e) {
59
+ result.errors.push(`Failed reading transcript ${tf}: ${e.message}`);
60
+ }
61
+ }
62
+ }
63
+ if (eligibleObservations.length === 0 && transcriptErrors.length === 0) {
64
+ return result;
65
+ }
66
+ result.observationsProcessed = eligibleObservations.length;
67
+ // 3. Attempt LLM-based distillation if provider is explicitly requested
68
+ let synthesized = null;
69
+ const hasExplicitProvider = Boolean(options.provider || options.cli || options.agy || options.apiKey);
70
+ if (hasExplicitProvider) {
71
+ try {
72
+ const provider = await createLLMProvider({
73
+ provider: options.provider,
74
+ apiKey: options.apiKey,
75
+ model: options.model,
76
+ forceCli: options.cli,
77
+ forceAgy: options.agy
78
+ });
79
+ synthesized = await this.distillWithLLM(provider, eligibleObservations, transcriptErrors);
80
+ }
81
+ catch (err) {
82
+ result.errors.push(`LLM distillation failed, falling back to deterministic consolidation: ${err.message}`);
83
+ }
84
+ }
85
+ // 4. Fallback: Deterministic consolidation if LLM was unavailable or returned empty
86
+ if (!synthesized || (!synthesized.newUnits?.length && !synthesized.unitUpdates?.length)) {
87
+ synthesized = this.distillDeterministic(eligibleObservations, targetDir, poolDir);
88
+ }
89
+ // 5. Apply consolidation (either staged proposals or direct atomic upsert)
90
+ const stageOnly = options.stageOnly && !options.autoApprove;
91
+ if (stageOnly) {
92
+ // Stage new units
93
+ if (synthesized.newUnits) {
94
+ for (const u of synthesized.newUnits) {
95
+ const proposal = {
96
+ id: `staged-${u.id}-${Date.now().toString(36)}`,
97
+ targetUnitId: u.id,
98
+ domain: u.domain,
99
+ action: u.type === 'architecture_decision' ? 'record_decision' : 'create',
100
+ title: u.title,
101
+ proposed_rule: u.rule,
102
+ proposed_do: u.do,
103
+ proposed_dont: u.dont,
104
+ proposed_decision: u.decision,
105
+ reason: u.reason || 'Synthesized from runtime agent observations',
106
+ timestamp: new Date().toISOString(),
107
+ status: 'staged'
108
+ };
109
+ CatalogStore.stageProposal(proposal, { targetDir, poolDir });
110
+ result.proposalsStaged.push(proposal.id);
111
+ }
112
+ }
113
+ // Stage unit updates
114
+ if (synthesized.unitUpdates) {
115
+ for (const up of synthesized.unitUpdates) {
116
+ const proposal = {
117
+ id: `staged-update-${up.targetUnitId}-${Date.now().toString(36)}`,
118
+ targetUnitId: up.targetUnitId,
119
+ domain: 'development',
120
+ action: 'append_rules',
121
+ proposed_do: up.appendDo,
122
+ proposed_dont: up.appendDont,
123
+ reason: up.reason || 'Appended directives from consolidated session observations',
124
+ timestamp: new Date().toISOString(),
125
+ status: 'staged'
126
+ };
127
+ CatalogStore.stageProposal(proposal, { targetDir, poolDir });
128
+ result.proposalsStaged.push(proposal.id);
129
+ }
130
+ }
131
+ }
132
+ else {
133
+ // Direct upsert new units
134
+ if (synthesized.newUnits && synthesized.newUnits.length > 0) {
135
+ const unitsToUpsert = synthesized.newUnits.map(u => ({
136
+ id: u.id,
137
+ domain: u.domain || 'decisions',
138
+ type: u.type || (u.decision ? 'architecture_decision' : 'development_standard'),
139
+ title: u.title,
140
+ rule: u.rule,
141
+ decision: u.decision,
142
+ do: u.do || ['Adhere to synthesized pattern.'],
143
+ dont: u.dont || ['Do not repeat recorded trial-and-error trap.'],
144
+ reason: u.reason || 'Consolidated out-of-band via akbo dream.',
145
+ applies_to: u.applies_to || [],
146
+ status: 'approved',
147
+ version: '1.0.0',
148
+ authority: { level: 'synthesized_dream', confidence: 'verified' }
149
+ }));
150
+ const upsertRes = await CatalogStore.upsertUnits(unitsToUpsert, { targetDir, poolDir, validate: false });
151
+ if (upsertRes.success) {
152
+ result.unitsCreated.push(...upsertRes.units);
153
+ }
154
+ else if (upsertRes.error) {
155
+ result.errors.push(`Failed to upsert new units: ${upsertRes.error}`);
156
+ }
157
+ }
158
+ // Direct update existing units
159
+ if (synthesized.unitUpdates && synthesized.unitUpdates.length > 0) {
160
+ for (const up of synthesized.unitUpdates) {
161
+ const existing = CatalogStore.getUnit(up.targetUnitId, { targetDir, poolDir });
162
+ if (existing && existing.unit) {
163
+ const unit = existing.unit;
164
+ let modified = false;
165
+ if (up.appendDo && up.appendDo.length > 0) {
166
+ unit.do = Array.from(new Set([...(unit.do || []), ...up.appendDo]));
167
+ modified = true;
168
+ }
169
+ if (up.appendDont && up.appendDont.length > 0) {
170
+ unit.dont = Array.from(new Set([...(unit.dont || []), ...up.appendDont]));
171
+ modified = true;
172
+ }
173
+ if (modified) {
174
+ // Bump version patch
175
+ const vParts = (unit.version || '1.0.0').split('.');
176
+ if (vParts.length === 3) {
177
+ vParts[2] = String(parseInt(vParts[2], 10) + 1);
178
+ unit.version = vParts.join('.');
179
+ }
180
+ unit.authority = { level: 'synthesized_dream', confidence: 'verified' };
181
+ const updateRes = await CatalogStore.upsertUnits([unit], { targetDir, poolDir, validate: false });
182
+ if (updateRes.success) {
183
+ result.unitsUpdated.push(up.targetUnitId);
184
+ }
185
+ }
186
+ }
187
+ }
188
+ }
189
+ }
190
+ // 6. Mark processed observations as consolidated
191
+ this.markObservationsConsolidated(poolDir, eligibleObservations.map(o => o.id));
192
+ return result;
193
+ }
194
+ /**
195
+ * Distills observations using an LLM provider.
196
+ */
197
+ async distillWithLLM(provider, observations, transcriptErrors) {
198
+ const prompt = `You are an AI Memory Consolidation Engine ("Dreaming") for a software codebase.
199
+ Your goal is to review runtime session observations and execution errors from past agent tasks and synthesize them into durable, compounding architectural rules or decision records.
200
+
201
+ Observations:
202
+ ${JSON.stringify(observations, null, 2)}
203
+
204
+ Execution Errors / Stack Traces:
205
+ ${transcriptErrors.slice(0, 10).join('\n---\n')}
206
+
207
+ Instructions:
208
+ 1. Discard transient one-off noise (e.g. typos, temporary connection dropouts).
209
+ 2. For recurring traps or newly discovered patterns:
210
+ - Propose a new Knowledge Unit (type: 'development_standard' or 'architecture_decision') with clean ID (e.g. DEV-TRAP-001 or ADR-002), clear title, rule or decision, do list, dont list, and reason.
211
+ - OR propose an update to an existing standard if known.
212
+ 3. Emit strictly valid JSON conforming to:
213
+ {
214
+ "newUnits": [
215
+ {
216
+ "id": "DEV-TRAP-001",
217
+ "domain": "development",
218
+ "type": "development_standard",
219
+ "title": "Clear descriptive title",
220
+ "rule": "Exact standard rule",
221
+ "do": ["Required action"],
222
+ "dont": ["Forbidden action"],
223
+ "reason": "Why this prevents errors",
224
+ "applies_to": ["src/**"]
225
+ }
226
+ ],
227
+ "unitUpdates": [
228
+ {
229
+ "targetUnitId": "ARCH-SYS-001",
230
+ "appendDo": ["Additional positive instruction"],
231
+ "appendDont": ["Additional forbidden practice"],
232
+ "reason": "Reason for update"
233
+ }
234
+ ]
235
+ }`;
236
+ return await provider.generateJson(prompt);
237
+ }
238
+ /**
239
+ * Deterministically distills observations without LLM tokens.
240
+ */
241
+ distillDeterministic(observations, targetDir, poolDir) {
242
+ const newUnits = [];
243
+ const unitUpdates = [];
244
+ const graphBuilder = new GraphBuilder(targetDir, poolDir);
245
+ const existingInvariants = graphBuilder.loadKnowledgeUnits();
246
+ for (const obs of observations) {
247
+ if (!obs.finding)
248
+ continue;
249
+ // Check if observation matches an existing invariant by topic or file
250
+ let matchedUnit;
251
+ if (obs.associated_files && obs.associated_files.length > 0) {
252
+ for (const file of obs.associated_files) {
253
+ matchedUnit = existingInvariants.find(inv => graphBuilder.matchesAppliesTo(inv, file));
254
+ if (matchedUnit)
255
+ break;
256
+ }
257
+ }
258
+ if (!matchedUnit && obs.topic) {
259
+ const topicNorm = obs.topic.toLowerCase().replace(/[^a-z0-9]/g, '');
260
+ matchedUnit = existingInvariants.find(inv => {
261
+ const invIdNorm = inv.id.toLowerCase().replace(/[^a-z0-9]/g, '');
262
+ const invTitleNorm = inv.title.toLowerCase().replace(/[^a-z0-9]/g, '');
263
+ return invIdNorm.includes(topicNorm) || invTitleNorm.includes(topicNorm);
264
+ });
265
+ }
266
+ if (matchedUnit && obs.reproducible_fix) {
267
+ unitUpdates.push({
268
+ targetUnitId: matchedUnit.id,
269
+ appendDo: [obs.reproducible_fix],
270
+ appendDont: [`Do not repeat: ${obs.finding}`],
271
+ reason: `Consolidated observation: ${obs.finding}`
272
+ });
273
+ }
274
+ else {
275
+ const topicSlug = (obs.topic || 'convention')
276
+ .toUpperCase()
277
+ .replace(/[^A-Z0-9]/g, '-')
278
+ .slice(0, 12);
279
+ const hash = Math.random().toString(36).substring(2, 6).toUpperCase();
280
+ const id = `ADR-${topicSlug}-${hash}`;
281
+ newUnits.push({
282
+ id,
283
+ domain: 'decisions',
284
+ type: 'architecture_decision',
285
+ title: `${obs.topic || 'Runtime'}: Fix for ${obs.finding.slice(0, 40)}`,
286
+ decision: obs.reproducible_fix || obs.finding,
287
+ reason: obs.finding,
288
+ applies_to: obs.associated_files || []
289
+ });
290
+ }
291
+ }
292
+ return { newUnits, unitUpdates };
293
+ }
294
+ /**
295
+ * Updates observation files in .akb/sessions/ marking processed observation IDs as consolidated.
296
+ */
297
+ markObservationsConsolidated(poolDir, processedIds) {
298
+ if (processedIds.length === 0)
299
+ return;
300
+ const idSet = new Set(processedIds);
301
+ const sessionsBase = path.join(poolDir, '.akb', 'sessions');
302
+ if (!fs.existsSync(sessionsBase))
303
+ return;
304
+ const dirs = fs.readdirSync(sessionsBase).map(d => path.join(sessionsBase, d));
305
+ for (const d of dirs) {
306
+ const obsFile = path.join(d, 'observations.jsonl');
307
+ if (fs.existsSync(obsFile)) {
308
+ try {
309
+ const content = fs.readFileSync(obsFile, 'utf-8');
310
+ const lines = content.split('\n').filter(l => l.trim().length > 0);
311
+ const updatedLines = [];
312
+ for (const line of lines) {
313
+ try {
314
+ const obs = JSON.parse(line);
315
+ if (idSet.has(obs.id)) {
316
+ obs.status = 'consolidated';
317
+ }
318
+ updatedLines.push(JSON.stringify(obs));
319
+ }
320
+ catch {
321
+ updatedLines.push(line);
322
+ }
323
+ }
324
+ fs.writeFileSync(obsFile, updatedLines.join('\n') + '\n', 'utf-8');
325
+ }
326
+ catch { }
327
+ }
328
+ }
329
+ }
330
+ }
@@ -471,7 +471,11 @@ export class GraphBuilder {
471
471
  metadata: {
472
472
  rule: unit.rule,
473
473
  reason: unit.reason,
474
- applies_to: unit.applies_to
474
+ applies_to: unit.applies_to,
475
+ supersedes: unit.supersedes,
476
+ superseded_by: unit.superseded_by,
477
+ valid_from: unit.valid_from,
478
+ status: unit.status
475
479
  }
476
480
  });
477
481
  }
@@ -882,6 +886,12 @@ export class GraphBuilder {
882
886
  for (const rel of unit.related_items || []) {
883
887
  addEdge({ source: invId, target: `invariant:${rel}`, type: 'RELATES_TO' });
884
888
  }
889
+ if (unit.supersedes) {
890
+ addEdge({ source: invId, target: `invariant:${unit.supersedes}`, type: 'SUPERSEDES' });
891
+ }
892
+ if (unit.superseded_by) {
893
+ addEdge({ source: `invariant:${unit.superseded_by}`, target: invId, type: 'SUPERSEDES' });
894
+ }
885
895
  for (const proj of nonSolutionProjects) {
886
896
  const projFile = proj.file || '';
887
897
  const projDir = projFile ? path.dirname(projFile) : '';
@@ -951,6 +961,8 @@ export class GraphBuilder {
951
961
  continue;
952
962
  const projDir = path.dirname(proj.file).replace(/\\/g, '/');
953
963
  const isDirectMatch = normTarget === proj.file ||
964
+ projDir === '.' ||
965
+ projDir === '' ||
954
966
  normTarget.startsWith(projDir + '/') ||
955
967
  normTarget.toLowerCase().includes(projDir.toLowerCase() + '/');
956
968
  const isSubdirMatch = hasSpecificDir && projDir.toLowerCase().includes(targetDir.toLowerCase());
@@ -1046,6 +1058,12 @@ export class GraphBuilder {
1046
1058
  }
1047
1059
  }
1048
1060
  }
1061
+ // Invalidate/warn if any active invariant is superseded
1062
+ for (const inv of activeInvariants) {
1063
+ if (inv.superseded_by && !deprecationWarnings.some(w => w.includes(inv.id))) {
1064
+ deprecationWarnings.push(`Invariant ${inv.id} is SUPERSEDED by ${inv.superseded_by}. All new implementations must conform to ${inv.superseded_by}.`);
1065
+ }
1066
+ }
1049
1067
  // Build structured Markdown prompt slice
1050
1068
  const lines = [];
1051
1069
  if (deprecationWarnings.length > 0) {
@@ -0,0 +1,33 @@
1
+ export interface GuardViolation {
2
+ invariantId: string;
3
+ title: string;
4
+ rule: string;
5
+ forbiddenPattern: string;
6
+ severity: 'block' | 'warn';
7
+ reason: string;
8
+ }
9
+ export interface GuardEvaluationResult {
10
+ allowed: boolean;
11
+ targetFile: string;
12
+ violations: GuardViolation[];
13
+ warnings: string[];
14
+ }
15
+ export interface CheckStagedResult {
16
+ success: boolean;
17
+ filesChecked: number;
18
+ violations: Record<string, GuardViolation[]>;
19
+ warnings: Record<string, string[]>;
20
+ }
21
+ export declare class GuardService {
22
+ private targetDir;
23
+ private poolDir?;
24
+ constructor(targetDir?: string, poolDir?: string);
25
+ /**
26
+ * Evaluates proposed file content or diff against applicable invariants and architectural standards.
27
+ */
28
+ evaluate(filePath: string, contentOrDiff: string): GuardEvaluationResult;
29
+ /**
30
+ * Executes pre-commit / CI gate verification across git staged files.
31
+ */
32
+ checkStaged(): CheckStagedResult;
33
+ }
@@ -0,0 +1,167 @@
1
+ import path from 'node:path';
2
+ import { execSync } from 'node:child_process';
3
+ import { GraphBuilder } from './graph_builder.js';
4
+ import { StandardsLoader } from './standards_loader.js';
5
+ import { KnowledgePoolResolver } from './pool_resolver.js';
6
+ export class GuardService {
7
+ targetDir;
8
+ poolDir;
9
+ constructor(targetDir = process.cwd(), poolDir) {
10
+ this.targetDir = path.resolve(targetDir);
11
+ this.poolDir = poolDir;
12
+ }
13
+ /**
14
+ * Evaluates proposed file content or diff against applicable invariants and architectural standards.
15
+ */
16
+ evaluate(filePath, contentOrDiff) {
17
+ const poolConfig = KnowledgePoolResolver.resolve(this.targetDir, { explicitPoolDir: this.poolDir });
18
+ const graphBuilder = new GraphBuilder(this.targetDir, poolConfig.poolDir);
19
+ const invariants = graphBuilder.loadKnowledgeUnits();
20
+ const standards = StandardsLoader.load(this.targetDir, poolConfig.poolDir);
21
+ const normPath = filePath.replace(/\\/g, '/');
22
+ const applicableInvariants = invariants.filter(inv => graphBuilder.matchesAppliesTo(inv, normPath));
23
+ const violations = [];
24
+ const warnings = [];
25
+ // 1. Check deprecated patterns from .akb/standards.yaml
26
+ if (standards?.standards?.deprecated_patterns) {
27
+ for (const dep of standards.standards.deprecated_patterns) {
28
+ if (dep.appliesTo && !graphBuilder.matchesAppliesTo({ applies_to: [dep.appliesTo] }, normPath)) {
29
+ continue;
30
+ }
31
+ try {
32
+ const reg = new RegExp(dep.pattern, 'im');
33
+ if (reg.test(contentOrDiff)) {
34
+ violations.push({
35
+ invariantId: 'STANDARDS-DEPRECATED',
36
+ title: `Deprecated Pattern: ${dep.pattern}`,
37
+ rule: `Pattern "${dep.pattern}" is deprecated${dep.migrationTarget ? `. Migrate to ${dep.migrationTarget}` : ''}.`,
38
+ forbiddenPattern: dep.pattern,
39
+ severity: 'block',
40
+ reason: dep.reason || dep.description || 'Violates repository architectural standards.'
41
+ });
42
+ }
43
+ }
44
+ catch {
45
+ if (contentOrDiff.includes(dep.pattern)) {
46
+ violations.push({
47
+ invariantId: 'STANDARDS-DEPRECATED',
48
+ title: `Deprecated Pattern: ${dep.pattern}`,
49
+ rule: `Pattern "${dep.pattern}" is deprecated.`,
50
+ forbiddenPattern: dep.pattern,
51
+ severity: 'block',
52
+ reason: dep.reason || dep.description || 'Violates repository architectural standards.'
53
+ });
54
+ }
55
+ }
56
+ }
57
+ }
58
+ // 2. Check active Knowledge Units
59
+ for (const inv of applicableInvariants) {
60
+ if (inv.superseded_by) {
61
+ warnings.push(`Warning: Applicable invariant ${inv.id} has been superseded by ${inv.superseded_by}.`);
62
+ }
63
+ const dontItems = inv.dont || [];
64
+ for (const dont of dontItems) {
65
+ // Extract backticked code tokens or common forbidden code expressions (e.g. `require()`, `eval()`, `CommonJS require`)
66
+ const backtickMatches = dont.match(/`([^`]+)`/g);
67
+ const codeTokens = backtickMatches
68
+ ? backtickMatches.map(m => m.replace(/`/g, '').trim())
69
+ : [];
70
+ // Check explicit code tokens found in backticks
71
+ for (const token of codeTokens) {
72
+ if (token.length > 2 && contentOrDiff.includes(token)) {
73
+ violations.push({
74
+ invariantId: inv.id,
75
+ title: inv.title,
76
+ rule: inv.rule,
77
+ forbiddenPattern: token,
78
+ severity: inv.status === 'draft' ? 'warn' : 'block',
79
+ reason: `Violates "dont" directive: "${dont}". ${inv.reason}`
80
+ });
81
+ }
82
+ }
83
+ // Direct pattern matching for common keywords mentioned in "dont"
84
+ const patternsToTest = [
85
+ { keyword: 'require(', label: 'CommonJS require()' },
86
+ { keyword: 'eval(', label: 'eval()' },
87
+ { keyword: 'Thread.Sleep(', label: 'Thread.Sleep()' },
88
+ { keyword: 'DROP TABLE', label: 'Raw SQL DROP TABLE' },
89
+ { keyword: 'TRUNCATE TABLE', label: 'Raw SQL TRUNCATE TABLE' }
90
+ ];
91
+ for (const pt of patternsToTest) {
92
+ if (dont.toLowerCase().includes(pt.keyword.toLowerCase()) && contentOrDiff.includes(pt.keyword)) {
93
+ if (!violations.some(v => v.invariantId === inv.id && v.forbiddenPattern === pt.keyword)) {
94
+ violations.push({
95
+ invariantId: inv.id,
96
+ title: inv.title,
97
+ rule: inv.rule,
98
+ forbiddenPattern: pt.keyword,
99
+ severity: inv.status === 'draft' ? 'warn' : 'block',
100
+ reason: `Violates "dont" directive: "${dont}". ${inv.reason}`
101
+ });
102
+ }
103
+ }
104
+ }
105
+ }
106
+ }
107
+ const blockingViolations = violations.filter(v => v.severity === 'block');
108
+ return {
109
+ allowed: blockingViolations.length === 0,
110
+ targetFile: normPath,
111
+ violations,
112
+ warnings
113
+ };
114
+ }
115
+ /**
116
+ * Executes pre-commit / CI gate verification across git staged files.
117
+ */
118
+ checkStaged() {
119
+ const result = {
120
+ success: true,
121
+ filesChecked: 0,
122
+ violations: {},
123
+ warnings: {}
124
+ };
125
+ let stagedFilesStr = '';
126
+ try {
127
+ stagedFilesStr = execSync('git diff --cached --name-only', {
128
+ cwd: this.targetDir,
129
+ encoding: 'utf-8',
130
+ stdio: ['pipe', 'pipe', 'ignore']
131
+ }).trim();
132
+ }
133
+ catch {
134
+ return result;
135
+ }
136
+ if (!stagedFilesStr) {
137
+ return result;
138
+ }
139
+ const stagedFiles = stagedFilesStr
140
+ .split('\n')
141
+ .map(f => f.trim())
142
+ .filter(f => f.length > 0);
143
+ for (const file of stagedFiles) {
144
+ result.filesChecked++;
145
+ let diff = '';
146
+ try {
147
+ diff = execSync(`git diff --cached -- "${file}"`, {
148
+ cwd: this.targetDir,
149
+ encoding: 'utf-8',
150
+ stdio: ['pipe', 'pipe', 'ignore']
151
+ });
152
+ }
153
+ catch { }
154
+ if (!diff)
155
+ continue;
156
+ const evalRes = this.evaluate(file, diff);
157
+ if (!evalRes.allowed) {
158
+ result.success = false;
159
+ result.violations[file] = evalRes.violations;
160
+ }
161
+ if (evalRes.warnings.length > 0) {
162
+ result.warnings[file] = evalRes.warnings;
163
+ }
164
+ }
165
+ return result;
166
+ }
167
+ }
@@ -20,6 +20,14 @@ export declare class HookGenerator {
20
20
  writeMarkdownHook(filePath: string, content: string, options?: WriteHooksOptions): void;
21
21
  generateAgentsMd(index: ProposedIndex, units: KnowledgeUnitContent[]): string;
22
22
  generateClaudeMd(index: ProposedIndex, units: KnowledgeUnitContent[]): string;
23
+ /**
24
+ * Generates standard llms.txt file (compact index for LLMs and AI coding agents).
25
+ */
26
+ generateLlmsTxt(index: ProposedIndex, units: KnowledgeUnitContent[]): string;
27
+ /**
28
+ * Generates standard llms-full.txt file (comprehensive context including full invariant rules).
29
+ */
30
+ generateLlmsFullTxt(index: ProposedIndex, units: KnowledgeUnitContent[]): string;
23
31
  generateCursorRules(): string;
24
32
  generateMcpConfig(): string;
25
33
  writeAllHooks(index: ProposedIndex, units: KnowledgeUnitContent[], options?: WriteHooksOptions): string[];
@@ -104,6 +104,61 @@ ${invariants}
104
104
  generateClaudeMd(index, units) {
105
105
  return this.generateAgentsMd(index, units);
106
106
  }
107
+ /**
108
+ * Generates standard llms.txt file (compact index for LLMs and AI coding agents).
109
+ */
110
+ generateLlmsTxt(index, units) {
111
+ const systemName = index.system_name || 'System';
112
+ const desc = index.description || 'AI-Native Knowledge Base & Operational Architecture Standard';
113
+ const unitList = units.map(u => {
114
+ const summary = u.rule || u.decision || u.reason || '';
115
+ const cleanSummary = summary.length > 120 ? summary.slice(0, 117) + '...' : summary;
116
+ return `- [${u.title}](knowledge/${u.domain}/${u.id}.yaml): ${cleanSummary}`;
117
+ }).join('\n');
118
+ return `# ${systemName}
119
+
120
+ > ${desc}
121
+
122
+ ## Overview
123
+ This repository enforces an automated AI-Native Knowledge Base System (AKBO) with strict invariants.
124
+ Before executing tasks, coding agents must consult knowledge/index.yaml and adhere to active domain standards.
125
+
126
+ ## Core Directives & Commands
127
+ - Inspect context: \`akbo context <target-file>\`
128
+ - Search invariants: \`akbo invariants -f <file> -d <domain>\`
129
+ - Verify rules: \`akbo validate\`
130
+
131
+ ## Knowledge Base Units
132
+ ${unitList}
133
+ `;
134
+ }
135
+ /**
136
+ * Generates standard llms-full.txt file (comprehensive context including full invariant rules).
137
+ */
138
+ generateLlmsFullTxt(index, units) {
139
+ const systemName = index.system_name || 'System';
140
+ const desc = index.description || 'Comprehensive AI-Native Knowledge Base & Architecture Index';
141
+ const fullUnits = units.map(u => {
142
+ const isDecision = u.type === 'architecture_decision';
143
+ const body = isDecision
144
+ ? `**Decision**: ${u.decision || ''}\n**Context**: ${u.context || u.reason || ''}`
145
+ : `**Rule**: ${u.rule || ''}\n\n**Do**:\n${(u.do || []).map((d) => ` - ${d}`).join('\n')}\n\n**Don't**:\n${(u.dont || []).map((d) => ` - ${d}`).join('\n')}\n\n**Reason**: ${u.reason || ''}`;
146
+ return `### ${u.id}: ${u.title} (${u.domain})
147
+ - **Type**: ${u.type}
148
+ - **Status**: ${u.status || 'approved'}
149
+ - **Version**: ${u.version || '1.0.0'}
150
+ - **Applies To**: ${(u.applies_to || []).join(', ') || 'all'}
151
+
152
+ ${body}
153
+ `;
154
+ }).join('\n---\n\n');
155
+ return `# ${systemName} — Full AI Context
156
+
157
+ > ${desc}
158
+
159
+ ${fullUnits}
160
+ `;
161
+ }
107
162
  generateCursorRules() {
108
163
  return `# Cursor Rules - AI-Native Knowledge Base Protocol
109
164
  Always read knowledge/index.yaml first before proposing or executing code changes.
@@ -193,7 +248,18 @@ Keep README.md continuously updated in lockstep whenever adding or modifying CLI
193
248
  writtenFiles.push(cursorMcpPath);
194
249
  writeSafeMcpConfig(vscodeMcpPath);
195
250
  writtenFiles.push(vscodeMcpPath);
196
- // 4. JSON Schemas & .vscode/settings.json IDE autocomplete mappings
251
+ // 4. llms.txt & llms-full.txt
252
+ const llmsTxtContent = this.generateLlmsTxt(index, units);
253
+ const llmsTxtPath = path.join(this.repoRoot, 'llms.txt');
254
+ const llmsTxtEol = this.detectEol(llmsTxtPath);
255
+ fs.writeFileSync(llmsTxtPath, this.formatWithEol(llmsTxtContent, llmsTxtEol), 'utf-8');
256
+ writtenFiles.push(llmsTxtPath);
257
+ const llmsFullTxtContent = this.generateLlmsFullTxt(index, units);
258
+ const llmsFullTxtPath = path.join(this.repoRoot, 'llms-full.txt');
259
+ const llmsFullTxtEol = this.detectEol(llmsFullTxtPath);
260
+ fs.writeFileSync(llmsFullTxtPath, this.formatWithEol(llmsFullTxtContent, llmsFullTxtEol), 'utf-8');
261
+ writtenFiles.push(llmsFullTxtPath);
262
+ // 5. JSON Schemas & .vscode/settings.json IDE autocomplete mappings
197
263
  const schemaGen = new SchemaGenerator(this.repoRoot);
198
264
  const { writtenSchemas, settingsPath } = schemaGen.writeAll();
199
265
  writtenFiles.push(...writtenSchemas);