akbo-cli 0.0.0-stage → 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.
Files changed (70) hide show
  1. package/README.md +786 -2
  2. package/dist/catalog_store.d.ts +131 -0
  3. package/dist/catalog_store.js +506 -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 +1961 -0
  8. package/dist/dream_engine.d.ts +61 -0
  9. package/dist/dream_engine.js +330 -0
  10. package/dist/extractors/base.d.ts +35 -0
  11. package/dist/extractors/base.js +17 -0
  12. package/dist/extractors/custom_extractor.d.ts +55 -0
  13. package/dist/extractors/custom_extractor.js +198 -0
  14. package/dist/extractors/dotnet_extractor.d.ts +11 -0
  15. package/dist/extractors/dotnet_extractor.js +579 -0
  16. package/dist/extractors/golang_extractor.d.ts +11 -0
  17. package/dist/extractors/golang_extractor.js +73 -0
  18. package/dist/extractors/index.d.ts +14 -0
  19. package/dist/extractors/index.js +30 -0
  20. package/dist/extractors/jvm_extractor.d.ts +11 -0
  21. package/dist/extractors/jvm_extractor.js +319 -0
  22. package/dist/extractors/node_extractor.d.ts +11 -0
  23. package/dist/extractors/node_extractor.js +306 -0
  24. package/dist/extractors/proto_graphql_extractor.d.ts +11 -0
  25. package/dist/extractors/proto_graphql_extractor.js +125 -0
  26. package/dist/extractors/python_extractor.d.ts +11 -0
  27. package/dist/extractors/python_extractor.js +298 -0
  28. package/dist/extractors/rust_extractor.d.ts +11 -0
  29. package/dist/extractors/rust_extractor.js +66 -0
  30. package/dist/graph_builder.d.ts +87 -0
  31. package/dist/graph_builder.js +1516 -0
  32. package/dist/guard_service.d.ts +33 -0
  33. package/dist/guard_service.js +167 -0
  34. package/dist/harvester.d.ts +38 -0
  35. package/dist/harvester.js +461 -0
  36. package/dist/hook_generator.d.ts +34 -0
  37. package/dist/hook_generator.js +269 -0
  38. package/dist/importers/skill_importer.d.ts +43 -0
  39. package/dist/importers/skill_importer.js +470 -0
  40. package/dist/index.d.ts +20 -0
  41. package/dist/index.js +20 -0
  42. package/dist/indexer.d.ts +19 -0
  43. package/dist/indexer.js +108 -0
  44. package/dist/init_service.d.ts +37 -0
  45. package/dist/init_service.js +246 -0
  46. package/dist/mcp_server.d.ts +10 -0
  47. package/dist/mcp_server.js +846 -0
  48. package/dist/pool_resolver.d.ts +40 -0
  49. package/dist/pool_resolver.js +84 -0
  50. package/dist/provider.d.ts +135 -0
  51. package/dist/provider.js +880 -0
  52. package/dist/query_service.d.ts +33 -0
  53. package/dist/query_service.js +161 -0
  54. package/dist/schema_generator.d.ts +236 -0
  55. package/dist/schema_generator.js +264 -0
  56. package/dist/standards_loader.d.ts +7 -0
  57. package/dist/standards_loader.js +33 -0
  58. package/dist/types.d.ts +323 -0
  59. package/dist/types.js +123 -0
  60. package/dist/unit_synthesizer.d.ts +22 -0
  61. package/dist/unit_synthesizer.js +196 -0
  62. package/dist/validator.d.ts +13 -0
  63. package/dist/validator.js +152 -0
  64. package/dist/version.d.ts +6 -0
  65. package/dist/version.js +16 -0
  66. package/dist/watcher.d.ts +38 -0
  67. package/dist/watcher.js +132 -0
  68. package/package.json +56 -6
  69. package/schemas/index-schema.json +98 -0
  70. package/schemas/knowledge-unit.json +154 -0
