@astratra/conscience 0.0.0-stage → 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.
Files changed (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.fr.md +954 -0
  3. package/README.md +915 -2
  4. package/package.json +50 -4
  5. package/src/autoconscience/experiments/common.js +76 -0
  6. package/src/autoconscience/experiments/execution.js +33 -0
  7. package/src/autoconscience/experiments/holdout.js +88 -0
  8. package/src/autoconscience/experiments/laboratory.js +99 -0
  9. package/src/autoconscience/experiments/replay.js +113 -0
  10. package/src/autoconscience/experiments/runner.js +54 -0
  11. package/src/autoconscience/experiments/sandbox.js +58 -0
  12. package/src/autoconscience/index.d.ts +203 -0
  13. package/src/autoconscience/index.js +116 -0
  14. package/src/autoconscience/lessons.js +32 -0
  15. package/src/autoconscience/shadow/candidate.js +69 -0
  16. package/src/autoconscience/shadow/index.d.ts +169 -0
  17. package/src/autoconscience/shadow/index.js +11 -0
  18. package/src/autoconscience/shadow/report.js +125 -0
  19. package/src/autoconscience/shadow/runner.js +384 -0
  20. package/src/autoconscience/shadow/store.js +98 -0
  21. package/src/autoconscience/signals.js +88 -0
  22. package/src/autoconscience/statistics.js +84 -0
  23. package/src/autoconscience/vigilance/abstention.js +123 -0
  24. package/src/autoconscience/vigilance/adversary.js +145 -0
  25. package/src/autoconscience/vigilance/common.js +56 -0
  26. package/src/autoconscience/vigilance/drift.js +306 -0
  27. package/src/autoconscience/vigilance/followups.js +100 -0
  28. package/src/autoconscience/vigilance/index.d.ts +190 -0
  29. package/src/autoconscience/vigilance/index.js +23 -0
  30. package/src/autoconscience/vigilance/lessonTests.js +40 -0
  31. package/src/autoconscience/vigilance/library.js +162 -0
  32. package/src/autoconscience/vigilance/roles.js +122 -0
  33. package/src/autoconscience/vigilance/store.js +166 -0
  34. package/src/conscience.js +559 -0
  35. package/src/diff.js +27 -0
  36. package/src/errors.js +11 -0
  37. package/src/governor/approvals.js +132 -0
  38. package/src/governor/changes.js +269 -0
  39. package/src/governor/governor.js +286 -0
  40. package/src/governor/index.d.ts +385 -0
  41. package/src/governor/index.js +22 -0
  42. package/src/governor/policy.js +136 -0
  43. package/src/governor/postgres.js +243 -0
  44. package/src/governor/remote.js +305 -0
  45. package/src/governor/review.js +191 -0
  46. package/src/governor/rollout.js +66 -0
  47. package/src/governor/stores.js +136 -0
  48. package/src/governor/util.js +53 -0
  49. package/src/guard.js +21 -0
  50. package/src/index.d.ts +244 -0
  51. package/src/index.js +23 -0
  52. package/src/memoryStore.js +65 -0
  53. package/src/postgres.js +93 -0
  54. package/src/records.js +220 -0
@@ -0,0 +1,243 @@
1
+ 'use strict';
2
+ const { prefixOf, requireQueryable } = require('./util');
3
+ const { boundedLimit } = require('./stores');
4
+
5
+ const DEFAULT_PREFIX = 'astratra_governor';
6
+ const names = (options) => {
7
+ const p = prefixOf(options, DEFAULT_PREFIX);
8
+ return { proposals: `"${p}_proposals"`, audit: `"${p}_audit"`, spend: `"${p}_spend"`, controls: `"${p}_controls"`, objects: `"${p}_objects"`, versions: `"${p}_versions"`, findings: `"${p}_findings"`, raw: p };
9
+ };
10
+
11
+ /** SQL that creates the governor tables. Idempotent: run it at every start or in a migration. */
12
+ function postgresGovernorSchema(options) {
13
+ const t = names(options);
14
+ return `CREATE TABLE IF NOT EXISTS ${t.proposals} (
15
+ organisation_id text NOT NULL,
16
+ id text NOT NULL,
17
+ status text NOT NULL CHECK (status IN ('rejected', 'pending_approval', 'approved', 'declined', 'expired')),
18
+ fingerprint text NOT NULL,
19
+ data jsonb NOT NULL,
20
+ created_at timestamptz NOT NULL,
21
+ PRIMARY KEY (organisation_id, id)
22
+ );
23
+ CREATE INDEX IF NOT EXISTS "${t.raw}_proposals_status_idx" ON ${t.proposals} (organisation_id, status, created_at DESC);
24
+ CREATE TABLE IF NOT EXISTS ${t.audit} (
25
+ seq bigserial PRIMARY KEY,
26
+ id text NOT NULL UNIQUE,
27
+ organisation_id text,
28
+ proposal_id text,
29
+ at timestamptz NOT NULL,
30
+ data jsonb NOT NULL
31
+ );
32
+ CREATE INDEX IF NOT EXISTS "${t.raw}_audit_org_idx" ON ${t.audit} (organisation_id, seq DESC);
33
+ CREATE TABLE IF NOT EXISTS ${t.spend} (
34
+ organisation_id text NOT NULL,
35
+ id text NOT NULL,
36
+ agent_id text NOT NULL,
37
+ cycle_id text,
38
+ cost double precision NOT NULL CHECK (cost >= 0),
39
+ at timestamptz NOT NULL,
40
+ PRIMARY KEY (organisation_id, id)
41
+ );
42
+ CREATE INDEX IF NOT EXISTS "${t.raw}_spend_at_idx" ON ${t.spend} (organisation_id, at);
43
+ CREATE TABLE IF NOT EXISTS ${t.controls} (
44
+ key text PRIMARY KEY,
45
+ data jsonb NOT NULL
46
+ );
47
+ CREATE TABLE IF NOT EXISTS ${t.objects} (
48
+ organisation_id text NOT NULL,
49
+ kind text NOT NULL,
50
+ id text NOT NULL,
51
+ revision integer NOT NULL,
52
+ has_candidate boolean NOT NULL,
53
+ data jsonb NOT NULL,
54
+ PRIMARY KEY (organisation_id, kind, id)
55
+ );
56
+ CREATE INDEX IF NOT EXISTS "${t.raw}_objects_candidate_idx" ON ${t.objects} (has_candidate) WHERE has_candidate;
57
+ CREATE TABLE IF NOT EXISTS ${t.versions} (
58
+ organisation_id text NOT NULL,
59
+ kind text NOT NULL,
60
+ id text NOT NULL,
61
+ version_id text NOT NULL,
62
+ number integer NOT NULL,
63
+ data jsonb NOT NULL,
64
+ PRIMARY KEY (organisation_id, kind, id, version_id)
65
+ );
66
+ CREATE TABLE IF NOT EXISTS ${t.findings} (
67
+ organisation_id text NOT NULL,
68
+ id text NOT NULL,
69
+ received_at timestamptz NOT NULL,
70
+ data jsonb NOT NULL,
71
+ PRIMARY KEY (organisation_id, id)
72
+ );
73
+ CREATE INDEX IF NOT EXISTS "${t.raw}_findings_at_idx" ON ${t.findings} (organisation_id, received_at DESC);`;
74
+ }
75
+
76
+ const json = (row) => (row ? (typeof row.data === 'string' ? JSON.parse(row.data) : row.data) : null);
77
+
78
+ /**
79
+ * Governor store on PostgreSQL. `db` is any `{ query(sql, params) }`; when it
80
+ * also has `connect()` (a `pg` Pool), spending is reserved inside a
81
+ * transaction under an advisory lock per organisation, so two concurrent
82
+ * spends never both pass a budget. Every value is a SQL parameter.
83
+ */
84
+ function createPostgresGovernorStore(db, options) {
85
+ requireQueryable(db);
86
+ const t = names(options);
87
+
88
+ async function withTransaction(fn) {
89
+ if (typeof db.connect !== 'function') return fn(db);
90
+ const client = await db.connect();
91
+ try {
92
+ await client.query('BEGIN');
93
+ const result = await fn(client);
94
+ await client.query('COMMIT');
95
+ return result;
96
+ } catch (error) {
97
+ await client.query('ROLLBACK').catch(() => {});
98
+ throw error;
99
+ } finally { client.release(); }
100
+ }
101
+
102
+ return {
103
+ async putProposal(record) {
104
+ const inserted = await db.query(
105
+ `INSERT INTO ${t.proposals} (organisation_id, id, status, fingerprint, data, created_at) VALUES ($1, $2, $3, $4, $5::jsonb, $6::timestamptz)
106
+ ON CONFLICT (organisation_id, id) DO NOTHING RETURNING data`,
107
+ [record.organisationId, record.id, record.status, record.fingerprint, JSON.stringify(record), record.createdAt]);
108
+ if (inserted.rows.length) return { record: json(inserted.rows[0]), created: true };
109
+ return { record: await this.getProposal(record.organisationId, record.id), created: false };
110
+ },
111
+ async getProposal(organisationId, id) {
112
+ return json((await db.query(`SELECT data FROM ${t.proposals} WHERE organisation_id = $1 AND id = $2`, [organisationId, id])).rows[0]);
113
+ },
114
+ async transitionProposal(organisationId, id, fromStatus, patch, guard) {
115
+ const params = [organisationId, id, fromStatus, patch.status ?? fromStatus, JSON.stringify(patch)];
116
+ let sql = `UPDATE ${t.proposals} SET status = $4, data = data || $5::jsonb WHERE organisation_id = $1 AND id = $2 AND status = $3`;
117
+ if (guard?.approvals !== undefined) { params.push(guard.approvals); sql += ` AND jsonb_array_length(coalesce(data->'approvals', '[]'::jsonb)) = $${params.length}`; }
118
+ return json((await db.query(`${sql} RETURNING data`, params)).rows[0]);
119
+ },
120
+ async listProposals(filter = {}) {
121
+ const params = [filter.organisationId];
122
+ let sql = `SELECT data FROM ${t.proposals} WHERE organisation_id = $1`;
123
+ if (filter.status != null) { params.push(filter.status); sql += ` AND status = $${params.length}`; }
124
+ if (filter.statuses != null) { params.push(filter.statuses); sql += ` AND status = ANY($${params.length}::text[])`; }
125
+ if (filter.since != null) { params.push(filter.since); sql += ` AND coalesce((data->>'decidedAt')::timestamptz, created_at) >= $${params.length}::timestamptz`; }
126
+ params.push(boundedLimit(filter.limit));
127
+ sql += ` ORDER BY created_at DESC, id LIMIT $${params.length}`;
128
+ return (await db.query(sql, params)).rows.map(json);
129
+ },
130
+ async appendAudit(entry) {
131
+ await db.query(`INSERT INTO ${t.audit} (id, organisation_id, proposal_id, at, data) VALUES ($1, $2, $3, $4::timestamptz, $5::jsonb)`,
132
+ [entry.id, entry.organisationId, entry.proposalId, entry.at, JSON.stringify(entry)]);
133
+ return entry;
134
+ },
135
+ async listAudit(filter = {}) {
136
+ const params = []; const parts = [];
137
+ if (filter.organisationId !== undefined) {
138
+ if (filter.organisationId === null) parts.push('organisation_id IS NULL');
139
+ else { params.push(filter.organisationId); parts.push(`organisation_id = $${params.length}`); }
140
+ }
141
+ if (filter.proposalId != null) { params.push(filter.proposalId); parts.push(`proposal_id = $${params.length}`); }
142
+ if (filter.actions != null) { params.push(filter.actions); parts.push(`data->>'action' = ANY($${params.length}::text[])`); }
143
+ if (filter.since != null) { params.push(filter.since); parts.push(`at >= $${params.length}::timestamptz`); }
144
+ if (filter.objectKind != null) { params.push(filter.objectKind); parts.push(`data->>'objectKind' = $${params.length}`); }
145
+ if (filter.objectId != null) { params.push(filter.objectId); parts.push(`data->>'objectId' = $${params.length}`); }
146
+ params.push(boundedLimit(filter.limit));
147
+ const where = parts.length ? ` WHERE ${parts.join(' AND ')}` : '';
148
+ return (await db.query(`SELECT data FROM ${t.audit}${where} ORDER BY seq DESC LIMIT $${params.length}`, params)).rows.map(json);
149
+ },
150
+ async reserveSpend(entry, limits) {
151
+ return withTransaction(async (q) => {
152
+ await q.query('SELECT pg_advisory_xact_lock(hashtext($1))', [`${t.raw}:${entry.organisationId}`]);
153
+ const sums = async () => {
154
+ const row = (await q.query(
155
+ `SELECT coalesce(sum(cost) FILTER (WHERE $2::text IS NOT NULL AND cycle_id = $2), 0)::float8 AS cycle,
156
+ coalesce(sum(cost) FILTER (WHERE at >= to_timestamp($3::double precision / 1000) AND agent_id = $4), 0)::float8 AS agent,
157
+ coalesce(sum(cost) FILTER (WHERE at >= to_timestamp($3::double precision / 1000)), 0)::float8 AS organisation
158
+ FROM ${t.spend} WHERE organisation_id = $1`,
159
+ [entry.organisationId, entry.cycleId, limits.since, entry.agentId])).rows[0];
160
+ return { cycle: Number(row.cycle), agent: Number(row.agent), organisation: Number(row.organisation) };
161
+ };
162
+ const exists = (await q.query(`SELECT 1 FROM ${t.spend} WHERE organisation_id = $1 AND id = $2`, [entry.organisationId, entry.id])).rows.length > 0;
163
+ if (exists) return { reserved: true, created: false, totals: await sums() };
164
+ const totals = await sums();
165
+ const fits = (entry.cycleId == null || totals.cycle + entry.cost <= limits.perCycle)
166
+ && totals.agent + entry.cost <= limits.perAgent
167
+ && totals.organisation + entry.cost <= limits.perOrganisation;
168
+ if (!fits) return { reserved: false, created: false, totals };
169
+ await q.query(`INSERT INTO ${t.spend} (organisation_id, id, agent_id, cycle_id, cost, at) VALUES ($1, $2, $3, $4, $5, to_timestamp($6::double precision / 1000))`,
170
+ [entry.organisationId, entry.id, entry.agentId, entry.cycleId, entry.cost, entry.at]);
171
+ return { reserved: true, created: true, totals: await sums() };
172
+ });
173
+ },
174
+ async getControl(key) {
175
+ return json((await db.query(`SELECT data FROM ${t.controls} WHERE key = $1`, [key])).rows[0]);
176
+ },
177
+ async setControl(key, value) {
178
+ await db.query(`INSERT INTO ${t.controls} (key, data) VALUES ($1, $2::jsonb) ON CONFLICT (key) DO UPDATE SET data = EXCLUDED.data`, [key, JSON.stringify(value)]);
179
+ return value;
180
+ },
181
+
182
+ async getObject(organisationId, kind, id) {
183
+ return json((await db.query(`SELECT data FROM ${t.objects} WHERE organisation_id = $1 AND kind = $2 AND id = $3`, [organisationId, kind, id])).rows[0]);
184
+ },
185
+ async createObject(state) {
186
+ const inserted = await db.query(
187
+ `INSERT INTO ${t.objects} (organisation_id, kind, id, revision, has_candidate, data) VALUES ($1, $2, $3, $4, $5, $6::jsonb)
188
+ ON CONFLICT (organisation_id, kind, id) DO NOTHING RETURNING data`,
189
+ [state.organisationId, state.kind, state.id, state.revision, state.candidate != null, JSON.stringify(state)]);
190
+ if (inserted.rows.length) return { record: json(inserted.rows[0]), created: true };
191
+ return { record: await this.getObject(state.organisationId, state.kind, state.id), created: false };
192
+ },
193
+ async updateObject(organisationId, kind, id, expectedRevision, next) {
194
+ return json((await db.query(
195
+ `UPDATE ${t.objects} SET revision = $5, has_candidate = $6, data = $7::jsonb
196
+ WHERE organisation_id = $1 AND kind = $2 AND id = $3 AND revision = $4 RETURNING data`,
197
+ [organisationId, kind, id, expectedRevision, next.revision, next.candidate != null, JSON.stringify(next)])).rows[0]);
198
+ },
199
+ async listObjects(filter = {}) {
200
+ const params = []; const parts = [];
201
+ if (filter.organisationId != null) { params.push(filter.organisationId); parts.push(`organisation_id = $${params.length}`); }
202
+ if (filter.kind != null) { params.push(filter.kind); parts.push(`kind = $${params.length}`); }
203
+ if (filter.hasCandidate) parts.push('has_candidate');
204
+ params.push(boundedLimit(filter.limit));
205
+ const where = parts.length ? ` WHERE ${parts.join(' AND ')}` : '';
206
+ return (await db.query(`SELECT data FROM ${t.objects}${where} ORDER BY organisation_id, kind, id LIMIT $${params.length}`, params)).rows.map(json);
207
+ },
208
+ async putVersion(record) {
209
+ const inserted = await db.query(
210
+ `INSERT INTO ${t.versions} (organisation_id, kind, id, version_id, number, data) VALUES ($1, $2, $3, $4, $5, $6::jsonb)
211
+ ON CONFLICT (organisation_id, kind, id, version_id) DO NOTHING RETURNING data`,
212
+ [record.organisationId, record.kind, record.id, record.versionId, record.number, JSON.stringify(record)]);
213
+ if (inserted.rows.length) return { record: json(inserted.rows[0]), created: true };
214
+ return { record: await this.getVersion(record.organisationId, record.kind, record.id, record.versionId), created: false };
215
+ },
216
+ async getVersion(organisationId, kind, id, versionId) {
217
+ return json((await db.query(`SELECT data FROM ${t.versions} WHERE organisation_id = $1 AND kind = $2 AND id = $3 AND version_id = $4`, [organisationId, kind, id, versionId])).rows[0]);
218
+ },
219
+ async listVersions(filter) {
220
+ return (await db.query(
221
+ `SELECT data FROM ${t.versions} WHERE organisation_id = $1 AND kind = $2 AND id = $3 ORDER BY number LIMIT $4`,
222
+ [filter.organisationId, filter.kind, filter.id, boundedLimit(filter.limit, 1000)])).rows.map(json);
223
+ },
224
+
225
+ async putFinding(record) {
226
+ const inserted = await db.query(
227
+ `INSERT INTO ${t.findings} (organisation_id, id, received_at, data) VALUES ($1, $2, $3::timestamptz, $4::jsonb)
228
+ ON CONFLICT (organisation_id, id) DO NOTHING RETURNING data`,
229
+ [record.organisationId, record.id, record.receivedAt, JSON.stringify(record)]);
230
+ if (inserted.rows.length) return { record: json(inserted.rows[0]), created: true };
231
+ return { record: json((await db.query(`SELECT data FROM ${t.findings} WHERE organisation_id = $1 AND id = $2`, [record.organisationId, record.id])).rows[0]), created: false };
232
+ },
233
+ async listFindings(filter = {}) {
234
+ const params = [filter.organisationId]; let sql = `SELECT data FROM ${t.findings} WHERE organisation_id = $1`;
235
+ if (filter.since != null) { params.push(filter.since); sql += ` AND received_at >= $${params.length}::timestamptz`; }
236
+ if (filter.until != null) { params.push(filter.until); sql += ` AND received_at <= $${params.length}::timestamptz`; }
237
+ params.push(boundedLimit(filter.limit));
238
+ return (await db.query(`${sql} ORDER BY received_at DESC, id LIMIT $${params.length}`, params)).rows.map(json);
239
+ }
240
+ };
241
+ }
242
+
243
+ module.exports = { postgresGovernorSchema, createPostgresGovernorStore };
@@ -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 };