@astratra/conscience 1.0.0 → 1.2.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.
package/README.fr.md CHANGED
@@ -257,6 +257,59 @@ Le bilan ne recopie aucun texte libre de l'auteur, seulement des identifiants,
257
257
  des codes, des nombres et les objets `tests` et plan de retour arrière fournis.
258
258
  Tout est lu dans une seule organisation.
259
259
 
260
+ ### Réglages distants (tableau de bord)
261
+
262
+ `createRemoteSettings` permet à un tableau de bord d'allumer ou d'éteindre
263
+ l'agent, de tirer ou de lever son arrêt d'urgence, de nommer ses approbateurs et
264
+ de régler sa réflexion, et aux humains d'y approuver ou refuser les
265
+ propositions. Le gouverneur reste seul juge : l'adaptateur transforme les
266
+ réglages en options du gouverneur et soumet chaque décision humaine par
267
+ `approveProposal` / `declineProposal`. Il n'importe que ce dossier : vous lui
268
+ passez la fonction qui lit les réglages.
269
+
270
+ ```js
271
+ const { createRemoteSettings, createPostgresGovernorStore } = require('@astratra/conscience/governor');
272
+
273
+ const remote = createRemoteSettings({
274
+ read: () => tableau.lireReglages(), // votre client, avec son propre cache
275
+ policy: politiqueLocale, // constitution, permissions, PLAFONDS de budget
276
+ organisationId: 'org-1',
277
+ storage: { load: () => cache.lire(), save: (s) => cache.ecrire(s) } // facultatif : survit aux redémarrages
278
+ });
279
+ const store = createPostgresGovernorStore(pool);
280
+
281
+ setInterval(async () => {
282
+ await remote.refresh(); // ne lève jamais
283
+ const governor = remote.governor({ store }); // à redemander à chaque fois : refait quand la politique change
284
+ await remote.sync(governor); // arrêt d'urgence distant, appliqué tout de suite
285
+ const resultats = await remote.applyDecisions(governor, await tableau.lireDecisions());
286
+ // renvoyer les résultats (applied, already_applied, refused + code ; failed = réessayer plus tard)
287
+ }, 60_000);
288
+
289
+ if (remote.reflectionDue()) await lancerCycle({ cycleId: remote.reflectionCycleId() });
290
+ ```
291
+
292
+ Réglages (`conscience-settings/1`) : `version`, `enabled`, `halted`,
293
+ `resumedBy`, `approvers`, `reflection { automatic, hour, timeZone }`,
294
+ `cyclesPerDay`. Règles :
295
+
296
+ | Situation | Effet |
297
+ |---|---|
298
+ | Source muette, lente ou invalide | Le dernier réglage valide reste (`source: 'last_known'`), en mémoire ou dans `storage` |
299
+ | Aucun réglage valide jamais reçu | Tout éteint : désactivé, gouverneur arrêté, aucun approbateur |
300
+ | `version` plus ancienne que celle en vigueur | Ignorée (`stale_settings`) |
301
+ | `halted: true` | Appliqué aussitôt, même dans une réponse invalide ou périmée ; `sync` tire l'arrêt d'urgence du gouverneur (les candidates reviennent à la version stable) |
302
+ | Arrêt levé | `sync` ne relâche qu'un arrêt qu'il a tiré, et seulement au nom de l'humain de `resumedBy` ; un arrêt tiré par quelqu'un d'autre reste |
303
+ | `enabled: false` | Gouverneur arrêté ; `reflectionDue()` vaut faux |
304
+ | `cyclesPerDay` | `perAgent` et `perOrganisation` deviennent `min(local, cyclesPerDay × costPerCycle)`, jamais au-dessus des valeurs locales |
305
+ | `approvers` | Les approbateurs du gouverneur ; dans la liste locale `approvers` quand elle existe |
306
+ | Tout le reste (`constitution`, `budgets`, `permissions`, `approvals`…) | Jamais appliqué, listé dans `current().ignored` |
307
+
308
+ `applyDecisions` se rejoue sans risque : une décision que le gouverneur a déjà
309
+ revient en `already_applied`, une approbation n'est donc jamais comptée deux
310
+ fois. Approbateurs, arrêt, portées protégées, rôles et expiration restent
311
+ vérifiés par le gouverneur.
312
+
260
313
  ### Contrôle au démarrage
261
314
 
262
315
  `assertGovernorReady(governor, { organisationId })` lève `governor_missing`,
@@ -872,6 +925,93 @@ supprimer avec la personne.
872
925
  (schéma : `postgresShadowSchema({ prefix })`, table `<prefix>_runs`). Même
873
926
  contrat, mêmes tests, toute valeur est un paramètre SQL.
874
927
 
