@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.
@@ -111,7 +111,7 @@ export interface ChangeProposal {
111
111
 
112
112
  export interface AuditEntry {
113
113
  id: string; at: string; policyVersion: string; organisationId: string | null; proposalId: string | null;
114
- action: 'evaluate' | 'approve' | 'decline' | 'approval_expired' | 'expire' | 'halt' | 'resume' | 'spend' | 'spend_refused' | 'register' | 'stage' | 'deploy' | 'promote' | 'rollback' | 'emergency_revert' | 'finding';
114
+ action: 'evaluate' | 'approve' | 'decline' | 'approval_expired' | 'expire' | 'halt' | 'resume' | 'spend' | 'spend_refused' | 'register' | 'stage' | 'deploy' | 'promote' | 'rollback' | 'emergency_revert' | 'finding' | ToolAuditAction;
115
115
  decision: string; reasons: string[]; actor: Actor | null; [key: string]: unknown;
116
116
  }
117
117
 
@@ -383,3 +383,180 @@ export function parseRemoteSettings(raw: unknown): RemoteSettings;
383
383
  export function remotePolicy(localPolicy: GovernorPolicyInput, settings: RemoteSettings | null, options?: { costPerCycle?: number }): GovernorPolicyInput;
384
384
  export const REMOTE_SETTINGS_SCHEMA: 'conscience-settings/1';
385
385
  export const DECISION_RESULTS: readonly ['applied', 'already_applied', 'refused', 'failed'];
386
+
387
+ /** Native driver objects; pass connection.db and connection.getClient() with mongoose. */
388
+ export interface MongoDatabase { collection(name: string): any; client?: MongoSessionClient }
389
+ export interface MongoSessionClient { startSession(): any }
390
+ export interface MongoStoreOptions { prefix?: string; client?: MongoSessionClient }
391
+ /** Requires a replica set or sharded cluster for atomic spending. */
392
+ export function createMongoGovernorStore(db: MongoDatabase, options?: MongoStoreOptions): GovernorStore;
393
+ export function mongoGovernorIndexes(db: MongoDatabase, options?: { prefix?: string }): Promise<void>;
394
+
395
+ /* ---- Tool policy and calendar budget (generic: families, levels, caps and vocabulary are yours) ---- */
396
+
397
+ export type ToolAuditAction = 'tool_decision' | 'tool_outcome' | 'tool_halt' | 'tool_halt_denied' | 'tool_resume' | 'tool_resume_denied';
398
+ export const TOOL_LEVELS: { readonly READ: 'read'; readonly CONTROLLED: 'controlled'; readonly SENSITIVE: 'sensitive' };
399
+ export const TOOL_DECISIONS: { readonly ALLOWED: 'allowed'; readonly PENDING: 'pending'; readonly REFUSED: 'refused' };
400
+ export const TOOL_REASONS: {
401
+ readonly HALTED: 'emergency_stop'; readonly DISABLED: 'disabled'; readonly UNAVAILABLE: 'settings_unavailable'; readonly UNKNOWN_TOOL: 'unknown_tool';
402
+ readonly FAMILY_DISABLED: 'family_disabled'; readonly INVALID_INPUT: 'invalid_input'; readonly BUDGET: 'budget_exceeded'; readonly CAP: 'cap_reached';
403
+ readonly SENSITIVE: 'sensitive_tool'; readonly UNTRUSTED: 'untrusted_context'; readonly THRESHOLD: 'over_threshold';
404
+ };
405
+ export type ToolLevel = 'read' | 'controlled' | 'sensitive';
406
+ export type ToolDecisionWord = 'allowed' | 'pending' | 'refused';
407
+ export type ToolReasonCode = typeof TOOL_REASONS[keyof typeof TOOL_REASONS];
408
+
409
+ /** An actor of a tool call or of the kill switch. `roles` are checked against emergency.activateRoles / releaseRoles. */
410
+ export interface ToolActor { kind: string; id: string; roles?: string[] }
411
+
412
+ export interface ToolDefinition {
413
+ /** Letters, digits, _ . : - ; starts with a letter. */
414
+ name: string;
415
+ family: string;
416
+ /** One of the level words (the canonical ones, or yours when labels.levels renames them). */
417
+ level: string;
418
+ /** Returns false, { ok: false }, or { ok: true, value } (the value replaces the input). May throw: invalid. */
419
+ validate?(input: any): boolean | { ok: boolean; value?: unknown };
420
+ /** Controlled tools only: true sends the call to a person (an amount over your own threshold, for instance). Throwing counts as true. */
421
+ overThreshold?(input: any, settings: ToolSettings): boolean;
422
+ /** At most this many calls of the tool in one run; the next ones are refused (cap_reached). */
423
+ maxPerRun?: number;
424
+ /** Whole units this call is expected to consume: refused up front when it cannot fit in the budget. */
425
+ estimatedCost?: number;
426
+ /** Stays callable when the budget is exhausted (read-only state, for instance). */
427
+ budgetExempt?: boolean;
428
+ }
429
+
430
+ /** Settings read before EACH call; anything else you put in is handed back to your validate and overThreshold functions. */
431
+ export interface ToolSettings {
432
+ /** false: every call is refused (disabled). */
433
+ enabled?: boolean;
434
+ /** family -> on/off. A family that is not listed is on. */
435
+ families?: Record<string, boolean>;
436
+ /** Cap of the calendar budget, whole units. Overrides the default limit of the budget. */
437
+ budgetLimit?: number | null;
438
+ /** Calls of all tools in one run. */
439
+ maxCallsPerRun?: number | null;
440
+ [key: string]: unknown;
441
+ }
442
+
443
+ export interface ToolRun { calls: number; byTool: Record<string, number>; untrusted: boolean; /** Call after the run read content from outside (a web page, a file...). */ markUntrusted(): void }
444
+
445
+ export interface ToolCall {
446
+ tool: string;
447
+ input?: unknown;
448
+ /** The counters of the run (createRun()). Without it each call is a run of its own. */
449
+ run?: ToolRun;
450
+ actor?: ToolActor | null;
451
+ organisationId?: string | null;
452
+ /** The caller flags this call as made in an untrusted context. */
453
+ untrusted?: boolean;
454
+ /** Budget scope; defaults to organisationId, then "default". */
455
+ budgetScope?: string;
456
+ /** execute() only: the caller's own abort signal. */
457
+ signal?: AbortSignal;
458
+ }
459
+
460
+ export interface ToolDecision {
461
+ allowed: boolean;
462
+ /** 'allowed' | 'pending' | 'refused', or your word. */
463
+ decision: string;
464
+ /** Why it is not allowed (a TOOL_REASONS value, or your word); null when allowed. */
465
+ code: string | null;
466
+ reasons: string[];
467
+ tool: string; family: string | null; level: string | null;
468
+ /** The input after validate(). */
469
+ input: unknown;
470
+ budget: BudgetStanding | null;
471
+ /** Rank of this call in its run. */
472
+ rank: number;
473
+ /** Id of the audit record of this decision. */
474
+ auditId: string;
475
+ }
476
+ export interface ToolExecution<T = unknown> extends ToolDecision { executed: boolean; interrupted: boolean; result?: T }
477
+
478
+ export interface ToolPolicyOptions {
479
+ tools: ToolDefinition[];
480
+ /** When given, every tool's family must be in the list. */
481
+ families?: string[];
482
+ /** Static settings under what settings() returns. */
483
+ defaults?: ToolSettings;
484
+ /** Read before every call. May throw: the call is refused (settings_unavailable). */
485
+ settings?(context: { organisationId: string | null; actor: ToolActor | null }): ToolSettings | Promise<ToolSettings>;
486
+ /** A calendar budget (createCalendarBudget) or its options. */
487
+ budget?: CalendarBudget | CalendarBudgetOptions;
488
+ /** Levels whose calls wait for a person after an untrusted read (default: only the controlled level). */
489
+ untrustedPendingLevels?: string[];
490
+ emergency?: {
491
+ /** Roles allowed to pull the kill switch (default: any actor with an id). */
492
+ activateRoles?: string[];
493
+ /** Roles allowed to release it (default: any human). A model or an engine never can. */
494
+ releaseRoles?: string[];
495
+ };
496
+ /** Rename the words you get back: canonical word -> your word. Tools declare their level in your word. */
497
+ labels?: { levels?: Partial<Record<ToolLevel, string>>; decisions?: Partial<Record<ToolDecisionWord, string>>; codes?: Partial<Record<ToolReasonCode, string>> };
498
+ /** Audit journal and kill switch keys (default: memory). Use the store of your governor. */
499
+ store?: Pick<GovernorStore, 'appendAudit' | 'listAudit' | 'getControl' | 'setControl'>;
500
+ /** A governor whose kill switch also stops the tools. */
501
+ governor?: Governor;
502
+ version?: string;
503
+ /** How often a running tool looks at the kill switch pulled by another process (default 1000, 0 = off). */
504
+ pollMs?: number;
505
+ now?(): number;
506
+ idFactory?(): string;
507
+ onEvent?(event: { type: 'tool_policy' } & AuditEntry): void | Promise<void>;
508
+ }
509
+
510
+ export interface ToolPolicy {
511
+ readonly version: string;
512
+ createRun(): ToolRun;
513
+ /** The decision for one call; audited. Throws only when the journal cannot be written. */
514
+ decide(call: ToolCall): Promise<ToolDecision>;
515
+ /** Decides, then runs fn only when allowed, and cuts it at once on an emergency stop (signal + abandon). */
516
+ execute<T>(call: ToolCall, fn: (input: any, context: { signal: AbortSignal; decision: ToolDecision }) => T | Promise<T>): Promise<ToolExecution<Awaited<T>>>;
517
+ /** Names of the tools to offer the model now (none when stopped or disabled). */
518
+ availableTools(context?: { organisationId?: string | null }): Promise<string[]>;
519
+ listTools(): Array<{ name: string; family: string; level: string; maxPerRun: number | null; estimatedCost: number; budgetExempt: boolean }>;
520
+ halt(options: { by: ToolActor; reason?: string; organisationId?: string }): Promise<unknown>;
521
+ resume(options: { by: ToolActor; organisationId?: string }): Promise<unknown>;
522
+ isHalted(organisationId?: string | null): Promise<boolean>;
523
+ /** Counts what a call really consumed (whole units, idempotent by id), in the period of `at` (default now). */
524
+ recordSpend(spend: { id: string; amount: number; organisationId?: string; scope?: string; at?: number }): Promise<{ added: boolean; scope: string; period: string; spent: number }>;
525
+ budgetStatus(query?: { organisationId?: string; scope?: string; at?: number; estimate?: number }): Promise<BudgetStanding>;
526
+ listAudit: GovernorStore['listAudit'];
527
+ }
528
+ export function createToolPolicy(options: ToolPolicyOptions): ToolPolicy;
529
+
530
+ export interface BudgetStanding {
531
+ /** false when the cap is reached (or the estimate does not fit). */
532
+ allowed: boolean; exceeded: boolean; scope: string; period: string; spent: number; limit: number | null; remaining: number | null;
533
+ }
534
+ /** spent/limit/remaining are whole units of your choice (cents, thousandths of cents, tokens...). No fractions. */
535
+ export interface ToolBudgetStore {
536
+ getSpent(scope: string, period: string): Promise<number>;
537
+ /** Idempotent by (scope, id): a replay adds nothing and returns added: false. */
538
+ addSpend(entry: { scope: string; period: string; id: string; amount: number; at: string }): Promise<{ added: boolean; spent: number }>;
539
+ }
540
+ export interface CalendarBudgetOptions {
541
+ /** 'month' (default), 'day', or a function (instant, timeZone) => key. */
542
+ period?: 'month' | 'day' | ((at: Date, timeZone: string) => string);
543
+ /** IANA time zone (default UTC). */
544
+ timeZone?: string;
545
+ /** Default cap in whole units; absent: no cap. */
546
+ limit?: number | null;
547
+ scope?: string;
548
+ store?: ToolBudgetStore;
549
+ now?(): number;
550
+ }
551
+ export interface CalendarBudget {
552
+ check(query?: { scope?: string; limit?: number | null; estimate?: number; at?: number | Date }): Promise<BudgetStanding>;
553
+ record(spend: { id: string; amount: number; scope?: string; at?: number | Date }): Promise<{ added: boolean; scope: string; period: string; spent: number }>;
554
+ periodKey(at?: number | Date): string;
555
+ readonly period: string; readonly timeZone: string;
556
+ }
557
+ export function createCalendarBudget(options?: CalendarBudgetOptions): CalendarBudget;
558
+ /** "2026-10" (month) or "2026-10-31" (day) of an instant, in a time zone. */
559
+ export function calendarPeriodKey(at: number | Date, options?: { period?: CalendarBudgetOptions['period']; timeZone?: string }): string;
560
+ export function createMemoryToolBudgetStore(): ToolBudgetStore;
561
+ export function createPostgresToolBudgetStore(db: Queryable, options?: { prefix?: string }): ToolBudgetStore;
562
+ export function postgresToolBudgetSchema(options?: { prefix?: string }): string;
@@ -13,7 +13,15 @@ const { SEVERITIES, REPORT_SCHEMA } = require('./review');
13
13
  const { bucket } = require('./rollout');
14
14
  const { createRemoteSettings, parseRemoteSettings, remotePolicy, REMOTE_SETTINGS_SCHEMA, DECISION_RESULTS } = require('./remote');
15
15
 
16
+ const { createMongoGovernorStore, mongoGovernorIndexes } = require('./mongo');
17
+ const { createToolPolicy, TOOL_LEVELS, TOOL_DECISIONS, TOOL_REASONS } = require('./tools');
18
+ const { createCalendarBudget, calendarPeriodKey, createMemoryToolBudgetStore } = require('./calendar');
19
+ const { postgresToolBudgetSchema, createPostgresToolBudgetStore } = require('./toolBudgetPostgres');
20
+
16
21
  module.exports = {
22
+ createToolPolicy, TOOL_LEVELS, TOOL_DECISIONS, TOOL_REASONS, createCalendarBudget, calendarPeriodKey, createMemoryToolBudgetStore,
23
+ postgresToolBudgetSchema, createPostgresToolBudgetStore,
24
+ createMongoGovernorStore, mongoGovernorIndexes,
17
25
  createGovernor, assertGovernorReady, isGovernor, validatePolicy, scopesOf, protectedRulesTouched,
18
26
  createMemoryGovernorStore, createPostgresGovernorStore, postgresGovernorSchema, GovernorError,
19
27
  PROPOSAL_STATUSES: STATUSES, REASONS, PROTECTED_SCOPES, MODIFIABLE_KINDS, AUTOMATIC_CHANGES, DEFAULT_CONSTITUTION,
@@ -0,0 +1,132 @@
1
+ 'use strict';
2
+ const { copy } = require('./util');
3
+ const { boundedLimit } = require('./stores');
4
+ const { collections, read, keyOf, literal, insertOnce, sequence, list } = require('./mongoUtil');
5
+ const suffixes = ['proposals', 'audit', 'spend', 'controls', 'objects', 'versions', 'findings', 'sequences', 'locks'];
6
+ const tables = (db, options) => collections(db, options, 'astratra_governor', suffixes);
7
+ const objectKey = (organisationId, kind, id) => keyOf(organisationId, kind, id);
8
+
9
+ /** Explicit, repeatable migration; never run implicitly by the store. */
10
+ async function mongoGovernorIndexes(db, options) {
11
+ const t = tables(db, options);
12
+ await t.proposals.createIndex({ 'data.organisationId': 1, 'data.status': 1, 'data.createdAt': -1, 'data.id': 1 });
13
+ await t.audit.createIndex({ 'data.id': 1 }, { unique: true });
14
+ await t.audit.createIndex({ 'data.organisationId': 1, seq: -1 });
15
+ await t.spend.createIndex({ organisationId: 1, at: 1 });
16
+ await t.objects.createIndex({ 'data.organisationId': 1, 'data.kind': 1, 'data.id': 1 });
17
+ await t.objects.createIndex({ 'data.candidate': 1 });
18
+ await t.versions.createIndex({ 'data.organisationId': 1, 'data.kind': 1, 'data.id': 1, 'data.number': 1 });
19
+ await t.findings.createIndex({ 'data.organisationId': 1, 'data.receivedAt': -1, 'data.id': 1 });
20
+ // Materialize transaction collections before the first reservation.
21
+ for (const name of ['locks', 'controls', 'sequences']) await t[name].createIndex({ _id: 1 });
22
+ }
23
+
24
+ /** Native Db, also available as a mongoose connection's .db. No driver import. */
25
+ function createMongoGovernorStore(db, options = {}) {
26
+ const t = tables(db, options);
27
+ const client = options.client ?? db.client;
28
+ if (!client || typeof client.startSession !== 'function') throw new TypeError('A MongoClient with startSession() is required.');
29
+ const get = async (table, key) => read(await table.findOne({ _id: key }));
30
+ return {
31
+ putProposal(record) { return insertOnce(t.proposals, keyOf(record.organisationId, record.id), record); },
32
+ getProposal(organisationId, id) { return get(t.proposals, keyOf(organisationId, id)); },
33
+ async transitionProposal(organisationId, id, fromStatus, patch, guard) {
34
+ const filter = { _id: keyOf(organisationId, id), 'data.status': fromStatus };
35
+ if (guard?.approvals !== undefined) filter.$expr = { $eq: [{ $size: { $ifNull: ['$data.approvals', []] } }, guard.approvals] };
36
+ return read(await t.proposals.findOneAndUpdate(filter,
37
+ [{ $set: { data: { $mergeObjects: ['$data', literal(patch)] } } }],
38
+ { returnDocument: 'after', includeResultMetadata: false }));
39
+ },
40
+ listProposals(filter = {}) {
41
+ const query = { 'data.organisationId': filter.organisationId };
42
+ if (filter.status != null) query['data.status'] = { $eq: filter.status };
43
+ if (filter.statuses != null) query.$and = [{ 'data.status': { $in: filter.statuses } }];
44
+ if (filter.since != null) query.$expr = { $gte: [{ $ifNull: ['$data.decidedAt', '$data.createdAt'] }, literal(filter.since)] };
45
+ return list(t.proposals, query, { 'data.createdAt': -1, 'data.id': 1 }, boundedLimit(filter.limit));
46
+ },
47
+ async appendAudit(entry) {
48
+ const seq = await sequence(t.sequences, 'audit');
49
+ await t.audit.insertOne({ _id: entry.id, data: copy(entry), seq });
50
+ return copy(entry);
51
+ },
52
+ listAudit(filter = {}) {
53
+ const query = {};
54
+ for (const field of ['organisationId', 'proposalId', 'objectKind', 'objectId']) {
55
+ if (filter[field] !== undefined && (field === 'organisationId' || filter[field] != null)) query[`data.${field}`] = { $eq: filter[field] };
56
+ }
57
+ if (filter.actions != null) query['data.action'] = { $in: filter.actions };
58
+ if (filter.since != null) query['data.at'] = { $gte: filter.since };
59
+ return list(t.audit, query, { seq: -1 }, boundedLimit(filter.limit));
60
+ },
61
+ async reserveSpend(entry, limits) {
62
+ if (!Number.isFinite(entry.cost) || entry.cost < 0) throw new TypeError('Spend cost must be finite and nonnegative.');
63
+ // A permanent organisation lock document is updated in every transaction.
64
+ // Conflicting reservations retry through withTransaction, with a new snapshot.
65
+ try {
66
+ await t.locks.updateOne({ _id: entry.organisationId }, { $setOnInsert: { revision: 0 } }, { upsert: true });
67
+ } catch (error) {
68
+ if (error.code !== 11000) throw error;
69
+ if (!await t.locks.findOne({ _id: entry.organisationId })) throw error;
70
+ }
71
+ const session = client.startSession();
72
+ try {
73
+ return await session.withTransaction(async () => {
74
+ await t.locks.updateOne({ _id: entry.organisationId }, { $inc: { revision: 1 } }, { session });
75
+ const rows = await t.spend.find({ organisationId: entry.organisationId }, { session }).toArray();
76
+ const sums = () => {
77
+ const totals = { cycle: 0, agent: 0, organisation: 0 };
78
+ for (const row of rows) {
79
+ if (entry.cycleId != null && row.cycleId === entry.cycleId) totals.cycle += row.cost;
80
+ if (row.at >= limits.since) {
81
+ totals.organisation += row.cost;
82
+ if (row.agentId === entry.agentId) totals.agent += row.cost;
83
+ }
84
+ }
85
+ return totals;
86
+ };
87
+ if (rows.some((row) => row._id === keyOf(entry.organisationId, entry.id))) return { reserved: true, created: false, totals: sums() };
88
+ const totals = sums();
89
+ if ((entry.cycleId != null && totals.cycle + entry.cost > limits.perCycle)
90
+ || totals.agent + entry.cost > limits.perAgent || totals.organisation + entry.cost > limits.perOrganisation) return { reserved: false, created: false, totals };
91
+ const row = { ...copy(entry), _id: keyOf(entry.organisationId, entry.id) };
92
+ await t.spend.insertOne(row, { session });
93
+ rows.push(row);
94
+ return { reserved: true, created: true, totals: sums() };
95
+ }, { readConcern: { level: 'snapshot' }, writeConcern: { w: 'majority' }, readPreference: 'primary' });
96
+ } finally { await session.endSession(); }
97
+ },
98
+ getControl(key) { return get(t.controls, key); },
99
+ async setControl(key, value) {
100
+ await t.controls.updateOne({ _id: key }, { $set: { data: copy(value) } }, { upsert: true });
101
+ return copy(value);
102
+ },
103
+ getObject(organisationId, kind, id) { return get(t.objects, objectKey(organisationId, kind, id)); },
104
+ createObject(state) { return insertOnce(t.objects, objectKey(state.organisationId, state.kind, state.id), state); },
105
+ async updateObject(organisationId, kind, id, expectedRevision, next) {
106
+ return read(await t.objects.findOneAndUpdate({ _id: objectKey(organisationId, kind, id), 'data.revision': expectedRevision },
107
+ { $set: { data: copy(next) } }, { returnDocument: 'after', includeResultMetadata: false }));
108
+ },
109
+ listObjects(filter = {}) {
110
+ const query = {};
111
+ for (const field of ['organisationId', 'kind']) if (filter[field] != null) query[`data.${field}`] = { $eq: filter[field] };
112
+ if (filter.hasCandidate) query['data.candidate'] = { $ne: null };
113
+ return list(t.objects, query, { 'data.organisationId': 1, 'data.kind': 1, 'data.id': 1 }, boundedLimit(filter.limit));
114
+ },
115
+ putVersion(record) { return insertOnce(t.versions, keyOf(record.organisationId, record.kind, record.id, record.versionId), record); },
116
+ getVersion(organisationId, kind, id, versionId) { return get(t.versions, keyOf(organisationId, kind, id, versionId)); },
117
+ listVersions(filter) {
118
+ return list(t.versions, { 'data.organisationId': filter.organisationId, 'data.kind': filter.kind, 'data.id': filter.id }, { 'data.number': 1 }, boundedLimit(filter.limit, 1000));
119
+ },
120
+ putFinding(record) { return insertOnce(t.findings, keyOf(record.organisationId, record.id), record); },
121
+ listFindings(filter = {}) {
122
+ const query = { 'data.organisationId': filter.organisationId };
123
+ if (filter.since != null || filter.until != null) {
124
+ query['data.receivedAt'] = {};
125
+ if (filter.since != null) query['data.receivedAt'].$gte = filter.since;
126
+ if (filter.until != null) query['data.receivedAt'].$lte = filter.until;
127
+ }
128
+ return list(t.findings, query, { 'data.receivedAt': -1, 'data.id': 1 }, boundedLimit(filter.limit));
129
+ }
130
+ };
131
+ }
132
+ module.exports = { createMongoGovernorStore, mongoGovernorIndexes };
@@ -0,0 +1,33 @@
1
+ 'use strict';
2
+ const { prefixOf, copy } = require('./util');
3
+
4
+ function collections(db, options, fallback, suffixes) {
5
+ if (!db || typeof db.collection !== 'function') throw new TypeError('A native MongoDB Db is required.');
6
+ const prefix = prefixOf(options, fallback);
7
+ return Object.fromEntries(suffixes.map((name) => [name, db.collection(`${prefix}_${name}`)]));
8
+ }
9
+ const read = (row) => copy(row?.data ?? null);
10
+ const keyOf = (...parts) => JSON.stringify(parts);
11
+ const literal = (value) => ({ $literal: copy(value) });
12
+
13
+ async function insertOnce(collection, key, data, extra = {}) {
14
+ const document = { _id: key, data: copy(data), ...extra };
15
+ try {
16
+ await collection.insertOne(document);
17
+ return { record: copy(data), created: true };
18
+ } catch (error) {
19
+ if (error.code !== 11000) throw error;
20
+ const old = await collection.findOne({ _id: key });
21
+ if (!old) throw error;
22
+ return { record: read(old), created: false };
23
+ }
24
+ }
25
+ async function sequence(collection, name) {
26
+ const row = await collection.findOneAndUpdate({ _id: name }, { $inc: { value: 1 } },
27
+ { upsert: true, returnDocument: 'after', includeResultMetadata: false });
28
+ return row.value;
29
+ }
30
+ async function list(collection, filter, sort, limit) {
31
+ return (await collection.find(filter).sort(sort).limit(limit).toArray()).map(read);
32
+ }
33
+ module.exports = { collections, read, keyOf, literal, insertOnce, sequence, list };
@@ -0,0 +1,59 @@
1
+ 'use strict';
2
+ const { prefixOf, requireQueryable } = require('./util');
3
+
4
+ const DEFAULT_PREFIX = 'astratra_tools';
5
+ const names = (options) => {
6
+ const p = prefixOf(options, DEFAULT_PREFIX);
7
+ return { totals: `"${p}_budget_totals"`, entries: `"${p}_budget_entries"`, raw: p };
8
+ };
9
+
10
+ /** SQL that creates the tool budget tables. Idempotent: run it at every start or in a migration. */
11
+ function postgresToolBudgetSchema(options) {
12
+ const t = names(options);
13
+ return `CREATE TABLE IF NOT EXISTS ${t.totals} (
14
+ scope text NOT NULL,
15
+ period text NOT NULL,
16
+ spent bigint NOT NULL DEFAULT 0 CHECK (spent >= 0),
17
+ PRIMARY KEY (scope, period)
18
+ );
19
+ CREATE TABLE IF NOT EXISTS ${t.entries} (
20
+ scope text NOT NULL,
21
+ id text NOT NULL,
22
+ period text NOT NULL,
23
+ amount bigint NOT NULL CHECK (amount >= 0),
24
+ at timestamptz NOT NULL,
25
+ PRIMARY KEY (scope, id)
26
+ );`;
27
+ }
28
+
29
+ /**
30
+ * Tool budget store on PostgreSQL. `db` is any `{ query(sql, params) }`. A
31
+ * consumption is added by ONE statement (entry and total together), so it is
32
+ * atomic and idempotent without a transaction. Amounts are bigint integers.
33
+ */
34
+ function createPostgresToolBudgetStore(db, options = {}) {
35
+ requireQueryable(db);
36
+ const t = names(options);
37
+ return {
38
+ async getSpent(scope, period) {
39
+ const row = (await db.query(`SELECT spent::text AS spent FROM ${t.totals} WHERE scope = $1 AND period = $2`, [scope, period])).rows[0];
40
+ return row ? Number(row.spent) : 0;
41
+ },
42
+ async addSpend({ scope, period, id, amount, at }) {
43
+ const row = (await db.query(
44
+ `WITH ins AS (
45
+ INSERT INTO ${t.entries} (scope, id, period, amount, at) VALUES ($1, $2, $3, $4, $5::timestamptz)
46
+ ON CONFLICT (scope, id) DO NOTHING RETURNING amount
47
+ ), upd AS (
48
+ INSERT INTO ${t.totals} (scope, period, spent) SELECT $1, $3, amount FROM ins
49
+ ON CONFLICT (scope, period) DO UPDATE SET spent = ${t.totals}.spent + EXCLUDED.spent RETURNING spent
50
+ )
51
+ SELECT (SELECT count(*) FROM ins)::int AS added,
52
+ coalesce((SELECT spent FROM upd), (SELECT spent FROM ${t.totals} WHERE scope = $1 AND period = $3), 0)::text AS spent`,
53
+ [scope, id, period, amount, at])).rows[0];
54
+ return { added: Number(row.added) > 0, spent: Number(row.spent) };
55
+ }
56
+ };
57
+ }
58
+
59
+ module.exports = { postgresToolBudgetSchema, createPostgresToolBudgetStore };