@technomoron/agent-brain 0.0.0-stage → 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.
Files changed (39) hide show
  1. package/CHANGES.md +18 -0
  2. package/LICENSE +21 -0
  3. package/README.md +855 -2
  4. package/dist/agent-brain.js +6 -0
  5. package/dist/brain/built-in-skills.js +24 -0
  6. package/dist/brain/cli.js +265 -0
  7. package/dist/brain/config.js +92 -0
  8. package/dist/brain/connectors.js +63 -0
  9. package/dist/brain/consolidation-skill.js +5 -0
  10. package/dist/brain/consolidation.js +134 -0
  11. package/dist/brain/git.js +139 -0
  12. package/dist/brain/github-reviews.js +174 -0
  13. package/dist/brain/projects.js +136 -0
  14. package/dist/brain/remote-policy.js +126 -0
  15. package/dist/brain/remote-server.js +211 -0
  16. package/dist/brain/repositories.js +28 -0
  17. package/dist/brain/repository-discovery.js +76 -0
  18. package/dist/brain/server.js +283 -0
  19. package/dist/brain/skills.js +54 -0
  20. package/dist/brain/store.js +499 -0
  21. package/dist/brain/todos.js +155 -0
  22. package/dist/brain/windows-pipe.js +19 -0
  23. package/dist/version.js +22 -0
  24. package/examples/brain.jsonc +7 -0
  25. package/examples/remote.jsonc +22 -0
  26. package/ops/config-deploy-entry.sh +3 -0
  27. package/ops/config-deploy-root.cjs +111 -0
  28. package/ops/config-deploy.cjs +176 -0
  29. package/ops/config-policy.cjs +220 -0
  30. package/ops/config-sync.cjs +72 -0
  31. package/ops/systemd/agent-brain.service +14 -0
  32. package/package.json +55 -4
  33. package/skills/brain-consolidate/SKILL.md +42 -0
  34. package/skills/brain-import/SKILL.md +56 -0
  35. package/skills/brain-memory/SKILL.md +73 -0
  36. package/skills/brain-review/SKILL.md +38 -0
  37. package/skills/code-review-organizer/SKILL.md +150 -0
  38. package/skills/review-items/SKILL.md +43 -0
  39. package/skills/todo-manager/SKILL.md +8 -0
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getSkills = getSkills;
4
+ exports.listSkills = listSkills;
5
+ exports.getSkill = getSkill;
6
+ const path = require("node:path");
7
+ const zod_1 = require("zod");
8
+ const store_1 = require("./store");
9
+ const templates_1 = require("@technomoron/agent-run/dist/templates");
10
+ const manifest_1 = require("@technomoron/agent-run/dist/manifest");
11
+ const metadata = zod_1.z.object({
12
+ name: zod_1.z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/),
13
+ description: zod_1.z.string().trim().min(1),
14
+ tags: zod_1.z.array(zod_1.z.string()).default([]),
15
+ extends: zod_1.z.string().regex(/^(?:global|pool):[a-zA-Z0-9][a-zA-Z0-9._-]*$/).optional()
16
+ });
17
+ function getSkills(store) {
18
+ const profile = store.profile ?? 'default';
19
+ const directory = store.scopeDirectory(store.profile ? 'project' : 'default');
20
+ const env = (0, templates_1.createNunjucksEnv)(store.configRoot);
21
+ const context = (0, templates_1.buildRenderContext)(store.projectRoot, directory, store.configRoot, (0, manifest_1.normalizeManifest)((0, manifest_1.loadManifest)(store.configRoot, directory, profile), profile), env);
22
+ const skillEnv = (0, templates_1.createSkillNunjucksEnv)(store.configRoot, directory, undefined, store.pool);
23
+ const skills = new Map();
24
+ const parentSkills = new Map();
25
+ for (const { scope, directory } of store.scopes) {
26
+ for (const file of store.files(path.join(directory, 'skills')).filter((file) => path.basename(file) === 'SKILL.md')) {
27
+ const text = skillEnv.render(path.relative(store.configRoot, file), context);
28
+ const document = (0, store_1.readMarkdown)(text);
29
+ const parsed = metadata.parse(document.metadata);
30
+ if (path.basename(path.dirname(file)) !== parsed.name)
31
+ throw new Error(`Skill name must match directory: ${file}`);
32
+ let content = document.content;
33
+ if (parsed.extends) {
34
+ const parent = parentSkills.get(parsed.extends);
35
+ if (!parent || parent.scope === scope)
36
+ throw new Error(`Missing ancestor ${parsed.extends} for skill ${parsed.name}`);
37
+ content = `${parent.content}\n\n${content}`;
38
+ }
39
+ const skill = { ...parsed, scope, content, source: path.relative(store.configRoot, file) };
40
+ skills.set(parsed.name, skill);
41
+ parentSkills.set(`${scope}:${parsed.name}`, skill);
42
+ }
43
+ }
44
+ return [...skills.values()];
45
+ }
46
+ function listSkills(store) {
47
+ return getSkills(store).map(({ content: _content, ...skill }) => skill);
48
+ }
49
+ function getSkill(store, name) {
50
+ const skill = getSkills(store).find((item) => item.name === name);
51
+ if (!skill)
52
+ throw new Error(`Skill not found: ${name}`);
53
+ return skill;
54
+ }
@@ -0,0 +1,499 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BrainStore = exports.knowledgeDirectories = exports.knowledgeChanges = exports.knowledgeMetadata = exports.knowledgeInput = exports.reviewStateSchema = exports.severitySchema = exports.typeSchema = exports.scopeSchema = void 0;
4
+ exports.readMarkdown = readMarkdown;
5
+ const fs = require("node:fs");
6
+ const path = require("node:path");
7
+ const node_crypto_1 = require("node:crypto");
8
+ const node_sqlite_1 = require("node:sqlite");
9
+ const yaml_1 = require("yaml");
10
+ const zod_1 = require("zod");
11
+ const project_1 = require("@technomoron/agent-run/dist/project");
12
+ const utils_1 = require("@technomoron/agent-run/dist/utils");
13
+ const config_1 = require("./config");
14
+ exports.scopeSchema = zod_1.z.enum(['global', 'pool', 'project', 'default']);
15
+ exports.typeSchema = zod_1.z.enum(['rule', 'preference', 'convention', 'constraint', 'decision', 'spec', 'review', 'memory', 'observation']);
16
+ exports.severitySchema = zod_1.z.enum(['critical', 'high', 'medium', 'low']);
17
+ exports.reviewStateSchema = zod_1.z.enum(['open', 'fixed', 'wontfix']);
18
+ const severityPrefix = { critical: 'C', high: 'H', medium: 'M', low: 'L' };
19
+ const severityOrder = { critical: 0, high: 1, medium: 2, low: 3 };
20
+ exports.knowledgeInput = zod_1.z.object({
21
+ scope: exports.scopeSchema,
22
+ type: exports.typeSchema,
23
+ title: zod_1.z.string().trim().min(1).max(300),
24
+ content: zod_1.z.string().trim().min(1).max(200000),
25
+ authority: zod_1.z.enum(['user', 'inferred']).default('inferred'),
26
+ recall: zod_1.z.enum(['always', 'relevant']).default('relevant'),
27
+ severity: exports.severitySchema.optional(),
28
+ tags: zod_1.z.array(zod_1.z.string().max(100)).max(50).default([]),
29
+ applies_to: zod_1.z.array(zod_1.z.string().max(500)).max(50).default([]),
30
+ // Naming only. The id in the front matter stays the identity, so files can be renamed freely.
31
+ filename: zod_1.z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, 'Use lower-case words separated by single dashes, with no extension').max(100).optional()
32
+ }).strict();
33
+ // finding and state stay optional so review files written before they existed keep parsing.
34
+ exports.knowledgeMetadata = exports.knowledgeInput.omit({ content: true, filename: true }).extend({
35
+ id: zod_1.z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/),
36
+ status: zod_1.z.enum(['active', 'deprecated']).default('active'),
37
+ finding: zod_1.z.string().regex(/^[CHML][1-9][0-9]*$/).optional(),
38
+ state: exports.reviewStateSchema.optional(),
39
+ created: zod_1.z.string().default(''),
40
+ updated: zod_1.z.string().default(''),
41
+ reason: zod_1.z.string().optional(),
42
+ promoted_from: zod_1.z.string().optional()
43
+ }).strict();
44
+ // Spelled out rather than derived from knowledgeInput: .partial() keeps .default(), so a
45
+ // derived schema would silently reset every field the caller did not mention.
46
+ exports.knowledgeChanges = zod_1.z.object({
47
+ title: zod_1.z.string().trim().min(1).max(300).optional(),
48
+ content: zod_1.z.string().trim().min(1).max(200000).optional(),
49
+ recall: zod_1.z.enum(['always', 'relevant']).optional(),
50
+ tags: zod_1.z.array(zod_1.z.string().max(100)).max(50).optional(),
51
+ applies_to: zod_1.z.array(zod_1.z.string().max(500)).max(50).optional()
52
+ }).strict();
53
+ const reviewClosureSchema = zod_1.z.object({
54
+ id: zod_1.z.string(), finding: zod_1.z.string().regex(/^[CHML][1-9][0-9]*$/), severity: exports.severitySchema,
55
+ scope: exports.scopeSchema, title: zod_1.z.string(), state: zod_1.z.enum(['fixed', 'wontfix']),
56
+ closed: zod_1.z.string(), reason: zod_1.z.string(), source: zod_1.z.string(), revision: zod_1.z.string()
57
+ }).strict();
58
+ const reviewCountersSchema = zod_1.z.object({ C: zod_1.z.number().int().nonnegative(), H: zod_1.z.number().int().nonnegative(), M: zod_1.z.number().int().nonnegative(), L: zod_1.z.number().int().nonnegative() }).strict();
59
+ exports.knowledgeDirectories = {
60
+ rule: 'rules', preference: 'preferences', convention: 'conventions', constraint: 'constraints',
61
+ decision: 'decisions', spec: 'specs', review: 'reviews', memory: 'memory', observation: 'observations'
62
+ };
63
+ function readMarkdown(text) {
64
+ const normalized = text.replace(/\r\n/g, '\n');
65
+ const match = /^---\n([\s\S]*?)\n---(?:\n|$)/.exec(normalized);
66
+ if (normalized.startsWith('---\n') && !match)
67
+ throw new Error('Unterminated YAML front matter');
68
+ return match ? { metadata: (0, yaml_1.parse)(match[1], { maxAliasCount: 50 }), content: normalized.slice(match[0].length).trim() }
69
+ : { metadata: null, content: normalized.trim() };
70
+ }
71
+ function hash(text) { return (0, node_crypto_1.createHash)('sha256').update(text).digest('hex'); }
72
+ class BrainStore {
73
+ brokenFile(file, error, id) {
74
+ const message = error instanceof zod_1.z.ZodError
75
+ ? error.issues.map((issue) => `${issue.path.join('.') || 'metadata'}: ${issue.message}`).join('; ')
76
+ : error instanceof Error ? error.message.split('\n')[0] : String(error);
77
+ return { source: path.relative(this.configRoot, file), status: 'broken', error: message, ...(id ? { id } : {}) };
78
+ }
79
+ withDiagnostics(value) {
80
+ const brokenFiles = [...this.knowledgeErrors, ...this.todoErrors];
81
+ if (!brokenFiles.length)
82
+ return value;
83
+ return Array.isArray(value) ? { items: value, brokenFiles } : { ...value, brokenFiles };
84
+ }
85
+ assertReadable(id, errors) {
86
+ const matches = errors.filter((item) => item.id === id || item.source === id || path.basename(item.source, '.md') === id);
87
+ if (matches.length)
88
+ throw new Error(`Cannot read or update broken file: ${matches.map((item) => `${item.source}: ${item.error}`).join('; ')}. Correct the file on disk first.`);
89
+ }
90
+ constructor(configRoot, cwd) {
91
+ this.configRoot = configRoot;
92
+ this.cwd = cwd;
93
+ this.knowledgeErrors = [];
94
+ this.todoErrors = [];
95
+ this.configRoot = path.resolve(configRoot);
96
+ const registration = (0, config_1.registeredBrainProject)(this.configRoot, cwd);
97
+ this.projectRoot = registration?.root ?? (0, project_1.findProjectRoot)(cwd);
98
+ this.pool = registration?.pool;
99
+ const resolved = (0, project_1.resolveProfileResult)(this.projectRoot, this.configRoot).profile;
100
+ this.profile = resolved && resolved !== 'default' && ['agent-run.jsonc', 'local.md.njk', 'AGENTS-MODS.md'].some((file) => fs.existsSync(path.join(this.configRoot, resolved, file))) ? resolved : null;
101
+ this.scopes = [{ scope: 'global', directory: path.join(this.configRoot, 'global') },
102
+ ...(this.pool ? [{ scope: 'pool', directory: path.join(this.configRoot, 'pools', this.pool) }] : []),
103
+ { scope: this.profile ? 'project' : 'default', directory: path.join(this.configRoot, this.profile ?? 'default') }];
104
+ this.budget = (0, config_1.readBrainConfig)(this.configRoot)?.contextBudget ?? 16000;
105
+ this.directory('index');
106
+ this.directory('runtime');
107
+ this.db = new node_sqlite_1.DatabaseSync(this.safePath('index', 'knowledge.sqlite'));
108
+ this.db.exec('PRAGMA busy_timeout = 5000; PRAGMA journal_mode = WAL; CREATE VIRTUAL TABLE IF NOT EXISTS knowledge USING fts5(source UNINDEXED, environment UNINDEXED, title, content, tags);');
109
+ }
110
+ close() { this.db.close(); }
111
+ safePath(...parts) {
112
+ const target = path.resolve(this.configRoot, ...parts);
113
+ if (!(0, utils_1.isSamePathOrDescendant)(target, this.configRoot))
114
+ throw new Error('Path escapes the brain configuration directory');
115
+ let current = this.configRoot;
116
+ for (const part of path.relative(this.configRoot, target).split(path.sep).filter(Boolean)) {
117
+ current = path.join(current, part);
118
+ try {
119
+ if (fs.lstatSync(current).isSymbolicLink())
120
+ throw new Error(`Symlinks are not supported in brain storage: ${current}`);
121
+ }
122
+ catch (error) {
123
+ if (error.code !== 'ENOENT')
124
+ throw error;
125
+ }
126
+ }
127
+ return target;
128
+ }
129
+ directory(...parts) {
130
+ const directory = this.safePath(...parts);
131
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
132
+ return directory;
133
+ }
134
+ scopeDirectory(scope) {
135
+ const directory = this.scopes.find((entry) => entry.scope === scope)?.directory;
136
+ if (!directory)
137
+ throw new Error(`Scope ${scope} is not available in this environment`);
138
+ return this.safePath(directory);
139
+ }
140
+ files(directory, options = {}) {
141
+ const { onError } = options;
142
+ try {
143
+ this.safePath(directory);
144
+ if (!fs.existsSync(directory))
145
+ return [];
146
+ return fs.readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name)).flatMap((entry) => {
147
+ try {
148
+ const file = this.safePath(directory, entry.name);
149
+ return entry.isDirectory() ? this.files(file, options) : entry.isFile() && (options.includeAllFiles || entry.name.endsWith('.md')) ? [file] : [];
150
+ }
151
+ catch (error) {
152
+ if (!onError)
153
+ throw error;
154
+ onError(path.join(directory, entry.name), error);
155
+ return [];
156
+ }
157
+ });
158
+ }
159
+ catch (error) {
160
+ if (!onError)
161
+ throw error;
162
+ onError(directory, error);
163
+ return [];
164
+ }
165
+ }
166
+ read(file) {
167
+ const target = this.safePath(file);
168
+ if (fs.statSync(target).size > 1024 * 1024)
169
+ throw new Error(`Markdown file exceeds 1 MiB: ${file}`);
170
+ return fs.readFileSync(target, 'utf8');
171
+ }
172
+ atomicWrite(file, text) {
173
+ const target = this.safePath(file);
174
+ this.directory(path.dirname(target));
175
+ const temporary = `${target}.${(0, node_crypto_1.randomUUID)()}.tmp`;
176
+ try {
177
+ fs.writeFileSync(temporary, text, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
178
+ fs.renameSync(temporary, target);
179
+ }
180
+ finally {
181
+ fs.rmSync(temporary, { force: true });
182
+ }
183
+ }
184
+ writeLocked(fn) {
185
+ const file = this.safePath('runtime', 'brain-write.lock');
186
+ let descriptor;
187
+ try {
188
+ descriptor = fs.openSync(file, 'wx', 0o600);
189
+ }
190
+ catch (error) {
191
+ if (error.code === 'EEXIST')
192
+ throw new Error('Another brain write is in progress. Retry; after a crashed writer, remove runtime/brain-write.lock.');
193
+ throw error;
194
+ }
195
+ try {
196
+ fs.writeSync(descriptor, String(process.pid));
197
+ return fn();
198
+ }
199
+ finally {
200
+ fs.closeSync(descriptor);
201
+ fs.unlinkSync(file);
202
+ }
203
+ }
204
+ allKnowledge() {
205
+ this.knowledgeErrors.length = 0;
206
+ const result = [];
207
+ for (const { scope, directory } of this.scopes) {
208
+ const directories = [...Object.entries(exports.knowledgeDirectories), ['memory', path.join('notes', 'memory')]];
209
+ if (scope === 'global')
210
+ directories.push(['memory', path.relative(directory, path.join(this.configRoot, 'notes', 'memory'))]);
211
+ for (const [type, folder] of directories) {
212
+ for (const file of this.files(path.join(directory, folder), { onError: (file, error) => this.knowledgeErrors.push(this.brokenFile(file, error)) })) {
213
+ let id;
214
+ try {
215
+ const text = this.read(file);
216
+ const document = readMarkdown(text);
217
+ if (document.metadata && typeof document.metadata === 'object' && 'id' in document.metadata && typeof document.metadata.id === 'string')
218
+ id = document.metadata.id;
219
+ const source = path.relative(this.configRoot, file);
220
+ const legacy = document.metadata !== null && typeof document.metadata === 'object' && !Array.isArray(document.metadata)
221
+ && !('id' in document.metadata) && !('type' in document.metadata);
222
+ const legacyStatus = legacy ? document.metadata.status : undefined;
223
+ const metadata = document.metadata === null || legacy ? {
224
+ id: `document-${hash(source).slice(0, 24)}`, scope, type,
225
+ title: /^#\s+(.+)$/m.exec(document.content)?.[1] ?? path.basename(file, '.md'),
226
+ status: type === 'review' && ['addressed', 'resolved', 'done', 'closed'].includes(String(legacyStatus)) ? 'deprecated' : 'active',
227
+ created: '', updated: ''
228
+ } : { title: /^#\s+(.+)$/m.exec(document.content)?.[1] ?? path.basename(file, '.md'), ...document.metadata };
229
+ const parsed = exports.knowledgeMetadata.safeParse(metadata);
230
+ if (!parsed.success)
231
+ throw parsed.error;
232
+ if (parsed.data.scope !== scope)
233
+ throw new Error(`Knowledge scope does not match its directory: ${source}`);
234
+ result.push({ ...parsed.data, content: legacy ? text.trim() : document.content, source, revision: hash(text) });
235
+ }
236
+ catch (error) {
237
+ this.knowledgeErrors.push(this.brokenFile(file, error, id));
238
+ }
239
+ }
240
+ }
241
+ }
242
+ const counts = new Map();
243
+ for (const item of [...result, ...this.knowledgeErrors]) {
244
+ if (item.id)
245
+ counts.set(item.id, (counts.get(item.id) ?? 0) + 1);
246
+ }
247
+ for (const item of result) {
248
+ if (counts.get(item.id) > 1)
249
+ this.knowledgeErrors.push(this.brokenFile(path.join(this.configRoot, item.source), new Error(`Duplicate knowledge id: ${item.id}`), item.id));
250
+ }
251
+ return result.filter((item) => counts.get(item.id) === 1);
252
+ }
253
+ search(query, options = {}) {
254
+ return this.searchItems(this.allKnowledge(), query, options);
255
+ }
256
+ searchItems(items, query, options = {}) {
257
+ const environment = this.profile ?? 'default';
258
+ this.refreshIndex(items, environment);
259
+ const terms = query.match(/[\p{L}\p{N}_-]+/gu)?.slice(0, 50) ?? [];
260
+ const ranked = terms.length ? this.db.prepare('SELECT source FROM knowledge WHERE knowledge MATCH ? AND environment = ? ORDER BY bm25(knowledge, 0, 0, 5, 1, 3), source')
261
+ .all(terms.map((term) => `"${term.replace(/"/g, '""')}"`).join(' OR '), environment).map((row) => String(row.source)) : items.map((item) => item.source);
262
+ const bySource = new Map(items.map((item) => [item.source, item]));
263
+ return ranked.map((source) => bySource.get(source)).filter((item) => item !== undefined).filter((item) => (options.includeDeprecated || item.status === 'active') && (!options.scopes || options.scopes.includes(item.scope)) &&
264
+ (!options.types || options.types.includes(item.type))).slice(0, options.limit ?? 50);
265
+ }
266
+ refreshIndex(items, environment) {
267
+ const desired = new Map(items.map((item) => [item.source, {
268
+ source: item.source, title: item.title, content: item.content, tags: [...item.tags, item.finding ?? ''].join(' ').trim()
269
+ }]));
270
+ const changes = () => {
271
+ const current = this.db.prepare('SELECT rowid, source, title, content, tags FROM knowledge WHERE environment = ?').all(environment);
272
+ const unchanged = new Set();
273
+ const removed = current.filter((row) => {
274
+ const item = desired.get(String(row.source));
275
+ if (item && !unchanged.has(item.source) && row.title === item.title && row.content === item.content && row.tags === item.tags) {
276
+ unchanged.add(item.source);
277
+ return false;
278
+ }
279
+ return true;
280
+ });
281
+ return { removed, added: [...desired.values()].filter((item) => !unchanged.has(item.source)) };
282
+ };
283
+ const pending = changes();
284
+ if (!pending.removed.length && !pending.added.length)
285
+ return;
286
+ this.db.exec('BEGIN IMMEDIATE');
287
+ try {
288
+ // Another connection may have refreshed the index while we waited for the lock.
289
+ const { removed, added } = changes();
290
+ const remove = this.db.prepare('DELETE FROM knowledge WHERE rowid = ?');
291
+ for (const row of removed)
292
+ remove.run(row.rowid);
293
+ const insert = this.db.prepare('INSERT INTO knowledge(source, environment, title, content, tags) VALUES (?, ?, ?, ?, ?)');
294
+ for (const item of added)
295
+ insert.run(item.source, environment, item.title, item.content, item.tags);
296
+ this.db.exec('COMMIT');
297
+ }
298
+ catch (error) {
299
+ this.db.exec('ROLLBACK');
300
+ throw error;
301
+ }
302
+ }
303
+ context(task, files = [], symbols = []) {
304
+ const scanned = this.allKnowledge();
305
+ const all = scanned.filter((item) => item.status === 'active');
306
+ const always = all.filter((item) => item.recall === 'always');
307
+ const matching = all.filter((item) => item.applies_to.some((pattern) => files.some((file) => {
308
+ const relative = path.isAbsolute(file) ? path.relative(this.projectRoot, file) : file;
309
+ return path.matchesGlob(relative, pattern);
310
+ })));
311
+ const selected = [...new Map([...always, ...matching, ...this.searchItems(scanned, [task, ...symbols].join(' '))].map((item) => [item.id, item])).values()];
312
+ let size = 0;
313
+ const items = selected.filter((item) => {
314
+ const length = JSON.stringify(item).length;
315
+ if (size + length > this.budget)
316
+ return false;
317
+ size += length;
318
+ return true;
319
+ });
320
+ return { items, omitted: selected.length - items.length, profile: this.profile, scopes: this.scopes.map((scope) => scope.scope) };
321
+ }
322
+ remember(input) {
323
+ const value = exports.knowledgeInput.parse(input);
324
+ if (value.type === 'review' && (value.scope === 'pool' || (this.pool && value.scope !== 'project')))
325
+ throw new Error('Review findings must belong to an individual repository');
326
+ if (value.authority === 'inferred' && value.type !== 'observation' && value.type !== 'memory' && value.type !== 'review') {
327
+ throw new Error('Inferred knowledge must remain an observation, memory, or review until explicitly confirmed.');
328
+ }
329
+ if (value.scope === 'global' && value.authority !== 'user')
330
+ throw new Error('Global writes require explicit user authority.');
331
+ if (value.type === 'review' && !value.severity)
332
+ throw new Error('Review findings require a severity: critical, high, medium, or low.');
333
+ if (value.type !== 'review' && value.severity)
334
+ throw new Error('Severity applies only to review findings.');
335
+ return this.writeLocked(() => {
336
+ const now = new Date().toISOString();
337
+ const { content, filename, ...metadata } = value;
338
+ const review = value.severity ? { finding: this.nextFinding(value.scope, value.severity), state: 'open' } : {};
339
+ const item = { ...metadata, ...review, id: (0, node_crypto_1.randomUUID)(), status: 'active', created: now, updated: now };
340
+ const directory = path.join(this.scopeDirectory(value.scope), exports.knowledgeDirectories[value.type]);
341
+ this.atomicWrite(this.availableFile(directory, filename, item.id), `---\n${(0, yaml_1.stringify)(item)}---\n\n${content}\n`);
342
+ return this.allKnowledge().find((entry) => entry.id === item.id);
343
+ });
344
+ }
345
+ /** Chosen name when one is given and free, otherwise the same name with the id appended. */
346
+ availableFile(directory, filename, id) {
347
+ if (!filename)
348
+ return path.join(directory, `${id}.md`);
349
+ const preferred = path.join(directory, `${filename}.md`);
350
+ return fs.existsSync(preferred) ? path.join(directory, `${filename}-${id}.md`) : preferred;
351
+ }
352
+ /** Revise an item in place, keeping its id, filename, scope, type, authority, and history. */
353
+ amend(id, revision, changes) {
354
+ const parsed = exports.knowledgeChanges.parse(changes);
355
+ if (Object.keys(parsed).length === 0)
356
+ throw new Error('Supply at least one field to change.');
357
+ return this.writeLocked(() => {
358
+ const item = this.get(id);
359
+ if (item.revision !== revision)
360
+ throw new Error('Knowledge changed; read the current revision before amending.');
361
+ if (item.status !== 'active')
362
+ throw new Error('Deprecated knowledge cannot be amended.');
363
+ const { source, revision: _revision, content, ...metadata } = item;
364
+ const { content: nextContent, ...nextMetadata } = parsed;
365
+ this.atomicWrite(source, `---\n${(0, yaml_1.stringify)({ ...metadata, ...nextMetadata, updated: new Date().toISOString() })}---\n\n${nextContent ?? content}\n`);
366
+ return this.get(id);
367
+ });
368
+ }
369
+ /** Next unused finding label for a severity, counting resolved findings so numbers are never reused. */
370
+ nextFinding(scope, severity) {
371
+ const prefix = severityPrefix[severity];
372
+ const used = this.allKnowledge()
373
+ .filter((item) => item.scope === scope && item.type === 'review' && item.finding?.startsWith(prefix))
374
+ .map((item) => Number.parseInt(item.finding.slice(prefix.length), 10))
375
+ .filter((sequence) => Number.isSafeInteger(sequence));
376
+ if (this.knowledgeErrors.some((item) => (0, utils_1.isSamePathOrDescendant)(path.join(this.configRoot, item.source), path.join(this.scopeDirectory(scope), 'reviews')))) {
377
+ throw new Error('Cannot assign a review number while review files are broken. List reviews and correct the reported files first.');
378
+ }
379
+ const counters = this.reviewCounters(scope);
380
+ const next = Math.max(counters[prefix], 0, ...used) + 1;
381
+ this.reserveFinding(scope, `${prefix}${next}`);
382
+ return `${prefix}${next}`;
383
+ }
384
+ /** Review findings in severity then sequence order. Open findings only unless states are given. */
385
+ reviews(options = {}) {
386
+ const sequence = (item) => Number.parseInt(item.finding.slice(1), 10);
387
+ return this.allKnowledge()
388
+ .filter((item) => (!this.pool || item.scope === 'project') && item.type === 'review' && item.finding && item.severity)
389
+ .filter((item) => !options.severity || options.severity.includes(item.severity))
390
+ .filter((item) => (options.state ?? ['open']).includes(item.state ?? 'open'))
391
+ .sort((left, right) => severityOrder[left.severity] - severityOrder[right.severity] || sequence(left) - sequence(right));
392
+ }
393
+ reviewCounters(scope) {
394
+ const file = this.safePath(this.scopeDirectory(scope), 'review-counters.json');
395
+ return fs.existsSync(file) ? reviewCountersSchema.parse(JSON.parse(fs.readFileSync(file, 'utf8'))) : { C: 0, H: 0, M: 0, L: 0 };
396
+ }
397
+ reserveFinding(scope, finding) {
398
+ const counters = this.reviewCounters(scope);
399
+ const prefix = finding[0];
400
+ const number = Number(finding.slice(1));
401
+ if (!Number.isSafeInteger(number) || number < 1)
402
+ throw new Error('Invalid review number');
403
+ counters[prefix] = Math.max(counters[prefix], number);
404
+ this.atomicWrite(path.join(this.scopeDirectory(scope), 'review-counters.json'), JSON.stringify(counters) + '\n');
405
+ }
406
+ closedReviews(scope) {
407
+ const file = this.safePath(this.scopeDirectory(scope), 'review-history.jsonl');
408
+ if (!fs.existsSync(file))
409
+ return [];
410
+ return fs.readFileSync(file, 'utf8').split('\n').filter((line) => line.trim()).map((line) => {
411
+ const record = reviewClosureSchema.parse(JSON.parse(line));
412
+ if (record.scope !== scope)
413
+ throw new Error(`Review history scope mismatch: ${file}`);
414
+ return record;
415
+ });
416
+ }
417
+ reviewHistory(options = {}) {
418
+ const query = options.query?.toLowerCase();
419
+ const items = this.scopes.filter((entry) => (!this.pool || entry.scope === 'project') && (!options.scope || entry.scope === options.scope))
420
+ .flatMap((entry) => this.closedReviews(entry.scope))
421
+ .filter((item) => (!options.state || item.state === options.state) && (!query || [item.id, item.finding, item.title, item.reason].some((value) => value.toLowerCase().includes(query))))
422
+ .sort((a, b) => b.closed.localeCompare(a.closed) || a.id.localeCompare(b.id));
423
+ const offset = options.offset ?? 0;
424
+ return { items: items.slice(offset, offset + (options.limit ?? 100)), total: items.length };
425
+ }
426
+ archiveReview(item, state, reason, closed) {
427
+ if (!item.finding || !item.severity)
428
+ throw new Error('Only numbered review findings can be archived.');
429
+ const records = this.closedReviews(item.scope);
430
+ const existing = records.find((record) => record.id === item.id);
431
+ if (existing && (existing.revision !== item.revision || existing.state !== state))
432
+ throw new Error('Archived review conflicts with the current file; inspect review history before updating.');
433
+ const record = existing ?? { id: item.id, finding: item.finding, severity: item.severity, scope: item.scope, title: item.title, state, closed, reason, source: item.source, revision: item.revision };
434
+ // Persist the number and closure before removing the full finding. A retry can finish deletion.
435
+ this.reserveFinding(item.scope, item.finding);
436
+ if (!existing)
437
+ this.atomicWrite(path.join(this.scopeDirectory(item.scope), 'review-history.jsonl'), [...records, record].map((entry) => JSON.stringify(entry)).join('\n') + '\n');
438
+ fs.unlinkSync(this.safePath(item.source));
439
+ return record;
440
+ }
441
+ archiveReviews(scope) {
442
+ return this.writeLocked(() => {
443
+ const history = this.closedReviews(scope);
444
+ return this.allKnowledge().filter((item) => item.scope === scope && item.type === 'review' && item.finding)
445
+ .filter((item) => item.state === 'fixed' || item.state === 'wontfix' || history.some((record) => record.id === item.id))
446
+ .map((item) => {
447
+ const prior = history.find((record) => record.id === item.id);
448
+ return this.archiveReview(item, prior?.state ?? item.state, prior?.reason ?? item.reason ?? '', prior?.closed ?? item.updated);
449
+ });
450
+ });
451
+ }
452
+ resolveReview(id, revision, state, reason) {
453
+ return this.writeLocked(() => {
454
+ const item = this.get(id);
455
+ if (item.type !== 'review' || !item.finding)
456
+ throw new Error('Only review findings can be resolved.');
457
+ if (item.revision !== revision)
458
+ throw new Error('Knowledge changed; read the current revision before updating.');
459
+ return this.archiveReview(item, state, reason ?? '', new Date().toISOString());
460
+ });
461
+ }
462
+ deprecate(id, revision, reason) {
463
+ return this.writeLocked(() => {
464
+ const item = this.get(id);
465
+ if (item.revision !== revision)
466
+ throw new Error('Knowledge changed; read the current revision before updating.');
467
+ const { source, revision: _revision, content, ...metadata } = item;
468
+ this.atomicWrite(source, `---\n${(0, yaml_1.stringify)({ ...metadata, status: 'deprecated', updated: new Date().toISOString(), ...(reason ? { reason } : {}) })}---\n\n${content}\n`);
469
+ return this.get(id);
470
+ });
471
+ }
472
+ promote(id, scope, revision) {
473
+ if (this.get(id).type === 'review' && (scope === 'pool' || (this.pool && scope !== 'project')))
474
+ throw new Error('Review findings must belong to an individual repository');
475
+ return this.writeLocked(() => {
476
+ const item = this.get(id);
477
+ if (item.revision !== revision)
478
+ throw new Error('Knowledge changed; read the current revision before promoting.');
479
+ if (item.status !== 'active')
480
+ throw new Error('Deprecated knowledge cannot be promoted.');
481
+ if (item.scope === scope)
482
+ throw new Error('Knowledge already belongs to this scope.');
483
+ const { source: _source, revision: _revision, content, ...metadata } = item;
484
+ const renumbered = item.severity ? { finding: this.nextFinding(scope, item.severity) } : {};
485
+ const promoted = { ...metadata, ...renumbered, id: (0, node_crypto_1.randomUUID)(), scope, authority: 'user', promoted_from: id, updated: new Date().toISOString() };
486
+ const target = path.join(this.scopeDirectory(scope), exports.knowledgeDirectories[item.type]);
487
+ this.atomicWrite(this.availableFile(target, path.basename(item.source, '.md'), promoted.id), `---\n${(0, yaml_1.stringify)(promoted)}---\n\n${content}\n`);
488
+ return this.get(promoted.id);
489
+ });
490
+ }
491
+ get(id) {
492
+ const item = this.allKnowledge().find((entry) => entry.id === id);
493
+ this.assertReadable(id, this.knowledgeErrors);
494
+ if (!item)
495
+ throw new Error(`Knowledge not found in the active scopes: ${id}. For consolidated records, look up this ID with knowledge_history${this.knowledgeErrors.length ? '. Some files are broken; list or search knowledge for their paths and errors' : ''}`);
496
+ return item;
497
+ }
498
+ }
499
+ exports.BrainStore = BrainStore;