@astratra/conscience 1.0.0 → 1.1.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 +53 -0
- package/README.md +51 -0
- package/package.json +1 -1
- package/src/governor/index.d.ts +78 -1
- package/src/governor/index.js +3 -1
- package/src/governor/remote.js +305 -0
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`,
|
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`,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@astratra/conscience",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.1.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"
|
package/src/governor/index.d.ts
CHANGED
|
@@ -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,80 @@ 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'];
|
package/src/governor/index.js
CHANGED
|
@@ -11,10 +11,12 @@ 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');
|
|
14
15
|
|
|
15
16
|
module.exports = {
|
|
16
17
|
createGovernor, assertGovernorReady, isGovernor, validatePolicy, scopesOf, protectedRulesTouched,
|
|
17
18
|
createMemoryGovernorStore, createPostgresGovernorStore, postgresGovernorSchema, GovernorError,
|
|
18
19
|
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
|
|
20
|
+
RISK_LEVELS, DECLINE_REASONS, FINDING_SEVERITIES: SEVERITIES, MORNING_REPORT_SCHEMA: REPORT_SCHEMA, rolloutBucket: bucket,
|
|
21
|
+
createRemoteSettings, parseRemoteSettings, remotePolicy, REMOTE_SETTINGS_SCHEMA, DECISION_RESULTS
|
|
20
22
|
};
|
|
@@ -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 };
|