928
+ ## Stockage MongoDB
929
+
930
+ Installer le pilote comme dépendance facultative seulement pour MongoDB :
931
+
932
+ ```sh
933
+ npm install mongodb
934
+ ```
935
+
936
+ Les deux magasins reçoivent un `Db` du pilote officiel. Ils n'importent jamais
937
+ le pilote et n'ouvrent aucune connexion. Avec mongoose, attendre la connexion,
938
+ puis fournir `connection.db` et, pour le gouverneur, `connection.getClient()`
939
+ dans l'option `client`. Le pilote est une peerDependency optionnelle
940
+ (`^6.0.0 || ^7.0.0`) ; mongoose n'est pas une dépendance.
941
+
942
+ ```js
943
+ const { MongoClient } = require('mongodb');
944
+ const { createMongoGovernorStore, mongoGovernorIndexes, createGovernor } = require('@astratra/conscience/governor');
945
+ const { createMongoConscienceStore, mongoConscienceIndexes, createConscience } = require('@astratra/conscience');
946
+
947
+ const client = new MongoClient(process.env.DATABASE_URL);
948
+ await client.connect();
949
+ const db = client.db();
950
+ await mongoGovernorIndexes(db, { prefix: 'app_governor' });
951
+ await mongoConscienceIndexes(db, { prefix: 'app_memory' });
952
+ const governor = createGovernor({
953
+ budgets: { perCycle: 1, perAgent: 5, perOrganisation: 20 }
954
+ }, { store: createMongoGovernorStore(db, { prefix: 'app_governor', client }) });
955
+ const conscience = createConscience({
956
+ governor, masker: (texte) => masquerDansApplication(texte),
957
+ store: createMongoConscienceStore(db, { prefix: 'app_memory' })
958
+ });
959
+ ```
960
+
961
+ Les fonctions d'index sont des migrations explicites et idempotentes, à appeler
962
+ avant l'utilisation. Un préfixe contient lettres, chiffres et traits de
963
+ soulignement, commence par une lettre ou un trait de soulignement, et ne dépasse
964
+ pas 41 caractères. Valeurs par défaut : `astratra_governor` et
965
+ `astratra_conscience`. Collections du gouverneur : suffixes `proposals`, `audit`,
966
+ `spend`, `controls`, `objects`, `versions`, `findings`, `sequences`, `locks`.
967
+ Mémoire des décisions : `records` et `sequences`.
968
+
969
+ L'identité est encodée dans l'index unique `_id` : organisation et identifiant,
970
+ avec type et version si nécessaire. Une insertion rend le contenu existant sans
971
+ le modifier. Les approbations comparent atomiquement statut et nombre
972
+ d'approbations ; les objets comparent leur révision. Les identifiants d'audit
973
+ sont uniques, avec un compteur persistant pour l'ordre. Les records ont aussi
974
+ un compteur pour départager les dates égales ; le remplacement conserve l'ordre.
975
+ Filtres, rétention et `conscience.eraseSubject()` suivent le contrat PostgreSQL,
976
+ avec isolation des organisations et invalidation des preuves. L'effacement
977
+ porte sur la mémoire des décisions ; la conservation de l'audit du gouverneur
978
+ reste une politique de l'application, comme avec PostgreSQL.
979
+
980
+ **Les budgets atomiques nécessitent un replica set ou un cluster shardé**
981
+ (MongoDB 4.2+, selon la compatibilité serveur du pilote). Chaque réservation
982
+ modifie un verrou d'organisation dans une transaction avec lecture snapshot et
983
+ écriture majority. Le pilote rejoue les transactions en conflit : deux dépenses
984
+ concurrentes ne peuvent pas dépasser ensemble un plafond. Un serveur standalone
985
+ fait échouer la dépense, sans repli non atomique. L'option `client`, si fournie,
986
+ doit désigner le propriétaire de `db`. L'application ferme ses connexions ; le
987
+ magasin ferme les sessions courtes qu'il crée pour réserver. Une opération
988
+ complète du gouverneur n'est pas transactionnelle : état et audit restent des
989
+ écritures séparées, comme dans l'implémentation PostgreSQL. Une erreur de base
990
+ remonte sans autoriser de dépense. Les limites MongoDB de taille de document
991
+ s'appliquent à chaque record.
992
+
993
+ Les mêmes suites de contrat du gouverneur, des approbations et changements, des
994
+ records et de leur évaluation tournent avec un faux client et MongoDB réel :
995
+
996
+ ```sh
997
+ npm test -w @astratra/conscience
998
+ MONGO_TEST_URL=mongodb://127.0.0.1:27017/conscience_test?replicaSet=rs0 npm test -w @astratra/conscience
999
+ ```
1000
+
1001
+ Sans `MONGO_TEST_URL`, les tests réels sont sautés avec une raison. Avec une URL,
1002
+ la connexion et le replica set ou cluster shardé doivent fonctionner : une erreur
1003
+ fait échouer la suite. Chaque test crée un préfixe aléatoire et supprime seulement
1004
+ ses collections, jamais la base. Un replica set local de `mongodb-memory-server`
1005
+ peut fournir cette URL. Les magasins de vigilance et de mode ombre conservent
1006
+ leurs adaptateurs actuels : ces deux magasins MongoDB couvrent le gouverneur et
1007
+ les records des décisions.
1008
+
1009
+ Vérification par mutations (trois régressions détectées puis restaurées) :
1010
+
1011
+ ```sh
1012
+ node packages/conscience/test/mongo-mutations.js
1013
+ ```
1014
+
875
1015
  ## Tests
876
1016
 
