@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,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 };
@@ -0,0 +1,136 @@
1
+ 'use strict';
2
+ const { copy } = require('./util');
3
+
4
+ const proposalKey = (organisationId, id) => `${organisationId}\u0000${id}`;
5
+ const boundedLimit = (limit, fallback = 100) => Math.min(Math.max(Number(limit) || fallback, 1), 1000);
6
+
7
+ function sumsOf(entries, entry, limits) {
8
+ let cycle = 0; let agent = 0; let organisation = 0;
9
+ for (const row of entries) {
10
+ if (row.organisationId !== entry.organisationId) continue;
11
+ if (entry.cycleId != null && row.cycleId === entry.cycleId) cycle += row.cost;
12
+ if (row.at < limits.since) continue;
13
+ organisation += row.cost;
14
+ if (row.agentId === entry.agentId) agent += row.cost;
15
+ }
16
+ return { cycle, agent, organisation };
17
+ }
18
+
19
+ const objectKey = (organisationId, kind, id) => `${organisationId}\u0000${kind}\u0000${id}`;
20
+ const approvalCount = (record) => (Array.isArray(record.approvals) ? record.approvals.length : 0);
21
+ const decidedOrCreated = (record) => record.decidedAt ?? record.createdAt;
22
+
23
+ /**
24
+ * Governor store kept in memory: proposals, audit journal, spending, controls.
25
+ * Copies on every read and write; lost when the process exits.
26
+ */
27
+ function createMemoryGovernorStore() {
28
+ const proposals = new Map();
29
+ const audit = [];
30
+ const spend = new Map();
31
+ const controls = new Map();
32
+ const objects = new Map();
33
+ const versions = new Map();
34
+ const findings = new Map();
35
+ return {
36
+ async putProposal(record) {
37
+ const key = proposalKey(record.organisationId, record.id);
38
+ const old = proposals.get(key);
39
+ if (old) return { record: copy(old), created: false };
40
+ proposals.set(key, copy(record));
41
+ return { record: copy(record), created: true };
42
+ },
43
+ async getProposal(organisationId, id) { return copy(proposals.get(proposalKey(organisationId, id))); },
44
+ async transitionProposal(organisationId, id, fromStatus, patch, guard) {
45
+ const key = proposalKey(organisationId, id);
46
+ const old = proposals.get(key);
47
+ if (!old || old.status !== fromStatus) return null;
48
+ if (guard?.approvals !== undefined && approvalCount(old) !== guard.approvals) return null;
49
+ const next = { ...old, ...copy(patch) };
50
+ proposals.set(key, next);
51
+ return copy(next);
52
+ },
53
+ async listProposals(filter = {}) {
54
+ return [...proposals.values()]
55
+ .filter((p) => p.organisationId === filter.organisationId && (filter.status == null || p.status === filter.status)
56
+ && (filter.statuses == null || filter.statuses.includes(p.status))
57
+ && (filter.since == null || decidedOrCreated(p) >= filter.since))
58
+ .sort((a, b) => (a.createdAt < b.createdAt ? 1 : a.createdAt > b.createdAt ? -1 : 0))
59
+ .slice(0, boundedLimit(filter.limit)).map(copy);
60
+ },
61
+ async appendAudit(entry) { audit.push(copy(entry)); return copy(entry); },
62
+ async listAudit(filter = {}) {
63
+ return audit
64
+ .filter((e) => (filter.organisationId === undefined || e.organisationId === filter.organisationId)
65
+ && (filter.proposalId == null || e.proposalId === filter.proposalId)
66
+ && (filter.actions == null || filter.actions.includes(e.action))
67
+ && (filter.since == null || e.at >= filter.since)
68
+ && (filter.objectKind == null || e.objectKind === filter.objectKind)
69
+ && (filter.objectId == null || e.objectId === filter.objectId))
70
+ .slice(-boundedLimit(filter.limit)).reverse().map(copy);
71
+ },
72
+ async reserveSpend(entry, limits) {
73
+ const key = proposalKey(entry.organisationId, entry.id);
74
+ const entries = [...spend.values()];
75
+ if (spend.has(key)) return { reserved: true, created: false, totals: sumsOf(entries, entry, limits) };
76
+ const totals = sumsOf(entries, entry, limits);
77
+ const fits = (entry.cycleId == null || totals.cycle + entry.cost <= limits.perCycle)
78
+ && totals.agent + entry.cost <= limits.perAgent
79
+ && totals.organisation + entry.cost <= limits.perOrganisation;
80
+ if (!fits) return { reserved: false, created: false, totals };
81
+ spend.set(key, copy(entry));
82
+ return { reserved: true, created: true, totals: sumsOf([...spend.values()], entry, limits) };
83
+ },
84
+ async getControl(key) { return controls.has(key) ? copy(controls.get(key)) : null; },
85
+ async setControl(key, value) { controls.set(key, copy(value)); return copy(value); },
86
+
87
+ async getObject(organisationId, kind, id) { return copy(objects.get(objectKey(organisationId, kind, id))); },
88
+ async createObject(state) {
89
+ const key = objectKey(state.organisationId, state.kind, state.id);
90
+ if (objects.has(key)) return { record: copy(objects.get(key)), created: false };
91
+ objects.set(key, copy(state));
92
+ return { record: copy(state), created: true };
93
+ },
94
+ async updateObject(organisationId, kind, id, expectedRevision, next) {
95
+ const key = objectKey(organisationId, kind, id);
96
+ const old = objects.get(key);
97
+ if (!old || old.revision !== expectedRevision) return null;
98
+ objects.set(key, copy(next));
99
+ return copy(next);
100
+ },
101
+ async listObjects(filter = {}) {
102
+ return [...objects.values()]
103
+ .filter((o) => (filter.organisationId == null || o.organisationId === filter.organisationId)
104
+ && (filter.kind == null || o.kind === filter.kind) && (!filter.hasCandidate || o.candidate != null))
105
+ .sort((a, b) => (objectKey(a.organisationId, a.kind, a.id) < objectKey(b.organisationId, b.kind, b.id) ? -1 : 1))
106
+ .slice(0, boundedLimit(filter.limit)).map(copy);
107
+ },
108
+ async putVersion(record) {
109
+ const key = `${objectKey(record.organisationId, record.kind, record.id)}\u0000${record.versionId}`;
110
+ if (versions.has(key)) return { record: copy(versions.get(key)), created: false };
111
+ versions.set(key, copy(record));
112
+ return { record: copy(record), created: true };
113
+ },
114
+ async getVersion(organisationId, kind, id, versionId) { return copy(versions.get(`${objectKey(organisationId, kind, id)}\u0000${versionId}`)); },
115
+ async listVersions(filter) {
116
+ return [...versions.values()]
117
+ .filter((v) => v.organisationId === filter.organisationId && v.kind === filter.kind && v.id === filter.id)
118
+ .sort((a, b) => a.number - b.number).slice(0, boundedLimit(filter.limit, 1000)).map(copy);
119
+ },
120
+
121
+ async putFinding(record) {
122
+ const key = proposalKey(record.organisationId, record.id);
123
+ if (findings.has(key)) return { record: copy(findings.get(key)), created: false };
124
+ findings.set(key, copy(record));
125
+ return { record: copy(record), created: true };
126
+ },
127
+ async listFindings(filter = {}) {
128
+ return [...findings.values()]
129
+ .filter((f) => f.organisationId === filter.organisationId && (filter.since == null || f.receivedAt >= filter.since) && (filter.until == null || f.receivedAt <= filter.until))
130
+ .sort((a, b) => (a.receivedAt < b.receivedAt ? 1 : a.receivedAt > b.receivedAt ? -1 : a.id < b.id ? -1 : 1))
131
+ .slice(0, boundedLimit(filter.limit)).map(copy);
132
+ }
133
+ };
134
+ }
135
+
136
+ module.exports = { createMemoryGovernorStore, boundedLimit };
@@ -0,0 +1,53 @@
1
+ 'use strict';
2
+ /*
3
+ * Plain helpers of the governor. This folder imports Node built-ins and its own
4
+ * files only: no language model, no AI package, nothing that could make a
5
+ * governance decision depend on generated text. A test walks the import graph.
6
+ */
7
+ const crypto = require('node:crypto');
8
+
9
+ class GovernorError extends Error {
10
+ constructor(code, message) {
11
+ super(message);
12
+ this.name = 'GovernorError';
13
+ this.code = code;
14
+ }
15
+ }
16
+
17
+ /** JSON with sorted keys, so equal values always give the same text. */
18
+ function canonical(value) {
19
+ if (value === undefined) return 'null';
20
+ if (value === null || typeof value !== 'object') return JSON.stringify(value);
21
+ if (value instanceof Date) return JSON.stringify(value.toISOString());
22
+ if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
23
+ const keys = Object.keys(value).filter((key) => value[key] !== undefined).sort();
24
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(',')}}`;
25
+ }
26
+
27
+ const sha256 = (text) => crypto.createHash('sha256').update(text).digest('hex');
28
+ const fingerprintOf = (value) => sha256(canonical(value));
29
+ const copy = (value) => (value == null ? null : JSON.parse(JSON.stringify(value)));
30
+
31
+ function deepFreeze(value) {
32
+ if (value && typeof value === 'object' && !Object.isFrozen(value)) {
33
+ Object.freeze(value);
34
+ for (const child of Object.values(value)) deepFreeze(child);
35
+ }
36
+ return value;
37
+ }
38
+
39
+ const isNonEmptyString = (value) => typeof value === 'string' && value.trim().length > 0;
40
+ const SQL_IDENTIFIER = /^[a-zA-Z_][a-zA-Z0-9_]{0,40}$/;
41
+
42
+ function prefixOf(options = {}, fallback) {
43
+ const name = options.prefix ?? fallback;
44
+ if (typeof name !== 'string' || !SQL_IDENTIFIER.test(name)) throw new Error('prefix must be a plain SQL identifier of at most 41 characters.');
45
+ return name;
46
+ }
47
+
48
+ function requireQueryable(db) {
49
+ if (!db || typeof db.query !== 'function') throw new Error('A database with query(sql, params) is required.');
50
+ return db;
51
+ }
52
+
53
+ module.exports = { GovernorError, canonical, sha256, fingerprintOf, copy, deepFreeze, isNonEmptyString, prefixOf, requireQueryable };
package/src/guard.js ADDED
@@ -0,0 +1,21 @@
1
+ 'use strict';
2
+ /*
3
+ * Memory guard (34). Everything this package stores (context, observations,
4
+ * lessons, corrections) is untrusted data: it may have been written by a
5
+ * person, a tool or a model that was itself manipulated. Nothing here ever
6
+ * reads stored text as an instruction, and the helpers below frame it before
7
+ * a future model reads it, with the framing of @astratra/ai/guards.
8
+ */
9
+ const { frameUntrusted } = require('@astratra/ai/guards');
10
+
11
+ /** Frames one stored text as data for a model. */
12
+ function frameStoredText(text, { source = 'conscience-memory', nonce } = {}) {
13
+ return frameUntrusted(String(text ?? ''), { source, nonce });
14
+ }
15
+
16
+ /** Frames records (decisions, outcomes, lessons...) as one JSON block of data. */
17
+ function frameRecordsForModel(records, { source = 'conscience-memory', nonce } = {}) {
18
+ return frameUntrusted(JSON.stringify(records ?? [], null, 2), { source, nonce });
19
+ }
20
+
21
+ module.exports = { frameStoredText, frameRecordsForModel };