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