877
1017
  ```sh
package/README.md CHANGED
@@ -244,6 +244,57 @@ The report copies no free text of the proposer, only ids, codes, numbers and the
244
244
  `tests` and rollback plan objects it supplied. Everything is read inside one
245
245
  organisation.
246
246
 
247
+ ### Remote settings (dashboard)
248
+
249
+ `createRemoteSettings` lets a dashboard turn the agent on or off, pull or
250
+ release its kill switch, name its approvers and set its reflection schedule,
251
+ and lets humans approve or decline proposals there. The governor stays the only
252
+ judge: the adapter turns the settings into governor options and submits each
253
+ human decision through `approveProposal` / `declineProposal`. It imports
254
+ nothing but this folder: you pass the function that reads the settings.
255
+
256
+ ```js
257
+ const { createRemoteSettings, createPostgresGovernorStore } = require('@astratra/conscience/governor');
258
+
259
+ const remote = createRemoteSettings({
260
+ read: () => dashboard.readSettings(), // your client, with its own cache
261
+ policy: localPolicy, // constitution, permissions, budget CEILINGS
262
+ organisationId: 'org-1',
263
+ storage: { load: () => cache.get(), save: (s) => cache.set(s) } // optional: survives restarts
264
+ });
265
+ const store = createPostgresGovernorStore(pool);
266
+
267
+ setInterval(async () => {
268
+ await remote.refresh(); // never throws
269
+ const governor = remote.governor({ store }); // ask for it each time: rebuilt when the policy changes
270
+ await remote.sync(governor); // remote kill switch, applied now
271
+ const results = await remote.applyDecisions(governor, await dashboard.readDecisions());
272
+ // report results back (applied, already_applied, refused + code; failed = retry later)
273
+ }, 60_000);
274
+
275
+ if (remote.reflectionDue()) await runCycle({ cycleId: remote.reflectionCycleId() });
276
+ ```
277
+
278
+ Settings (`conscience-settings/1`): `version`, `enabled`, `halted`,
279
+ `resumedBy`, `approvers`, `reflection { automatic, hour, timeZone }`,
280
+ `cyclesPerDay`. Rules:
281
+
282
+ | Situation | Effect |
283
+ |---|---|
284
+ | Source silent, slow or invalid | The last valid settings stay (`source: 'last_known'`), from memory or `storage` |
285
+ | Nothing valid ever seen | Everything off: disabled, governor halted, no approver |
286
+ | Older `version` than the one in force | Ignored (`stale_settings`) |
287
+ | `halted: true` | Applied at once, even inside an invalid or stale answer; `sync` pulls the governor's kill switch (candidates go back to stable) |
288
+ | Halt released | `sync` resumes only a halt it pulled, and only as the human named in `resumedBy`; a halt pulled by anyone else stays |
289
+ | `enabled: false` | Governor halted; `reflectionDue()` is false |
290
+ | `cyclesPerDay` | `perAgent` and `perOrganisation` become `min(local, cyclesPerDay × costPerCycle)`, never above the local values |
291
+ | `approvers` | The governor's approvers; within the local `approvers` list when it has one |
292
+ | Anything else (`constitution`, `budgets`, `permissions`, `approvals`…) | Never applied, listed in `current().ignored` |
293
+
294
+ `applyDecisions` is safe to replay: a decision the governor already holds comes
295
+ back as `already_applied`, so one approval is never counted twice. Approvers,
296
+ halt, protected scopes, roles and expiry are still checked by the governor.
297
+
247
298
  ### Bootstrap check
248
299
 
249
300
  `assertGovernorReady(governor, { organisationId })` throws `governor_missing`,
@@ -836,6 +887,90 @@ organisation is refused. Runs carry the `userId` of the request: register
836
887
  (schema: `postgresShadowSchema({ prefix })`, table `<prefix>_runs`). Same
837
888
  contract, same tests, every value a SQL parameter.
838
889
 
890
+ ## MongoDB storage
891
+
892
+ Install the optional peer dependency only when using MongoDB:
893
+
894
+ ```sh
895
+ npm install mongodb
896
+ ```
897
+
898
+ Both stores accept a native driver `Db`. They never import the driver or open a
899
+ connection themselves. With mongoose, wait for the connection, then pass
900
+ `connection.db`; pass `connection.getClient()` as `client` for the governor.
901
+ The driver is an optional peer (`^6.0.0 || ^7.0.0`), with no mandatory runtime
902
+ installation and no mongoose dependency.
903
+
904
+ ```js
905
+ const { MongoClient } = require('mongodb');
906
+ const { createMongoGovernorStore, mongoGovernorIndexes, createGovernor } = require('@astratra/conscience/governor');
907
+ const { createMongoConscienceStore, mongoConscienceIndexes, createConscience } = require('@astratra/conscience');
908
+
909
+ const client = new MongoClient(process.env.DATABASE_URL);
910
+ await client.connect();
911
+ const db = client.db();
912
+ await mongoGovernorIndexes(db, { prefix: 'app_governor' });
913
+ await mongoConscienceIndexes(db, { prefix: 'app_memory' });
914
+ const governor = createGovernor({
915
+ budgets: { perCycle: 1, perAgent: 5, perOrganisation: 20 }
916
+ }, { store: createMongoGovernorStore(db, { prefix: 'app_governor', client }) });
917
+ const conscience = createConscience({
918
+ governor, masker: (text) => maskInApplication(text),
919
+ store: createMongoConscienceStore(db, { prefix: 'app_memory' })
920
+ });
921
+ ```
922
+
923
+ The index functions are explicit, idempotent migrations; call them before using
924
+ the stores. Prefixes accept letters, digits and underscores, begin with a
925
+ letter or underscore, and contain at most 41 characters. Defaults are
926
+ `astratra_governor` and `astratra_conscience`. Governor collections have suffixes
927
+ `proposals`, `audit`, `spend`, `controls`, `objects`, `versions`, `findings`,
928
+ `sequences`, `locks`; decision memory uses `records` and `sequences`.
929
+
930
+ Identity is encoded in the unique `_id`: organisation plus record id (and kind
931
+ or version where needed). Inserts return existing content unchanged; approval
932
+ transitions compare status and approval count atomically, and object updates
933
+ compare revision. Audit ids are unique and a persistent counter orders entries.
934
+ Records use a persistent counter to order equal timestamps; replacement keeps
935
+ that order. Filters, retention and `conscience.eraseSubject()` use the same
936
+ contract as the PostgreSQL store, including organisation isolation and evidence
937
+ invalidation. Erasure affects decision memory; governor audit retention remains
938
+ application policy, as with PostgreSQL.
939
+
940
+ **Atomic spending requires a replica set or sharded cluster** (MongoDB 4.2+,
941
+ subject to the driver's server compatibility). Each reservation updates an
942
+ organisation lock inside a snapshot transaction, with majority write concern.
943
+ Conflicting transactions retry through the driver, preventing two concurrent
944
+ reservations from exceeding a budget. A standalone server fails spending; there
945
+ is no unsafe fallback. Pass the client owning `db` if supplying `client`.
946
+ Connections and sessions are caller-owned except the short-lived reservation
947
+ sessions, which the store closes. The stores do not make an entire governor
948
+ operation transactional: state and audit writes remain separate, as in the
949
+ PostgreSQL implementation. Database errors propagate; they never authorize a
950
+ spend. MongoDB's normal document size limits apply to individual records.
951
+
952
+ The shared governor, approval/change, conscience and evaluation contract suites
953
+ run against a fake client and, optionally, real MongoDB:
954
+
955
+ ```sh
956
+ npm test -w @astratra/conscience
957
+ MONGO_TEST_URL=mongodb://127.0.0.1:27017/conscience_test?replicaSet=rs0 npm test -w @astratra/conscience
958
+ ```
959
+
960
+ Without `MONGO_TEST_URL`, real MongoDB tests skip with a reason. A supplied URL
961
+ must connect to a replica set or sharded cluster; connection or topology errors
962
+ fail the suite. Tests create random collection prefixes and drop only their own
963
+ collections, never the database. A local `mongodb-memory-server` replica set
964
+ can supply the same URL. The vigilance and shadow stores retain their existing
965
+ storage adapters; these two MongoDB stores cover the governor and decision
966
+ records only.
967
+
968
+ Mutation checks (three regressions, each detected, then restored):
969
+
970
+ ```sh
971
+ node packages/conscience/test/mongo-mutations.js
972
+ ```
973
+
839
974
  ## Tests
840
975
 
841
976
  ```sh
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astratra/conscience",
3
- "version": "1.0.0",
3
+ "version": "1.2.0",
4
4
  "description": "Documented memory of an AI agent's decisions (outcomes, corrections, lessons with evidence, self-model, lineage, erasure) under a deterministic governor with no language model: constitution, permissions, budgets, isolation, kill switch, human approval.",
