@astratra/conscience 1.1.0 → 1.3.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,388 @@
1
+ 'use strict';
2
+ const crypto = require('node:crypto');
3
+ const { GovernorError, fingerprintOf, copy, isNonEmptyString } = require('./util');
4
+ const { createMemoryGovernorStore } = require('./stores');
5
+ const { createCalendarBudget, isAmount } = require('./calendar');
6
+
7
+ /*
8
+ * Tool policy: decides, by code and outside any model, whether ONE call of a tool
9
+ * may run. Generic on purpose: families, levels, caps and every word of the
10
+ * vocabulary come from configuration; nothing here knows what a tool does.
11
+ *
12
+ * Order of examination of a call:
13
+ * emergency stop > agent disabled > unknown tool > family disabled > invalid input
14
+ * > calendar budget > caps > level (sensitive, untrusted context, over threshold).
15
+ * Whatever cannot be read (settings, kill switch, budget) refuses: it never lets a call through.
16
+ */
17
+
18
+ const TOOL_LEVELS = Object.freeze({ READ: 'read', CONTROLLED: 'controlled', SENSITIVE: 'sensitive' });
19
+ const TOOL_DECISIONS = Object.freeze({ ALLOWED: 'allowed', PENDING: 'pending', REFUSED: 'refused' });
20
+ const TOOL_REASONS = Object.freeze({
21
+ HALTED: 'emergency_stop',
22
+ DISABLED: 'disabled',
23
+ UNAVAILABLE: 'settings_unavailable',
24
+ UNKNOWN_TOOL: 'unknown_tool',
25
+ FAMILY_DISABLED: 'family_disabled',
26
+ INVALID_INPUT: 'invalid_input',
27
+ BUDGET: 'budget_exceeded',
28
+ CAP: 'cap_reached',
29
+ SENSITIVE: 'sensitive_tool',
30
+ UNTRUSTED: 'untrusted_context',
31
+ THRESHOLD: 'over_threshold'
32
+ });
33
+
34
+ const LEVELS = Object.values(TOOL_LEVELS);
35
+ const DECISIONS = Object.values(TOOL_DECISIONS);
36
+ const CODES = Object.values(TOOL_REASONS);
37
+ const TOOL_NAME = /^[a-zA-Z][a-zA-Z0-9_.:-]{0,127}$/;
38
+ const GLOBAL = '*';
39
+ const NEVER_RELEASE = Object.freeze(['model', 'engine']);
40
+
41
+ const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
42
+ const fail = (message) => { throw new GovernorError('tool_policy_invalid', `Invalid tool policy: ${message}`); };
43
+ const stringList = (value, field) => {
44
+ if (!Array.isArray(value) || !value.length || !value.every(isNonEmptyString)) fail(`${field} must be a non-empty array of strings.`);
45
+ return [...new Set(value)];
46
+ };
47
+
48
+ /** Vocabulary: canonical word -> your word. Only the words you list are renamed. */
49
+ function vocabulary(labels = {}, canonical, field) {
50
+ if (!isObject(labels)) fail(`labels.${field} must be an object.`);
51
+ const toApp = {}; const toCanonical = {};
52
+ for (const word of canonical) {
53
+ const mine = labels[word] ?? word;
54
+ if (!isNonEmptyString(mine)) fail(`labels.${field}.${word} must be a non-empty string.`);
55
+ toApp[word] = mine;
56
+ if (toCanonical[mine] !== undefined) fail(`labels.${field} gives the same word to two entries ("${mine}").`);
57
+ toCanonical[mine] = word;
58
+ }
59
+ for (const word of Object.keys(labels)) if (!canonical.includes(word)) fail(`labels.${field}.${word} is not one of: ${canonical.join(', ')}.`);
60
+ return { toApp, toCanonical };
61
+ }
62
+
63
+ function normalizeSettings(raw) {
64
+ if (!isObject(raw)) throw new GovernorError('settings_invalid', 'Tool settings must be an object.');
65
+ const out = {};
66
+ if (raw.enabled !== undefined) { if (typeof raw.enabled !== 'boolean') throw new GovernorError('settings_invalid', 'enabled must be a boolean.'); out.enabled = raw.enabled; }
67
+ if (raw.families !== undefined) {
68
+ if (!isObject(raw.families) || !Object.values(raw.families).every((value) => typeof value === 'boolean')) throw new GovernorError('settings_invalid', 'families must map a family to a boolean.');
69
+ out.families = { ...raw.families };
70
+ }
71
+ if (raw.budgetLimit !== undefined && raw.budgetLimit !== null) { if (!isAmount(raw.budgetLimit)) throw new GovernorError('settings_invalid', 'budgetLimit must be an integer >= 0.'); out.budgetLimit = raw.budgetLimit; }
72
+ if (raw.maxCallsPerRun !== undefined && raw.maxCallsPerRun !== null) {
73
+ if (!Number.isSafeInteger(raw.maxCallsPerRun) || raw.maxCallsPerRun < 1) throw new GovernorError('settings_invalid', 'maxCallsPerRun must be an integer >= 1.');
74
+ out.maxCallsPerRun = raw.maxCallsPerRun;
75
+ }
76
+ for (const [key, value] of Object.entries(raw)) if (!['enabled', 'families', 'budgetLimit', 'maxCallsPerRun'].includes(key)) out[key] = copy(value);
77
+ return out;
78
+ }
79
+
80
+ function normalizeTool(definition, levelOf, families) {
81
+ if (!isObject(definition)) fail('a tool must be an object.');
82
+ if (!TOOL_NAME.test(definition.name ?? '')) fail(`invalid tool name: ${definition.name}.`);
83
+ const name = definition.name;
84
+ if (!isNonEmptyString(definition.family)) fail(`${name}: family is required.`);
85
+ if (families && !families.includes(definition.family)) fail(`${name}: family "${definition.family}" is not in families.`);
86
+ const level = levelOf.toCanonical[definition.level];
87
+ if (!level) fail(`${name}: level must be one of ${Object.keys(levelOf.toCanonical).join(', ')}.`);
88
+ for (const field of ['validate', 'overThreshold']) if (definition[field] !== undefined && typeof definition[field] !== 'function') fail(`${name}: ${field} must be a function.`);
89
+ if (definition.maxPerRun !== undefined && (!Number.isSafeInteger(definition.maxPerRun) || definition.maxPerRun < 1)) fail(`${name}: maxPerRun must be an integer >= 1.`);
90
+ if (definition.estimatedCost !== undefined && !isAmount(definition.estimatedCost)) fail(`${name}: estimatedCost must be an integer >= 0.`);
91
+ return Object.freeze({
92
+ name, family: definition.family, level, validate: definition.validate ?? null, overThreshold: definition.overThreshold ?? null,
93
+ maxPerRun: definition.maxPerRun ?? null, estimatedCost: definition.estimatedCost ?? 0, budgetExempt: definition.budgetExempt === true
94
+ });
95
+ }
96
+
97
+ const actorOf = (actor) => (isObject(actor)
98
+ ? { kind: String(actor.kind ?? ''), id: String(actor.id ?? ''), roles: Array.isArray(actor.roles) ? actor.roles.map(String) : [] }
99
+ : null);
100
+ const hasRole = (actor, roles) => actor.roles.some((role) => roles.includes(role));
101
+
102
+ /**
103
+ * Builds the tool policy.
104
+ * options: tools, families?, defaults?, settings?, budget?, emergency?, labels?, untrustedPendingLevels?,
105
+ * store?, governor?, version?, pollMs?, now?, idFactory?, onEvent?
106
+ */
107
+ function createToolPolicy(options = {}) {
108
+ if (!isObject(options)) fail('options must be an object.');
109
+ const labels = options.labels ?? {};
110
+ const levelWords = vocabulary(labels.levels, LEVELS, 'levels');
111
+ const decisionWords = vocabulary(labels.decisions, DECISIONS, 'decisions');
112
+ const codeWords = vocabulary(labels.codes, CODES, 'codes');
113
+ const families = options.families === undefined ? null : stringList(options.families, 'families');
114
+ if (!Array.isArray(options.tools) || !options.tools.length) fail('tools must list at least one tool.');
115
+ const tools = new Map();
116
+ for (const definition of options.tools) {
117
+ const tool = normalizeTool(definition, levelWords, families);
118
+ if (tools.has(tool.name)) fail(`tool declared twice: ${tool.name}.`);
119
+ tools.set(tool.name, tool);
120
+ }
121
+ const untrustedLevels = (options.untrustedPendingLevels ?? [levelWords.toApp.controlled]).map((word) => {
122
+ const level = levelWords.toCanonical[word];
123
+ if (!level) fail(`untrustedPendingLevels: unknown level ${word}.`);
124
+ return level;
125
+ });
126
+ const emergency = options.emergency ?? {};
127
+ const activateRoles = emergency.activateRoles === undefined ? null : stringList(emergency.activateRoles, 'emergency.activateRoles');
128
+ const releaseRoles = emergency.releaseRoles === undefined ? null : stringList(emergency.releaseRoles, 'emergency.releaseRoles');
129
+
130
+ const store = options.store ?? createMemoryGovernorStore();
131
+ for (const method of ['appendAudit', 'getControl', 'setControl']) {
132
+ if (typeof store[method] !== 'function') throw new GovernorError('governor_unavailable', `Tool policy store is missing ${method}().`);
133
+ }
134
+ const now = options.now ?? Date.now;
135
+ const newId = options.idFactory ?? (() => crypto.randomUUID());
136
+ const version = options.version ?? '1';
137
+ const pollMs = options.pollMs ?? 1000;
138
+ if (!Number.isSafeInteger(pollMs) || pollMs < 0) fail('pollMs must be an integer >= 0 (0 turns the polling off).');
139
+ const readSettings = options.settings ?? null;
140
+ if (readSettings !== null && typeof readSettings !== 'function') fail('settings must be a function.');
141
+ const defaults = normalizeSettings(options.defaults ?? {});
142
+ const budget = options.budget == null ? null : (typeof options.budget.check === 'function' ? options.budget : createCalendarBudget({ now, ...options.budget }));
143
+ if (budget && typeof budget.record !== 'function') fail('budget must have check() and record().');
144
+ const governor = options.governor ?? null;
145
+ if (governor && typeof governor.isHalted !== 'function') fail('governor must be built by createGovernor().');
146
+
147
+ const active = new Set();
148
+ const iso = () => new Date(now()).toISOString();
149
+
150
+ async function audit(entry) {
151
+ const full = { id: newId(), at: iso(), policyVersion: version, organisationId: null, proposalId: null, reasons: [], actor: null, ...entry };
152
+ await store.appendAudit(full);
153
+ try { await options.onEvent?.({ type: 'tool_policy', ...copy(full) }); } catch (_error) { /* Observers never change a decision. */ }
154
+ return full;
155
+ }
156
+
157
+ async function haltState(organisationId) {
158
+ const global = await store.getControl(`tools-halt:${GLOBAL}`);
159
+ if (global?.halted) return { halted: true, scope: GLOBAL, reason: global.reason ?? null };
160
+ if (organisationId != null) {
161
+ const local = await store.getControl(`tools-halt:${organisationId}`);
162
+ if (local?.halted) return { halted: true, scope: organisationId, reason: local.reason ?? null };
163
+ }
164
+ if (governor && await governor.isHalted(organisationId ?? undefined)) return { halted: true, scope: 'governor', reason: 'governor_halted' };
165
+ return { halted: false };
166
+ }
167
+
168
+ async function currentSettings(call) {
169
+ const raw = readSettings ? await readSettings({ organisationId: call.organisationId ?? null, actor: actorOf(call.actor) }) : {};
170
+ const settings = normalizeSettings(raw ?? {});
171
+ return { ...defaults, ...settings, families: { ...defaults.families, ...settings.families } };
172
+ }
173
+
174
+ function createRun() {
175
+ const run = { calls: 0, byTool: {}, untrusted: false, markUntrusted() { run.untrusted = true; } };
176
+ return run;
177
+ }
178
+
179
+ const refuse = (code, extra = {}) => ({ decision: TOOL_DECISIONS.REFUSED, code, ...extra });
180
+
181
+ /* The verdict for one call, in canonical words. */
182
+ async function judge(call, tool, run, rank, rankOfTool) {
183
+ const organisationId = call.organisationId ?? null;
184
+ let state;
185
+ try { state = await haltState(organisationId); } catch (_error) { return refuse(TOOL_REASONS.UNAVAILABLE); }
186
+ if (state.halted) return refuse(TOOL_REASONS.HALTED, { haltScope: state.scope });
187
+ let settings;
188
+ try { settings = await currentSettings(call); } catch (_error) { return refuse(TOOL_REASONS.UNAVAILABLE); }
189
+ if (settings.enabled === false) return refuse(TOOL_REASONS.DISABLED);
190
+ if (!tool) return refuse(TOOL_REASONS.UNKNOWN_TOOL);
191
+ if (settings.families[tool.family] === false) return refuse(TOOL_REASONS.FAMILY_DISABLED);
192
+
193
+ let input = call.input ?? {};
194
+ if (tool.validate) {
195
+ let verdict;
196
+ try { verdict = tool.validate(input); } catch (_error) { verdict = false; }
197
+ if (verdict === false || (isObject(verdict) && verdict.ok === false)) return refuse(TOOL_REASONS.INVALID_INPUT);
198
+ if (isObject(verdict) && verdict.ok === true && 'value' in verdict) input = verdict.value;
199
+ }
200
+
201
+ let standing = null;
202
+ if (budget && !tool.budgetExempt) {
203
+ try {
204
+ standing = await budget.check({ scope: call.budgetScope ?? organisationId ?? undefined, limit: settings.budgetLimit, estimate: tool.estimatedCost });
205
+ } catch (_error) { return refuse(TOOL_REASONS.UNAVAILABLE, { input }); }
206
+ if (!standing.allowed) return refuse(TOOL_REASONS.BUDGET, { input, budget: standing });
207
+ }
208
+
209
+ if (settings.maxCallsPerRun !== undefined && rank > settings.maxCallsPerRun) return refuse(TOOL_REASONS.CAP, { input, budget: standing });
210
+ if (tool.maxPerRun !== null && rankOfTool > tool.maxPerRun) return refuse(TOOL_REASONS.CAP, { input, budget: standing });
211
+
212
+ const pending = (code) => ({ decision: TOOL_DECISIONS.PENDING, code, input, budget: standing });
213
+ if (tool.level === TOOL_LEVELS.SENSITIVE) return pending(TOOL_REASONS.SENSITIVE);
214
+ /* Content read from outside could carry a hidden instruction: a person looks first. */
215
+ if ((run.untrusted || call.untrusted === true) && untrustedLevels.includes(tool.level)) return pending(TOOL_REASONS.UNTRUSTED);
216
+ if (tool.level === TOOL_LEVELS.CONTROLLED && tool.overThreshold) {
217
+ let over = false;
218
+ try { over = tool.overThreshold(input, settings) === true; } catch (_error) { over = true; }
219
+ if (over) return pending(TOOL_REASONS.THRESHOLD);
220
+ }
221
+ return { decision: TOOL_DECISIONS.ALLOWED, code: null, input, budget: standing };
222
+ }
223
+
224
+ /* Canonical result -> the application's words. */
225
+ function present(result) {
226
+ return {
227
+ ...result,
228
+ decision: decisionWords.toApp[result.decision],
229
+ code: result.code == null ? null : codeWords.toApp[result.code],
230
+ reasons: result.code == null ? [] : [codeWords.toApp[result.code]],
231
+ level: result.level == null ? null : levelWords.toApp[result.level]
232
+ };
233
+ }
234
+
235
+ async function decideCanonical(call) {
236
+ if (!isObject(call)) throw new GovernorError('invalid_call', 'A tool call must be an object { tool, input, ... }.');
237
+ const run = call.run ?? createRun();
238
+ const name = typeof call.tool === 'string' ? call.tool : call.tool?.name;
239
+ const tool = tools.get(name) ?? null;
240
+ /* Counted at once: calls asked together cannot all slip under a cap. */
241
+ run.calls += 1;
242
+ run.byTool[name] = (run.byTool[name] ?? 0) + 1;
243
+ const verdict = await judge(call, tool, run, run.calls, run.byTool[name]);
244
+ const actor = actorOf(call.actor);
245
+ const record = await audit({
246
+ action: 'tool_decision', organisationId: call.organisationId ?? null, actor,
247
+ tool: String(name ?? '').slice(0, 200), family: tool?.family ?? null, level: tool?.level ?? null,
248
+ decision: verdict.decision, reasons: verdict.code ? [verdict.code] : [],
249
+ inputFingerprint: fingerprintOf(call.input ?? null), callRank: run.calls,
250
+ budget: verdict.budget ? { period: verdict.budget.period, spent: verdict.budget.spent, limit: verdict.budget.limit } : null,
251
+ untrusted: run.untrusted || call.untrusted === true
252
+ });
253
+ return {
254
+ allowed: verdict.decision === TOOL_DECISIONS.ALLOWED, decision: verdict.decision, code: verdict.code ?? null,
255
+ tool: record.tool, family: tool?.family ?? null, level: tool?.level ?? null,
256
+ input: verdict.input ?? call.input ?? null, budget: verdict.budget ?? null, rank: run.calls, auditId: record.id
257
+ };
258
+ }
259
+
260
+ /**
261
+ * Decision for ONE call { tool, input, run?, actor?, organisationId?, untrusted?, budgetScope? }.
262
+ * Never throws for a refusal; throws only if the audit journal cannot be written (nothing runs then).
263
+ */
264
+ const decide = async (call) => present(await decideCanonical(call));
265
+
266
+ /** True when the actor may pull the kill switch. */
267
+ function mayHalt(actor) {
268
+ if (!actor || !isNonEmptyString(actor.id)) return false;
269
+ return activateRoles ? hasRole(actor, activateRoles) : true;
270
+ }
271
+ /** True when the actor may release it. A model or an engine never does; without releaseRoles, only a human. */
272
+ function mayResume(actor) {
273
+ if (!actor || !isNonEmptyString(actor.id) || NEVER_RELEASE.includes(actor.kind)) return false;
274
+ return releaseRoles ? hasRole(actor, releaseRoles) : actor.kind === 'human';
275
+ }
276
+
277
+ async function control(halted, { by, reason, organisationId } = {}) {
278
+ const actor = actorOf(by);
279
+ const scope = organisationId == null ? GLOBAL : String(organisationId);
280
+ const action = halted ? 'tool_halt' : 'tool_resume';
281
+ if (!(halted ? mayHalt(actor) : mayResume(actor))) {
282
+ await audit({ action: `${action}_denied`, organisationId: scope === GLOBAL ? null : scope, actor, decision: 'refused', reasons: ['actor_not_allowed'] });
283
+ throw new GovernorError('actor_not_allowed', halted ? 'This actor may not pull the tool kill switch.' : 'This actor may not release the tool kill switch.');
284
+ }
285
+ const value = { halted, by: actor, reason: reason == null ? null : String(reason).slice(0, 2000), at: iso() };
286
+ await store.setControl(`tools-halt:${scope}`, value);
287
+ await audit({ action, organisationId: scope === GLOBAL ? null : scope, actor, decision: halted ? 'halted' : 'running', reasons: halted && value.reason ? [value.reason] : [] });
288
+ if (halted) {
289
+ for (const running of [...active]) if (scope === GLOBAL || running.organisationId === scope) running.interrupt(TOOL_REASONS.HALTED);
290
+ }
291
+ return value;
292
+ }
293
+
294
+ const raceAbort = (promise, signal) => new Promise((resolve, reject) => {
295
+ const onAbort = () => reject(signal.reason);
296
+ if (signal.aborted) { onAbort(); return; }
297
+ signal.addEventListener('abort', onAbort, { once: true });
298
+ promise.then(resolve, reject).finally(() => signal.removeEventListener('abort', onAbort));
299
+ });
300
+
301
+ /**
302
+ * Decides, then runs `fn(input, { signal, decision })` only when allowed. The kill switch is read before the
303
+ * call and again while it runs (in-process at once, other processes every pollMs); on a stop the signal aborts
304
+ * and the call is cut, even if the tool ignores the signal. A pending or refused call is never run.
305
+ * Returns { ...decision, executed, result? } or, when cut, a refused decision with interrupted: true.
306
+ */
307
+ async function execute(call, fn) {
308
+ if (typeof fn !== 'function') throw new GovernorError('invalid_call', 'execute needs the function to run.');
309
+ const verdict = await decideCanonical(call);
310
+ if (!verdict.allowed) return { ...present(verdict), executed: false, interrupted: false };
311
+ const controller = new globalThis.AbortController();
312
+ let stopped = false;
313
+ const running = {
314
+ organisationId: call.organisationId ?? null,
315
+ interrupt(code) { if (stopped) return; stopped = true; controller.abort(new GovernorError(code, 'The tool call was cut by the emergency stop.')); }
316
+ };
317
+ active.add(running);
318
+ const outer = call.signal;
319
+ const onOuter = () => controller.abort(outer.reason);
320
+ if (outer) { if (outer.aborted) onOuter(); else outer.addEventListener('abort', onOuter, { once: true }); }
321
+ let timer = null;
322
+ if (pollMs > 0) {
323
+ let reading = false;
324
+ timer = setInterval(async () => {
325
+ if (reading) return;
326
+ reading = true;
327
+ try { if ((await haltState(running.organisationId)).halted) running.interrupt(TOOL_REASONS.HALTED); } catch (_error) { running.interrupt(TOOL_REASONS.HALTED); } finally { reading = false; }
328
+ }, pollMs);
329
+ timer.unref?.();
330
+ }
331
+ const outcome = async (kind, extra = {}) => audit({
332
+ action: 'tool_outcome', organisationId: call.organisationId ?? null, actor: actorOf(call.actor), tool: verdict.tool, family: verdict.family, level: verdict.level,
333
+ decision: kind, reasons: extra.reason ? [extra.reason] : [], decisionAuditId: verdict.auditId
334
+ });
335
+ try {
336
+ /* The stop may have been pulled between the decision and now. */
337
+ if ((await haltState(running.organisationId)).halted) running.interrupt(TOOL_REASONS.HALTED);
338
+ const result = await raceAbort(Promise.resolve().then(() => fn(verdict.input, { signal: controller.signal, decision: present(verdict) })), controller.signal);
339
+ await outcome('ok');
340
+ return { ...present(verdict), executed: true, interrupted: false, result };
341
+ } catch (error) {
342
+ if (stopped) {
343
+ await outcome('interrupted', { reason: TOOL_REASONS.HALTED });
344
+ return { ...present({ ...verdict, allowed: false, decision: TOOL_DECISIONS.REFUSED, code: TOOL_REASONS.HALTED }), executed: false, interrupted: true };
345
+ }
346
+ if (outer?.aborted) { await outcome('aborted'); throw error; }
347
+ await outcome('error', { reason: String(error?.name ?? 'Error').slice(0, 100) });
348
+ throw error;
349
+ } finally {
350
+ if (timer) clearInterval(timer);
351
+ outer?.removeEventListener('abort', onOuter);
352
+ active.delete(running);
353
+ }
354
+ }
355
+
356
+ /** Tools the model may be offered: none when stopped or disabled, else those whose family is on. */
357
+ async function availableTools(call = {}) {
358
+ try {
359
+ if ((await haltState(call.organisationId ?? null)).halted) return [];
360
+ const settings = await currentSettings(call);
361
+ if (settings.enabled === false) return [];
362
+ return [...tools.values()].filter((tool) => settings.families[tool.family] !== false).map((tool) => tool.name);
363
+ } catch (_error) { return []; }
364
+ }
365
+
366
+ const describe = () => [...tools.values()].map((tool) => ({
367
+ name: tool.name, family: tool.family, level: levelWords.toApp[tool.level], maxPerRun: tool.maxPerRun, estimatedCost: tool.estimatedCost, budgetExempt: tool.budgetExempt
368
+ }));
369
+
370
+ return Object.freeze({
371
+ version, createRun, decide, execute, availableTools, listTools: describe,
372
+ halt: (opts) => control(true, opts),
373
+ resume: (opts) => control(false, opts),
374
+ isHalted: async (organisationId) => (await haltState(organisationId ?? null)).halted,
375
+ /** Counts what a call really consumed (idempotent on id). Needs a budget. */
376
+ recordSpend: (spend = {}) => {
377
+ if (!budget) throw new GovernorError('budget_invalid', 'This tool policy has no budget.');
378
+ return budget.record({ ...spend, scope: spend.scope ?? spend.organisationId ?? undefined });
379
+ },
380
+ budgetStatus: (query = {}) => {
381
+ if (!budget) throw new GovernorError('budget_invalid', 'This tool policy has no budget.');
382
+ return budget.check({ ...query, scope: query.scope ?? query.organisationId ?? undefined });
383
+ },
384
+ listAudit: (filter = {}) => store.listAudit(filter)
385
+ });
386
+ }
387
+
388
+ module.exports = { createToolPolicy, TOOL_LEVELS, TOOL_DECISIONS, TOOL_REASONS };
package/src/index.d.ts CHANGED
@@ -242,3 +242,6 @@ export const EVIDENCE_DEGREES: readonly EvidenceDegree[];
242
242
  export const EVIDENCE_KINDS: readonly EvidenceKind[];
