@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,132 @@
1
+ 'use strict';
2
+ /*
3
+ * Approval matrix of the governor (proposition 20): which roles may approve
4
+ * which kind of change, when a second approval is needed, how long an approval
5
+ * stays valid, and the register of rejection reasons. Pure functions of the
6
+ * policy and the proposal: no model, no clock of its own.
7
+ */
8
+ const { GovernorError, isNonEmptyString } = require('./util');
9
+
10
+ const RISK_LEVELS = Object.freeze(['low', 'medium', 'high', 'critical']);
11
+ const DEFAULT_EXPIRY_MS = 7 * 24 * 3600 * 1000;
12
+ const CODE = /^[a-z][a-z0-9_]{1,40}$/;
13
+
14
+ /* Register of the reasons a person gives when declining a proposal. A policy can add codes, never remove one. */
15
+ const DECLINE_REASONS = Object.freeze([
16
+ 'insufficient_evidence', 'risk_too_high', 'not_needed', 'wrong_scope', 'poor_tests',
17
+ 'no_rollback_plan', 'conflicts_with_policy', 'bad_timing', 'duplicate', 'other'
18
+ ]);
19
+
20
+ const rank = (level) => RISK_LEVELS.indexOf(level);
21
+ const fail = (message) => { throw new GovernorError('policy_invalid', `Invalid governor policy: ${message}`); };
22
+
23
+ function validateApprovals(input, modifiable) {
24
+ const source = input ?? {};
25
+ if (typeof source !== 'object' || Array.isArray(source)) fail('approvals must be an object.');
26
+ const stringList = (value, label) => {
27
+ if (!Array.isArray(value) || !value.length || !value.every(isNonEmptyString)) fail(`${label} must be a non-empty array of strings.`);
28
+ return [...new Set(value)];
29
+ };
30
+
31
+ let roles = null;
32
+ if (source.roles != null) {
33
+ if (typeof source.roles !== 'object' || Array.isArray(source.roles)) fail('approvals.roles must map a human identity to its roles.');
34
+ roles = {};
35
+ for (const [id, list] of Object.entries(source.roles)) roles[id] = stringList(list, `approvals.roles.${id}`);
36
+ }
37
+
38
+ const matrix = {};
39
+ for (const [key, entry] of Object.entries(source.matrix ?? {})) {
40
+ if (key !== 'default' && !modifiable.includes(key)) fail(`approvals.matrix.${key}: use a modifiable kind (${modifiable.join(', ')}) or "default".`);
41
+ if (!entry || typeof entry !== 'object') fail(`approvals.matrix.${key} must be an object.`);
42
+ const approvals = entry.approvals ?? 1;
43
+ if (!Number.isInteger(approvals) || approvals < 1 || approvals > 5) fail(`approvals.matrix.${key}.approvals must be an integer from 1 to 5.`);
44
+ matrix[key] = { roles: entry.roles == null ? null : stringList(entry.roles, `approvals.matrix.${key}.roles`), approvals };
45
+ }
46
+ if (Object.values(matrix).some((entry) => entry.roles) && !roles) fail('approvals.matrix lists roles, so approvals.roles must say who holds them.');
47
+
48
+ const floors = {};
49
+ for (const kind of modifiable) floors[kind] = 'medium';
50
+ for (const [kind, level] of Object.entries(source.floors ?? {})) {
51
+ if (!modifiable.includes(kind)) fail(`approvals.floors.${kind} is not a modifiable kind.`);
52
+ if (rank(level) < 0) fail(`approvals.floors.${kind} must be one of ${RISK_LEVELS.join(', ')}.`);
53
+ floors[kind] = level;
54
+ }
55
+ const doubleApprovalFrom = source.doubleApprovalFrom ?? 'high';
56
+ if (rank(doubleApprovalFrom) < 0) fail(`approvals.doubleApprovalFrom must be one of ${RISK_LEVELS.join(', ')}.`);
57
+ if (source.distinctRoles !== undefined && typeof source.distinctRoles !== 'boolean') fail('approvals.distinctRoles must be a boolean.');
58
+ const expiresInMs = source.expiresInMs ?? DEFAULT_EXPIRY_MS;
59
+ if (!Number.isInteger(expiresInMs) || expiresInMs <= 0) fail('approvals.expiresInMs must be a positive integer (milliseconds).');
60
+ const extra = source.declineReasons ?? [];
61
+ if (!Array.isArray(extra) || !extra.every((code) => typeof code === 'string' && CODE.test(code))) fail('approvals.declineReasons must be codes like "too_costly".');
62
+ return {
63
+ roles, matrix, floors, doubleApprovalFrom, distinctRoles: source.distinctRoles === true, expiresInMs,
64
+ declineReasons: [...new Set([...DECLINE_REASONS, ...extra])]
65
+ };
66
+ }
67
+
68
+ /**
69
+ * What a proposal needs before it counts as approved. The risk is the higher of
70
+ * the floor of its kind (set by the policy) and the level the proposer
71
+ * declared: a proposer can raise the bar, never lower it.
72
+ */
73
+ function assess(rules, proposal) {
74
+ const kind = proposal.target?.kind;
75
+ const a = rules.approvals;
76
+ const floor = a.floors[kind] ?? 'medium';
77
+ const asked = Object.hasOwn(proposal, 'declaredRisk') ? proposal.declaredRisk : proposal.risk;
78
+ const declared = RISK_LEVELS.includes(asked) ? asked : null;
79
+ const risk = declared && rank(declared) > rank(floor) ? declared : floor;
80
+ const entry = a.matrix[kind] ?? a.matrix.default ?? null;
81
+ const double = rank(risk) >= rank(a.doubleApprovalFrom);
82
+ return {
83
+ risk,
84
+ requiredApprovals: Math.max(entry?.approvals ?? 1, double ? 2 : 1),
85
+ allowedRoles: entry?.roles ?? null,
86
+ distinctRoles: a.distinctRoles && double
87
+ };
88
+ }
89
+
90
+ /** The role an approver acts under, or a GovernorError when the matrix does not allow them. */
91
+ function actingRole(rules, assessment, who, requestedRole) {
92
+ const held = rules.approvals.roles?.[who.id] ?? [];
93
+ if (requestedRole != null && !held.includes(requestedRole)) throw new GovernorError('approver_role_missing', 'This person does not hold the role they ask to act under.');
94
+ if (!assessment.allowedRoles) return requestedRole ?? held[0] ?? null;
95
+ const usable = held.filter((role) => assessment.allowedRoles.includes(role));
96
+ const role = requestedRole ?? usable[0];
97
+ if (!role || !assessment.allowedRoles.includes(role)) {
98
+ throw new GovernorError('approver_role_missing', `This change needs one of the roles: ${assessment.allowedRoles.join(', ')}.`);
99
+ }
100
+ return role;
101
+ }
102
+
103
+ /** Approvals still valid at `atMs`. */
104
+ const liveApprovals = (proposal, atMs) => (Array.isArray(proposal.approvals) ? proposal.approvals : []).filter((a) => Date.parse(a.expiresAt) > atMs);
105
+
106
+ /**
107
+ * Checks, from the stored record alone, that a proposal really holds the
108
+ * approvals the current policy demands: humans only, distinct people, allowed
109
+ * roles, enough of them, none expired. Returns { ok, code, reason }.
110
+ */
111
+ function checkApprovals(rules, proposal, atMs) {
112
+ const assessment = assess(rules, proposal);
113
+ const all = Array.isArray(proposal.approvals) ? proposal.approvals : [];
114
+ const live = liveApprovals(proposal, atMs);
115
+ const bad = (code, reason) => ({ ok: false, code, reason, assessment });
116
+ if (all.some((a) => a.approver?.kind !== 'human' || !isNonEmptyString(a.approver?.id))) return bad('approver_not_human', 'An approval does not come from a human identity.');
117
+ if (!all.length) return bad('approval_invalid', 'The proposal holds no recorded approval.');
118
+ if (live.length < assessment.requiredApprovals) {
119
+ return live.length < all.length ? bad('approval_expired', 'An approval has expired: ask for a new decision.') : bad('approval_insufficient', 'The approvals are not enough for this risk.');
120
+ }
121
+ if (new Set(live.map((a) => a.approver.id)).size < live.length) return bad('approval_invalid', 'The same person approved twice.');
122
+ if (live.some((a) => a.approver.id === proposal.proposedBy?.id && proposal.proposedBy?.kind === 'human')) return bad('self_approval', 'A person approved their own proposal.');
123
+ if (rules.approvers && live.some((a) => !rules.approvers.includes(a.approver.id))) return bad('approver_not_allowed', 'An approver is not in the policy list.');
124
+ if (assessment.allowedRoles) {
125
+ const held = (a) => rules.approvals.roles?.[a.approver.id] ?? [];
126
+ if (live.some((a) => !a.role || !held(a).includes(a.role) || !assessment.allowedRoles.includes(a.role))) return bad('approver_role_missing', 'An approval was given without an allowed role.');
127
+ }
128
+ if (assessment.distinctRoles && new Set(live.map((a) => a.role)).size < Math.min(2, assessment.requiredApprovals)) return bad('approval_roles_not_distinct', 'A high-risk change needs two different roles.');
129
+ return { ok: true, assessment };
130
+ }
131
+
132
+ module.exports = { RISK_LEVELS, DECLINE_REASONS, DEFAULT_EXPIRY_MS, validateApprovals, assess, actingRole, liveApprovals, checkApprovals, rank };
@@ -0,0 +1,269 @@
1
+ 'use strict';
2
+ /*
3
+ * Reversible changes (proposition 06). A managed object (instructions,
4
+ * threshold, tool description, routing rule) has a stable version and at most
5
+ * one candidate. A candidate is created only from a proposal that a human
6
+ * approved, starts at 0 % exposure, grows by decision of a human, and can be
7
+ * rolled back at any moment. Every step is audited with the version before and
8
+ * after. Nothing here calls a model.
9
+ */
10
+ const { GovernorError, fingerprintOf, copy, isNonEmptyString } = require('./util');
11
+ const { protectedRulesTouched } = require('./policy');
12
+ const { checkApprovals } = require('./approvals');
13
+ const { normalizeExposure, servesCandidate, seedOf, flagKeyOf, toFlagRules } = require('./rollout');
14
+
15
+ const MAX_RETRIES = 6;
16
+ const ACTOR_KINDS_STAGE = ['human', 'system', 'engine'];
17
+ const ACTOR_KINDS_BASELINE = ['human', 'system'];
18
+
19
+ function createChanges(ctx) {
20
+ const { rules, store, now, iso, audit, haltState, assertSingleOrganisation, normalizeProposal } = ctx;
21
+
22
+ const actorOf = (actor, kinds, code = 'actor_not_allowed') => {
23
+ const who = actor && typeof actor === 'object' ? { kind: String(actor.kind ?? ''), id: String(actor.id ?? '') } : null;
24
+ if (!who || !isNonEmptyString(who.id)) throw new GovernorError('actor_required', 'Say who acts.');
25
+ if (kinds && !kinds.includes(who.kind)) throw new GovernorError(code, `This action is for: ${kinds.join(', ')}.`);
26
+ return who;
27
+ };
28
+
29
+ async function assertRunning(organisationId) {
30
+ if ((await haltState(organisationId)).halted) throw new GovernorError('governor_halted', 'The governor is halted: no change may start or grow.');
31
+ }
32
+
33
+ function coordinates(input) {
34
+ const organisationId = assertSingleOrganisation(input.organisationId);
35
+ if (!isNonEmptyString(input.kind) || !isNonEmptyString(input.id)) throw new GovernorError('invalid_object', 'An object needs its kind and its id.');
36
+ if (!rules.permissions.modifiable.includes(input.kind)) throw new GovernorError('not_allowlisted', `"${input.kind}" is not a modifiable kind.`);
37
+ return { organisationId, kind: input.kind, id: input.id };
38
+ }
39
+
40
+ async function loadObject({ organisationId, kind, id }) {
41
+ const state = await store.getObject(organisationId, kind, id);
42
+ if (!state) throw new GovernorError('not_found', 'Object not registered.');
43
+ return state;
44
+ }
45
+
46
+ /* Compare-and-set loop on the object state: concurrent changes never overwrite each other. */
47
+ async function mutate(at, fn) {
48
+ for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
49
+ const state = await loadObject(at);
50
+ const result = await fn(state);
51
+ if (result === null) return { state, changed: false };
52
+ const next = { ...result.next, revision: state.revision + 1, updatedAt: iso() };
53
+ const stored = await store.updateObject(at.organisationId, at.kind, at.id, state.revision, next);
54
+ if (stored) return { state: stored, before: state, changed: true, extra: result.extra };
55
+ }
56
+ throw new GovernorError('change_conflict', 'The object kept changing: try again.');
57
+ }
58
+
59
+ const sameContent = (version, content) => version.fingerprint === fingerprintOf(content);
60
+
61
+ async function registerObject(input = {}) {
62
+ const at = coordinates(input);
63
+ const who = actorOf(input.by, ACTOR_KINDS_BASELINE);
64
+ await assertRunning(at.organisationId);
65
+ if (input.content === undefined || input.content === null) throw new GovernorError('invalid_object', 'A baseline needs its content.');
66
+ if (protectedRulesTouched(rules, { target: { kind: at.kind, id: at.id }, change: input.content }).length) throw new GovernorError('protected_scope', 'A protected scope cannot be versioned here.');
67
+ const content = copy(input.content);
68
+ const version = { ...at, versionId: 'v1', number: 1, content, fingerprint: fingerprintOf(content), parent: null, source: 'baseline', proposalId: null, createdAt: iso(), createdBy: who };
69
+ const state = { ...at, revision: 1, stable: 'v1', stableHistory: ['v1'], candidate: null, rollout: null, nextNumber: 2, createdAt: version.createdAt, updatedAt: version.createdAt };
70
+ const existing = await store.getObject(at.organisationId, at.kind, at.id);
71
+ if (existing) {
72
+ const current = await store.getVersion(at.organisationId, at.kind, at.id, 'v1');
73
+ if (current && sameContent(current, content)) return { object: existing, version: current, created: false };
74
+ throw new GovernorError('object_exists', 'This object is already registered with another baseline.');
75
+ }
76
+ const putVersion = await store.putVersion(version);
77
+ const created = await store.createObject(state);
78
+ if (!created.created) throw new GovernorError('object_exists', 'This object is already registered.');
79
+ await audit({ action: 'register', organisationId: at.organisationId, decision: 'registered', objectKind: at.kind, objectId: at.id, fromVersion: null, toVersion: 'v1', actor: who });
80
+ return { object: created.record, version: putVersion.record, created: true };
81
+ }
82
+
83
+ async function stageChange(proposalId, input = {}) {
84
+ const who = actorOf(input.by, ACTOR_KINDS_STAGE);
85
+ const organisationId = assertSingleOrganisation(input.organisationId);
86
+ await assertRunning(organisationId);
87
+ const proposal = await store.getProposal(organisationId, proposalId);
88
+ if (!proposal) throw new GovernorError('not_found', 'Proposal not found.');
89
+ if (normalizeProposal({ ...proposal, risk: proposal.declaredRisk ?? null }).fingerprint !== proposal.fingerprint) throw new GovernorError('proposal_tampered', 'The stored proposal no longer matches its fingerprint.');
90
+ if (proposal.status === 'expired') throw new GovernorError('approval_expired', 'The approval of this proposal has expired.');
91
+ if (proposal.status !== 'approved') throw new GovernorError('not_approved', `Proposal is ${proposal.status}: only a proposal approved by a human can be staged.`);
92
+ if (protectedRulesTouched(rules, proposal).length) throw new GovernorError('protected_scope', 'The proposal touches a protected scope: it can never be applied.');
93
+ if (!rules.permissions.modifiable.includes(proposal.target.kind)) throw new GovernorError('not_allowlisted', 'The target kind is no longer allowed.');
94
+ if (new Set([proposal.organisationId, ...(proposal.organisationIds ?? []), ...(proposal.target.organisationId ? [proposal.target.organisationId] : [])]).size > 1) {
95
+ throw new GovernorError('cross_organisation', 'The proposal touches another organisation.');
96
+ }
97
+ const at = { organisationId, kind: proposal.target.kind, id: proposal.target.id };
98
+
99
+ const state = await loadObject(at);
100
+ const staged = state.candidate ? await store.getVersion(organisationId, at.kind, at.id, state.candidate) : null;
101
+ if (staged?.proposalId === proposal.id) return { object: state, version: staged, created: false };
102
+ if (proposal.staged) throw new GovernorError('already_staged', 'This proposal was already staged: propose again.');
103
+
104
+ const check = checkApprovals(rules, proposal, now());
105
+ if (!check.ok) {
106
+ if (check.code === 'approval_expired') {
107
+ const expired = await store.transitionProposal(organisationId, proposal.id, 'approved', { status: 'expired', decidedAt: iso() });
108
+ if (expired) await audit({ action: 'expire', organisationId, proposalId: proposal.id, decision: 'expired', reasons: ['approval_expired'], actor: who });
109
+ }
110
+ throw new GovernorError(check.code, check.reason);
111
+ }
112
+ if (state.candidate) throw new GovernorError('candidate_exists', 'This object already has a candidate: promote or roll it back first.');
113
+ if (proposal.target.version != null && proposal.target.version !== state.stable) throw new GovernorError('stale_base', `The proposal targets ${proposal.target.version}, the stable version is ${state.stable}.`);
114
+
115
+ const number = state.nextNumber;
116
+ const versionId = `v${number}`;
117
+ const content = copy(proposal.change);
118
+ const record = {
119
+ ...at, versionId, number, content, fingerprint: fingerprintOf(content), parent: state.stable, source: 'proposal',
120
+ proposalId: proposal.id, createdAt: iso(), createdBy: who, approvedBy: proposal.approvals.map((a) => ({ id: a.approver.id, role: a.role ?? null, at: a.at }))
121
+ };
122
+ const put = await store.putVersion(record);
123
+ if (!put.created && put.record.proposalId !== proposal.id) throw new GovernorError('change_conflict', 'Another change is being staged on this object.');
124
+ const outcome = await mutate(at, (current) => {
125
+ if (current.candidate) {
126
+ if (current.candidate === versionId) return null;
127
+ throw new GovernorError('candidate_exists', 'This object already has a candidate.');
128
+ }
129
+ if (current.stable !== state.stable) throw new GovernorError('stale_base', 'The stable version changed while staging.');
130
+ return { next: { ...current, candidate: versionId, rollout: { percentage: 0, cohorts: [], startedAt: iso(), updatedAt: iso(), updatedBy: who }, nextNumber: Math.max(current.nextNumber, number + 1) } };
131
+ });
132
+ await store.transitionProposal(organisationId, proposal.id, 'approved', { staged: { versionId, at: iso(), by: who } });
133
+ if (outcome.changed) {
134
+ await audit({
135
+ action: 'stage', organisationId, proposalId: proposal.id, decision: 'staged', objectKind: at.kind, objectId: at.id,
136
+ fromVersion: state.stable, toVersion: versionId, rolloutBefore: null, rolloutAfter: { percentage: 0, cohorts: [] }, actor: who,
137
+ approvedBy: record.approvedBy
138
+ });
139
+ }
140
+ return { object: outcome.state, version: put.record, created: outcome.changed };
141
+ }
142
+
143
+ async function deployChange(input = {}) {
144
+ const at = coordinates(input);
145
+ const who = actorOf(input.by, ['human'], 'approver_not_human');
146
+ if (rules.approvers && !rules.approvers.includes(who.id)) throw new GovernorError('approver_not_allowed', 'This person is not an approver in the governor policy.');
147
+ await assertRunning(at.organisationId);
148
+ const outcome = await mutate(at, (state) => {
149
+ if (!state.candidate) throw new GovernorError('no_candidate', 'This object has no candidate to deploy.');
150
+ const exposure = normalizeExposure(input, state.rollout);
151
+ return { next: { ...state, rollout: { ...exposure, startedAt: state.rollout?.startedAt ?? iso(), updatedAt: iso(), updatedBy: who } } };
152
+ });
153
+ await audit({
154
+ action: 'deploy', organisationId: at.organisationId, decision: 'deployed', objectKind: at.kind, objectId: at.id,
155
+ fromVersion: outcome.before.stable, toVersion: outcome.state.candidate, rolloutBefore: outcome.before.rollout && { percentage: outcome.before.rollout.percentage, cohorts: outcome.before.rollout.cohorts },
156
+ rolloutAfter: { percentage: outcome.state.rollout.percentage, cohorts: outcome.state.rollout.cohorts }, actor: who
157
+ });
158
+ return outcome.state;
159
+ }
160
+
161
+ async function promoteChange(input = {}) {
162
+ const at = coordinates(input);
163
+ const who = actorOf(input.by, ['human'], 'approver_not_human');
164
+ if (rules.approvers && !rules.approvers.includes(who.id)) throw new GovernorError('approver_not_allowed', 'This person is not an approver in the governor policy.');
165
+ await assertRunning(at.organisationId);
166
+ const outcome = await mutate(at, (state) => {
167
+ if (!state.candidate) throw new GovernorError('no_candidate', 'This object has no candidate to promote.');
168
+ if (state.rollout?.percentage !== 100 || state.rollout.cohorts.length) throw new GovernorError('rollout_incomplete', 'Deploy the candidate to 100 % of everyone before promoting it.');
169
+ return { next: { ...state, stable: state.candidate, stableHistory: [...state.stableHistory, state.candidate], candidate: null, rollout: null } };
170
+ });
171
+ await audit({ action: 'promote', organisationId: at.organisationId, decision: 'promoted', objectKind: at.kind, objectId: at.id, fromVersion: outcome.before.stable, toVersion: outcome.state.stable, rolloutBefore: { percentage: 100, cohorts: [] }, rolloutAfter: null, actor: who });
172
+ return outcome.state;
173
+ }
174
+
175
+ /* Back to the previous state: discards the candidate, or restores the version that was stable before the last promotion. */
176
+ async function rollback(at, who, reason, action) {
177
+ const outcome = await mutate(at, (state) => {
178
+ if (state.candidate) return { next: { ...state, candidate: null, rollout: null }, extra: { mode: 'candidate_discarded', discarded: state.candidate, restored: state.stable } };
179
+ if (state.stableHistory.length < 2) throw new GovernorError('nothing_to_rollback', 'There is no earlier version to return to.');
180
+ const history = state.stableHistory.slice(0, -1);
181
+ return { next: { ...state, stable: history[history.length - 1], stableHistory: history }, extra: { mode: 'stable_restored', discarded: state.stable, restored: history[history.length - 1] } };
182
+ });
183
+ const { mode, discarded, restored } = outcome.extra;
184
+ await audit({
185
+ action, organisationId: at.organisationId, decision: mode, objectKind: at.kind, objectId: at.id, fromVersion: discarded, toVersion: restored,
186
+ rolloutBefore: outcome.before.rollout && { percentage: outcome.before.rollout.percentage, cohorts: outcome.before.rollout.cohorts }, rolloutAfter: null,
187
+ reason: reason == null ? null : String(reason).slice(0, 500), actor: who
188
+ });
189
+ return { object: outcome.state, mode, discardedVersion: discarded, restoredVersion: restored };
190
+ }
191
+
192
+ /** Always possible, even while halted, by any identified actor: going back is the safe direction. */
193
+ async function rollbackChange(input = {}) {
194
+ const at = coordinates(input);
195
+ return rollback(at, actorOf(input.by), input.reason, 'rollback');
196
+ }
197
+
198
+ /** Emergency stop: every candidate of the scope goes back to its stable version. Never throws; returns what failed. */
199
+ async function revertAllCandidates({ organisationId, by, reason }) {
200
+ const reverted = []; const failures = []; const skip = new Set();
201
+ for (;;) {
202
+ const batch = (await store.listObjects({ organisationId: organisationId ?? undefined, hasCandidate: true, limit: 1000 }))
203
+ .filter((o) => !skip.has(`${o.organisationId}\u0000${o.kind}\u0000${o.id}`));
204
+ if (!batch.length) break;
205
+ for (const object of batch) {
206
+ const at = { organisationId: object.organisationId, kind: object.kind, id: object.id };
207
+ try {
208
+ const result = await rollback(at, by, reason, 'emergency_revert');
209
+ reverted.push({ ...at, discardedVersion: result.discardedVersion, restoredVersion: result.restoredVersion });
210
+ } catch (error) {
211
+ failures.push({ ...at, code: error.code ?? 'error' });
212
+ skip.add(`${at.organisationId}\u0000${at.kind}\u0000${at.id}`);
213
+ }
214
+ }
215
+ }
216
+ return { reverted, failures };
217
+ }
218
+
219
+ /** Which version does this caller get? Halted, no candidate, or outside the rollout: the stable one. */
220
+ async function resolveVersion(input = {}) {
221
+ const at = coordinates(input);
222
+ const state = await loadObject(at);
223
+ const pick = async (versionId, source, reason) => {
224
+ const version = await store.getVersion(at.organisationId, at.kind, at.id, versionId);
225
+ return { versionId, source, reason, content: version.content, number: version.number };
226
+ };
227
+ if (!state.candidate) return pick(state.stable, 'stable', 'no_candidate');
228
+ if ((await haltState(at.organisationId)).halted) return pick(state.stable, 'stable', 'halted');
229
+ const context = { targetingKey: input.targetingKey, attributes: input.attributes };
230
+ let served = false;
231
+ if (ctx.flags) {
232
+ try { served = (await ctx.flags.resolveBoolean(flagKeyOf(at.organisationId, at.kind, at.id), false, context))?.value === true; } catch (_error) { served = false; }
233
+ } else served = servesCandidate(state.rollout, seedOf(at.organisationId, at.kind, at.id, state.candidate), context);
234
+ return served ? pick(state.candidate, 'candidate', 'in_rollout') : pick(state.stable, 'stable', 'not_in_rollout');
235
+ }
236
+
237
+ const statusOf = (state, versionId) => (versionId === state.stable ? 'stable' : versionId === state.candidate ? 'candidate' : state.stableHistory.includes(versionId) ? 'previous' : 'discarded');
238
+
239
+ async function listVersions(input = {}) {
240
+ const at = coordinates(input);
241
+ const state = await loadObject(at);
242
+ const versions = await store.listVersions({ ...at, limit: input.limit });
243
+ return versions.map((version) => ({ ...version, status: statusOf(state, version.versionId) }));
244
+ }
245
+
246
+ async function getObject(input = {}) {
247
+ const at = coordinates(input);
248
+ return store.getObject(at.organisationId, at.kind, at.id);
249
+ }
250
+
251
+ async function listObjects(input = {}) {
252
+ const organisationId = assertSingleOrganisation(input.organisationId);
253
+ return store.listObjects({ organisationId, kind: input.kind, hasCandidate: input.hasCandidate === true, limit: input.limit });
254
+ }
255
+
256
+ async function getChangeHistory(input = {}) {
257
+ const at = coordinates(input);
258
+ return store.listAudit({ organisationId: at.organisationId, objectKind: at.kind, objectId: at.id, limit: input.limit });
259
+ }
260
+
261
+ async function exportFlagRules(input = {}) {
262
+ const organisationId = assertSingleOrganisation(input.organisationId);
263
+ return toFlagRules(await store.listObjects({ organisationId, hasCandidate: true, limit: 1000 }));
264
+ }
265
+
266
+ return { registerObject, stageChange, deployChange, promoteChange, rollbackChange, revertAllCandidates, resolveVersion, listVersions, getObject, listObjects, getChangeHistory, exportFlagRules };
267
+ }
268
+
269
+ module.exports = { createChanges };