5
5
  "engines": {
6
6
  "node": ">=20"
@@ -32,7 +32,8 @@
32
32
  "@astratra/ai": "^1.8.0"
33
33
  },
34
34
  "devDependencies": {
35
- "pg": "^8.13.1"
35
+ "pg": "^8.13.1",
36
+ "mongoose": "^8.24.2"
36
37
  },
37
38
  "exports": {
38
39
  ".": {
@@ -48,5 +49,13 @@
48
49
  "default": "./src/autoconscience/index.js"
49
50
  },
50
51
  "./package.json": "./package.json"
52
+ },
53
+ "peerDependencies": {
54
+ "mongodb": "^6.0.0 || ^7.0.0"
55
+ },
56
+ "peerDependenciesMeta": {
57
+ "mongodb": {
58
+ "optional": true
59
+ }
51
60
  }
52
61
  }
@@ -288,7 +288,7 @@ export class GovernorError extends Error {
288
288
  | 'self_approval' | 'not_found' | 'not_pending' | 'protected_scope' | 'invalid_spend' | 'actor_required'
289
289
  | 'not_approved' | 'approval_expired' | 'approval_insufficient' | 'approval_invalid' | 'approver_role_missing' | 'approval_roles_not_distinct' | 'already_approved' | 'decline_reason_required'
290
290
  | 'proposal_tampered' | 'already_staged' | 'candidate_exists' | 'stale_base' | 'change_conflict' | 'no_candidate' | 'rollout_incomplete' | 'invalid_rollout'
291
- | 'nothing_to_rollback' | 'object_exists' | 'invalid_object' | 'invalid_finding' | 'invalid_period' | 'actor_not_allowed' | string;
291
+ | 'nothing_to_rollback' | 'object_exists' | 'invalid_object' | 'invalid_finding' | 'invalid_period' | 'actor_not_allowed' | 'invalid_settings' | string;
292
292
  constructor(code: string, message: string);
293
293
  }
294
294
 
@@ -306,3 +306,88 @@ export const FINDING_SEVERITIES: readonly FindingSeverity[];
306
306
  export const MORNING_REPORT_SCHEMA: 'morning-report/1';
307
307
  /** The bucket (0 to 1) of an identifier, identical to bucket() of @astratra/flags. */
308
308
  export function rolloutBucket(seed: string, identifier: string | null | undefined): number | null;
