@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,286 @@
1
+ 'use strict';
2
+ const crypto = require('node:crypto');
3
+ const { GovernorError, fingerprintOf, copy, isNonEmptyString } = require('./util');
4
+ const { validatePolicy, protectedRulesTouched } = require('./policy');
5
+ const { RISK_LEVELS, assess, actingRole, liveApprovals } = require('./approvals');
6
+ const { createChanges } = require('./changes');
7
+ const { createReview } = require('./review');
8
+ const { createMemoryGovernorStore } = require('./stores');
9
+
10
+ const STATUSES = Object.freeze(['rejected', 'pending_approval', 'approved', 'declined', 'expired']);
11
+ const PROPOSER_KINDS = Object.freeze(['engine', 'model', 'human', 'system']);
12
+ const REASONS = Object.freeze({
13
+ HALTED: 'governor_halted',
14
+ INVALID: 'invalid_proposal',
15
+ CROSS_ORGANISATION: 'cross_organisation',
16
+ PROTECTED: 'protected_scope',
17
+ NOT_ALLOWLISTED: 'not_allowlisted',
18
+ HUMAN_APPROVAL: 'human_approval_required',
19
+ BUDGET: 'budget_exceeded'
20
+ });
21
+ const GLOBAL = '*';
22
+
23
+ /* Governors built by createGovernor. A look-alike object never passes the bootstrap check. */
24
+ const genuine = new WeakSet();
25
+
26
+ const actorOf = (actor) => (actor && typeof actor === 'object' ? { kind: String(actor.kind ?? ''), id: String(actor.id ?? '') } : null);
27
+
28
+ /**
29
+ * Deterministic governor: constitution, permissions, spending, isolation,
30
+ * kill switch, human approvals and an audit journal. No model is consulted;
31
+ * the same policy and the same proposal always give the same decision.
32
+ */
33
+ function createGovernor(policy, options = {}) {
34
+ const rules = validatePolicy(policy);
35
+ const store = options.store ?? createMemoryGovernorStore();
36
+ for (const method of ['putProposal', 'getProposal', 'transitionProposal', 'listProposals', 'appendAudit', 'listAudit', 'reserveSpend', 'getControl', 'setControl',
37
+ 'getObject', 'createObject', 'updateObject', 'listObjects', 'putVersion', 'getVersion', 'listVersions', 'putFinding', 'listFindings']) {
38
+ if (typeof store[method] !== 'function') throw new GovernorError('governor_unavailable', `Governor store is missing ${method}().`);
39
+ }
40
+ const now = options.now ?? Date.now;
41
+ const newId = options.idFactory ?? (() => crypto.randomUUID());
42
+ const iso = () => new Date(now()).toISOString();
43
+
44
+ async function audit(entry) {
45
+ const full = { id: newId(), at: iso(), policyVersion: rules.version, organisationId: null, proposalId: null, reasons: [], actor: null, ...entry };
46
+ await store.appendAudit(full);
47
+ try { await options.onEvent?.({ type: 'governor', ...copy(full) }); } catch (_error) { /* Observers never change a decision. */ }
48
+ return full;
49
+ }
50
+
51
+ async function haltState(organisationId) {
52
+ if (rules.halted) return { halted: true, scope: GLOBAL, reason: 'policy' };
53
+ const global = await store.getControl(`halt:${GLOBAL}`);
54
+ if (global?.halted) return { halted: true, scope: GLOBAL, reason: global.reason ?? null };
55
+ if (organisationId != null) {
56
+ const local = await store.getControl(`halt:${organisationId}`);
57
+ if (local?.halted) return { halted: true, scope: organisationId, reason: local.reason ?? null };
58
+ }
59
+ return { halted: false };
60
+ }
61
+
62
+ function assertSingleOrganisation(...ids) {
63
+ const list = ids.flat().filter((id) => id !== undefined && id !== null);
64
+ if (!list.length || !list.every(isNonEmptyString)) throw new GovernorError('organisation_required', 'An operation needs exactly one organisation.');
65
+ if (new Set(list).size !== 1) throw new GovernorError(REASONS.CROSS_ORGANISATION, 'An operation may touch only one organisation.');
66
+ return list[0];
67
+ }
68
+
69
+ function normalizeProposal(input) {
70
+ if (!input || typeof input !== 'object') throw new GovernorError(REASONS.INVALID, 'A proposal must be an object.');
71
+ if (!isNonEmptyString(input.organisationId)) throw new GovernorError('organisation_required', 'A proposal needs its organisationId.');
72
+ const target = input.target && typeof input.target === 'object'
73
+ ? { kind: input.target.kind ?? null, id: input.target.id ?? null, version: input.target.version ?? null, organisationId: input.target.organisationId ?? null }
74
+ : null;
75
+ const content = {
76
+ organisationId: input.organisationId, target, change: input.change === undefined ? null : copy(input.change),
77
+ justification: input.justification ?? null, scopes: Array.isArray(input.scopes) ? input.scopes.map(String) : [],
78
+ organisationIds: Array.isArray(input.organisationIds) ? input.organisationIds.map(String) : [],
79
+ proposedBy: actorOf(input.proposedBy), owner: input.owner ?? null, tests: copy(input.tests) ?? null,
80
+ replay: copy(input.replay) ?? null, rollback: copy(input.rollback) ?? null, risk: input.risk ?? null
81
+ };
82
+ const fingerprint = fingerprintOf(content);
83
+ return { id: isNonEmptyString(input.id) ? input.id : `proposal_${fingerprint.slice(0, 32)}`, ...content, fingerprint };
84
+ }
85
+
86
+ function judge(proposal, halted) {
87
+ const reasons = [];
88
+ let touched = [];
89
+ if (halted) reasons.push(REASONS.HALTED);
90
+ const target = proposal.target;
91
+ if (!target || !isNonEmptyString(target.kind) || !isNonEmptyString(target.id) || proposal.change === null
92
+ || !proposal.proposedBy || !PROPOSER_KINDS.includes(proposal.proposedBy.kind) || !proposal.proposedBy.id
93
+ || (proposal.risk !== null && !RISK_LEVELS.includes(proposal.risk))) reasons.push(REASONS.INVALID);
94
+ const orgs = new Set([proposal.organisationId, ...proposal.organisationIds, ...(target?.organisationId ? [target.organisationId] : [])]);
95
+ if (orgs.size > 1) reasons.push(REASONS.CROSS_ORGANISATION);
96
+ touched = protectedRulesTouched(rules, proposal);
97
+ if (touched.length) reasons.push(REASONS.PROTECTED);
98
+ if (target && !rules.permissions.modifiable.includes(target.kind)) reasons.push(REASONS.NOT_ALLOWLISTED);
99
+ if (reasons.length) return { status: 'rejected', reasons, rules: touched };
100
+ return { status: 'pending_approval', reasons: [REASONS.HUMAN_APPROVAL], rules: [] };
101
+ }
102
+
103
+ async function evaluatePolicy(input) {
104
+ const proposal = normalizeProposal(input);
105
+ const existing = await store.getProposal(proposal.organisationId, proposal.id);
106
+ if (existing) {
107
+ if (existing.fingerprint !== proposal.fingerprint) throw new GovernorError('proposal_conflict', 'A different proposal already uses this id.');
108
+ return existing;
109
+ }
110
+ const halted = (await haltState(proposal.organisationId)).halted;
111
+ const verdict = judge(proposal, halted);
112
+ const at = iso();
113
+ const assessment = assess(rules, proposal);
114
+ const record = {
115
+ ...proposal, ...verdict, risk: assessment.risk, declaredRisk: proposal.risk, requiredApprovals: assessment.requiredApprovals, approvals: [], declineReason: null,
116
+ policyVersion: rules.version, createdAt: at, decidedAt: verdict.status === 'rejected' ? at : null, approver: null, note: null
117
+ };
118
+ const { record: stored, created } = await store.putProposal(record);
119
+ if (!created) {
120
+ if (stored.fingerprint !== proposal.fingerprint) throw new GovernorError('proposal_conflict', 'A different proposal already uses this id.');
121
+ return stored;
122
+ }
123
+ await audit({ action: 'evaluate', organisationId: record.organisationId, proposalId: record.id, decision: record.status, reasons: record.reasons, rules: record.rules, actor: record.proposedBy });
124
+ return stored;
125
+ }
126
+
127
+ function requireHuman(approver) {
128
+ const who = actorOf(approver);
129
+ if (!who || who.kind !== 'human' || !isNonEmptyString(who.id)) {
130
+ throw new GovernorError('approver_not_human', 'Only a human identity supplied by the application can decide on a proposal; a model never can.');
131
+ }
132
+ if (rules.approvers && !rules.approvers.includes(who.id)) throw new GovernorError('approver_not_allowed', 'This person is not an approver in the governor policy.');
133
+ return who;
134
+ }
135
+
136
+ async function decide(id, { approver, organisationId, note, role, reasonCode } = {}, status) {
137
+ const who = requireHuman(approver);
138
+ if (!isNonEmptyString(organisationId)) throw new GovernorError('organisation_required', 'A decision needs its organisationId.');
139
+ if (status === 'declined' && !rules.approvals.declineReasons.includes(reasonCode)) {
140
+ throw new GovernorError('decline_reason_required', `Say why with a code from the register: ${rules.approvals.declineReasons.join(', ')}.`);
141
+ }
142
+ const text = note == null ? null : String(note).slice(0, 2000);
143
+ for (let attempt = 0; attempt < 5; attempt++) {
144
+ const proposal = await store.getProposal(organisationId, id);
145
+ if (!proposal) throw new GovernorError('not_found', 'Proposal not found.');
146
+ if (proposal.status !== 'pending_approval') throw new GovernorError('not_pending', `Proposal is ${proposal.status}, not pending approval.`);
147
+ const guard = { approvals: (proposal.approvals ?? []).length };
148
+ if (status === 'declined') {
149
+ const updated = await store.transitionProposal(organisationId, id, 'pending_approval', { status, approver: who, decidedAt: iso(), note: text, declineReason: reasonCode }, guard);
150
+ if (!updated) continue;
151
+ await audit({ action: 'decline', organisationId, proposalId: id, decision: status, reasons: [reasonCode], reasonCode, actor: who });
152
+ return updated;
153
+ }
154
+ if (proposal.proposedBy?.kind === 'human' && proposal.proposedBy.id === who.id) throw new GovernorError('self_approval', 'A person cannot approve their own proposal.');
155
+ if ((await haltState(organisationId)).halted) throw new GovernorError(REASONS.HALTED, 'The governor is halted.');
156
+ if (protectedRulesTouched(rules, proposal).length) throw new GovernorError(REASONS.PROTECTED, 'The proposal touches a protected scope.');
157
+ const assessment = assess(rules, proposal);
158
+ const acting = actingRole(rules, assessment, who, role);
159
+ const atMs = now();
160
+ const prior = liveApprovals(proposal, atMs);
161
+ if (prior.some((a) => a.approver.id === who.id)) throw new GovernorError('already_approved', 'This person already approved this proposal.');
162
+ const entry = { approver: who, role: acting, at: iso(), expiresAt: new Date(atMs + rules.approvals.expiresInMs).toISOString(), note: text };
163
+ const approvals = [...prior, entry];
164
+ const complete = approvals.length >= assessment.requiredApprovals && (!assessment.distinctRoles || new Set(approvals.map((a) => a.role)).size >= 2);
165
+ const patch = complete
166
+ ? { status: 'approved', approver: who, decidedAt: iso(), note: text, approvals, risk: assessment.risk, requiredApprovals: assessment.requiredApprovals }
167
+ : { status: 'pending_approval', approvals, risk: assessment.risk, requiredApprovals: assessment.requiredApprovals };
168
+ const updated = await store.transitionProposal(organisationId, id, 'pending_approval', patch, guard);
169
+ if (!updated) continue;
170
+ if (prior.length < (proposal.approvals ?? []).length) await audit({ action: 'approval_expired', organisationId, proposalId: id, decision: 'dropped', reasons: ['approval_expired'], count: (proposal.approvals ?? []).length - prior.length });
171
+ await audit({
172
+ action: 'approve', organisationId, proposalId: id, decision: complete ? 'approved' : 'partial', actor: who, role: acting, risk: assessment.risk,
173
+ approvalsRecorded: approvals.length, approvalsRequired: assessment.requiredApprovals, expiresAt: entry.expiresAt
174
+ });
175
+ return updated;
176
+ }
177
+ throw new GovernorError('not_pending', 'Proposal is no longer pending approval.');
178
+ }
179
+
180
+ /** Approved proposals whose approvals ran out before anyone staged them become "expired". */
181
+ async function expireApprovals({ organisationId, by } = {}) {
182
+ const org = assertSingleOrganisation(organisationId);
183
+ const expired = [];
184
+ for (const proposal of await store.listProposals({ organisationId: org, status: 'approved', limit: 1000 })) {
185
+ if (proposal.staged || liveApprovals(proposal, now()).length >= assess(rules, proposal).requiredApprovals) continue;
186
+ const updated = await store.transitionProposal(org, proposal.id, 'approved', { status: 'expired', decidedAt: iso() });
187
+ if (!updated) continue;
188
+ expired.push(proposal.id);
189
+ await audit({ action: 'expire', organisationId: org, proposalId: proposal.id, decision: 'expired', reasons: ['approval_expired'], actor: actorOf(by) });
190
+ }
191
+ return expired;
192
+ }
193
+
194
+ async function authorizeSpend(input = {}) {
195
+ const organisationId = assertSingleOrganisation(input.organisationId);
196
+ if (!isNonEmptyString(input.id)) throw new GovernorError('invalid_spend', 'A spend needs a stable id (idempotency).');
197
+ if (!isNonEmptyString(input.agentId)) throw new GovernorError('invalid_spend', 'A spend needs its agentId.');
198
+ if (typeof input.cost !== 'number' || !Number.isFinite(input.cost) || input.cost < 0) throw new GovernorError('invalid_spend', 'cost must be a finite number >= 0.');
199
+ const limits = { perCycle: rules.budgets.perCycle, perAgent: rules.budgets.perAgent, perOrganisation: rules.budgets.perOrganisation, since: now() - rules.budgets.periodMs };
200
+ if ((await haltState(organisationId)).halted) {
201
+ await audit({ action: 'spend_refused', organisationId, decision: 'refused', reasons: [REASONS.HALTED], spendId: input.id });
202
+ return { allowed: false, reasons: [REASONS.HALTED], totals: null, limits };
203
+ }
204
+ const entry = { id: input.id, organisationId, agentId: input.agentId, cycleId: input.cycleId ?? null, cost: input.cost, at: now() };
205
+ const result = await store.reserveSpend(entry, limits);
206
+ const reasons = result.reserved ? [] : [REASONS.BUDGET];
207
+ if (result.created || !result.reserved) await audit({ action: result.reserved ? 'spend' : 'spend_refused', organisationId, decision: result.reserved ? 'allowed' : 'refused', reasons, spendId: input.id, cost: input.cost });
208
+ return { allowed: result.reserved, reasons, totals: result.totals, limits };
209
+ }
210
+
211
+ async function setHalt(halted, { by, reason, organisationId } = {}) {
212
+ const who = actorOf(by);
213
+ if (!who || !isNonEmptyString(who.id)) throw new GovernorError('actor_required', 'Say who pulls or releases the kill switch.');
214
+ if (!halted && who.kind !== 'human') throw new GovernorError('approver_not_human', 'Only a human can release the kill switch.');
215
+ const scope = organisationId == null ? GLOBAL : assertSingleOrganisation(organisationId);
216
+ const value = { halted, by: who, reason: reason == null ? null : String(reason).slice(0, 2000), at: iso() };
217
+ await store.setControl(`halt:${scope}`, value);
218
+ await audit({ action: halted ? 'halt' : 'resume', organisationId: scope === GLOBAL ? null : scope, decision: halted ? 'halted' : 'running', actor: who });
219
+ if (!halted) return value;
220
+ /* The emergency stop also brings every candidate back to its stable version. */
221
+ const { reverted, failures } = await changes.revertAllCandidates({ organisationId: scope === GLOBAL ? null : scope, by: who, reason: value.reason });
222
+ return { ...value, reverted, failures };
223
+ }
224
+
225
+ async function assertReady({ organisationId } = {}) {
226
+ let state;
227
+ try { state = await haltState(organisationId); } catch (error) {
228
+ throw new GovernorError('governor_unavailable', `Governor unavailable: its store cannot be read (${error.message}).`);
229
+ }
230
+ if (state.halted) throw new GovernorError(REASONS.HALTED, 'The governor kill switch is on: reflective operations are stopped.');
231
+ return true;
232
+ }
233
+
234
+ const changes = createChanges({ rules, store, now, iso, audit, haltState, assertSingleOrganisation, normalizeProposal, flags: options.flags ?? null });
235
+ const review = createReview({ rules, store, now, iso, audit, haltState, assertSingleOrganisation });
236
+
237
+ const governor = Object.freeze({
238
+ getPolicy: () => copy(rules),
239
+ evaluatePolicy,
240
+ approveProposal: (id, options) => decide(id, options, 'approved'),
241
+ declineProposal: (id, options) => decide(id, options, 'declined'),
242
+ getProposal: (organisationId, id) => store.getProposal(organisationId, id),
243
+ listProposals: (filter = {}) => { assertSingleOrganisation(filter.organisationId); return store.listProposals(filter); },
244
+ listAudit: (filter = {}) => store.listAudit(filter),
245
+ authorizeSpend,
246
+ assertSingleOrganisation,
247
+ halt: (options) => setHalt(true, options),
248
+ resume: (options) => setHalt(false, options),
249
+ isHalted: async (organisationId) => (await haltState(organisationId)).halted,
250
+ assertReady,
251
+ expireApprovals,
252
+ registerObject: changes.registerObject,
253
+ stageChange: (proposalId, input) => changes.stageChange(proposalId, input),
254
+ deployChange: changes.deployChange,
255
+ promoteChange: changes.promoteChange,
256
+ rollbackChange: changes.rollbackChange,
257
+ resolveVersion: changes.resolveVersion,
258
+ getObject: changes.getObject,
259
+ listObjects: changes.listObjects,
260
+ listVersions: changes.listVersions,
261
+ getChangeHistory: changes.getChangeHistory,
262
+ exportFlagRules: changes.exportFlagRules,
263
+ recordFinding: review.recordFinding,
264
+ listFindings: review.listFindings,
265
+ listRejectionSignals: review.listRejectionSignals,
266
+ morningReport: review.morningReport,
267
+ verifyApprovalInvariant: review.verifyApprovalInvariant
268
+ });
269
+ genuine.add(governor);
270
+ return governor;
271
+ }
272
+
273
+ /**
274
+ * Bootstrap check (40): call before any reflective write. Throws a
275
+ * GovernorError when the governor is absent, not built by createGovernor, its
276
+ * store is unreachable, or its kill switch is on.
277
+ */
278
+ async function assertGovernorReady(governor, options = {}) {
279
+ if (governor == null) throw new GovernorError('governor_missing', 'No governor: reflective operations refuse to start without one (createGovernor(policy)).');
280
+ if (!genuine.has(governor)) throw new GovernorError('governor_invalid', 'This object is not a governor built by createGovernor().');
281
+ return governor.assertReady(options);
282
+ }
283
+
284
+ const isGovernor = (value) => genuine.has(value);
285
+
286
+ module.exports = { createGovernor, assertGovernorReady, isGovernor, STATUSES, REASONS };