@astratra/conscience 0.0.0-stage → 1.0.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/LICENSE +21 -0
- package/README.fr.md +901 -0
- package/README.md +864 -2
- package/package.json +50 -4
- package/src/autoconscience/experiments/common.js +76 -0
- package/src/autoconscience/experiments/execution.js +33 -0
- package/src/autoconscience/experiments/holdout.js +88 -0
- package/src/autoconscience/experiments/laboratory.js +99 -0
- package/src/autoconscience/experiments/replay.js +113 -0
- package/src/autoconscience/experiments/runner.js +54 -0
- package/src/autoconscience/experiments/sandbox.js +58 -0
- package/src/autoconscience/index.d.ts +203 -0
- package/src/autoconscience/index.js +116 -0
- package/src/autoconscience/lessons.js +32 -0
- package/src/autoconscience/shadow/candidate.js +69 -0
- package/src/autoconscience/shadow/index.d.ts +169 -0
- package/src/autoconscience/shadow/index.js +11 -0
- package/src/autoconscience/shadow/report.js +125 -0
- package/src/autoconscience/shadow/runner.js +384 -0
- package/src/autoconscience/shadow/store.js +98 -0
- package/src/autoconscience/signals.js +88 -0
- package/src/autoconscience/statistics.js +84 -0
- package/src/autoconscience/vigilance/abstention.js +123 -0
- package/src/autoconscience/vigilance/adversary.js +145 -0
- package/src/autoconscience/vigilance/common.js +56 -0
- package/src/autoconscience/vigilance/drift.js +306 -0
- package/src/autoconscience/vigilance/followups.js +100 -0
- package/src/autoconscience/vigilance/index.d.ts +190 -0
- package/src/autoconscience/vigilance/index.js +23 -0
- package/src/autoconscience/vigilance/lessonTests.js +40 -0
- package/src/autoconscience/vigilance/library.js +162 -0
- package/src/autoconscience/vigilance/roles.js +122 -0
- package/src/autoconscience/vigilance/store.js +166 -0
- package/src/conscience.js +559 -0
- package/src/diff.js +27 -0
- package/src/errors.js +11 -0
- package/src/governor/approvals.js +132 -0
- package/src/governor/changes.js +269 -0
- package/src/governor/governor.js +286 -0
- package/src/governor/index.d.ts +308 -0
- package/src/governor/index.js +20 -0
- package/src/governor/policy.js +136 -0
- package/src/governor/postgres.js +243 -0
- package/src/governor/review.js +191 -0
- package/src/governor/rollout.js +66 -0
- package/src/governor/stores.js +136 -0
- package/src/governor/util.js +53 -0
- package/src/guard.js +21 -0
- package/src/index.d.ts +244 -0
- package/src/index.js +23 -0
- package/src/memoryStore.js +65 -0
- package/src/postgres.js +93 -0
- 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 };
|
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
/** Deterministic governor: no language model is imported or consulted. */
|
|
2
|
+
|
|
3
|
+
export type ProtectedScope = 'permissions' | 'budgets' | 'security' | 'privacy' | 'constitution' | 'approvals' | 'isolation' | 'governor';
|
|
4
|
+
export type ModifiableKind = 'instructions' | 'threshold' | 'tool_description' | 'routing';
|
|
5
|
+
export type ProposalStatus = 'rejected' | 'pending_approval' | 'approved' | 'declined' | 'expired';
|
|
6
|
+
export type RiskLevel = 'low' | 'medium' | 'high' | 'critical';
|
|
7
|
+
export type DeclineReason = 'insufficient_evidence' | 'risk_too_high' | 'not_needed' | 'wrong_scope' | 'poor_tests' | 'no_rollback_plan' | 'conflicts_with_policy' | 'bad_timing' | 'duplicate' | 'other' | (string & {});
|
|
8
|
+
export type FindingSeverity = 'info' | 'low' | 'medium' | 'high' | 'critical';
|
|
9
|
+
export type GovernorReason = 'governor_halted' | 'invalid_proposal' | 'cross_organisation' | 'protected_scope' | 'not_allowlisted' | 'human_approval_required' | 'budget_exceeded';
|
|
10
|
+
|
|
11
|
+
/** A protected rule: reflection may never change what it covers. `protectedScope` is a scope name, `kind:id`, or a prefix ending in `*`. */
|
|
12
|
+
export interface ConstitutionRule { id: string; description: string; protectedScope: string; owner: string }
|
|
13
|
+
|
|
14
|
+
export interface GovernorPolicyInput {
|
|
15
|
+
version?: string;
|
|
16
|
+
/** Spending caps, in your own cost unit. periodMs (default one day) is the window of perAgent and perOrganisation. */
|
|
17
|
+
budgets: { perCycle: number; perAgent: number; perOrganisation: number; periodMs?: number };
|
|
18
|
+
/** Added to the default constitution, which can never be removed. */
|
|
19
|
+
constitution?: ConstitutionRule[];
|
|
20
|
+
/** Objects a proposal may target; a subset of the four modifiable kinds. */
|
|
21
|
+
permissions?: { modifiable?: ModifiableKind[] };
|
|
22
|
+
/** Only 'none' in this version: every proposal waits for a human. */
|
|
23
|
+
automaticChanges?: 'none';
|
|
24
|
+
isolation?: 'organisation';
|
|
25
|
+
/** Human identities allowed to approve; any human when absent. */
|
|
26
|
+
approvers?: string[];
|
|
27
|
+
/** Static kill switch: true keeps the governor halted until the policy changes. */
|
|
28
|
+
halted?: boolean;
|
|
29
|
+
/** Approval matrix, double approval, expiry and the register of decline reasons. */
|
|
30
|
+
approvals?: ApprovalsPolicyInput;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface ApprovalsPolicyInput {
|
|
34
|
+
/** Roles of each human identity. Required when the matrix names roles. */
|
|
35
|
+
roles?: Record<string, string[]>;
|
|
36
|
+
/** Who may approve a kind of change (or "default"), and how many approvals it needs at least. */
|
|
37
|
+
matrix?: Partial<Record<ModifiableKind | 'default', { roles?: string[]; approvals?: number }>>;
|
|
38
|
+
/** Minimum risk of a kind of change (default "medium" for all). A proposer can raise the risk, never lower it. */
|
|
39
|
+
floors?: Partial<Record<ModifiableKind, RiskLevel>>;
|
|
40
|
+
/** From this risk, two distinct people must approve (default "high"). */
|
|
41
|
+
doubleApprovalFrom?: RiskLevel;
|
|
42
|
+
/** With a double approval, the approvals must come from two different roles. */
|
|
43
|
+
distinctRoles?: boolean;
|
|
44
|
+
/** How long an approval stays valid, in milliseconds (default 7 days). */
|
|
45
|
+
expiresInMs?: number;
|
|
46
|
+
/** Extra codes added to the register of decline reasons. */
|
|
47
|
+
declineReasons?: string[];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface ApprovalsPolicy {
|
|
51
|
+
roles: Record<string, string[]> | null;
|
|
52
|
+
matrix: Partial<Record<ModifiableKind | 'default', { roles: string[] | null; approvals: number }>>;
|
|
53
|
+
floors: Record<string, RiskLevel>;
|
|
54
|
+
doubleApprovalFrom: RiskLevel; distinctRoles: boolean; expiresInMs: number; declineReasons: string[];
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface GovernorPolicy {
|
|
58
|
+
version: string;
|
|
59
|
+
budgets: { perCycle: number; perAgent: number; perOrganisation: number; periodMs: number };
|
|
60
|
+
constitution: ConstitutionRule[];
|
|
61
|
+
permissions: { modifiable: ModifiableKind[] };
|
|
62
|
+
automaticChanges: 'none';
|
|
63
|
+
isolation: 'organisation';
|
|
64
|
+
approvers: string[] | null;
|
|
65
|
+
halted: boolean;
|
|
66
|
+
approvals: ApprovalsPolicy;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export interface Actor { kind: string; id: string }
|
|
70
|
+
export interface HumanActor { kind: 'human'; id: string }
|
|
71
|
+
|
|
72
|
+
export interface ChangeProposalInput {
|
|
73
|
+
/** Stable id; derived from the content when absent (the same proposal twice is one record). */
|
|
74
|
+
id?: string;
|
|
75
|
+
organisationId: string;
|
|
76
|
+
target: { kind: string; id: string; version?: string; organisationId?: string };
|
|
77
|
+
change: unknown;
|
|
78
|
+
justification?: string;
|
|
79
|
+
/** Scopes the proposal declares it touches. */
|
|
80
|
+
scopes?: string[];
|
|
81
|
+
/** Other organisations touched: any makes the proposal cross-organisation. */
|
|
82
|
+
organisationIds?: string[];
|
|
83
|
+
proposedBy: { kind: 'engine' | 'model' | 'human' | 'system'; id: string };
|
|
84
|
+
owner?: string;
|
|
85
|
+
tests?: unknown;
|
|
86
|
+
replay?: unknown;
|
|
87
|
+
rollback?: unknown;
|
|
88
|
+
/** Risk you declare; it can only raise the floor of the kind. */
|
|
89
|
+
risk?: RiskLevel;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export interface ApprovalRecord { approver: HumanActor; role: string | null; at: string; expiresAt: string; note: string | null }
|
|
93
|
+
|
|
94
|
+
export interface ChangeProposal {
|
|
95
|
+
id: string; organisationId: string;
|
|
96
|
+
target: { kind: string | null; id: string | null; version: string | null; organisationId: string | null } | null;
|
|
97
|
+
change: unknown; justification: string | null; scopes: string[]; organisationIds: string[];
|
|
98
|
+
proposedBy: Actor | null; owner: string | null; tests: unknown; replay: unknown; rollback: unknown;
|
|
99
|
+
fingerprint: string; status: ProposalStatus; reasons: GovernorReason[];
|
|
100
|
+
/** Constitution rules touched (ids). */
|
|
101
|
+
rules: string[];
|
|
102
|
+
policyVersion: string; createdAt: string; decidedAt: string | null; approver: HumanActor | null; note: string | null;
|
|
103
|
+
/** Effective risk: the higher of the floor of the kind and the declared risk. */
|
|
104
|
+
risk: RiskLevel; declaredRisk: RiskLevel | null; requiredApprovals: number;
|
|
105
|
+
/** Valid approvals recorded so far (one is enough below the double-approval risk). */
|
|
106
|
+
approvals: ApprovalRecord[];
|
|
107
|
+
declineReason: DeclineReason | null;
|
|
108
|
+
/** Set once a candidate version was created from this proposal. */
|
|
109
|
+
staged?: { versionId: string; at: string; by: Actor };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export interface AuditEntry {
|
|
113
|
+
id: string; at: string; policyVersion: string; organisationId: string | null; proposalId: string | null;
|
|
114
|
+
action: 'evaluate' | 'approve' | 'decline' | 'approval_expired' | 'expire' | 'halt' | 'resume' | 'spend' | 'spend_refused' | 'register' | 'stage' | 'deploy' | 'promote' | 'rollback' | 'emergency_revert' | 'finding';
|
|
115
|
+
decision: string; reasons: string[]; actor: Actor | null; [key: string]: unknown;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export interface SpendInput { id: string; organisationId: string; agentId: string; cycleId?: string | null; cost: number }
|
|
119
|
+
export interface SpendTotals { cycle: number; agent: number; organisation: number }
|
|
120
|
+
export interface SpendDecision { allowed: boolean; reasons: GovernorReason[]; totals: SpendTotals | null; limits: { perCycle: number; perAgent: number; perOrganisation: number; since: number } }
|
|
121
|
+
export interface HaltState { halted: boolean; by: Actor; reason: string | null; at: string }
|
|
122
|
+
|
|
123
|
+
export type ManagedKind = ModifiableKind;
|
|
124
|
+
export interface ObjectRef { organisationId: string; kind: ManagedKind; id: string }
|
|
125
|
+
export interface Exposure { percentage: number; cohorts: string[] }
|
|
126
|
+
export interface ObjectState extends ObjectRef {
|
|
127
|
+
revision: number;
|
|
128
|
+
/** The version served to everyone outside the rollout. */
|
|
129
|
+
stable: string;
|
|
130
|
+
/** Stable versions in order, the last one being `stable`: rollback walks back along it. */
|
|
131
|
+
stableHistory: string[];
|
|
132
|
+
candidate: string | null;
|
|
133
|
+
rollout: (Exposure & { startedAt: string; updatedAt: string; updatedBy: Actor }) | null;
|
|
134
|
+
nextNumber: number; createdAt: string; updatedAt: string;
|
|
135
|
+
}
|
|
136
|
+
export interface ObjectVersion extends ObjectRef {
|
|
137
|
+
versionId: string; number: number; content: unknown; fingerprint: string; parent: string | null;
|
|
138
|
+
source: 'baseline' | 'proposal'; proposalId: string | null; createdAt: string; createdBy: Actor;
|
|
139
|
+
approvedBy?: Array<{ id: string; role: string | null; at: string }>;
|
|
140
|
+
}
|
|
141
|
+
export interface ObjectVersionView extends ObjectVersion { status: 'stable' | 'candidate' | 'previous' | 'discarded' }
|
|
142
|
+
export interface ResolvedVersion { versionId: string; number: number; content: unknown; source: 'stable' | 'candidate'; reason: 'no_candidate' | 'halted' | 'not_in_rollout' | 'in_rollout' }
|
|
143
|
+
export interface RollbackResult { object: ObjectState; mode: 'candidate_discarded' | 'stable_restored'; discardedVersion: string; restoredVersion: string }
|
|
144
|
+
/** Rules in the shape of @astratra/flags (createMemorySource): one boolean flag per object that has a candidate. */
|
|
145
|
+
export interface ExportedFlagRules { flags: Record<string, { type: 'boolean'; default: false; value: true; rollout: number; seed: string; target?: { cohort: string[] } }> }
|
|
146
|
+
/** The part of an @astratra/flags FlagProvider the governor uses. Nothing is imported from that package. */
|
|
147
|
+
export interface FlagResolver { resolveBoolean(key: string, fallback?: boolean, context?: { targetingKey?: string; attributes?: Record<string, unknown> }): Promise<{ value: boolean }> }
|
|
148
|
+
|
|
149
|
+
export interface FindingInput {
|
|
150
|
+
id?: string; organisationId: string; runId?: string; code: string; severity: FindingSeverity;
|
|
151
|
+
subject: { kind: string; id: string }; decisionIds?: string[]; evidenceRefs?: string[]; sampleSize?: number; confidence?: number;
|
|
152
|
+
metrics?: unknown; recordedBy: Actor;
|
|
153
|
+
}
|
|
154
|
+
export interface Finding extends Required<Pick<FindingInput, 'organisationId' | 'code' | 'severity' | 'subject' | 'recordedBy'>> {
|
|
155
|
+
id: string; runId: string | null; decisionIds: string[]; evidenceRefs: string[]; sampleSize: number | null; confidence: number | null; metrics: unknown; receivedAt: string;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** A refusal, human or by code, as a signal for the evaluation and experiment phases. Codes only. */
|
|
159
|
+
export interface RejectionSignal {
|
|
160
|
+
proposalId: string; organisationId: string; origin: 'human' | 'governor'; reasonCodes: string[];
|
|
161
|
+
target: { kind: string | null; id: string | null; version: string | null }; risk: RiskLevel | null; scopes: string[]; rules: string[];
|
|
162
|
+
proposedBy: Actor | null; decidedBy: HumanActor | null; at: string;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** The morning report is data: ids, codes and numbers. An interface turns it into words. */
|
|
166
|
+
export interface MorningReport {
|
|
167
|
+
schema: 'morning-report/1'; organisationId: string; policyVersion: string; since: string; until: string; halted: boolean;
|
|
168
|
+
findings: { total: number; bySeverity: Record<FindingSeverity, number>; items: Finding[] };
|
|
169
|
+
pendingProposals: Array<{
|
|
170
|
+
id: string; target: { kind: string | null; id: string | null; version: string | null }; risk: RiskLevel; requiredApprovals: number; approvalsValid: number;
|
|
171
|
+
approvedBy: Array<{ id: string; role: string | null; at: string; expiresAt: string }>; allowedRoles: string[] | null; scopes: string[]; proposedBy: Actor | null;
|
|
172
|
+
owner: string | null; createdAt: string; hasJustification: boolean; hasTests: boolean; tests: unknown; hasReplay: boolean; hasRollbackPlan: boolean; rollbackPlan: unknown;
|
|
173
|
+
}>;
|
|
174
|
+
approvedAwaitingStage: Array<{ id: string; target: { kind: string | null; id: string | null; version: string | null }; risk: RiskLevel; approvedAt: string | null; expiresAt: string | null; valid: boolean; expired: boolean; approvalsValid: number }>;
|
|
175
|
+
rollouts: Array<{ kind: string; id: string; stableVersion: string; candidateVersion: string | null; proposalId: string | null; percentage: number; cohorts: string[]; startedAt: string | null; updatedAt: string | null }>;
|
|
176
|
+
rejections: RejectionSignal[];
|
|
177
|
+
rollbacks: Array<{ at: string; kind: string; id: string; fromVersion: string; toVersion: string; mode: string; emergency: boolean; reason: string | null; actor: Actor | null }>;
|
|
178
|
+
counts: { findings: number; pending: number; pendingHighRisk: number; approvedAwaitingStage: number; rollouts: number; rejections: number; humanRejections: number; rollbacks: number };
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export interface ApprovalInvariantReport { ok: boolean; checked: { proposals: number; versions: number }; violations: Array<{ type: 'proposal' | 'version'; code: string; proposalId?: string | null; versionId?: string; kind?: string; id?: string }> }
|
|
182
|
+
|
|
183
|
+
/** Storage of the governor. Implement it to use another database (see README). */
|
|
184
|
+
export interface GovernorStore {
|
|
185
|
+
/** Insert once; an existing (organisationId, id) is returned unchanged with created: false. */
|
|
186
|
+
putProposal(record: ChangeProposal): Promise<{ record: ChangeProposal; created: boolean }>;
|
|
187
|
+
getProposal(organisationId: string, id: string): Promise<ChangeProposal | null>;
|
|
188
|
+
/** Compare-and-set on status: returns null when the proposal is not in `fromStatus`. */
|
|
189
|
+
transitionProposal(organisationId: string, id: string, fromStatus: ProposalStatus, patch: Partial<ChangeProposal>, guard?: { approvals: number }): Promise<ChangeProposal | null>;
|
|
190
|
+
listProposals(filter: { organisationId: string; status?: ProposalStatus; statuses?: ProposalStatus[]; /** Decided (or, when pending, created) at or after this ISO date. */ since?: string; limit?: number }): Promise<ChangeProposal[]>;
|
|
191
|
+
appendAudit(entry: AuditEntry): Promise<AuditEntry>;
|
|
192
|
+
/** Newest first. organisationId: null lists global entries (kill switch). */
|
|
193
|
+
listAudit(filter: { organisationId?: string | null; proposalId?: string; actions?: string[]; since?: string; objectKind?: string; objectId?: string; limit?: number }): Promise<AuditEntry[]>;
|
|
194
|
+
/** Atomic check-and-insert, idempotent by (organisationId, id). */
|
|
195
|
+
reserveSpend(entry: { id: string; organisationId: string; agentId: string; cycleId: string | null; cost: number; at: number }, limits: { perCycle: number; perAgent: number; perOrganisation: number; since: number }): Promise<{ reserved: boolean; created: boolean; totals: SpendTotals }>;
|
|
196
|
+
getControl(key: string): Promise<any | null>;
|
|
197
|
+
setControl(key: string, value: unknown): Promise<unknown>;
|
|
198
|
+
/** Versioned objects. */
|
|
199
|
+
getObject(organisationId: string, kind: string, id: string): Promise<ObjectState | null>;
|
|
200
|
+
createObject(state: ObjectState): Promise<{ record: ObjectState; created: boolean }>;
|
|
201
|
+
/** Compare-and-set on `revision`: null when another writer got there first. */
|
|
202
|
+
updateObject(organisationId: string, kind: string, id: string, expectedRevision: number, next: ObjectState): Promise<ObjectState | null>;
|
|
203
|
+
listObjects(filter: { organisationId?: string; kind?: string; hasCandidate?: boolean; limit?: number }): Promise<ObjectState[]>;
|
|
204
|
+
putVersion(record: ObjectVersion): Promise<{ record: ObjectVersion; created: boolean }>;
|
|
205
|
+
getVersion(organisationId: string, kind: string, id: string, versionId: string): Promise<ObjectVersion | null>;
|
|
206
|
+
/** Oldest first. */
|
|
207
|
+
listVersions(filter: ObjectRef & { limit?: number }): Promise<ObjectVersion[]>;
|
|
208
|
+
putFinding(record: Finding): Promise<{ record: Finding; created: boolean }>;
|
|
209
|
+
listFindings(filter: { organisationId: string; since?: string; until?: string; limit?: number }): Promise<Finding[]>;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
export interface GovernorOptions {
|
|
213
|
+
/** Default: memory store (lost on exit). */
|
|
214
|
+
store?: GovernorStore;
|
|
215
|
+
now?(): number;
|
|
216
|
+
idFactory?(): string;
|
|
217
|
+
/** Called after each audit entry; errors are ignored. */
|
|
218
|
+
onEvent?(event: AuditEntry & { type: 'governor' }): void | Promise<void>;
|
|
219
|
+
/** An @astratra/flags FlagProvider (or anything with resolveBoolean): it then decides who sees a candidate. Absent: built-in rollout with the same hashing. */
|
|
220
|
+
flags?: FlagResolver;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
export interface Governor {
|
|
224
|
+
getPolicy(): GovernorPolicy;
|
|
225
|
+
/** Judges a proposal by code. Never applies anything: at best it waits for human approval. */
|
|
226
|
+
evaluatePolicy(proposal: ChangeProposalInput): Promise<ChangeProposal>;
|
|
227
|
+
/** Approver: a human identity supplied by your application, never a model. Approval does not apply the change. */
|
|
228
|
+
approveProposal(id: string, options: { approver: HumanActor; organisationId: string; note?: string; /** Role to act under, when the person holds several. */ role?: string }): Promise<ChangeProposal>;
|
|
229
|
+
/** reasonCode comes from the register (DECLINE_REASONS plus the policy's own codes). */
|
|
230
|
+
declineProposal(id: string, options: { approver: HumanActor; organisationId: string; reasonCode: DeclineReason; note?: string }): Promise<ChangeProposal>;
|
|
231
|
+
/** Moves approved proposals whose approvals ran out, and that nobody staged, to "expired". Returns their ids. */
|
|
232
|
+
expireApprovals(options: { organisationId: string; by?: Actor }): Promise<string[]>;
|
|
233
|
+
getProposal(organisationId: string, id: string): Promise<ChangeProposal | null>;
|
|
234
|
+
listProposals(filter: { organisationId: string; status?: ProposalStatus; limit?: number }): Promise<ChangeProposal[]>;
|
|
235
|
+
listAudit(filter?: { organisationId?: string | null; proposalId?: string; limit?: number }): Promise<AuditEntry[]>;
|
|
236
|
+
authorizeSpend(input: SpendInput): Promise<SpendDecision>;
|
|
237
|
+
/** Returns the single organisation of an operation, or throws (cross_organisation, organisation_required). */
|
|
238
|
+
assertSingleOrganisation(...organisationIds: Array<string | null | undefined | Array<string | null | undefined>>): string;
|
|
239
|
+
/** Kill switch. Any actor may pull it; global without organisationId. */
|
|
240
|
+
halt(options: { by: Actor; reason?: string; organisationId?: string }): Promise<HaltState & { reverted: Array<ObjectRef & { discardedVersion: string; restoredVersion: string }>; failures: Array<ObjectRef & { code: string }> }>;
|
|
241
|
+
/** Only a human releases it. */
|
|
242
|
+
resume(options: { by: HumanActor; reason?: string; organisationId?: string }): Promise<HaltState>;
|
|
243
|
+
isHalted(organisationId?: string): Promise<boolean>;
|
|
244
|
+
assertReady(options?: { organisationId?: string }): Promise<true>;
|
|
245
|
+
|
|
246
|
+
/** Declares the version in use today (version v1) of an object. Human or system only. */
|
|
247
|
+
registerObject(input: ObjectRef & { content: unknown; by: HumanActor | { kind: 'system'; id: string } }): Promise<{ object: ObjectState; version: ObjectVersion; created: boolean }>;
|
|
248
|
+
/** Creates the candidate version (0 % exposure) of an approved proposal. Never for a model's say-so: the approvals are re-checked. */
|
|
249
|
+
stageChange(proposalId: string, input: { organisationId: string; by: Actor }): Promise<{ object: ObjectState; version: ObjectVersion; created: boolean }>;
|
|
250
|
+
/** Sets the exposure of the candidate: percentage 0 to 100 and/or cohorts. A human only. */
|
|
251
|
+
deployChange(input: ObjectRef & { percentage?: number; cohorts?: string[]; by: HumanActor }): Promise<ObjectState>;
|
|
252
|
+
/** Makes the candidate stable once it reaches 100 % of everyone. A human only. */
|
|
253
|
+
promoteChange(input: ObjectRef & { by: HumanActor }): Promise<ObjectState>;
|
|
254
|
+
/** Discards the candidate, or restores the version that was stable before the last promotion. Any identified actor, any time. */
|
|
255
|
+
rollbackChange(input: ObjectRef & { by: Actor; reason?: string }): Promise<RollbackResult>;
|
|
256
|
+
/** Which version this caller gets. Halted or outside the rollout: the stable one. */
|
|
257
|
+
resolveVersion(input: ObjectRef & { targetingKey?: string; attributes?: Record<string, unknown> }): Promise<ResolvedVersion>;
|
|
258
|
+
getObject(input: ObjectRef): Promise<ObjectState | null>;
|
|
259
|
+
listObjects(input: { organisationId: string; kind?: ManagedKind; hasCandidate?: boolean; limit?: number }): Promise<ObjectState[]>;
|
|
260
|
+
listVersions(input: ObjectRef & { limit?: number }): Promise<ObjectVersionView[]>;
|
|
261
|
+
/** Audit entries of one object, newest first: who, what, when, version before and after. */
|
|
262
|
+
getChangeHistory(input: ObjectRef & { limit?: number }): Promise<AuditEntry[]>;
|
|
263
|
+
exportFlagRules(input: { organisationId: string }): Promise<ExportedFlagRules>;
|
|
264
|
+
|
|
265
|
+
recordFinding(input: FindingInput): Promise<Finding>;
|
|
266
|
+
listFindings(input: { organisationId: string; since?: Date | string | number; limit?: number }): Promise<Finding[]>;
|
|
267
|
+
listRejectionSignals(input: { organisationId: string; since?: Date | string | number; origin?: 'human' | 'governor'; reasonCode?: string; targetKind?: string; limit?: number }): Promise<RejectionSignal[]>;
|
|
268
|
+
morningReport(input: { organisationId: string; since: Date | string | number; until?: Date | string | number; limit?: number }): Promise<MorningReport>;
|
|
269
|
+
/** Checks that no stored approval or version rests on anything but human approvals. */
|
|
270
|
+
verifyApprovalInvariant(input: { organisationId: string }): Promise<ApprovalInvariantReport>;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
export function createGovernor(policy: GovernorPolicyInput, options?: GovernorOptions): Governor;
|
|
274
|
+
/** Bootstrap check before any reflective write: governor_missing, governor_invalid, governor_unavailable, governor_halted. */
|
|
275
|
+
export function assertGovernorReady(governor: Governor | null | undefined, options?: { organisationId?: string }): Promise<true>;
|
|
276
|
+
export function isGovernor(value: unknown): value is Governor;
|
|
277
|
+
export function validatePolicy(policy: GovernorPolicyInput | null | undefined): GovernorPolicy;
|
|
278
|
+
export function scopesOf(proposal: Partial<ChangeProposalInput>): Set<string>;
|
|
279
|
+
export function protectedRulesTouched(policy: GovernorPolicy, proposal: Partial<ChangeProposalInput>): string[];
|
|
280
|
+
export function createMemoryGovernorStore(): GovernorStore;
|
|
281
|
+
export interface Queryable { query(sql: string, params?: unknown[]): Promise<{ rows: any[]; rowCount?: number | null }>; connect?(): Promise<any> }
|
|
282
|
+
export function createPostgresGovernorStore(db: Queryable, options?: { prefix?: string }): GovernorStore;
|
|
283
|
+
export function postgresGovernorSchema(options?: { prefix?: string }): string;
|
|
284
|
+
|
|
285
|
+
export class GovernorError extends Error {
|
|
286
|
+
code: 'policy_missing' | 'policy_invalid' | 'governor_missing' | 'governor_invalid' | 'governor_unavailable' | 'governor_halted'
|
|
287
|
+
| 'organisation_required' | 'cross_organisation' | 'invalid_proposal' | 'proposal_conflict' | 'approver_not_human' | 'approver_not_allowed'
|
|
288
|
+
| 'self_approval' | 'not_found' | 'not_pending' | 'protected_scope' | 'invalid_spend' | 'actor_required'
|
|
289
|
+
| 'not_approved' | 'approval_expired' | 'approval_insufficient' | 'approval_invalid' | 'approver_role_missing' | 'approval_roles_not_distinct' | 'already_approved' | 'decline_reason_required'
|
|
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;
|
|
292
|
+
constructor(code: string, message: string);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
export const PROPOSAL_STATUSES: readonly ProposalStatus[];
|
|
296
|
+
export const REASONS: Readonly<{ HALTED: 'governor_halted'; INVALID: 'invalid_proposal'; CROSS_ORGANISATION: 'cross_organisation'; PROTECTED: 'protected_scope'; NOT_ALLOWLISTED: 'not_allowlisted'; HUMAN_APPROVAL: 'human_approval_required'; BUDGET: 'budget_exceeded' }>;
|
|
297
|
+
export const PROTECTED_SCOPES: readonly ProtectedScope[];
|
|
298
|
+
export const MODIFIABLE_KINDS: readonly ModifiableKind[];
|
|
299
|
+
export const AUTOMATIC_CHANGES: readonly ['none'];
|
|
300
|
+
export const DEFAULT_CONSTITUTION: readonly ConstitutionRule[];
|
|
301
|
+
|
|
302
|
+
export const RISK_LEVELS: readonly RiskLevel[];
|
|
303
|
+
/** The register of reasons a person can give when declining. */
|
|
304
|
+
export const DECLINE_REASONS: readonly DeclineReason[];
|
|
305
|
+
export const FINDING_SEVERITIES: readonly FindingSeverity[];
|
|
306
|
+
export const MORNING_REPORT_SCHEMA: 'morning-report/1';
|
|
307
|
+
/** The bucket (0 to 1) of an identifier, identical to bucket() of @astratra/flags. */
|
|
308
|
+
export function rolloutBucket(seed: string, identifier: string | null | undefined): number | null;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/*
|
|
3
|
+
* @astratra/conscience/governor: the deterministic governor. Imports Node
|
|
4
|
+
* built-ins and the files of this folder only (checked by a test).
|
|
5
|
+
*/
|
|
6
|
+
const { createGovernor, assertGovernorReady, isGovernor, STATUSES, REASONS } = require('./governor');
|
|
7
|
+
const { PROTECTED_SCOPES, MODIFIABLE_KINDS, AUTOMATIC_CHANGES, DEFAULT_CONSTITUTION, validatePolicy, scopesOf, protectedRulesTouched } = require('./policy');
|
|
8
|
+
const { createMemoryGovernorStore } = require('./stores');
|
|
9
|
+
const { postgresGovernorSchema, createPostgresGovernorStore } = require('./postgres');
|
|
10
|
+
const { GovernorError } = require('./util');
|
|
11
|
+
const { RISK_LEVELS, DECLINE_REASONS } = require('./approvals');
|
|
12
|
+
const { SEVERITIES, REPORT_SCHEMA } = require('./review');
|
|
13
|
+
const { bucket } = require('./rollout');
|
|
14
|
+
|
|
15
|
+
module.exports = {
|
|
16
|
+
createGovernor, assertGovernorReady, isGovernor, validatePolicy, scopesOf, protectedRulesTouched,
|
|
17
|
+
createMemoryGovernorStore, createPostgresGovernorStore, postgresGovernorSchema, GovernorError,
|
|
18
|
+
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
|
+
};
|