309
+
310
+ /* ---------- Remote settings (a dashboard turns the agent on, halts it, names approvers, decides) ---------- */
311
+
312
+ /** Remote settings as a dashboard sends them (schema "conscience-settings/1"). Unknown fields are ignored, never applied. */
313
+ export interface RemoteSettingsInput {
314
+ schema?: 'conscience-settings/1';
315
+ version?: number;
316
+ enabled: boolean;
317
+ halted: boolean;
318
+ /** Human identity who released the kill switch: the only one allowed to resume a halt pulled remotely. */
319
+ resumedBy?: string | null;
320
+ approvers?: string[];
321
+ reflection?: { automatic: boolean; hour: number; timeZone?: string };
322
+ cyclesPerDay?: number;
323
+ [field: string]: unknown;
324
+ }
325
+ export interface RemoteSettings {
326
+ version: number; enabled: boolean; halted: boolean; resumedBy: string | null; approvers: readonly string[];
327
+ reflection: { automatic: boolean; hour: number; timeZone: string }; cyclesPerDay: number;
328
+ /** Fields of the answer that were not applied (constitution, budgets, permissions… are never taken from a remote source). */
329
+ ignored: readonly string[];
330
+ }
331
+ export interface RemoteSettingsState {
332
+ /** remote: the last read succeeded; last_known: the source is silent or invalid, the last valid settings stay; none: nothing valid ever seen (all off). */
333
+ source: 'remote' | 'last_known' | 'none';
334
+ known: boolean; version: number | null; fetchedAt: string | null;
335
+ error: 'source_unavailable' | 'invalid_settings' | 'stale_settings' | null;
336
+ enabled: boolean; halted: boolean; resumedBy: string | null; approvers: string[];
337
+ reflection: { automatic: boolean; hour: number; timeZone: string }; cyclesPerDay: number; ignored: string[];
338
+ }
339
+ /** A human decision taken on the dashboard. */
340
+ export interface RemoteDecision { id: string; proposalId: string; decision: 'approve' | 'decline'; approver: HumanActor; reasonCode?: string | null; [field: string]: unknown }
341
+ export interface RemoteDecisionResult {
342
+ id: string | null; proposalId: string | null;
343
+ /** failed: the governor could not be reached, try again later (do not acknowledge). */
344
+ result: 'applied' | 'already_applied' | 'refused' | 'failed';
345
+ code: string | null;
346
+ }
347
+ export interface RemoteSettingsOptions {
348
+ /** Returns the remote settings (e.g. a dashboard client with its own cache). May throw: the last valid settings then stay. */
349
+ read(): Promise<RemoteSettingsInput | unknown> | RemoteSettingsInput | unknown;
350
+ /** The local policy: constitution, permissions, approval matrix, and budget CEILINGS. Remote settings only narrow it. */
351
+ policy: GovernorPolicyInput;
352
+ organisationId: string;
353
+ /** Budget units of one reflection cycle (default 1): perAgent and perOrganisation become min(local, cyclesPerDay × costPerCycle). */
354
+ costPerCycle?: number;
355
+ /** Keeps the last valid settings across restarts. */
356
+ storage?: { load(): unknown | Promise<unknown>; save(snapshot: { settings: unknown; fetchedAt: string | null }): void | Promise<void> };
357
+ now?(): number;
358
+ /** Who pulls the kill switch in the governor's journal (default { kind: 'system', id: 'remote-settings' }). Never a human. */
359
+ actor?: { kind: string; id: string };
360
+ onEvent?(event: { type: 'remote_settings'; action: string; [key: string]: unknown }): void;
361
+ }
362
+ export interface RemoteSettingsController {
363
+ /** Reads the source once; never throws. */
364
+ refresh(): Promise<{ source: RemoteSettingsState['source']; changed: boolean; error: RemoteSettingsState['error'] }>;
365
+ current(): RemoteSettingsState;
366
+ /** The governor policy in force: local policy narrowed by the remote settings; halted when disabled, halted or unknown. */
367
+ policy(): GovernorPolicyInput;
368
+ /** The governor for the policy in force, rebuilt when it changes. Ask for it each time instead of keeping it. */
369
+ governor(options?: GovernorOptions): Governor;
370
+ /** Applies the remote kill switch to the governor's store now; resumes only a halt it pulled, and only by the human in resumedBy. */
371
+ sync(governor: Governor): Promise<{ action: 'halt' | 'resume' | 'none'; halted: boolean; reason?: 'halted_by_another_actor' | 'resume_needs_human' }>;
372
+ /** Submits human decisions through approveProposal / declineProposal. Replays come back as already_applied. */
373
+ applyDecisions(governor: Governor, decisions: RemoteDecision[]): Promise<RemoteDecisionResult[]>;
374
+ /** True during the configured local hour when the agent is enabled, not halted, with automatic reflection. */
375
+ reflectionDue(at?: number): boolean;
376
+ /** reflection_YYYY-MM-DD in the configured time zone: one idempotent cycle per local day. */
377
+ reflectionCycleId(at?: number): string;
378
+ }
379
+ export function createRemoteSettings(options: RemoteSettingsOptions): RemoteSettingsController;
380
+ /** Validates remote settings; throws GovernorError invalid_settings. */
381
+ export function parseRemoteSettings(raw: unknown): RemoteSettings;
382
+ /** The local policy narrowed by remote settings (null: unknown, everything off). */
383
+ export function remotePolicy(localPolicy: GovernorPolicyInput, settings: RemoteSettings | null, options?: { costPerCycle?: number }): GovernorPolicyInput;
384
+ export const REMOTE_SETTINGS_SCHEMA: 'conscience-settings/1';
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>;
@@ -11,10 +11,15 @@ const { GovernorError } = require('./util');
11
11
  const { RISK_LEVELS, DECLINE_REASONS } = require('./approvals');
12
12
  const { SEVERITIES, REPORT_SCHEMA } = require('./review');
13
13
  const { bucket } = require('./rollout');
14
+ const { createRemoteSettings, parseRemoteSettings, remotePolicy, REMOTE_SETTINGS_SCHEMA, DECISION_RESULTS } = require('./remote');
15
+
16
+ const { createMongoGovernorStore, mongoGovernorIndexes } = require('./mongo');
14
17
 
15
18
  module.exports = {
19
+ createMongoGovernorStore, mongoGovernorIndexes,
16
20
  createGovernor, assertGovernorReady, isGovernor, validatePolicy, scopesOf, protectedRulesTouched,
17
21
  createMemoryGovernorStore, createPostgresGovernorStore, postgresGovernorSchema, GovernorError,
18
22
  PROPOSAL_STATUSES: STATUSES, REASONS, PROTECTED_SCOPES, MODIFIABLE_KINDS, AUTOMATIC_CHANGES, DEFAULT_CONSTITUTION,
19
- RISK_LEVELS, DECLINE_REASONS, FINDING_SEVERITIES: SEVERITIES, MORNING_REPORT_SCHEMA: REPORT_SCHEMA, rolloutBucket: bucket
23
+ RISK_LEVELS, DECLINE_REASONS, FINDING_SEVERITIES: SEVERITIES, MORNING_REPORT_SCHEMA: REPORT_SCHEMA, rolloutBucket: bucket,
24
+ createRemoteSettings, parseRemoteSettings, remotePolicy, REMOTE_SETTINGS_SCHEMA, DECISION_RESULTS
20
25
  };