@@ -0,0 +1,131 @@
1
+ import { type ValidationResult } from './validator.js';
2
+ import { type AgentObservation, type StagedKnowledgeUnitProposal } from './types.js';
3
+ export interface UpsertUnitsOptions {
4
+ targetDir: string;
5
+ poolDir?: string;
6
+ validate?: boolean;
7
+ }
8
+ export interface UpsertResult {
9
+ success: boolean;
10
+ count: number;
11
+ units: string[];
12
+ validation?: ValidationResult;
13
+ error?: string;
14
+ }
15
+ export interface GetUnitResult {
16
+ id: string;
17
+ domain: string;
18
+ file: string;
19
+ fullPath: string;
20
+ unit: Record<string, any>;
21
+ rawYaml: string;
22
+ }
23
+ export interface DeleteUnitResult {
24
+ success: boolean;
25
+ deletedId: string;
26
+ filePath?: string;
27
+ validation?: ValidationResult;
28
+ error?: string;
29
+ }
30
+ /**
31
+ * Detects whether content uses CRLF or LF line endings.
32
+ * Falls back to Windows default (\r\n) or POSIX default (\n).
33
+ */
34
+ export declare function detectEol(content?: string): string;
35
+ /**
36
+ * Normalizes text to the target EOL sequence (\r\n or \n).
37
+ */
38
+ export declare function normalizeEol(text: string, eol: string): string;
39
+ /**
40
+ * Normalizes applies_to glob patterns:
41
+ * - Converts backslashes (\) to POSIX slashes (/)
42
+ * - Strips leading ./
43
+ * - Strips repository root folder name prefix if present (e.g. "Monorepo/Subproject/**" -> "Subproject/**")
44
+ */
45
+ export declare function normalizeAppliesTo(patterns?: string[], repoRoot?: string): string[];
46
+ /**
47
+ * Atomically writes content to a file via a temporary file and rename,
48
+ * preserving target or detected EOL line endings.
49
+ */
50
+ export declare function atomicWriteFile(targetPath: string, content: string, explicitEol?: string): void;
51
+ /**
52
+ * Parses raw JSON or YAML text into an array of knowledge unit definitions.
53
+ * Defensively strips UTF-8 Byte Order Mark (BOM: \uFEFF) emitted by PowerShell.
54
+ */
55
+ export declare function parseUnitsFromText(rawText: string): Array<Record<string, any>>;
56
+ export declare class CatalogStore {
57
+ /**
58
+ * Upserts one or more knowledge units atomically into the pool's knowledge directory,
59
+ * updates knowledge/index.yaml once with atomic rename and EOL preservation,
60
+ * and optionally executes runtime validation.
61
+ */
62
+ static upsertUnits(units: Array<Record<string, any>>, options: UpsertUnitsOptions): Promise<UpsertResult>;
63
+ /**
64
+ * Retrieves a knowledge unit by ID from the knowledge pool.
65
+ */
66
+ static getUnit(id: string, options: {
67
+ targetDir: string;
68
+ poolDir?: string;
69
+ }): GetUnitResult | null;
70
+ /**
71
+ * Deletes a knowledge unit from the pool, removes its index reference,
72
+ * decrements unit count, clears caches, and optionally validates.
73
+ */
74
+ static deleteUnit(id: string, options: {
75
+ targetDir: string;
76
+ poolDir?: string;
77
+ validate?: boolean;
78
+ }): Promise<DeleteUnitResult>;
79
+ /**
80
+ * Records a task-level observation into an isolated agent session log (.akb/sessions/<agent_id>/observations.jsonl).
81
+ */
82
+ static recordObservation(options: {
83
+ targetDir: string;
84
+ poolDir?: string;
85
+ agentId?: string;
86
+ topic: string;
87
+ finding: string;
88
+ reproducible_fix?: string;
89
+ associated_files?: string[];
90
+ }): AgentObservation;
91
+ /**
92
+ * Retrieves all recorded observations across all agent sessions or for a specific agent.
93
+ */
94
+ static listObservations(options: {
95
+ targetDir: string;
96
+ poolDir?: string;
97
+ agentId?: string;
98
+ }): AgentObservation[];
99
+ /**
100
+ * Retrieves an agent's isolated session scratchpad markdown content.
101
+ */
102
+ static getScratchpad(options: {
103
+ targetDir: string;
104
+ poolDir?: string;
105
+ agentId?: string;
106
+ }): string;
107
+ /**
108
+ * Updates an agent's isolated session scratchpad markdown content.
109
+ */
110
+ static updateScratchpad(options: {
111
+ targetDir: string;
112
+ poolDir?: string;
113
+ agentId?: string;
114
+ content: string;
115
+ append?: boolean;
116
+ }): string;
117
+ /**
118
+ * Stages a proposed knowledge unit or rule update into .akb/staged/ before consolidation.
119
+ */
120
+ static stageProposal(proposal: StagedKnowledgeUnitProposal, options: {
121
+ targetDir: string;
122
+ poolDir?: string;
123
+ }): StagedKnowledgeUnitProposal;
124
+ /**
125
+ * Lists all currently staged knowledge proposals.
126
+ */
127
+ static listStagedProposals(options: {
128
+ targetDir: string;
129
+ poolDir?: string;
130
+ }): StagedKnowledgeUnitProposal[];
131
+ }
@@ -0,0 +1,506 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import YAML from 'yaml';
4
+ import { KnowledgePoolResolver } from './pool_resolver.js';
5
+ import { KnowledgeValidator } from './validator.js';
6
+ import { GraphBuilder } from './graph_builder.js';
7
+ import { StandardKnowledgeUnitSchema, DecisionKnowledgeUnitSchema } from './types.js';
8
+ /**
9
+ * Detects whether content uses CRLF or LF line endings.
10
+ * Falls back to Windows default (\r\n) or POSIX default (\n).
11
+ */
12
+ export function detectEol(content) {
13
+ if (content) {
14
+ if (content.includes('\r\n'))
15
+ return '\r\n';
16
+ if (content.includes('\n'))
17
+ return '\n';
18
+ }
19
+ return process.platform === 'win32' ? '\r\n' : '\n';
20
+ }
21
+ /**
22
+ * Normalizes text to the target EOL sequence (\r\n or \n).
23
+ */
24
+ export function normalizeEol(text, eol) {
25
+ const lf = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
26
+ return eol === '\n' ? lf : lf.replace(/\n/g, eol);
27
+ }
28
+ /**
29
+ * Normalizes applies_to glob patterns:
30
+ * - Converts backslashes (\) to POSIX slashes (/)
31
+ * - Strips leading ./
32
+ * - Strips repository root folder name prefix if present (e.g. "Monorepo/Subproject/**" -> "Subproject/**")
33
+ */
34
+ export function normalizeAppliesTo(patterns = [], repoRoot) {
35
+ const repoBase = repoRoot ? path.basename(repoRoot).toLowerCase() : undefined;
36
+ return patterns.map(pat => {
37
+ let p = pat.replace(/\\/g, '/').replace(/^\.\//, '');
38
+ if (repoBase && p.toLowerCase().startsWith(`${repoBase}/`)) {
39
+ p = p.slice(repoBase.length + 1);
40
+ }
41
+ return p;
42
+ });
43
+ }
44
+ /**
45
+ * Atomically writes content to a file via a temporary file and rename,
46
+ * preserving target or detected EOL line endings.
47
+ */
48
+ export function atomicWriteFile(targetPath, content, explicitEol) {
49
+ const dir = path.dirname(targetPath);
50
+ if (!fs.existsSync(dir)) {
51
+ fs.mkdirSync(dir, { recursive: true });
52
+ }
53
+ let existingContent;
54
+ if (fs.existsSync(targetPath)) {
55
+ try {
56
+ existingContent = fs.readFileSync(targetPath, 'utf-8');
57
+ }
58
+ catch { }
59
+ }
60
+ const targetEol = explicitEol || detectEol(existingContent);
61
+ const formattedContent = normalizeEol(content, targetEol);
62
+ const tmpPath = `${targetPath}.${Date.now()}.${Math.random().toString(36).substring(2, 8)}.tmp`;
63
+ fs.writeFileSync(tmpPath, formattedContent, 'utf-8');
64
+ fs.renameSync(tmpPath, targetPath);
65
+ }
66
+ /**
67
+ * Parses raw JSON or YAML text into an array of knowledge unit definitions.
68
+ * Defensively strips UTF-8 Byte Order Mark (BOM: \uFEFF) emitted by PowerShell.
69
+ */
70
+ export function parseUnitsFromText(rawText) {
71
+ const clean = rawText.replace(/^\uFEFF/, '').trim();
72
+ if (!clean)
73
+ return [];
74
+ let parsed;
75
+ if (clean.startsWith('{') || clean.startsWith('[')) {
76
+ try {
77
+ parsed = JSON.parse(clean);
78
+ }
79
+ catch {
80
+ parsed = YAML.parse(clean);
81
+ }
82
+ }
83
+ else {
84
+ parsed = YAML.parse(clean);
85
+ }
86
+ if (Array.isArray(parsed)) {
87
+ return parsed;
88
+ }
89
+ if (parsed && Array.isArray(parsed.units)) {
90
+ return parsed.units;
91
+ }
92
+ if (parsed && typeof parsed === 'object') {
93
+ return [parsed];
94
+ }
95
+ return [];
96
+ }
97
+ export class CatalogStore {
98
+ /**
99
+ * Upserts one or more knowledge units atomically into the pool's knowledge directory,
100
+ * updates knowledge/index.yaml once with atomic rename and EOL preservation,
101
+ * and optionally executes runtime validation.
102
+ */
103
+ static async upsertUnits(units, options) {
104
+ if (!units || units.length === 0) {
105
+ return { success: true, count: 0, units: [] };
106
+ }
107
+ const targetDir = path.resolve(options.targetDir);
108
+ const poolConfig = KnowledgePoolResolver.resolve(targetDir, { explicitPoolDir: options.poolDir });
109
+ const savedUnits = [];
110
+ // Process and validate all units before writing
111
+ const validatedData = [];
112
+ for (const unit of units) {
113
+ if (!unit.id || typeof unit.id !== 'string') {
114
+ return { success: false, count: 0, units: [], error: 'Every unit must have a non-empty string "id".' };
115
+ }
116
+ const domain = (unit.domain || 'development').trim();
117
+ const isDecision = unit.type === 'architecture_decision' || domain === 'decisions' || typeof unit.decision === 'string';
118
+ let validUnit;
119
+ if (isDecision) {
120
+ const payload = {
121
+ id: unit.id,
122
+ type: 'architecture_decision',
123
+ title: unit.title || unit.id,
124
+ domain: 'decisions',
125
+ decision: unit.decision || unit.rule || '',
126
+ context: unit.context || unit.reason || undefined,
127
+ status: unit.status || 'approved',
128
+ version: unit.version || '1.0.0',
129
+ authority: unit.authority || { level: 'human_curated', confidence: 'verified' },
130
+ owner: unit.owner || { team: 'core_architecture' },
131
+ applies_to: normalizeAppliesTo(unit.applies_to || [], targetDir),
132
+ related_items: unit.related_items || []
133
+ };
134
+ const validation = DecisionKnowledgeUnitSchema.safeParse(payload);
135
+ if (!validation.success) {
136
+ return {
137
+ success: false,
138
+ count: 0,
139
+ units: [],
140
+ error: `Validation failed for decision unit "${unit.id}": ${validation.error.message}`
141
+ };
142
+ }
143
+ validUnit = validation.data;
144
+ }
145
+ else {
146
+ const payload = {
147
+ id: unit.id,
148
+ type: unit.type || 'development_standard',
149
+ title: unit.title || unit.id,
150
+ domain,
151
+ status: unit.status || 'approved',
152
+ version: unit.version || '1.0.0',
153
+ authority: unit.authority || { level: 'human_curated', confidence: 'verified' },
154
+ owner: unit.owner || { team: 'core_architecture' },
155
+ applies_to: normalizeAppliesTo(unit.applies_to || [], targetDir),
156
+ rule: unit.rule || '',
157
+ do: Array.isArray(unit.do) && unit.do.length > 0 ? unit.do : ['Follow the standard rule directives.'],
158
+ dont: Array.isArray(unit.dont) && unit.dont.length > 0 ? unit.dont : ['Do not violate the standard rule directives.'],
159
+ reason: unit.reason || 'Guarantees architectural compliance and system consistency.',
160
+ related_items: unit.related_items || []
161
+ };
162
+ const validation = StandardKnowledgeUnitSchema.safeParse(payload);
163
+ if (!validation.success) {
164
+ return {
165
+ success: false,
166
+ count: 0,
167
+ units: [],
168
+ error: `Validation failed for unit "${unit.id}": ${validation.error.message}`
169
+ };
170
+ }
171
+ validUnit = validation.data;
172
+ }
173
+ const domainDir = path.join(poolConfig.knowledgeDir, validUnit.domain);
174
+ const unitFilePath = path.join(domainDir, `${validUnit.id}.yaml`);
175
+ const yamlString = YAML.stringify(validUnit);
176
+ validatedData.push({
177
+ filePath: unitFilePath,
178
+ yamlString,
179
+ id: validUnit.id,
180
+ domain: validUnit.domain,
181
+ title: validUnit.title
182
+ });
183
+ }
184
+ // Write all validated unit files atomically
185
+ for (const item of validatedData) {
186
+ atomicWriteFile(item.filePath, item.yamlString);
187
+ savedUnits.push({ id: item.id, domain: item.domain, title: item.title });
188
+ }
189
+ // Update poolDir/knowledge/index.yaml once atomically
190
+ const indexPath = path.join(poolConfig.knowledgeDir, 'index.yaml');
191
+ let indexObj = {
192
+ system_name: path.basename(targetDir),
193
+ repository_root: targetDir.replace(/\\/g, '/'),
194
+ knowledge_units_count: 0,
195
+ last_updated: new Date().toISOString().split('T')[0],
196
+ knowledge_units: {}
197
+ };
198
+ let existingIndexRaw;
199
+ if (fs.existsSync(indexPath)) {
200
+ try {
201
+ existingIndexRaw = fs.readFileSync(indexPath, 'utf-8');
202
+ indexObj = YAML.parse(existingIndexRaw) || indexObj;
203
+ }
204
+ catch { }
205
+ }
206
+ if (!indexObj.repository_root) {
207
+ indexObj.repository_root = targetDir.replace(/\\/g, '/');
208
+ }
209
+ indexObj.knowledge_units = indexObj.knowledge_units || {};
210
+ for (const saved of savedUnits) {
211
+ indexObj.knowledge_units[saved.domain] = indexObj.knowledge_units[saved.domain] || [];
212
+ const domainList = indexObj.knowledge_units[saved.domain];
213
+ const existingIdx = domainList.findIndex((u) => u.id === saved.id);
214
+ const entry = {
215
+ id: saved.id,
216
+ file: `knowledge/${saved.domain}/${saved.id}.yaml`,
217
+ title: saved.title
218
+ };
219
+ if (existingIdx >= 0) {
220
+ domainList[existingIdx] = entry;
221
+ }
222
+ else {
223
+ domainList.push(entry);
224
+ }
225
+ }
226
+ let totalCount = 0;
227
+ for (const d of Object.keys(indexObj.knowledge_units)) {
228
+ if (Array.isArray(indexObj.knowledge_units[d])) {
229
+ totalCount += indexObj.knowledge_units[d].length;
230
+ }
231
+ }
232
+ indexObj.knowledge_units_count = totalCount;
233
+ indexObj.last_updated = new Date().toISOString().split('T')[0];
234
+ atomicWriteFile(indexPath, YAML.stringify(indexObj), detectEol(existingIndexRaw));
235
+ // Invalidate caches
236
+ GraphBuilder.clearCache();
237
+ let validationResult;
238
+ if (options.validate) {
239
+ const validator = new KnowledgeValidator(targetDir, poolConfig.poolDir);
240
+ validationResult = await validator.validate();
241
+ }
242
+ return {
243
+ success: true,
244
+ count: savedUnits.length,
245
+ units: savedUnits.map(u => u.id),
246
+ validation: validationResult
247
+ };
248
+ }
249
+ /**
250
+ * Retrieves a knowledge unit by ID from the knowledge pool.
251
+ */
252
+ static getUnit(id, options) {
253
+ const targetDir = path.resolve(options.targetDir);
254
+ const poolConfig = KnowledgePoolResolver.resolve(targetDir, { explicitPoolDir: options.poolDir });
255
+ const kDir = poolConfig.knowledgeDir;
256
+ if (!fs.existsSync(kDir))
257
+ return null;
258
+ // First check index.yaml
259
+ const indexPath = path.join(kDir, 'index.yaml');
260
+ let targetRelFile;
261
+ if (fs.existsSync(indexPath)) {
262
+ try {
263
+ const indexDoc = YAML.parse(fs.readFileSync(indexPath, 'utf-8'));
264
+ if (indexDoc?.knowledge_units) {
265
+ for (const d of Object.keys(indexDoc.knowledge_units)) {
266
+ const list = indexDoc.knowledge_units[d];
267
+ if (Array.isArray(list)) {
268
+ const match = list.find((item) => item.id === id);
269
+ if (match && match.file) {
270
+ targetRelFile = match.file;
271
+ break;
272
+ }
273
+ }
274
+ }
275
+ }
276
+ }
277
+ catch { }
278
+ }
279
+ let fullPath = targetRelFile ? path.resolve(poolConfig.poolDir, targetRelFile) : undefined;
280
+ if (!fullPath || !fs.existsSync(fullPath)) {
281
+ // Direct file search across knowledge/<domain>/<id>.yaml
282
+ try {
283
+ const entries = fs.readdirSync(kDir, { withFileTypes: true });
284
+ for (const entry of entries) {
285
+ if (entry.isDirectory()) {
286
+ const candidate = path.join(kDir, entry.name, `${id}.yaml`);
287
+ const candidateYml = path.join(kDir, entry.name, `${id}.yml`);
288
+ if (fs.existsSync(candidate)) {
289
+ fullPath = candidate;
290
+ break;
291
+ }
292
+ if (fs.existsSync(candidateYml)) {
293
+ fullPath = candidateYml;
294
+ break;
295
+ }
296
+ }
297
+ }
298
+ }
299
+ catch { }
300
+ }
301
+ if (!fullPath || !fs.existsSync(fullPath)) {
302
+ return null;
303
+ }
304
+ const rawYaml = fs.readFileSync(fullPath, 'utf-8');
305
+ const unit = YAML.parse(rawYaml) || {};
306
+ const domain = unit.domain || path.basename(path.dirname(fullPath));
307
+ const relFile = path.relative(poolConfig.poolDir, fullPath).replace(/\\/g, '/');
308
+ return {
309
+ id: unit.id || id,
310
+ domain,
311
+ file: relFile,
312
+ fullPath,
313
+ unit,
314
+ rawYaml
315
+ };
316
+ }
317
+ /**
318
+ * Deletes a knowledge unit from the pool, removes its index reference,
319
+ * decrements unit count, clears caches, and optionally validates.
320
+ */
321
+ static async deleteUnit(id, options) {
322
+ const targetDir = path.resolve(options.targetDir);
323
+ const poolConfig = KnowledgePoolResolver.resolve(targetDir, { explicitPoolDir: options.poolDir });
324
+ const existing = CatalogStore.getUnit(id, options);
325
+ if (!existing) {
326
+ return {
327
+ success: false,
328
+ deletedId: id,
329
+ error: `Knowledge unit "${id}" was not found in knowledge pool.`
330
+ };
331
+ }
332
+ // Delete the YAML file
333
+ if (fs.existsSync(existing.fullPath)) {
334
+ fs.unlinkSync(existing.fullPath);
335
+ }
336
+ // Update index.yaml
337
+ const indexPath = path.join(poolConfig.knowledgeDir, 'index.yaml');
338
+ let existingIndexRaw;
339
+ if (fs.existsSync(indexPath)) {
340
+ try {
341
+ existingIndexRaw = fs.readFileSync(indexPath, 'utf-8');
342
+ const indexObj = YAML.parse(existingIndexRaw);
343
+ if (indexObj?.knowledge_units) {
344
+ for (const d of Object.keys(indexObj.knowledge_units)) {
345
+ if (Array.isArray(indexObj.knowledge_units[d])) {
346
+ indexObj.knowledge_units[d] = indexObj.knowledge_units[d].filter((u) => u.id !== id);
347
+ }
348
+ }
349
+ let total = 0;
350
+ for (const d of Object.keys(indexObj.knowledge_units)) {
351
+ if (Array.isArray(indexObj.knowledge_units[d])) {
352
+ total += indexObj.knowledge_units[d].length;
353
+ }
354
+ }
355
+ indexObj.knowledge_units_count = total;
356
+ indexObj.last_updated = new Date().toISOString().split('T')[0];
357
+ atomicWriteFile(indexPath, YAML.stringify(indexObj), detectEol(existingIndexRaw));
358
+ }
359
+ }
360
+ catch { }
361
+ }
362
+ GraphBuilder.clearCache();
363
+ let validationResult;
364
+ if (options.validate) {
365
+ const validator = new KnowledgeValidator(targetDir, poolConfig.poolDir);
366
+ validationResult = await validator.validate();
367
+ }
368
+ return {
369
+ success: true,
370
+ deletedId: id,
371
+ filePath: existing.fullPath,
372
+ validation: validationResult
373
+ };
374
+ }
375
+ /**
376
+ * Records a task-level observation into an isolated agent session log (.akb/sessions/<agent_id>/observations.jsonl).
377
+ */
378
+ static recordObservation(options) {
379
+ const targetDir = path.resolve(options.targetDir);
380
+ const poolConfig = KnowledgePoolResolver.resolve(targetDir, { explicitPoolDir: options.poolDir });
381
+ const agentId = (options.agentId || 'default').replace(/[^a-zA-Z0-9_-]/g, '_');
382
+ const sessionDir = path.join(poolConfig.poolDir, '.akb', 'sessions', agentId);
383
+ if (!fs.existsSync(sessionDir)) {
384
+ fs.mkdirSync(sessionDir, { recursive: true });
385
+ }
386
+ const obs = {
387
+ id: `obs-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`,
388
+ timestamp: new Date().toISOString(),
389
+ agentId,
390
+ topic: options.topic,
391
+ finding: options.finding,
392
+ reproducible_fix: options.reproducible_fix,
393
+ associated_files: options.associated_files || [],
394
+ status: 'recorded'
395
+ };
396
+ const obsFile = path.join(sessionDir, 'observations.jsonl');
397
+ const line = JSON.stringify(obs) + '\n';
398
+ fs.appendFileSync(obsFile, line, 'utf-8');
399
+ return obs;
400
+ }
401
+ /**
402
+ * Retrieves all recorded observations across all agent sessions or for a specific agent.
403
+ */
404
+ static listObservations(options) {
405
+ const targetDir = path.resolve(options.targetDir);
406
+ const poolConfig = KnowledgePoolResolver.resolve(targetDir, { explicitPoolDir: options.poolDir });
407
+ const sessionsBase = path.join(poolConfig.poolDir, '.akb', 'sessions');
408
+ if (!fs.existsSync(sessionsBase)) {
409
+ return [];
410
+ }
411
+ const results = [];
412
+ const agentDirs = options.agentId
413
+ ? [path.join(sessionsBase, options.agentId.replace(/[^a-zA-Z0-9_-]/g, '_'))]
414
+ : fs.readdirSync(sessionsBase).map(d => path.join(sessionsBase, d));
415
+ for (const d of agentDirs) {
416
+ const obsFile = path.join(d, 'observations.jsonl');
417
+ if (fs.existsSync(obsFile)) {
418
+ try {
419
+ const content = fs.readFileSync(obsFile, 'utf-8');
420
+ const lines = content.split('\n').filter(l => l.trim().length > 0);
421
+ for (const l of lines) {
422
+ try {
423
+ results.push(JSON.parse(l));
424
+ }
425
+ catch { }
426
+ }
427
+ }
428
+ catch { }
429
+ }
430
+ }
431
+ return results;
432
+ }
433
+ /**
434
+ * Retrieves an agent's isolated session scratchpad markdown content.
435
+ */
436
+ static getScratchpad(options) {
437
+ const targetDir = path.resolve(options.targetDir);
438
+ const poolConfig = KnowledgePoolResolver.resolve(targetDir, { explicitPoolDir: options.poolDir });
439
+ const agentId = (options.agentId || 'default').replace(/[^a-zA-Z0-9_-]/g, '_');
440
+ const padFile = path.join(poolConfig.poolDir, '.akb', 'sessions', agentId, 'scratchpad.md');
441
+ if (fs.existsSync(padFile)) {
442
+ try {
443
+ return fs.readFileSync(padFile, 'utf-8');
444
+ }
445
+ catch { }
446
+ }
447
+ return '';
448
+ }
449
+ /**
450
+ * Updates an agent's isolated session scratchpad markdown content.
451
+ */
452
+ static updateScratchpad(options) {
453
+ const targetDir = path.resolve(options.targetDir);
454
+ const poolConfig = KnowledgePoolResolver.resolve(targetDir, { explicitPoolDir: options.poolDir });
455
+ const agentId = (options.agentId || 'default').replace(/[^a-zA-Z0-9_-]/g, '_');
456
+ const sessionDir = path.join(poolConfig.poolDir, '.akb', 'sessions', agentId);
457
+ if (!fs.existsSync(sessionDir)) {
458
+ fs.mkdirSync(sessionDir, { recursive: true });
459
+ }
460
+ const padFile = path.join(sessionDir, 'scratchpad.md');
461
+ const existing = fs.existsSync(padFile) ? fs.readFileSync(padFile, 'utf-8') : '';
462
+ const newContent = options.append
463
+ ? existing + (existing.endsWith('\n') ? '' : '\n') + options.content + '\n'
464
+ : options.content;
465
+ atomicWriteFile(padFile, newContent);
466
+ return newContent;
467
+ }
468
+ /**
469
+ * Stages a proposed knowledge unit or rule update into .akb/staged/ before consolidation.
470
+ */
471
+ static stageProposal(proposal, options) {
472
+ const targetDir = path.resolve(options.targetDir);
473
+ const poolConfig = KnowledgePoolResolver.resolve(targetDir, { explicitPoolDir: options.poolDir });
474
+ const stagedDir = path.join(poolConfig.poolDir, '.akb', 'staged');
475
+ if (!fs.existsSync(stagedDir)) {
476
+ fs.mkdirSync(stagedDir, { recursive: true });
477
+ }
478
+ const file = path.join(stagedDir, `${proposal.id}.yaml`);
479
+ atomicWriteFile(file, YAML.stringify(proposal));
480
+ return proposal;
481
+ }
482
+ /**
483
+ * Lists all currently staged knowledge proposals.
484
+ */
485
+ static listStagedProposals(options) {
486
+ const targetDir = path.resolve(options.targetDir);
487
+ const poolConfig = KnowledgePoolResolver.resolve(targetDir, { explicitPoolDir: options.poolDir });
488
+ const stagedDir = path.join(poolConfig.poolDir, '.akb', 'staged');
489
+ if (!fs.existsSync(stagedDir)) {
490
+ return [];
491
+ }
492
+ const files = fs.readdirSync(stagedDir).filter(f => f.endsWith('.yaml') || f.endsWith('.yml'));
493
+ const proposals = [];
494
+ for (const f of files) {
495
+ try {
496
+ const content = fs.readFileSync(path.join(stagedDir, f), 'utf-8');
497
+ const parsed = YAML.parse(content);
498
+ if (parsed && parsed.id) {
499
+ proposals.push(parsed);
500
+ }
501
+ }
502
+ catch { }
503
+ }
504
+ return proposals;
505
+ }
506
+ }
@@ -0,0 +1,11 @@
1
+ export interface CleanOptions {
2
+ includeDist?: boolean;
3
+ }
4
+ export interface CleanResult {
5
+ removed: string[];
6
+ totalBytesFreed: number;
7
+ }
8
+ /**
9
+ * Safely removes intermediate and temporary AKBO artifacts while preserving user configurations.
10
+ */
11
+ export declare function cleanArtifacts(dir: string, options?: CleanOptions): CleanResult;