243
243
  export const PROVENANCE_KINDS: readonly ProvenanceKind[];
244
244
  export const ERASURE_MODES: readonly ['delete', 'anonymise'];
245
+
246
+ export function createMongoConscienceStore(db: import('./governor').MongoDatabase, options?: { prefix?: string }): ConscienceStore;
247
+ export function mongoConscienceIndexes(db: import('./governor').MongoDatabase, options?: { prefix?: string }): Promise<void>;
package/src/index.js CHANGED
@@ -13,7 +13,10 @@ const records = require('./records');
13
13
  const { assertGovernorReady, isGovernor } = require('./governor/governor');
14
14
  const { GovernorError } = require('./governor/util');
15
15
 
16
+ const { createMongoConscienceStore, mongoConscienceIndexes } = require('./mongo');
17
+
16
18
  module.exports = {
19
+ createMongoConscienceStore, mongoConscienceIndexes,
17
20
  createConscience, createMemoryConscienceStore, createPostgresConscienceStore, postgresConscienceSchema,
18
21
  frameStoredText, frameRecordsForModel, wordDelta, matchesFilter,
19
22
  ConscienceError, GovernorError, assertGovernorReady, isGovernor,
package/src/mongo.js ADDED
@@ -0,0 +1,52 @@
1
+ 'use strict';
2
+ const { copy } = require('./governor/util');
3
+ const { MAX_LIMIT } = require('./memoryStore');
4
+ const { collections, read, keyOf, insertOnce, sequence, list } = require('./governor/mongoUtil');
5
+ const tables = (db, options) => collections(db, options, 'astratra_conscience', ['records', 'sequences']);
6
+ const key = (e) => keyOf(e.organisationId, e.kind, e.id);
7
+
8
+ /** Explicit, repeatable migration. Identity uses MongoDB's unique _id index. */
9
+ async function mongoConscienceIndexes(db, options) {
10
+ const t = tables(db, options);
11
+ for (const fields of [
12
+ { 'data.organisationId': 1, 'data.kind': 1, 'data.recordedAt': 1, seq: 1 },
13
+ { 'data.organisationId': 1, 'data.userId': 1 },
14
+ { 'data.organisationId': 1, 'data.kind': 1, 'data.decisionId': 1 },
15
+ { 'data.organisationId': 1, 'data.kind': 1, 'data.lessonId': 1 },
16
+ { 'data.organisationId': 1, 'data.kind': 1, 'data.eventAt': 1 },
17
+ { 'data.organisationId': 1, 'data.evidenceRefs': 1 }
18
+ ]) await t.records.createIndex(fields);
19
+ await t.sequences.createIndex({ _id: 1 });
20
+ }
21
+ function createMongoConscienceStore(db, options) {
22
+ const t = tables(db, options);
23
+ return {
24
+ async put(envelope) {
25
+ return insertOnce(t.records, key(envelope), envelope, { seq: await sequence(t.sequences, 'records') });
26
+ },
27
+ async get(kind, organisationId, id) { return read(await t.records.findOne({ _id: keyOf(organisationId, kind, id) })); },
28
+ list(kind, filter = {}) {
29
+ const query = { 'data.organisationId': filter.organisationId, 'data.kind': kind };
30
+ for (const field of ['userId', 'agentId', 'decisionId', 'lessonId']) if (filter[field] !== undefined) query[`data.${field}`] = { $eq: filter[field] };
31
+ if (Array.isArray(filter.decisionIds)) query.$and = [{ 'data.decisionId': { $in: filter.decisionIds } }];
32
+ if (filter.evidenceRef != null) query['data.evidenceRefs'] = { $eq: filter.evidenceRef };
33
+ if (filter.eventFrom != null || filter.eventTo != null) {
34
+ query['data.eventAt'] = { $ne: null };
35
+ if (filter.eventFrom != null) query['data.eventAt'].$gte = filter.eventFrom;
36
+ if (filter.eventTo != null) query['data.eventAt'].$lt = filter.eventTo;
37
+ }
38
+ if (filter.recordedTo != null) query['data.recordedAt'] = { $lte: filter.recordedTo };
39
+ const order = filter.order === 'desc' ? -1 : 1;
40
+ return list(t.records, query, { 'data.recordedAt': order, seq: order }, Math.min(Math.max(Number(filter.limit) || 1000, 1), MAX_LIMIT));
41
+ },
42
+ async replace(envelope) {
43
+ return read(await t.records.findOneAndUpdate({ _id: key(envelope) }, { $set: { data: copy(envelope) } },
44
+ { returnDocument: 'after', includeResultMetadata: false }));
45
+ },
46
+ async remove(kind, organisationId, ids) {
47
+ if (!ids.length) return 0;
48
+ return (await t.records.deleteMany({ _id: { $in: ids.map((id) => keyOf(organisationId, kind, id)) } })).deletedCount;
49
+ }
50
+ };
51
+ }
52
+ module.exports = { createMongoConscienceStore, mongoConscienceIndexes };