@@ -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,305 @@
1
+ 'use strict';
2
+ /*
3
+ * Remote settings for the governor: a dashboard turns an agent on or off, pulls
4
+ * or releases its kill switch, names its approvers and sets its reflection
5
+ * schedule; humans approve or decline proposals there. This adapter turns
6
+ * those settings into governor options and applies the human decisions through
7
+ * the governor's own API. It imports Node built-ins and this folder only: the
8
+ * settings come from a function you pass (`read`), never from a client package.
9
+ *
10
+ * Rules, all deterministic:
11
+ * - a silent source (error, timeout, invalid answer) keeps the last valid settings;
12
+ * - no valid settings ever seen: everything is off (disabled, halted, no approver);
13
+ * - a remote kill switch applies at once, even inside an otherwise invalid answer;
14
+ * - remote settings never touch the constitution, protected scopes, permissions,
15
+ * the approval matrix, nor budgets beyond the local ceilings.
16
+ */
17
+ const { GovernorError, fingerprintOf, copy, isNonEmptyString } = require('./util');
18
+ const { validatePolicy } = require('./policy');
19
+ const { createGovernor } = require('./governor');
20
+
21
+ const SETTINGS_SCHEMA = 'conscience-settings/1';
22
+ const KNOWN_FIELDS = Object.freeze(['schema', 'version', 'enabled', 'halted', 'haltedAt', 'resumedBy', 'approvers', 'reflection', 'cyclesPerDay', 'updatedAt']);
23
+ const IDENTITY = /^[A-Za-z0-9_.:@-]{1,128}$/;
24
+ const MAX_APPROVERS = 50;
25
+ const MAX_CYCLES = 1000;
26
+ const DEFAULT_ACTOR = Object.freeze({ kind: 'system', id: 'remote-settings' });
27
+ const RESULTS = Object.freeze(['applied', 'already_applied', 'refused', 'failed']);
28
+
29
+ const invalid = (field) => new GovernorError('invalid_settings', `Remote settings rejected: ${field}.`);
30
+
31
+ function validTimeZone(value) {
32
+ if (typeof value !== 'string' || value.length > 64) return false;
33
+ try { new Intl.DateTimeFormat('en-US', { timeZone: value }); return true; } catch (_error) { return false; }
34
+ }
35
+
36
+ /**
37
+ * Checks remote settings and returns their complete, frozen form. Unknown
38
+ * fields are listed in `ignored`, never applied: a remote answer carrying a
39
+ * constitution, budgets or permissions changes none of them.
40
+ */
41
+ function parseRemoteSettings(raw) {
42
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw invalid('not an object');
43
+ if (raw.schema !== undefined && raw.schema !== SETTINGS_SCHEMA) throw invalid('schema');
44
+ const version = raw.version ?? 0;
45
+ if (!Number.isSafeInteger(version) || version < 0) throw invalid('version');
46
+ for (const field of ['enabled', 'halted']) if (typeof raw[field] !== 'boolean') throw invalid(field);
47
+ const approvers = raw.approvers ?? [];
48
+ if (!Array.isArray(approvers) || approvers.length > MAX_APPROVERS || !approvers.every((id) => typeof id === 'string' && IDENTITY.test(id))) throw invalid('approvers');
49
+ const reflection = raw.reflection ?? { automatic: false, hour: 4, timeZone: 'UTC' };
50
+ if (!reflection || typeof reflection !== 'object' || typeof reflection.automatic !== 'boolean'
51
+ || !Number.isInteger(reflection.hour) || reflection.hour < 0 || reflection.hour > 23 || !validTimeZone(reflection.timeZone ?? 'UTC')) throw invalid('reflection');
52
+ const cycles = raw.cyclesPerDay ?? 0;
53
+ if (!Number.isInteger(cycles) || cycles < 0 || cycles > MAX_CYCLES) throw invalid('cyclesPerDay');
54
+ const resumedBy = raw.resumedBy ?? null;
55
+ if (resumedBy !== null && (typeof resumedBy !== 'string' || !IDENTITY.test(resumedBy))) throw invalid('resumedBy');
56
+ return Object.freeze({
57
+ version, enabled: raw.enabled, halted: raw.halted, resumedBy: raw.halted ? null : resumedBy,
58
+ approvers: Object.freeze([...new Set(approvers)]),
59
+ reflection: Object.freeze({ automatic: reflection.automatic, hour: reflection.hour, timeZone: reflection.timeZone ?? 'UTC' }),
60
+ cyclesPerDay: cycles,
61
+ ignored: Object.freeze(Object.keys(raw).filter((key) => !KNOWN_FIELDS.includes(key)).sort())
62
+ });
63
+ }
64
+
65
+ /**
66
+ * The governor policy for these settings: the local policy, narrowed. Budgets
67
+ * per agent and per organisation become `cyclesPerDay × costPerCycle`, never
68
+ * above the local values; approvers are the remote ones (within the local list
69
+ * when it exists); disabled, halted or unknown settings halt the governor.
70
+ */
71
+ function remotePolicy(localPolicy, settings, { costPerCycle = 1 } = {}) {
72
+ const local = validatePolicy(localPolicy);
73
+ if (typeof costPerCycle !== 'number' || !Number.isFinite(costPerCycle) || costPerCycle < 0) throw new GovernorError('policy_invalid', 'costPerCycle must be a finite number >= 0.');
74
+ const base = copy(localPolicy);
75
+ if (!settings) return { ...base, version: `${local.version}.remote-none`, halted: true, approvers: [] };
76
+ const cap = settings.cyclesPerDay * costPerCycle;
77
+ const approvers = local.approvers ? settings.approvers.filter((id) => local.approvers.includes(id)) : [...settings.approvers];
78
+ return {
79
+ ...base,
80
+ version: `${local.version}.remote-${settings.version}`,
81
+ budgets: {
82
+ perCycle: local.budgets.perCycle,
83
+ perAgent: Math.min(local.budgets.perAgent, cap),
84
+ perOrganisation: Math.min(local.budgets.perOrganisation, cap),
85
+ periodMs: local.budgets.periodMs
86
+ },
87
+ approvers,
88
+ halted: local.halted || settings.halted || !settings.enabled
89
+ };
90
+ }
91
+
92
+ /* Governor options are equal when they hold the same values (the same store, the same clock…). */
93
+ function sameOptions(a, b) {
94
+ const keys = Object.keys(a);
95
+ return keys.length === Object.keys(b).length && keys.every((key) => a[key] === b[key]);
96
+ }
97
+
98
+ /** The hour (0 to 23) and the date (YYYY-MM-DD) of an instant in a time zone. */
99
+ function localTime(at, timeZone) {
100
+ const parts = Object.fromEntries(new Intl.DateTimeFormat('en-CA', {
101
+ timeZone, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', hourCycle: 'h23'
102
+ }).formatToParts(new Date(at)).map((part) => [part.type, part.value]));
103
+ return { hour: Number(parts.hour), date: `${parts.year}-${parts.month}-${parts.day}` };
104
+ }
105
+
106
+ function createRemoteSettings(options = {}) {
107
+ const { read, policy, organisationId, storage = null, costPerCycle = 1 } = options;
108
+ if (typeof read !== 'function') throw new GovernorError('invalid_settings', 'read() is required: a function that returns the remote settings.');
109
+ if (!isNonEmptyString(organisationId)) throw new GovernorError('organisation_required', 'Remote settings need the organisationId of this governor.');
110
+ validatePolicy(policy);
111
+ const now = options.now ?? Date.now;
112
+ const actor = { kind: String(options.actor?.kind ?? DEFAULT_ACTOR.kind), id: String(options.actor?.id ?? DEFAULT_ACTOR.id) };
113
+ if (actor.kind === 'human') throw new GovernorError('actor_not_allowed', 'The remote settings actor is a system, never a human.');
114
+
115
+ let settings = null;
116
+ let source = 'none';
117
+ let lastError = null;
118
+ let fetchedAt = null;
119
+ let forcedHalt = false;
120
+ let loaded = false;
121
+ let cached = null;
122
+
123
+ const emit = (event) => { try { options.onEvent?.({ type: 'remote_settings', ...event }); } catch (_error) { /* observers change nothing */ } };
124
+
125
+ async function loadStored() {
126
+ if (loaded || !storage || typeof storage.load !== 'function') { loaded = true; return; }
127
+ loaded = true;
128
+ try {
129
+ const snapshot = await storage.load();
130
+ if (snapshot && snapshot.settings) {
131
+ settings = parseRemoteSettings(snapshot.settings);
132
+ source = 'last_known';
133
+ fetchedAt = typeof snapshot.fetchedAt === 'string' ? snapshot.fetchedAt : null;
134
+ }
135
+ } catch (_error) { /* a broken cache is the same as no cache */ }
136
+ }
137
+
138
+ async function save() {
139
+ if (!storage || typeof storage.save !== 'function') return;
140
+ try { await storage.save({ settings: { ...settings, schema: SETTINGS_SCHEMA }, fetchedAt }); } catch (_error) { /* the memory copy stays */ }
141
+ }
142
+
143
+ /** Reads the source once. Never throws: the outcome says which settings are in force and why. */
144
+ async function refresh() {
145
+ await loadStored();
146
+ let raw;
147
+ try {
148
+ raw = await read();
149
+ } catch (_error) {
150
+ lastError = 'source_unavailable';
151
+ if (settings) source = 'last_known';
152
+ emit({ action: 'refresh', outcome: 'source_unavailable', source });
153
+ return { source, changed: false, error: lastError };
154
+ }
155
+ /* A kill switch is honoured even inside an answer that fails validation or is stale. */
156
+ const haltSignal = !!raw && typeof raw === 'object' && raw.halted === true;
157
+ let parsed;
158
+ try { parsed = parseRemoteSettings(raw); } catch (error) {
159
+ lastError = error.code ?? 'invalid_settings';
160
+ const changed = haltSignal && !forcedHalt;
161
+ if (haltSignal) forcedHalt = true;
162
+ if (settings) source = 'last_known';
163
+ emit({ action: 'refresh', outcome: lastError, source, halted: haltSignal });
164
+ return { source, changed, error: lastError };
165
+ }
166
+ if (settings && parsed.version < settings.version) {
167
+ lastError = 'stale_settings';
168
+ const changed = parsed.halted && !forcedHalt;
169
+ if (parsed.halted) forcedHalt = true;
170
+ source = 'last_known';
171
+ emit({ action: 'refresh', outcome: lastError, source });
172
+ return { source, changed, error: lastError };
173
+ }
174
+ const changed = !settings || fingerprintOf(settings) !== fingerprintOf(parsed) || forcedHalt;
175
+ settings = parsed;
176
+ forcedHalt = false;
177
+ source = 'remote';
178
+ lastError = null;
179
+ fetchedAt = new Date(now()).toISOString();
180
+ if (changed) await save();
181
+ emit({ action: 'refresh', outcome: 'ok', source, version: parsed.version, changed });
182
+ return { source, changed, error: null };
183
+ }
184
+
185
+ function current() {
186
+ const halted = !settings || settings.halted || forcedHalt;
187
+ return {
188
+ source, known: !!settings, version: settings?.version ?? null, fetchedAt, error: lastError,
189
+ enabled: !!settings && settings.enabled && !halted,
190
+ halted,
191
+ resumedBy: halted ? null : settings.resumedBy,
192
+ approvers: settings ? [...settings.approvers] : [],
193
+ reflection: settings ? { ...settings.reflection } : { automatic: false, hour: 4, timeZone: 'UTC' },
194
+ cyclesPerDay: settings?.cyclesPerDay ?? 0,
195
+ ignored: settings ? [...settings.ignored] : []
196
+ };
197
+ }
198
+
199
+ function effectivePolicy() {
200
+ const merged = remotePolicy(policy, settings, { costPerCycle });
201
+ return forcedHalt ? { ...merged, halted: true } : merged;
202
+ }
203
+
204
+ /** The governor for the settings in force, rebuilt only when they change its policy. Ask for it each time you need it. */
205
+ function governor(governorOptions = {}) {
206
+ const next = effectivePolicy();
207
+ const key = fingerprintOf(next);
208
+ if (!cached || cached.key !== key || !sameOptions(cached.options, governorOptions)) {
209
+ cached = { key, options: governorOptions, governor: createGovernor(next, { now, ...governorOptions }) };
210
+ }
211
+ return cached.governor;
212
+ }
213
+
214
+ /** The latest halt or resume of this organisation recorded by the governor. */
215
+ async function lastSwitch(target) {
216
+ const [entry] = await target.listAudit({ organisationId, actions: ['halt', 'resume'], limit: 1 });
217
+ return entry ?? null;
218
+ }
219
+
220
+ /**
221
+ * Applies the remote kill switch to the governor's store at once (candidates
222
+ * go back to their stable version). A halt pulled here is released only by
223
+ * the human named in `resumedBy`; a halt pulled by anyone else stays.
224
+ */
225
+ async function sync(target) {
226
+ const state = current();
227
+ const last = await lastSwitch(target);
228
+ const haltedHere = last?.action === 'halt';
229
+ if (state.halted) {
230
+ if (haltedHere) return { action: 'none', halted: true };
231
+ await target.halt({ by: actor, organisationId, reason: state.known ? 'remote_halt' : 'remote_unknown' });
232
+ emit({ action: 'halt', organisationId });
233
+ return { action: 'halt', halted: true };
234
+ }
235
+ if (!haltedHere) return { action: 'none', halted: false };
236
+ if (last.actor?.id !== actor.id || last.actor?.kind !== actor.kind) return { action: 'none', halted: true, reason: 'halted_by_another_actor' };
237
+ if (!state.resumedBy) return { action: 'none', halted: true, reason: 'resume_needs_human' };
238
+ await target.resume({ by: { kind: 'human', id: state.resumedBy }, organisationId, reason: 'remote_resume' });
239
+ emit({ action: 'resume', organisationId });
240
+ return { action: 'resume', halted: false };
241
+ }
242
+
243
+ function decisionOf(input) {
244
+ if (!input || typeof input !== 'object') return null;
245
+ const { id, proposalId, decision, approver, reasonCode } = input;
246
+ if (!isNonEmptyString(id) || !isNonEmptyString(proposalId) || !['approve', 'decline'].includes(decision)) return null;
247
+ if (!approver || approver.kind !== 'human' || !isNonEmptyString(approver.id)) return null;
248
+ if (decision === 'decline' && !isNonEmptyString(reasonCode)) return null;
249
+ return { id, proposalId, decision, approver: { kind: 'human', id: approver.id }, reasonCode: reasonCode ?? null };
250
+ }
251
+
252
+ async function alreadyDone(target, d) {
253
+ const proposal = await target.getProposal(organisationId, d.proposalId);
254
+ if (!proposal) return false;
255
+ if (d.decision === 'approve') return (proposal.approvals ?? []).some((a) => a.approver?.id === d.approver.id);
256
+ return proposal.status === 'declined' && proposal.approver?.id === d.approver.id;
257
+ }
258
+
259
+ /**
260
+ * Submits human decisions to the governor, one by one. Replays are safe: a
261
+ * decision already recorded comes back as `already_applied`. The governor
262
+ * keeps every check (approvers, halt, protected scopes, roles, expiry).
263
+ * `failed` means the governor could not be reached: try again later.
264
+ */
265
+ async function applyDecisions(target, decisions) {
266
+ const results = [];
267
+ for (const input of Array.isArray(decisions) ? decisions : []) {
268
+ const d = decisionOf(input);
269
+ const ref = { id: input?.id ?? null, proposalId: input?.proposalId ?? null };
270
+ if (!d) { results.push({ ...ref, result: 'refused', code: 'invalid_decision' }); continue; }
271
+ if (!settings) { results.push({ ...ref, result: 'refused', code: 'settings_unknown' }); continue; }
272
+ if (!settings.approvers.includes(d.approver.id)) { results.push({ ...ref, result: 'refused', code: 'approver_not_allowed' }); continue; }
273
+ try {
274
+ if (d.decision === 'approve') await target.approveProposal(d.proposalId, { approver: d.approver, organisationId });
275
+ else await target.declineProposal(d.proposalId, { approver: d.approver, organisationId, reasonCode: d.reasonCode });
276
+ results.push({ ...ref, result: 'applied', code: null });
277
+ } catch (error) {
278
+ if (!(error instanceof GovernorError)) { results.push({ ...ref, result: 'failed', code: 'governor_unavailable' }); continue; }
279
+ let done = error.code === 'already_approved';
280
+ if (!done && error.code === 'not_pending') {
281
+ try { done = await alreadyDone(target, d); } catch (_error) { results.push({ ...ref, result: 'failed', code: 'governor_unavailable' }); continue; }
282
+ }
283
+ results.push({ ...ref, result: done ? 'already_applied' : 'refused', code: done ? null : String(error.code ?? 'refused') });
284
+ }
285
+ }
286
+ emit({ action: 'decisions', count: results.length });
287
+ return results;
288
+ }
289
+
290
+ /** True during the configured local hour, when the agent is on and not halted. */
291
+ function reflectionDue(at = now()) {
292
+ const state = current();
293
+ if (!state.enabled || !state.reflection.automatic) return false;
294
+ return localTime(at, state.reflection.timeZone).hour === state.reflection.hour;
295
+ }
296
+
297
+ /** A stable id for the reflection cycle of the local day: an idempotent spend, one cycle per day. */
298
+ function reflectionCycleId(at = now()) {
299
+ return `reflection_${localTime(at, current().reflection.timeZone).date}`;
300
+ }
301
+
302
+ return Object.freeze({ refresh, current, policy: effectivePolicy, governor, sync, applyDecisions, reflectionDue, reflectionCycleId });
303
+ }
304
+
305
+ module.exports = { createRemoteSettings, parseRemoteSettings, remotePolicy, REMOTE_SETTINGS_SCHEMA: SETTINGS_SCHEMA, DECISION_RESULTS: RESULTS };
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 };