@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,136 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const { GovernorError, deepFreeze, isNonEmptyString, copy } = require('./util');
|
|
3
|
+
const { validateApprovals } = require('./approvals');
|
|
4
|
+
|
|
5
|
+
/** What reflection may never change, whatever the justification. */
|
|
6
|
+
const PROTECTED_SCOPES = Object.freeze(['permissions', 'budgets', 'security', 'privacy', 'constitution', 'approvals', 'isolation', 'governor']);
|
|
7
|
+
|
|
8
|
+
/** The only objects a proposal may target, unless the policy narrows the list. */
|
|
9
|
+
const MODIFIABLE_KINDS = Object.freeze(['instructions', 'threshold', 'tool_description', 'routing']);
|
|
10
|
+
|
|
11
|
+
/** Change modes. Only "none" exists in this version: every proposal waits for a human. */
|
|
12
|
+
const AUTOMATIC_CHANGES = Object.freeze(['none']);
|
|
13
|
+
|
|
14
|
+
/*
|
|
15
|
+
* Words that reveal a protected scope when they appear as a target kind, a
|
|
16
|
+
* declared scope or a key of the change. Keys are compared lower case with
|
|
17
|
+
* non-alphanumerics removed, so "organisationId" and "organisation_id" match.
|
|
18
|
+
*/
|
|
19
|
+
const SCOPE_WORDS = Object.freeze({
|
|
20
|
+
permissions: ['permission', 'permissions', 'role', 'roles', 'grant', 'grants', 'acl'],
|
|
21
|
+
budgets: ['budget', 'budgets', 'spend', 'spending', 'costcap', 'maxcost', 'quota', 'quotas'],
|
|
22
|
+
security: ['security', 'guard', 'guards', 'safety', 'sandbox'],
|
|
23
|
+
privacy: ['privacy', 'retention', 'erasure', 'consent', 'masking', 'masker', 'redaction'],
|
|
24
|
+
constitution: ['constitution', 'constitutionrule', 'constitutionrules'],
|
|
25
|
+
approvals: ['approval', 'approvals', 'approver', 'approvers', 'automaticchanges', 'autoapprove'],
|
|
26
|
+
isolation: ['isolation', 'organisation', 'organisationid', 'organization', 'organizationid', 'tenant', 'tenantid'],
|
|
27
|
+
governor: ['governor', 'policy', 'killswitch', 'halt', 'halted']
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
const DEFAULT_CONSTITUTION = Object.freeze(PROTECTED_SCOPES.map((scope) => Object.freeze({
|
|
31
|
+
id: `protect-${scope}`,
|
|
32
|
+
description: `Reflection may not change ${scope}.`,
|
|
33
|
+
protectedScope: scope,
|
|
34
|
+
owner: 'governor'
|
|
35
|
+
})));
|
|
36
|
+
|
|
37
|
+
const fail = (message) => { throw new GovernorError('policy_invalid', `Invalid governor policy: ${message}`); };
|
|
38
|
+
const normalWord = (value) => String(value).toLowerCase().replace(/[^a-z0-9]/g, '');
|
|
39
|
+
|
|
40
|
+
function validRule(rule, index) {
|
|
41
|
+
if (!rule || typeof rule !== 'object') fail(`constitution[${index}] must be an object.`);
|
|
42
|
+
for (const field of ['id', 'description', 'protectedScope', 'owner']) {
|
|
43
|
+
if (!isNonEmptyString(rule[field])) fail(`constitution[${index}].${field} must be a non-empty string.`);
|
|
44
|
+
}
|
|
45
|
+
return { id: rule.id, description: rule.description, protectedScope: rule.protectedScope.trim().toLowerCase(), owner: rule.owner };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function validBudget(budgets, field) {
|
|
49
|
+
const value = budgets[field];
|
|
50
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) fail(`budgets.${field} must be a finite number >= 0.`);
|
|
51
|
+
return value;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Checks a policy and returns its frozen, complete form. The default
|
|
56
|
+
* constitution is always included: a policy can add rules, never remove one.
|
|
57
|
+
*/
|
|
58
|
+
function validatePolicy(policy) {
|
|
59
|
+
if (policy == null) throw new GovernorError('policy_missing', 'No governor policy: reflection cannot start without one.');
|
|
60
|
+
if (typeof policy !== 'object' || Array.isArray(policy)) fail('must be an object.');
|
|
61
|
+
const version = policy.version ?? '1';
|
|
62
|
+
if (!isNonEmptyString(version)) fail('version must be a non-empty string.');
|
|
63
|
+
|
|
64
|
+
if (!policy.budgets || typeof policy.budgets !== 'object') fail('budgets { perCycle, perAgent, perOrganisation } are required.');
|
|
65
|
+
const budgets = {
|
|
66
|
+
perCycle: validBudget(policy.budgets, 'perCycle'),
|
|
67
|
+
perAgent: validBudget(policy.budgets, 'perAgent'),
|
|
68
|
+
perOrganisation: validBudget(policy.budgets, 'perOrganisation'),
|
|
69
|
+
periodMs: policy.budgets.periodMs ?? 86400000
|
|
70
|
+
};
|
|
71
|
+
if (!Number.isInteger(budgets.periodMs) || budgets.periodMs <= 0) fail('budgets.periodMs must be a positive integer.');
|
|
72
|
+
|
|
73
|
+
const extra = policy.constitution ?? [];
|
|
74
|
+
if (!Array.isArray(extra)) fail('constitution must be an array.');
|
|
75
|
+
const constitution = [...DEFAULT_CONSTITUTION.map(copy), ...extra.map(validRule)];
|
|
76
|
+
const ids = new Set();
|
|
77
|
+
for (const rule of constitution) { if (ids.has(rule.id)) fail(`constitution rule "${rule.id}" is declared twice.`); ids.add(rule.id); }
|
|
78
|
+
|
|
79
|
+
const modifiable = policy.permissions?.modifiable ?? [...MODIFIABLE_KINDS];
|
|
80
|
+
if (!Array.isArray(modifiable) || !modifiable.every(isNonEmptyString)) fail('permissions.modifiable must be an array of strings.');
|
|
81
|
+
for (const kind of modifiable) {
|
|
82
|
+
if (!MODIFIABLE_KINDS.includes(kind)) fail(`permissions.modifiable may only list ${MODIFIABLE_KINDS.join(', ')}; "${kind}" is not modifiable by a proposal.`);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const automaticChanges = policy.automaticChanges ?? 'none';
|
|
86
|
+
if (!AUTOMATIC_CHANGES.includes(automaticChanges)) fail('automaticChanges must be "none": every proposal waits for human approval.');
|
|
87
|
+
const isolation = policy.isolation ?? 'organisation';
|
|
88
|
+
if (isolation !== 'organisation') fail('isolation must be "organisation".');
|
|
89
|
+
|
|
90
|
+
const approvers = policy.approvers ?? null;
|
|
91
|
+
if (approvers !== null && (!Array.isArray(approvers) || !approvers.every(isNonEmptyString))) fail('approvers must be an array of human identities.');
|
|
92
|
+
|
|
93
|
+
if (policy.halted !== undefined && typeof policy.halted !== 'boolean') fail('halted must be a boolean.');
|
|
94
|
+
|
|
95
|
+
const kinds = [...new Set(modifiable)];
|
|
96
|
+
return deepFreeze({
|
|
97
|
+
version, budgets, constitution, permissions: { modifiable: kinds },
|
|
98
|
+
automaticChanges, isolation, approvers: approvers && [...new Set(approvers)], halted: policy.halted === true,
|
|
99
|
+
approvals: validateApprovals(policy.approvals, MODIFIABLE_KINDS.filter((kind) => kinds.includes(kind)))
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Every scope a proposal touches: target kind and id, declared scopes, keys of the change. */
|
|
104
|
+
function scopesOf(proposal) {
|
|
105
|
+
const out = new Set();
|
|
106
|
+
const add = (value) => { if (value != null && String(value).trim()) out.add(String(value).trim().toLowerCase()); };
|
|
107
|
+
const target = proposal.target || {};
|
|
108
|
+
add(target.kind);
|
|
109
|
+
if (target.kind != null && target.id != null) add(`${target.kind}:${target.id}`);
|
|
110
|
+
add(target.id);
|
|
111
|
+
for (const scope of Array.isArray(proposal.scopes) ? proposal.scopes : []) add(scope);
|
|
112
|
+
const keys = (value, depth) => {
|
|
113
|
+
if (depth > 32 || !value || typeof value !== 'object') return;
|
|
114
|
+
for (const [key, child] of Object.entries(value)) { add(key); keys(child, depth + 1); }
|
|
115
|
+
};
|
|
116
|
+
keys(proposal.change, 0);
|
|
117
|
+
return out;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Constitution rules a proposal would touch. Deterministic: names and keys, never free text. */
|
|
121
|
+
function protectedRulesTouched(policy, proposal) {
|
|
122
|
+
const scopes = scopesOf(proposal);
|
|
123
|
+
const words = new Set([...scopes].map(normalWord));
|
|
124
|
+
const touched = [];
|
|
125
|
+
for (const rule of policy.constitution) {
|
|
126
|
+
const scope = rule.protectedScope;
|
|
127
|
+
let hit;
|
|
128
|
+
if (scope.endsWith('*')) hit = [...scopes].some((value) => value.startsWith(scope.slice(0, -1)));
|
|
129
|
+
else hit = scopes.has(scope) || words.has(normalWord(scope));
|
|
130
|
+
if (!hit && SCOPE_WORDS[scope]) hit = SCOPE_WORDS[scope].some((word) => words.has(word));
|
|
131
|
+
if (hit) touched.push(rule.id);
|
|
132
|
+
}
|
|
133
|
+
return touched;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
module.exports = { PROTECTED_SCOPES, MODIFIABLE_KINDS, AUTOMATIC_CHANGES, DEFAULT_CONSTITUTION, SCOPE_WORDS, validatePolicy, scopesOf, protectedRulesTouched };
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const { prefixOf, requireQueryable } = require('./util');
|
|
3
|
+
const { boundedLimit } = require('./stores');
|
|
4
|
+
|
|
5
|
+
const DEFAULT_PREFIX = 'astratra_governor';
|
|
6
|
+
const names = (options) => {
|
|
7
|
+
const p = prefixOf(options, DEFAULT_PREFIX);
|
|
8
|
+
return { proposals: `"${p}_proposals"`, audit: `"${p}_audit"`, spend: `"${p}_spend"`, controls: `"${p}_controls"`, objects: `"${p}_objects"`, versions: `"${p}_versions"`, findings: `"${p}_findings"`, raw: p };
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
/** SQL that creates the governor tables. Idempotent: run it at every start or in a migration. */
|
|
12
|
+
function postgresGovernorSchema(options) {
|
|
13
|
+
const t = names(options);
|
|
14
|
+
return `CREATE TABLE IF NOT EXISTS ${t.proposals} (
|
|
15
|
+
organisation_id text NOT NULL,
|
|
16
|
+
id text NOT NULL,
|
|
17
|
+
status text NOT NULL CHECK (status IN ('rejected', 'pending_approval', 'approved', 'declined', 'expired')),
|
|
18
|
+
fingerprint text NOT NULL,
|
|
19
|
+
data jsonb NOT NULL,
|
|
20
|
+
created_at timestamptz NOT NULL,
|
|
21
|
+
PRIMARY KEY (organisation_id, id)
|
|
22
|
+
);
|
|
23
|
+
CREATE INDEX IF NOT EXISTS "${t.raw}_proposals_status_idx" ON ${t.proposals} (organisation_id, status, created_at DESC);
|
|
24
|
+
CREATE TABLE IF NOT EXISTS ${t.audit} (
|
|
25
|
+
seq bigserial PRIMARY KEY,
|
|
26
|
+
id text NOT NULL UNIQUE,
|
|
27
|
+
organisation_id text,
|
|
28
|
+
proposal_id text,
|
|
29
|
+
at timestamptz NOT NULL,
|
|
30
|
+
data jsonb NOT NULL
|
|
31
|
+
);
|
|
32
|
+
CREATE INDEX IF NOT EXISTS "${t.raw}_audit_org_idx" ON ${t.audit} (organisation_id, seq DESC);
|
|
33
|
+
CREATE TABLE IF NOT EXISTS ${t.spend} (
|
|
34
|
+
organisation_id text NOT NULL,
|
|
35
|
+
id text NOT NULL,
|
|
36
|
+
agent_id text NOT NULL,
|
|
37
|
+
cycle_id text,
|
|
38
|
+
cost double precision NOT NULL CHECK (cost >= 0),
|
|
39
|
+
at timestamptz NOT NULL,
|
|
40
|
+
PRIMARY KEY (organisation_id, id)
|
|
41
|
+
);
|
|
42
|
+
CREATE INDEX IF NOT EXISTS "${t.raw}_spend_at_idx" ON ${t.spend} (organisation_id, at);
|
|
43
|
+
CREATE TABLE IF NOT EXISTS ${t.controls} (
|
|
44
|
+
key text PRIMARY KEY,
|
|
45
|
+
data jsonb NOT NULL
|
|
46
|
+
);
|
|
47
|
+
CREATE TABLE IF NOT EXISTS ${t.objects} (
|
|
48
|
+
organisation_id text NOT NULL,
|
|
49
|
+
kind text NOT NULL,
|
|
50
|
+
id text NOT NULL,
|
|
51
|
+
revision integer NOT NULL,
|
|
52
|
+
has_candidate boolean NOT NULL,
|
|
53
|
+
data jsonb NOT NULL,
|
|
54
|
+
PRIMARY KEY (organisation_id, kind, id)
|
|
55
|
+
);
|
|
56
|
+
CREATE INDEX IF NOT EXISTS "${t.raw}_objects_candidate_idx" ON ${t.objects} (has_candidate) WHERE has_candidate;
|
|
57
|
+
CREATE TABLE IF NOT EXISTS ${t.versions} (
|
|
58
|
+
organisation_id text NOT NULL,
|
|
59
|
+
kind text NOT NULL,
|
|
60
|
+
id text NOT NULL,
|
|
61
|
+
version_id text NOT NULL,
|
|
62
|
+
number integer NOT NULL,
|
|
63
|
+
data jsonb NOT NULL,
|
|
64
|
+
PRIMARY KEY (organisation_id, kind, id, version_id)
|
|
65
|
+
);
|
|
66
|
+
CREATE TABLE IF NOT EXISTS ${t.findings} (
|
|
67
|
+
organisation_id text NOT NULL,
|
|
68
|
+
id text NOT NULL,
|
|
69
|
+
received_at timestamptz NOT NULL,
|
|
70
|
+
data jsonb NOT NULL,
|
|
71
|
+
PRIMARY KEY (organisation_id, id)
|
|
72
|
+
);
|
|
73
|
+
CREATE INDEX IF NOT EXISTS "${t.raw}_findings_at_idx" ON ${t.findings} (organisation_id, received_at DESC);`;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const json = (row) => (row ? (typeof row.data === 'string' ? JSON.parse(row.data) : row.data) : null);
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Governor store on PostgreSQL. `db` is any `{ query(sql, params) }`; when it
|
|
80
|
+
* also has `connect()` (a `pg` Pool), spending is reserved inside a
|
|
81
|
+
* transaction under an advisory lock per organisation, so two concurrent
|
|
82
|
+
* spends never both pass a budget. Every value is a SQL parameter.
|
|
83
|
+
*/
|
|
84
|
+
function createPostgresGovernorStore(db, options) {
|
|
85
|
+
requireQueryable(db);
|
|
86
|
+
const t = names(options);
|
|
87
|
+
|
|
88
|
+
async function withTransaction(fn) {
|
|
89
|
+
if (typeof db.connect !== 'function') return fn(db);
|
|
90
|
+
const client = await db.connect();
|
|
91
|
+
try {
|
|
92
|
+
await client.query('BEGIN');
|
|
93
|
+
const result = await fn(client);
|
|
94
|
+
await client.query('COMMIT');
|
|
95
|
+
return result;
|
|
96
|
+
} catch (error) {
|
|
97
|
+
await client.query('ROLLBACK').catch(() => {});
|
|
98
|
+
throw error;
|
|
99
|
+
} finally { client.release(); }
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return {
|
|
103
|
+
async putProposal(record) {
|
|
104
|
+
const inserted = await db.query(
|
|
105
|
+
`INSERT INTO ${t.proposals} (organisation_id, id, status, fingerprint, data, created_at) VALUES ($1, $2, $3, $4, $5::jsonb, $6::timestamptz)
|
|
106
|
+
ON CONFLICT (organisation_id, id) DO NOTHING RETURNING data`,
|
|
107
|
+
[record.organisationId, record.id, record.status, record.fingerprint, JSON.stringify(record), record.createdAt]);
|
|
108
|
+
if (inserted.rows.length) return { record: json(inserted.rows[0]), created: true };
|
|
109
|
+
return { record: await this.getProposal(record.organisationId, record.id), created: false };
|
|
110
|
+
},
|
|
111
|
+
async getProposal(organisationId, id) {
|
|
112
|
+
return json((await db.query(`SELECT data FROM ${t.proposals} WHERE organisation_id = $1 AND id = $2`, [organisationId, id])).rows[0]);
|
|
113
|
+
},
|
|
114
|
+
async transitionProposal(organisationId, id, fromStatus, patch, guard) {
|
|
115
|
+
const params = [organisationId, id, fromStatus, patch.status ?? fromStatus, JSON.stringify(patch)];
|
|
116
|
+
let sql = `UPDATE ${t.proposals} SET status = $4, data = data || $5::jsonb WHERE organisation_id = $1 AND id = $2 AND status = $3`;
|
|
117
|
+
if (guard?.approvals !== undefined) { params.push(guard.approvals); sql += ` AND jsonb_array_length(coalesce(data->'approvals', '[]'::jsonb)) = $${params.length}`; }
|
|
118
|
+
return json((await db.query(`${sql} RETURNING data`, params)).rows[0]);
|
|
119
|
+
},
|
|
120
|
+
async listProposals(filter = {}) {
|
|
121
|
+
const params = [filter.organisationId];
|
|
122
|
+
let sql = `SELECT data FROM ${t.proposals} WHERE organisation_id = $1`;
|
|
123
|
+
if (filter.status != null) { params.push(filter.status); sql += ` AND status = $${params.length}`; }
|
|
124
|
+
if (filter.statuses != null) { params.push(filter.statuses); sql += ` AND status = ANY($${params.length}::text[])`; }
|
|
125
|
+
if (filter.since != null) { params.push(filter.since); sql += ` AND coalesce((data->>'decidedAt')::timestamptz, created_at) >= $${params.length}::timestamptz`; }
|
|
126
|
+
params.push(boundedLimit(filter.limit));
|
|
127
|
+
sql += ` ORDER BY created_at DESC, id LIMIT $${params.length}`;
|
|
128
|
+
return (await db.query(sql, params)).rows.map(json);
|
|
129
|
+
},
|
|
130
|
+
async appendAudit(entry) {
|
|
131
|
+
await db.query(`INSERT INTO ${t.audit} (id, organisation_id, proposal_id, at, data) VALUES ($1, $2, $3, $4::timestamptz, $5::jsonb)`,
|
|
132
|
+
[entry.id, entry.organisationId, entry.proposalId, entry.at, JSON.stringify(entry)]);
|
|
133
|
+
return entry;
|
|
134
|
+
},
|
|
135
|
+
async listAudit(filter = {}) {
|
|
136
|
+
const params = []; const parts = [];
|
|
137
|
+
if (filter.organisationId !== undefined) {
|
|
138
|
+
if (filter.organisationId === null) parts.push('organisation_id IS NULL');
|
|
139
|
+
else { params.push(filter.organisationId); parts.push(`organisation_id = $${params.length}`); }
|
|
140
|
+
}
|
|
141
|
+
if (filter.proposalId != null) { params.push(filter.proposalId); parts.push(`proposal_id = $${params.length}`); }
|
|
142
|
+
if (filter.actions != null) { params.push(filter.actions); parts.push(`data->>'action' = ANY($${params.length}::text[])`); }
|
|
143
|
+
if (filter.since != null) { params.push(filter.since); parts.push(`at >= $${params.length}::timestamptz`); }
|
|
144
|
+
if (filter.objectKind != null) { params.push(filter.objectKind); parts.push(`data->>'objectKind' = $${params.length}`); }
|
|
145
|
+
if (filter.objectId != null) { params.push(filter.objectId); parts.push(`data->>'objectId' = $${params.length}`); }
|
|
146
|
+
params.push(boundedLimit(filter.limit));
|
|
147
|
+
const where = parts.length ? ` WHERE ${parts.join(' AND ')}` : '';
|
|
148
|
+
return (await db.query(`SELECT data FROM ${t.audit}${where} ORDER BY seq DESC LIMIT $${params.length}`, params)).rows.map(json);
|
|
149
|
+
},
|
|
150
|
+
async reserveSpend(entry, limits) {
|
|
151
|
+
return withTransaction(async (q) => {
|
|
152
|
+
await q.query('SELECT pg_advisory_xact_lock(hashtext($1))', [`${t.raw}:${entry.organisationId}`]);
|
|
153
|
+
const sums = async () => {
|
|
154
|
+
const row = (await q.query(
|
|
155
|
+
`SELECT coalesce(sum(cost) FILTER (WHERE $2::text IS NOT NULL AND cycle_id = $2), 0)::float8 AS cycle,
|
|
156
|
+
coalesce(sum(cost) FILTER (WHERE at >= to_timestamp($3::double precision / 1000) AND agent_id = $4), 0)::float8 AS agent,
|
|
157
|
+
coalesce(sum(cost) FILTER (WHERE at >= to_timestamp($3::double precision / 1000)), 0)::float8 AS organisation
|
|
158
|
+
FROM ${t.spend} WHERE organisation_id = $1`,
|
|
159
|
+
[entry.organisationId, entry.cycleId, limits.since, entry.agentId])).rows[0];
|
|
160
|
+
return { cycle: Number(row.cycle), agent: Number(row.agent), organisation: Number(row.organisation) };
|
|
161
|
+
};
|
|
162
|
+
const exists = (await q.query(`SELECT 1 FROM ${t.spend} WHERE organisation_id = $1 AND id = $2`, [entry.organisationId, entry.id])).rows.length > 0;
|
|
163
|
+
if (exists) return { reserved: true, created: false, totals: await sums() };
|
|
164
|
+
const totals = await sums();
|
|
165
|
+
const fits = (entry.cycleId == null || totals.cycle + entry.cost <= limits.perCycle)
|
|
166
|
+
&& totals.agent + entry.cost <= limits.perAgent
|
|
167
|
+
&& totals.organisation + entry.cost <= limits.perOrganisation;
|
|
168
|
+
if (!fits) return { reserved: false, created: false, totals };
|
|
169
|
+
await q.query(`INSERT INTO ${t.spend} (organisation_id, id, agent_id, cycle_id, cost, at) VALUES ($1, $2, $3, $4, $5, to_timestamp($6::double precision / 1000))`,
|
|
170
|
+
[entry.organisationId, entry.id, entry.agentId, entry.cycleId, entry.cost, entry.at]);
|
|
171
|
+
return { reserved: true, created: true, totals: await sums() };
|
|
172
|
+
});
|
|
173
|
+
},
|
|
174
|
+
async getControl(key) {
|
|
175
|
+
return json((await db.query(`SELECT data FROM ${t.controls} WHERE key = $1`, [key])).rows[0]);
|
|
176
|
+
},
|
|
177
|
+
async setControl(key, value) {
|
|
178
|
+
await db.query(`INSERT INTO ${t.controls} (key, data) VALUES ($1, $2::jsonb) ON CONFLICT (key) DO UPDATE SET data = EXCLUDED.data`, [key, JSON.stringify(value)]);
|
|
179
|
+
return value;
|
|
180
|
+
},
|
|
181
|
+
|
|
182
|
+
async getObject(organisationId, kind, id) {
|
|
183
|
+
return json((await db.query(`SELECT data FROM ${t.objects} WHERE organisation_id = $1 AND kind = $2 AND id = $3`, [organisationId, kind, id])).rows[0]);
|
|
184
|
+
},
|
|
185
|
+
async createObject(state) {
|
|
186
|
+
const inserted = await db.query(
|
|
187
|
+
`INSERT INTO ${t.objects} (organisation_id, kind, id, revision, has_candidate, data) VALUES ($1, $2, $3, $4, $5, $6::jsonb)
|
|
188
|
+
ON CONFLICT (organisation_id, kind, id) DO NOTHING RETURNING data`,
|
|
189
|
+
[state.organisationId, state.kind, state.id, state.revision, state.candidate != null, JSON.stringify(state)]);
|
|
190
|
+
if (inserted.rows.length) return { record: json(inserted.rows[0]), created: true };
|
|
191
|
+
return { record: await this.getObject(state.organisationId, state.kind, state.id), created: false };
|
|
192
|
+
},
|
|
193
|
+
async updateObject(organisationId, kind, id, expectedRevision, next) {
|
|
194
|
+
return json((await db.query(
|
|
195
|
+
`UPDATE ${t.objects} SET revision = $5, has_candidate = $6, data = $7::jsonb
|
|
196
|
+
WHERE organisation_id = $1 AND kind = $2 AND id = $3 AND revision = $4 RETURNING data`,
|
|
197
|
+
[organisationId, kind, id, expectedRevision, next.revision, next.candidate != null, JSON.stringify(next)])).rows[0]);
|
|
198
|
+
},
|
|
199
|
+
async listObjects(filter = {}) {
|
|
200
|
+
const params = []; const parts = [];
|
|
201
|
+
if (filter.organisationId != null) { params.push(filter.organisationId); parts.push(`organisation_id = $${params.length}`); }
|
|
202
|
+
if (filter.kind != null) { params.push(filter.kind); parts.push(`kind = $${params.length}`); }
|
|
203
|
+
if (filter.hasCandidate) parts.push('has_candidate');
|
|
204
|
+
params.push(boundedLimit(filter.limit));
|
|
205
|
+
const where = parts.length ? ` WHERE ${parts.join(' AND ')}` : '';
|
|
206
|
+
return (await db.query(`SELECT data FROM ${t.objects}${where} ORDER BY organisation_id, kind, id LIMIT $${params.length}`, params)).rows.map(json);
|
|
207
|
+
},
|
|
208
|
+
async putVersion(record) {
|
|
209
|
+
const inserted = await db.query(
|
|
210
|
+
`INSERT INTO ${t.versions} (organisation_id, kind, id, version_id, number, data) VALUES ($1, $2, $3, $4, $5, $6::jsonb)
|
|
211
|
+
ON CONFLICT (organisation_id, kind, id, version_id) DO NOTHING RETURNING data`,
|
|
212
|
+
[record.organisationId, record.kind, record.id, record.versionId, record.number, JSON.stringify(record)]);
|
|
213
|
+
if (inserted.rows.length) return { record: json(inserted.rows[0]), created: true };
|
|
214
|
+
return { record: await this.getVersion(record.organisationId, record.kind, record.id, record.versionId), created: false };
|
|
215
|
+
},
|
|
216
|
+
async getVersion(organisationId, kind, id, versionId) {
|
|
217
|
+
return json((await db.query(`SELECT data FROM ${t.versions} WHERE organisation_id = $1 AND kind = $2 AND id = $3 AND version_id = $4`, [organisationId, kind, id, versionId])).rows[0]);
|
|
218
|
+
},
|
|
219
|
+
async listVersions(filter) {
|
|
220
|
+
return (await db.query(
|
|
221
|
+
`SELECT data FROM ${t.versions} WHERE organisation_id = $1 AND kind = $2 AND id = $3 ORDER BY number LIMIT $4`,
|
|
222
|
+
[filter.organisationId, filter.kind, filter.id, boundedLimit(filter.limit, 1000)])).rows.map(json);
|
|
223
|
+
},
|
|
224
|
+
|
|
225
|
+
async putFinding(record) {
|
|
226
|
+
const inserted = await db.query(
|
|
227
|
+
`INSERT INTO ${t.findings} (organisation_id, id, received_at, data) VALUES ($1, $2, $3::timestamptz, $4::jsonb)
|
|
228
|
+
ON CONFLICT (organisation_id, id) DO NOTHING RETURNING data`,
|
|
229
|
+
[record.organisationId, record.id, record.receivedAt, JSON.stringify(record)]);
|
|
230
|
+
if (inserted.rows.length) return { record: json(inserted.rows[0]), created: true };
|
|
231
|
+
return { record: json((await db.query(`SELECT data FROM ${t.findings} WHERE organisation_id = $1 AND id = $2`, [record.organisationId, record.id])).rows[0]), created: false };
|
|
232
|
+
},
|
|
233
|
+
async listFindings(filter = {}) {
|
|
234
|
+
const params = [filter.organisationId]; let sql = `SELECT data FROM ${t.findings} WHERE organisation_id = $1`;
|
|
235
|
+
if (filter.since != null) { params.push(filter.since); sql += ` AND received_at >= $${params.length}::timestamptz`; }
|
|
236
|
+
if (filter.until != null) { params.push(filter.until); sql += ` AND received_at <= $${params.length}::timestamptz`; }
|
|
237
|
+
params.push(boundedLimit(filter.limit));
|
|
238
|
+
return (await db.query(`${sql} ORDER BY received_at DESC, id LIMIT $${params.length}`, params)).rows.map(json);
|
|
239
|
+
}
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
module.exports = { postgresGovernorSchema, createPostgresGovernorStore };
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/*
|
|
3
|
+
* Morning review (proposition 08), rejection signals and the approval
|
|
4
|
+
* invariant (proposition 20). The report is data: ids, codes, numbers and the
|
|
5
|
+
* objects the proposer supplied. It contains no generated sentence, so any
|
|
6
|
+
* interface can display it in its own words and languages. Same store, same
|
|
7
|
+
* period, same answer.
|
|
8
|
+
*/
|
|
9
|
+
const { GovernorError, fingerprintOf, copy, isNonEmptyString } = require('./util');
|
|
10
|
+
const { assess, liveApprovals, checkApprovals } = require('./approvals');
|
|
11
|
+
|
|
12
|
+
const SEVERITIES = Object.freeze(['info', 'low', 'medium', 'high', 'critical']);
|
|
13
|
+
const CODE = /^[a-z][a-z0-9_.-]{1,60}$/;
|
|
14
|
+
const REPORT_SCHEMA = 'morning-report/1';
|
|
15
|
+
|
|
16
|
+
function timeOf(value, label) {
|
|
17
|
+
const ms = value instanceof Date ? value.getTime() : typeof value === 'number' ? value : Date.parse(value);
|
|
18
|
+
if (!Number.isFinite(ms)) throw new GovernorError('invalid_period', `${label} must be a date.`);
|
|
19
|
+
return ms;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const targetOf = (proposal) => ({ kind: proposal.target?.kind ?? null, id: proposal.target?.id ?? null, version: proposal.target?.version ?? null });
|
|
23
|
+
const byIdAsc = (a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
|
|
24
|
+
|
|
25
|
+
function createReview(ctx) {
|
|
26
|
+
const { rules, store, now, iso, audit, assertSingleOrganisation, haltState } = ctx;
|
|
27
|
+
const bounded = (limit) => Math.min(Math.max(Number(limit) || 100, 1), 1000);
|
|
28
|
+
|
|
29
|
+
/* ---- findings received from the reflection engine ---- */
|
|
30
|
+
|
|
31
|
+
async function recordFinding(input = {}) {
|
|
32
|
+
if (!input || typeof input !== 'object') throw new GovernorError('invalid_finding', 'A finding must be an object.');
|
|
33
|
+
const organisationId = assertSingleOrganisation(input.organisationId);
|
|
34
|
+
if ((await haltState(organisationId)).halted) throw new GovernorError('governor_halted', 'The governor is halted: findings are not accepted.');
|
|
35
|
+
if (typeof input.code !== 'string' || !CODE.test(input.code)) throw new GovernorError('invalid_finding', 'code must be a short machine code such as "calibration_gap".');
|
|
36
|
+
if (!SEVERITIES.includes(input.severity)) throw new GovernorError('invalid_finding', `severity must be one of ${SEVERITIES.join(', ')}.`);
|
|
37
|
+
const subject = input.subject && typeof input.subject === 'object' ? { kind: String(input.subject.kind ?? ''), id: String(input.subject.id ?? '') } : null;
|
|
38
|
+
if (!subject || !subject.kind || !subject.id) throw new GovernorError('invalid_finding', 'subject { kind, id } is required.');
|
|
39
|
+
const list = (value) => (Array.isArray(value) ? value.map(String) : []);
|
|
40
|
+
const number = (value, label, min, max) => {
|
|
41
|
+
if (value == null) return null;
|
|
42
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value < min || value > max) throw new GovernorError('invalid_finding', `${label} is out of range.`);
|
|
43
|
+
return value;
|
|
44
|
+
};
|
|
45
|
+
const recordedBy = input.recordedBy && typeof input.recordedBy === 'object' ? { kind: String(input.recordedBy.kind ?? ''), id: String(input.recordedBy.id ?? '') } : null;
|
|
46
|
+
if (!recordedBy?.id) throw new GovernorError('actor_required', 'Say who reports the finding.');
|
|
47
|
+
const content = {
|
|
48
|
+
organisationId, runId: input.runId ?? null, code: input.code, severity: input.severity, subject, decisionIds: list(input.decisionIds),
|
|
49
|
+
evidenceRefs: list(input.evidenceRefs), sampleSize: number(input.sampleSize, 'sampleSize', 0, Number.MAX_SAFE_INTEGER),
|
|
50
|
+
confidence: number(input.confidence, 'confidence', 0, 1), metrics: copy(input.metrics) ?? null, recordedBy
|
|
51
|
+
};
|
|
52
|
+
const id = isNonEmptyString(input.id) ? input.id : `finding_${fingerprintOf(content).slice(0, 32)}`;
|
|
53
|
+
const { record, created } = await store.putFinding({ id, ...content, receivedAt: iso() });
|
|
54
|
+
if (created) await audit({ action: 'finding', organisationId, decision: 'received', reasons: [input.code], findingId: id, actor: recordedBy });
|
|
55
|
+
return record;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const listFindings = (filter = {}) => {
|
|
59
|
+
const organisationId = assertSingleOrganisation(filter.organisationId);
|
|
60
|
+
return store.listFindings({ organisationId, since: filter.since == null ? undefined : new Date(timeOf(filter.since, 'since')).toISOString(), limit: filter.limit });
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
/* ---- rejection signals, readable by the evaluation and experiment phases ---- */
|
|
64
|
+
|
|
65
|
+
function signalOf(proposal) {
|
|
66
|
+
const human = proposal.status === 'declined';
|
|
67
|
+
return {
|
|
68
|
+
proposalId: proposal.id, organisationId: proposal.organisationId, origin: human ? 'human' : 'governor',
|
|
69
|
+
reasonCodes: human ? [proposal.declineReason ?? 'other'] : [...proposal.reasons],
|
|
70
|
+
target: targetOf(proposal), risk: proposal.risk ?? null, scopes: [...(proposal.scopes ?? [])], rules: [...(proposal.rules ?? [])],
|
|
71
|
+
proposedBy: proposal.proposedBy, decidedBy: human ? proposal.approver : null, at: proposal.decidedAt ?? proposal.createdAt
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function listRejectionSignals(filter = {}) {
|
|
76
|
+
const organisationId = assertSingleOrganisation(filter.organisationId);
|
|
77
|
+
const statuses = filter.origin === 'human' ? ['declined'] : filter.origin === 'governor' ? ['rejected'] : ['declined', 'rejected'];
|
|
78
|
+
const proposals = await store.listProposals({
|
|
79
|
+
organisationId, statuses, limit: filter.limit == null ? 1000 : bounded(filter.limit),
|
|
80
|
+
since: filter.since == null ? undefined : new Date(timeOf(filter.since, 'since')).toISOString()
|
|
81
|
+
});
|
|
82
|
+
const signals = proposals.map(signalOf)
|
|
83
|
+
.filter((s) => filter.reasonCode == null || s.reasonCodes.includes(filter.reasonCode))
|
|
84
|
+
.filter((s) => filter.targetKind == null || s.target.kind === filter.targetKind);
|
|
85
|
+
return signals.sort((a, b) => (a.at < b.at ? 1 : a.at > b.at ? -1 : a.proposalId < b.proposalId ? -1 : 1)).slice(0, bounded(filter.limit));
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/* ---- the morning report ---- */
|
|
89
|
+
|
|
90
|
+
async function morningReport(input = {}) {
|
|
91
|
+
const organisationId = assertSingleOrganisation(input.organisationId);
|
|
92
|
+
const untilMs = input.until == null ? now() : timeOf(input.until, 'until');
|
|
93
|
+
const sinceMs = timeOf(input.since, 'since');
|
|
94
|
+
if (sinceMs > untilMs) throw new GovernorError('invalid_period', 'since must not be after until.');
|
|
95
|
+
const since = new Date(sinceMs).toISOString(); const until = new Date(untilMs).toISOString();
|
|
96
|
+
const limit = bounded(input.limit);
|
|
97
|
+
|
|
98
|
+
const [findings, pending, approved, signals, objects, rollbackEntries] = await Promise.all([
|
|
99
|
+
store.listFindings({ organisationId, since, until, limit }),
|
|
100
|
+
store.listProposals({ organisationId, status: 'pending_approval', limit: 1000 }),
|
|
101
|
+
store.listProposals({ organisationId, status: 'approved', limit: 1000 }),
|
|
102
|
+
listRejectionSignals({ organisationId, since, limit }),
|
|
103
|
+
store.listObjects({ organisationId, hasCandidate: true, limit: 1000 }),
|
|
104
|
+
store.listAudit({ organisationId, actions: ['rollback', 'emergency_revert'], since, limit })
|
|
105
|
+
]);
|
|
106
|
+
|
|
107
|
+
const findingItems = findings.filter((f) => f.receivedAt <= until).sort((a, b) => (a.receivedAt < b.receivedAt ? 1 : a.receivedAt > b.receivedAt ? -1 : byIdAsc(a, b)));
|
|
108
|
+
const bySeverity = Object.fromEntries(SEVERITIES.map((level) => [level, findingItems.filter((f) => f.severity === level).length]));
|
|
109
|
+
|
|
110
|
+
const pendingItems = pending.filter((p) => p.createdAt <= until).map((p) => {
|
|
111
|
+
const assessment = assess(rules, p);
|
|
112
|
+
const live = liveApprovals(p, untilMs);
|
|
113
|
+
return {
|
|
114
|
+
id: p.id, target: targetOf(p), risk: assessment.risk, requiredApprovals: assessment.requiredApprovals,
|
|
115
|
+
approvalsValid: live.length, approvedBy: live.map((a) => ({ id: a.approver.id, role: a.role ?? null, at: a.at, expiresAt: a.expiresAt })),
|
|
116
|
+
allowedRoles: assessment.allowedRoles, scopes: [...(p.scopes ?? [])], proposedBy: p.proposedBy, owner: p.owner ?? null, createdAt: p.createdAt,
|
|
117
|
+
hasJustification: p.justification != null && p.justification !== '',
|
|
118
|
+
hasTests: p.tests != null, tests: copy(p.tests), hasReplay: p.replay != null,
|
|
119
|
+
hasRollbackPlan: p.rollback != null, rollbackPlan: copy(p.rollback)
|
|
120
|
+
};
|
|
121
|
+
}).sort((a, b) => (a.createdAt < b.createdAt ? 1 : a.createdAt > b.createdAt ? -1 : byIdAsc(a, b)));
|
|
122
|
+
|
|
123
|
+
const awaiting = approved.filter((p) => !p.staged).map((p) => {
|
|
124
|
+
const check = checkApprovals(rules, p, untilMs);
|
|
125
|
+
const live = liveApprovals(p, untilMs);
|
|
126
|
+
const expiresAt = (p.approvals ?? []).map((a) => a.expiresAt).sort()[0] ?? null;
|
|
127
|
+
return { id: p.id, target: targetOf(p), risk: assess(rules, p).risk, approvedAt: p.decidedAt, expiresAt, valid: check.ok, expired: !check.ok && check.code === 'approval_expired', approvalsValid: live.length };
|
|
128
|
+
}).sort(byIdAsc);
|
|
129
|
+
|
|
130
|
+
const rollouts = objects.map((o) => ({
|
|
131
|
+
kind: o.kind, id: o.id, stableVersion: o.stable, candidateVersion: o.candidate, percentage: o.rollout?.percentage ?? 0, cohorts: [...(o.rollout?.cohorts ?? [])],
|
|
132
|
+
startedAt: o.rollout?.startedAt ?? null, updatedAt: o.rollout?.updatedAt ?? null
|
|
133
|
+
}));
|
|
134
|
+
for (const rollout of rollouts) {
|
|
135
|
+
const version = await store.getVersion(organisationId, rollout.kind, rollout.id, rollout.candidateVersion);
|
|
136
|
+
rollout.proposalId = version?.proposalId ?? null;
|
|
137
|
+
}
|
|
138
|
+
rollouts.sort((a, b) => (`${a.kind}:${a.id}` < `${b.kind}:${b.id}` ? -1 : 1));
|
|
139
|
+
|
|
140
|
+
const rollbacks = rollbackEntries.filter((e) => e.at <= until).map((e) => ({
|
|
141
|
+
at: e.at, kind: e.objectKind, id: e.objectId, fromVersion: e.fromVersion, toVersion: e.toVersion, mode: e.decision,
|
|
142
|
+
emergency: e.action === 'emergency_revert', reason: e.reason ?? null, actor: e.actor
|
|
143
|
+
})).sort((a, b) => (a.at < b.at ? 1 : a.at > b.at ? -1 : 0));
|
|
144
|
+
|
|
145
|
+
const rejections = signals.filter((s) => s.at <= until);
|
|
146
|
+
|
|
147
|
+
return {
|
|
148
|
+
schema: REPORT_SCHEMA, organisationId, policyVersion: rules.version, since, until, halted: (await haltState(organisationId)).halted,
|
|
149
|
+
findings: { total: findingItems.length, bySeverity, items: findingItems },
|
|
150
|
+
pendingProposals: pendingItems, approvedAwaitingStage: awaiting, rollouts, rejections, rollbacks,
|
|
151
|
+
counts: {
|
|
152
|
+
findings: findingItems.length, pending: pendingItems.length, pendingHighRisk: pendingItems.filter((p) => p.risk === 'high' || p.risk === 'critical').length,
|
|
153
|
+
approvedAwaitingStage: awaiting.length, rollouts: rollouts.length, rejections: rejections.length,
|
|
154
|
+
humanRejections: rejections.filter((s) => s.origin === 'human').length, rollbacks: rollbacks.length
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/* ---- the invariant: nothing is applied because a model approved it ---- */
|
|
160
|
+
|
|
161
|
+
async function verifyApprovalInvariant(input = {}) {
|
|
162
|
+
const organisationId = assertSingleOrganisation(input.organisationId);
|
|
163
|
+
const violations = [];
|
|
164
|
+
const proposals = await store.listProposals({ organisationId, statuses: ['approved', 'expired'], limit: 1000 });
|
|
165
|
+
const byId = new Map(proposals.map((p) => [p.id, p]));
|
|
166
|
+
for (const proposal of proposals) {
|
|
167
|
+
const check = checkApprovals(rules, proposal, 0);
|
|
168
|
+
if (!check.ok && check.code !== 'approval_expired') violations.push({ type: 'proposal', proposalId: proposal.id, code: check.code });
|
|
169
|
+
}
|
|
170
|
+
let versions = 0;
|
|
171
|
+
for (const object of await store.listObjects({ organisationId, limit: 1000 })) {
|
|
172
|
+
for (const version of await store.listVersions({ organisationId, kind: object.kind, id: object.id, limit: 1000 })) {
|
|
173
|
+
versions += 1;
|
|
174
|
+
if (version.source === 'baseline') {
|
|
175
|
+
if (!['human', 'system'].includes(version.createdBy?.kind)) violations.push({ type: 'version', versionId: version.versionId, kind: object.kind, id: object.id, code: 'baseline_not_human_or_system' });
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
const proposal = byId.get(version.proposalId) ?? await store.getProposal(organisationId, version.proposalId);
|
|
179
|
+
const check = proposal ? checkApprovals(rules, proposal, 0) : { ok: false, code: 'proposal_missing' };
|
|
180
|
+
if (!proposal || proposal.status === 'declined' || proposal.status === 'rejected' || proposal.status === 'pending_approval' || (!check.ok && check.code !== 'approval_expired')) {
|
|
181
|
+
violations.push({ type: 'version', versionId: version.versionId, kind: object.kind, id: object.id, proposalId: version.proposalId ?? null, code: proposal ? (check.code ?? `status_${proposal.status}`) : 'proposal_missing' });
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return { ok: violations.length === 0, checked: { proposals: proposals.length, versions }, violations };
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
return { recordFinding, listFindings, listRejectionSignals, morningReport, verifyApprovalInvariant };
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
module.exports = { createReview, SEVERITIES, REPORT_SCHEMA };
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/*
|
|
3
|
+
* Progressive exposure of a candidate version (proposition 06). The hashing is
|
|
4
|
+
* the one of @astratra/flags (FNV-1a over `seed NUL identifier`), copied here
|
|
5
|
+
* so that this folder imports nothing: the same seed and the same identifier
|
|
6
|
+
* give the same bucket in both. A real FlagProvider can be injected instead.
|
|
7
|
+
*/
|
|
8
|
+
const { GovernorError } = require('./util');
|
|
9
|
+
|
|
10
|
+
function fnv1a32(value) {
|
|
11
|
+
let hash = 0x811c9dc5;
|
|
12
|
+
for (const byte of Buffer.from(String(value), 'utf8')) {
|
|
13
|
+
hash ^= byte;
|
|
14
|
+
hash = Math.imul(hash, 0x01000193) >>> 0;
|
|
15
|
+
}
|
|
16
|
+
return hash >>> 0;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function bucket(seed, identifier) {
|
|
20
|
+
if (identifier === undefined || identifier === null || String(identifier) === '') return null;
|
|
21
|
+
return fnv1a32(`${seed}\u0000${identifier}`) / 0x100000000;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const seedOf = (organisationId, kind, id, versionId) => `conscience:${organisationId}:${kind}:${id}:${versionId}`;
|
|
25
|
+
const flagKeyOf = (organisationId, kind, id) => `conscience.${organisationId}.${kind}.${id}`;
|
|
26
|
+
|
|
27
|
+
function normalizeExposure(input = {}, previous = null) {
|
|
28
|
+
const percentage = input.percentage === undefined ? (previous?.percentage ?? 0) : input.percentage;
|
|
29
|
+
if (typeof percentage !== 'number' || !Number.isFinite(percentage) || percentage < 0 || percentage > 100) {
|
|
30
|
+
throw new GovernorError('invalid_rollout', 'percentage must be a number from 0 to 100.');
|
|
31
|
+
}
|
|
32
|
+
const cohorts = input.cohorts === undefined ? (previous?.cohorts ?? []) : input.cohorts;
|
|
33
|
+
if (!Array.isArray(cohorts) || !cohorts.every((c) => typeof c === 'string' && c.trim())) throw new GovernorError('invalid_rollout', 'cohorts must be an array of names.');
|
|
34
|
+
return { percentage, cohorts: [...new Set(cohorts)] };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Does this caller get the candidate? Cohorts say who is eligible (when listed),
|
|
39
|
+
* the percentage says which share of the eligible. No identity and no cohort
|
|
40
|
+
* means the stable version.
|
|
41
|
+
*/
|
|
42
|
+
function servesCandidate(exposure, seed, context = {}) {
|
|
43
|
+
if (!exposure || exposure.percentage <= 0) return false;
|
|
44
|
+
const attributes = context.attributes ?? {};
|
|
45
|
+
if (exposure.cohorts.length) {
|
|
46
|
+
const own = Array.isArray(attributes.cohorts) ? attributes.cohorts : [attributes.cohort];
|
|
47
|
+
if (!own.some((name) => exposure.cohorts.includes(name))) return false;
|
|
48
|
+
}
|
|
49
|
+
if (exposure.percentage >= 100) return true;
|
|
50
|
+
const fraction = bucket(seed, context.targetingKey);
|
|
51
|
+
return fraction !== null && fraction < exposure.percentage / 100;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Rules in the shape of @astratra/flags (createMemorySource), one boolean flag per object that has a candidate. */
|
|
55
|
+
function toFlagRules(objects) {
|
|
56
|
+
const flags = {};
|
|
57
|
+
for (const object of objects) {
|
|
58
|
+
if (!object.candidate || !object.rollout) continue;
|
|
59
|
+
const flag = { type: 'boolean', default: false, value: true, rollout: object.rollout.percentage, seed: seedOf(object.organisationId, object.kind, object.id, object.candidate) };
|
|
60
|
+
if (object.rollout.cohorts.length) flag.target = { cohort: object.rollout.cohorts };
|
|
61
|
+
flags[flagKeyOf(object.organisationId, object.kind, object.id)] = flag;
|
|
62
|
+
}
|
|
63
|
+
return { flags };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
module.exports = { fnv1a32, bucket, seedOf, flagKeyOf, normalizeExposure, servesCandidate, toFlagRules };
|