@geonosis/policy 1.2.0 → 1.3.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/README.md +16 -0
- package/dist/drizzle/index.cjs +86 -0
- package/dist/drizzle/index.d.cts +43 -0
- package/dist/index.cjs +832 -0
- package/dist/index.d.cts +383 -0
- package/dist/index.d.ts +9 -1
- package/dist/index.js +22 -0
- package/dist/medusa/index.cjs +91 -0
- package/dist/medusa/index.d.cts +81 -0
- package/dist/permissions/index.cjs +124 -0
- package/dist/permissions/index.d.cts +126 -0
- package/dist/types-DzC5zTZ8.d.cts +202 -0
- package/package.json +34 -10
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
import { a as PolicyRuleRow, b as PolicyAdapter, c as PolicyKindSpec, d as PolicyRule, e as PolicyTierSpec, f as Policy, P as PolicyQuery, g as PolicyData, h as PolicyDecision, i as PolicyScope, U as UnusableRule, J as JournalObservationEntry, j as PolicyJournal, k as PolicyConfigReader, l as PolicyRuleReader, m as PolicyReading } from './types-DzC5zTZ8.cjs';
|
|
2
|
+
export { A as Awaitable, n as POLICY_FALLBACK, o as POLICY_INVALID_VALUE, p as PolicyJournalEntry, S as SchemaLike } from './types-DzC5zTZ8.cjs';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* One suite every storage adapter passes.
|
|
6
|
+
*
|
|
7
|
+
* A real Medusa module and a real drizzle table are the consumers' to run this against; what runs
|
|
8
|
+
* here is a stub, which is the point — the checks are about what an adapter must MEAN, and neither
|
|
9
|
+
* store's presence changes one of them.
|
|
10
|
+
*
|
|
11
|
+
* It answers with a report rather than an exit code: a gate that cannot say what it measured has
|
|
12
|
+
* not been shown to measure anything.
|
|
13
|
+
*/
|
|
14
|
+
type ConformanceCheck = {
|
|
15
|
+
detail?: string;
|
|
16
|
+
name: string;
|
|
17
|
+
passed: boolean;
|
|
18
|
+
};
|
|
19
|
+
type ConformanceReport = {
|
|
20
|
+
adapter: string;
|
|
21
|
+
checks: ConformanceCheck[];
|
|
22
|
+
passed: boolean;
|
|
23
|
+
};
|
|
24
|
+
type PolicyAdapterHarness = {
|
|
25
|
+
/** An adapter whose store holds exactly this, and a way to read what its journal received. */
|
|
26
|
+
create: (input: {
|
|
27
|
+
config?: Record<string, unknown>;
|
|
28
|
+
rows: readonly PolicyRuleRow[];
|
|
29
|
+
}) => {
|
|
30
|
+
adapter: PolicyAdapter;
|
|
31
|
+
written: () => readonly unknown[];
|
|
32
|
+
};
|
|
33
|
+
/** An adapter over a store that is DOWN. Swallowing belongs inside the adapter, not around it. */
|
|
34
|
+
createBroken: () => PolicyAdapter;
|
|
35
|
+
name: string;
|
|
36
|
+
};
|
|
37
|
+
declare const runPolicyAdapterConformance: (harness: PolicyAdapterHarness) => Promise<ConformanceReport>;
|
|
38
|
+
|
|
39
|
+
type PolicyInput = {
|
|
40
|
+
/** What policy may constrain. A kind with no reader is an inert knob; a reader with no kind cannot be authored. */
|
|
41
|
+
kinds: readonly (PolicyKindSpec | string)[];
|
|
42
|
+
/**
|
|
43
|
+
* May the overriding tier beat a rule that does not say either way?
|
|
44
|
+
*
|
|
45
|
+
* dielime says yes (`rule.overridable !== false`), musa says no (`&& winner.overridable`).
|
|
46
|
+
* Neither is wrong for the other's business, so it is declared rather than assumed.
|
|
47
|
+
*/
|
|
48
|
+
overridableByDefault?: boolean;
|
|
49
|
+
rules?: readonly PolicyRule[];
|
|
50
|
+
/** VAGUEST first — the weight of a key is derived from where it sits. */
|
|
51
|
+
scopeKeys?: readonly string[];
|
|
52
|
+
/** STRONGEST first. */
|
|
53
|
+
tiers: readonly (PolicyTierSpec | string)[];
|
|
54
|
+
};
|
|
55
|
+
/**
|
|
56
|
+
* Declare a policy: the authorities, the things they may constrain, the subjects they may be aimed
|
|
57
|
+
* at, and — optionally — the rules themselves.
|
|
58
|
+
*
|
|
59
|
+
* A policy with no rules is INERT. Every read falls through to the caller's own constant and says
|
|
60
|
+
* so, which is the posture the mechanism is built for: the loader is generic, the domain limits
|
|
61
|
+
* live in data, and the kernel does nothing at all until someone writes a rule.
|
|
62
|
+
*/
|
|
63
|
+
declare const definePolicy: (input: PolicyInput) => Policy;
|
|
64
|
+
/**
|
|
65
|
+
* Holds a policy's declared scope order against the scope type's own key list, both directions and
|
|
66
|
+
* in position — the checkable artefact that stops a key added alphabetically from silently
|
|
67
|
+
* reordering the lattice. Call it once in a test beside the type.
|
|
68
|
+
*/
|
|
69
|
+
declare const assertScopeOrder: (policy: {
|
|
70
|
+
scopeKeys: readonly string[];
|
|
71
|
+
}, expected: readonly string[]) => void;
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* The precedence lattice — deciding which authority wins when several speak at once.
|
|
75
|
+
*
|
|
76
|
+
* A business is governed by several at a time: law, a signed agreement, its own SOP, a buyer's
|
|
77
|
+
* stated preference, the strategy currently running, an operator override typed at 6pm on a Friday.
|
|
78
|
+
* They contradict each other constantly, so "which one wins" must not be an accident of evaluation
|
|
79
|
+
* order — it is a declared ordering, and every decision carries a TRACE naming the winner and what
|
|
80
|
+
* it suppressed.
|
|
81
|
+
*
|
|
82
|
+
* Nothing in this file names a tier, a kind or a scope key. Two consumers wrote this lattice
|
|
83
|
+
* independently and disagreed on all three (dielime's strongest tier is `regulatory`, musa's is
|
|
84
|
+
* `physics`), which is why every one of them is data.
|
|
85
|
+
*/
|
|
86
|
+
/**
|
|
87
|
+
* The weight of a scope key, derived from where it was declared.
|
|
88
|
+
*
|
|
89
|
+
* Powers of two in declaration order, so a narrower key can never be outvoted by an accumulation of
|
|
90
|
+
* vaguer ones: an order-scoped rule beats one scoped to region + category + group together, which
|
|
91
|
+
* is the intent every time someone writes an order-scoped exception. Both consumers wrote exactly
|
|
92
|
+
* that by hand and each needed a test to catch a key that had been given no weight at all — a rule
|
|
93
|
+
* that matches but always loses. Deriving it designs the failure out.
|
|
94
|
+
*/
|
|
95
|
+
declare const specificityOf: (scopeKeys: readonly string[], scope: PolicyScope | undefined) => number;
|
|
96
|
+
/**
|
|
97
|
+
* Does this rule reach this subject?
|
|
98
|
+
*
|
|
99
|
+
* A rule scoped on a key the query does not carry does NOT apply, and neither does one scoped on a
|
|
100
|
+
* key this build has never heard of. That is the safe direction — a rule cannot reach a subject we
|
|
101
|
+
* know nothing about — but refusing quietly is the same failure in a new coat, which is what
|
|
102
|
+
* `unsupportedScopesOf` is for.
|
|
103
|
+
*/
|
|
104
|
+
declare const appliesTo: (rule: PolicyRule, query: PolicyQuery, scopeKeys: readonly string[]) => boolean;
|
|
105
|
+
declare const unsupportedScopesOf: (rules: readonly PolicyRule[], scopeKeys: readonly string[]) => {
|
|
106
|
+
id: string;
|
|
107
|
+
keys: string[];
|
|
108
|
+
}[];
|
|
109
|
+
declare const unusableRulesOf: (rules: readonly PolicyRule[], data: Pick<PolicyData, "kinds" | "tiers">) => UnusableRule[];
|
|
110
|
+
declare const usableRulesOf: (rules: readonly PolicyRule[], data: Pick<PolicyData, "kinds" | "tiers">) => PolicyRule[];
|
|
111
|
+
declare const unsetKindsOf: (rules: readonly PolicyRule[], kinds: readonly PolicyKindSpec[]) => string[];
|
|
112
|
+
/**
|
|
113
|
+
* Resolve one kind for one subject, with the whole trace.
|
|
114
|
+
*
|
|
115
|
+
* `undefined` when no rule speaks — silence is a legitimate answer and the caller's own default
|
|
116
|
+
* takes over. Never a thrown error: a missing rule is the normal state of most subjects, and of
|
|
117
|
+
* every subject in a build nobody has written a policy for yet.
|
|
118
|
+
*/
|
|
119
|
+
declare const resolveConstraint: <V = unknown>(data: PolicyData, kind: string, query?: PolicyQuery, rules?: readonly PolicyRule[]) => PolicyDecision<V> | undefined;
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* The learning loop — a business improves from its own operations, visibly, versioned and
|
|
123
|
+
* reversibly.
|
|
124
|
+
*
|
|
125
|
+
* Shaped after ACE (Generator / Reflector / Curator): the playbook EVOLVES by increments rather
|
|
126
|
+
* than rewrites, which is what stops accumulated context from collapsing as it grows.
|
|
127
|
+
*
|
|
128
|
+
* observeJournal deterministic signal extraction — no model, fully testable. The strongest
|
|
129
|
+
* signals are BEHAVIOURAL: a human reversing an automated decision is unambiguous
|
|
130
|
+
* feedback in a way a survey never is.
|
|
131
|
+
* reflect folds repeats into one candidate each. An agent may propose candidates too;
|
|
132
|
+
* they enter through this same gate.
|
|
133
|
+
* curate merges by stable id, ACCUMULATING evidence instead of overwriting statements.
|
|
134
|
+
* promote evidence-gated. demote is always available and always recorded — auditable
|
|
135
|
+
* unlearning is the point.
|
|
136
|
+
*
|
|
137
|
+
* The safety rail is the lattice: an active learning becomes a rule at the ADVISORY tier, which
|
|
138
|
+
* can only ever fill silence. The loop can suggest; it can never quietly change what a business does.
|
|
139
|
+
*/
|
|
140
|
+
type LearningKind =
|
|
141
|
+
/** A working practice worth repeating. */
|
|
142
|
+
'heuristic'
|
|
143
|
+
/** A trap worth naming, so the next session starts knowing it. */
|
|
144
|
+
| 'pitfall'
|
|
145
|
+
/** Policy and the people running the business disagree, repeatedly. */
|
|
146
|
+
| 'rule-friction'
|
|
147
|
+
/** The same sequence keeps being run by hand — name it. */
|
|
148
|
+
| 'macro'
|
|
149
|
+
/** A knob that exists but nothing sets, so a hardcoded default rules instead. */
|
|
150
|
+
| 'unset-policy';
|
|
151
|
+
type LearningStatus = 'active' | 'candidate' | 'demoted';
|
|
152
|
+
type LearningEvidence = {
|
|
153
|
+
/** Ids of the journal entries that support it. */
|
|
154
|
+
journalRefs: string[];
|
|
155
|
+
/** Measured effect, when there is one. */
|
|
156
|
+
metric?: {
|
|
157
|
+
delta: number;
|
|
158
|
+
name: string;
|
|
159
|
+
};
|
|
160
|
+
observations: number;
|
|
161
|
+
updatedAt: string;
|
|
162
|
+
};
|
|
163
|
+
type Learning = {
|
|
164
|
+
demotedReason?: string;
|
|
165
|
+
evidence: LearningEvidence;
|
|
166
|
+
/** Stable key — curation merges on this, so evidence accumulates. */
|
|
167
|
+
id: string;
|
|
168
|
+
kind: LearningKind;
|
|
169
|
+
scope?: PolicyScope;
|
|
170
|
+
/** What was learned, in words a human can audit and edit. */
|
|
171
|
+
statement: string;
|
|
172
|
+
status: LearningStatus;
|
|
173
|
+
/** The advisory constraint this implies, if any. */
|
|
174
|
+
suggests?: {
|
|
175
|
+
kind: string;
|
|
176
|
+
value: unknown;
|
|
177
|
+
};
|
|
178
|
+
};
|
|
179
|
+
type Playbook = {
|
|
180
|
+
entries: Learning[];
|
|
181
|
+
version: number;
|
|
182
|
+
};
|
|
183
|
+
type Observation = {
|
|
184
|
+
id: string;
|
|
185
|
+
journalRefs: string[];
|
|
186
|
+
kind: LearningKind;
|
|
187
|
+
scope?: PolicyScope;
|
|
188
|
+
statement: string;
|
|
189
|
+
suggests?: {
|
|
190
|
+
kind: string;
|
|
191
|
+
value: unknown;
|
|
192
|
+
};
|
|
193
|
+
};
|
|
194
|
+
declare const emptyPlaybook: () => Playbook;
|
|
195
|
+
/** Repeated evidence, not one lucky quarter. */
|
|
196
|
+
declare const DEFAULT_MIN_OBSERVATIONS = 3;
|
|
197
|
+
declare class LearningError extends Error {
|
|
198
|
+
readonly code: 'INSUFFICIENT_EVIDENCE' | 'UNKNOWN_LEARNING';
|
|
199
|
+
constructor(code: 'INSUFFICIENT_EVIDENCE' | 'UNKNOWN_LEARNING', message: string);
|
|
200
|
+
}
|
|
201
|
+
type ObserveOptions = {
|
|
202
|
+
/** How few repeats of one operation are still a one-off. */
|
|
203
|
+
minRepeatsForMacro?: number;
|
|
204
|
+
/** The prefix a refusal carries, so friction is countable per rule. That word is a repo's own. */
|
|
205
|
+
refusalPrefix?: string;
|
|
206
|
+
/** What a human doing the undoing tends to call it. */
|
|
207
|
+
reversalVerbs?: RegExp;
|
|
208
|
+
};
|
|
209
|
+
/**
|
|
210
|
+
* The deterministic signals in a journal. Only behaviour that actually happened counts; nothing is
|
|
211
|
+
* inferred from intent alone.
|
|
212
|
+
*/
|
|
213
|
+
declare const observeJournal: (entries: readonly JournalObservationEntry[], options?: ObserveOptions) => Observation[];
|
|
214
|
+
/** Fold repeats into one candidate each — the statistical reflector. */
|
|
215
|
+
declare const reflect: (observations: readonly Observation[], now?: Date) => Learning[];
|
|
216
|
+
/**
|
|
217
|
+
* Merge candidates into the playbook. Evidence ACCUMULATES, and a statement is only refreshed while
|
|
218
|
+
* the entry is still under review — an active learning's wording is stable, which is what makes the
|
|
219
|
+
* playbook readable a year later.
|
|
220
|
+
*/
|
|
221
|
+
declare const curate: (playbook: Playbook, candidates: readonly Learning[]) => Playbook;
|
|
222
|
+
declare const promote: (playbook: Playbook, id: string, options?: {
|
|
223
|
+
metric?: {
|
|
224
|
+
delta: number;
|
|
225
|
+
name: string;
|
|
226
|
+
};
|
|
227
|
+
minObservations?: number;
|
|
228
|
+
}) => Playbook;
|
|
229
|
+
/** Demotion is always available and always recorded — auditable unlearning. */
|
|
230
|
+
declare const demote: (playbook: Playbook, id: string, reason: string) => Playbook;
|
|
231
|
+
/**
|
|
232
|
+
* Active learnings that imply a constraint, as rules at the tier the policy calls advisory.
|
|
233
|
+
*
|
|
234
|
+
* dielime writes `tier: 'learned'` into this function. Here the tier is read off the lattice,
|
|
235
|
+
* because a policy that declares none has nowhere safe to put a suggestion — and quietly choosing
|
|
236
|
+
* one would hand a suggestion the authority of an SOP.
|
|
237
|
+
*/
|
|
238
|
+
declare const playbookRules: (policy: Policy, playbook: Playbook) => PolicyRule[];
|
|
239
|
+
/** The playbook as agent-readable guidance — a delta on top of a built prompt, never a replacement. */
|
|
240
|
+
declare const playbookGuidance: (playbook: Playbook) => string;
|
|
241
|
+
|
|
242
|
+
/** One journal row derived from something that happened. */
|
|
243
|
+
type DomainJournalRow = {
|
|
244
|
+
actor_id: null | string;
|
|
245
|
+
actor_kind: 'system' | 'user';
|
|
246
|
+
event_name: string;
|
|
247
|
+
op: string;
|
|
248
|
+
subject: string;
|
|
249
|
+
};
|
|
250
|
+
type JournalRowOptions = {
|
|
251
|
+
/** Where this build puts the human who caused it, when there is one. */
|
|
252
|
+
actorKeys?: readonly string[];
|
|
253
|
+
/** Where this build puts the id of the thing an event is about. */
|
|
254
|
+
subjectKeys: readonly string[];
|
|
255
|
+
};
|
|
256
|
+
/**
|
|
257
|
+
* The journal row for one domain event, or `null` when there is nothing countable to say.
|
|
258
|
+
*
|
|
259
|
+
* The learning loop reads four signals: a human reversing an automated decision, repeated refusals
|
|
260
|
+
* of the same rule, readers falling back to their own defaults, and the same operation run over and
|
|
261
|
+
* over. A reader journals its own fallbacks, so the third arrives on its own — the other three are
|
|
262
|
+
* computed from things that HAPPENED, and without this they are computed over an empty table.
|
|
263
|
+
*
|
|
264
|
+
* The keys are the caller's, with no default: which field carries the id of the thing an event is
|
|
265
|
+
* about is a fact about one system, and guessing would be quietly wrong rather than loudly absent.
|
|
266
|
+
*/
|
|
267
|
+
declare const journalRowForEvent: (eventName: string, data: unknown, options: JournalRowOptions) => DomainJournalRow | null;
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* The policy as prose, generated beside the data it renders.
|
|
271
|
+
*
|
|
272
|
+
* musa checks in `policy/policy.json` and a `POLICY.md` written from it on every change, and the
|
|
273
|
+
* argument for generating rather than writing it is in that file's own history: two of its sections
|
|
274
|
+
* were prose, and both had gone stale and were telling agents the opposite of what the code did. A
|
|
275
|
+
* markdown that has to be remembered separately drifts, and a drifted one is worse than none — it
|
|
276
|
+
* reads authoritative while the engine enforces something else.
|
|
277
|
+
*
|
|
278
|
+
* So every count, every precedence sentence and every honesty report below is DERIVED.
|
|
279
|
+
*/
|
|
280
|
+
type PolicyMarkdownOptions = {
|
|
281
|
+
generator?: string;
|
|
282
|
+
playbook?: Playbook;
|
|
283
|
+
rules?: readonly PolicyRule[];
|
|
284
|
+
/** What a reader should edit instead of this file. */
|
|
285
|
+
source?: string;
|
|
286
|
+
title?: string;
|
|
287
|
+
};
|
|
288
|
+
declare const generatePolicyMarkdown: (policy: Policy, options?: PolicyMarkdownOptions) => string;
|
|
289
|
+
type DescribePolicyOptions = {
|
|
290
|
+
/** Instructions ride in EVERY context, so this stays bounded. */
|
|
291
|
+
maxRules?: number;
|
|
292
|
+
playbook?: Playbook;
|
|
293
|
+
rules?: readonly PolicyRule[];
|
|
294
|
+
};
|
|
295
|
+
/**
|
|
296
|
+
* The same policy, bounded, for the channel an agent is handed when it connects.
|
|
297
|
+
*
|
|
298
|
+
* Persisting policy is only half the job: an agent that has to discover the rules by tripping over
|
|
299
|
+
* them will trip over them in front of a customer.
|
|
300
|
+
*/
|
|
301
|
+
declare const describePolicy: (policy: Policy, options?: DescribePolicyOptions) => string;
|
|
302
|
+
|
|
303
|
+
type ReadPolicyOptions<V> = {
|
|
304
|
+
config?: PolicyConfigReader;
|
|
305
|
+
/** The caller's own constant — the floor, and the type of the answer. */
|
|
306
|
+
fallback: V;
|
|
307
|
+
journal?: PolicyJournal;
|
|
308
|
+
/** A named operation, so repeats become countable per operation rather than per request. */
|
|
309
|
+
op?: string;
|
|
310
|
+
rule?: PolicyRuleReader;
|
|
311
|
+
/** Opt out of recording. Only for a caller that runs per request inside a loop. */
|
|
312
|
+
silent?: boolean;
|
|
313
|
+
/** What the decision is about — an order id, a company id. */
|
|
314
|
+
subject?: string;
|
|
315
|
+
};
|
|
316
|
+
/**
|
|
317
|
+
* Read one constraint, with the caller's own default as the floor.
|
|
318
|
+
*
|
|
319
|
+
* This is what a reader calls instead of reaching for a hardcoded constant. It answers with the
|
|
320
|
+
* resolved value when policy speaks, the admin-set value when it does not, and the caller's own
|
|
321
|
+
* constant when nobody has said anything — and, the part that matters, it RECORDS that last case,
|
|
322
|
+
* so "nothing sets this" becomes a countable signal rather than a silence indistinguishable from
|
|
323
|
+
* working.
|
|
324
|
+
*
|
|
325
|
+
* The resolution order is authored rule → config row → constant. A rule wins because it carries an
|
|
326
|
+
* authority, a subject and a reason where a config row carries only a value; a config row beats the
|
|
327
|
+
* constant because a value an admin actually typed must beat one a developer compiled in, or the
|
|
328
|
+
* settings screen is a screen of knobs nothing reads.
|
|
329
|
+
*/
|
|
330
|
+
declare const readPolicy: <V>(policy: Policy, kind: string, query: PolicyQuery | undefined, options: ReadPolicyOptions<V>) => Promise<PolicyReading<V>>;
|
|
331
|
+
type PolicyOrDefaultInput<V> = {
|
|
332
|
+
fallback: V;
|
|
333
|
+
journal?: PolicyJournal;
|
|
334
|
+
kind: string;
|
|
335
|
+
op: string;
|
|
336
|
+
subject?: string;
|
|
337
|
+
value: V;
|
|
338
|
+
};
|
|
339
|
+
/**
|
|
340
|
+
* Apply a resolved value, falling back to the caller's own default when it turns out to be
|
|
341
|
+
* unusable.
|
|
342
|
+
*
|
|
343
|
+
* A validator that refuses a zero-day expiry or a zero-hour SLA is right to. But a number an admin
|
|
344
|
+
* mistypes would then throw inside the work it was informing, and every one of those operations
|
|
345
|
+
* would fail until somebody noticed — the customer paying for a misconfiguration. An unusable value
|
|
346
|
+
* is a gap that arrived through a different door, so it is treated like every other gap: recorded
|
|
347
|
+
* once per boot, and the default takes over while the mistake stays visible.
|
|
348
|
+
*
|
|
349
|
+
* A default that ALSO fails still throws. That is a bug in our own code rather than a
|
|
350
|
+
* misconfiguration, and swallowing it would leave the caller with no value at all.
|
|
351
|
+
*/
|
|
352
|
+
declare const policyOrDefault: <T, V>(policy: Policy, input: PolicyOrDefaultInput<V>, apply: (value: V) => T) => Promise<T>;
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* A stored row, as a rule the lattice can use.
|
|
356
|
+
*
|
|
357
|
+
* This is the one part of a storage adapter that is not the store's own vocabulary, so it lives
|
|
358
|
+
* once: two adapters that each did their own mapping would drift on what `overridable: true` means,
|
|
359
|
+
* or on whether a null scope is a scope of nothing.
|
|
360
|
+
*/
|
|
361
|
+
declare const toPolicyRule: (row: PolicyRuleRow) => PolicyRule;
|
|
362
|
+
/** The rules still in force. A retired row stays readable — it just stops deciding. */
|
|
363
|
+
declare const toPolicyRules: (rows: readonly PolicyRuleRow[]) => PolicyRule[];
|
|
364
|
+
|
|
365
|
+
/** A rule as a store hands it back: the kernel's shape, plus whether it is still in force. */
|
|
366
|
+
type ExistingPolicyRule = PolicyRule & {
|
|
367
|
+
status?: string;
|
|
368
|
+
};
|
|
369
|
+
/**
|
|
370
|
+
* Which seed rules to author, given what is already there. Idempotent by ID and by COVERAGE.
|
|
371
|
+
*
|
|
372
|
+
* The coverage half is the one that was learned the hard way: a first seeding run produced two
|
|
373
|
+
* active rules for one constraint with identical scope and value — the seed's, and one an admin had
|
|
374
|
+
* authored by hand two days earlier. Same effect, two keys, and a conflict the lattice reports and
|
|
375
|
+
* a human has to unpick.
|
|
376
|
+
*
|
|
377
|
+
* A seed provides DEFAULTS. If the business has already said something about a constraint at the
|
|
378
|
+
* same scope, it has spoken, and the seed's opinion is not wanted. A RETIRED rule is not a current
|
|
379
|
+
* opinion, so it does not block.
|
|
380
|
+
*/
|
|
381
|
+
declare const rulesToSeed: <T extends PolicyRule>(seed: readonly T[], existing: readonly ExistingPolicyRule[]) => T[];
|
|
382
|
+
|
|
383
|
+
export { type ConformanceCheck, type ConformanceReport, DEFAULT_MIN_OBSERVATIONS, type DescribePolicyOptions, type DomainJournalRow, type ExistingPolicyRule, JournalObservationEntry, type JournalRowOptions, type Learning, LearningError, type LearningEvidence, type LearningKind, type LearningStatus, type Observation, type ObserveOptions, type Playbook, Policy, PolicyAdapter, type PolicyAdapterHarness, PolicyConfigReader, PolicyData, PolicyDecision, type PolicyInput, PolicyJournal, PolicyKindSpec, type PolicyMarkdownOptions, type PolicyOrDefaultInput, PolicyQuery, PolicyReading, PolicyRule, PolicyRuleReader, PolicyRuleRow, PolicyScope, PolicyTierSpec, type ReadPolicyOptions, UnusableRule, appliesTo, assertScopeOrder, curate, definePolicy, demote, describePolicy, emptyPlaybook, generatePolicyMarkdown, journalRowForEvent, observeJournal, playbookGuidance, playbookRules, policyOrDefault, promote, readPolicy, reflect, resolveConstraint, rulesToSeed, runPolicyAdapterConformance, specificityOf, toPolicyRule, toPolicyRules, unsetKindsOf, unsupportedScopesOf, unusableRulesOf, usableRulesOf };
|
package/dist/index.d.ts
CHANGED
|
@@ -61,6 +61,14 @@ type PolicyInput = {
|
|
|
61
61
|
* live in data, and the kernel does nothing at all until someone writes a rule.
|
|
62
62
|
*/
|
|
63
63
|
declare const definePolicy: (input: PolicyInput) => Policy;
|
|
64
|
+
/**
|
|
65
|
+
* Holds a policy's declared scope order against the scope type's own key list, both directions and
|
|
66
|
+
* in position — the checkable artefact that stops a key added alphabetically from silently
|
|
67
|
+
* reordering the lattice. Call it once in a test beside the type.
|
|
68
|
+
*/
|
|
69
|
+
declare const assertScopeOrder: (policy: {
|
|
70
|
+
scopeKeys: readonly string[];
|
|
71
|
+
}, expected: readonly string[]) => void;
|
|
64
72
|
|
|
65
73
|
/**
|
|
66
74
|
* The precedence lattice — deciding which authority wins when several speak at once.
|
|
@@ -372,4 +380,4 @@ type ExistingPolicyRule = PolicyRule & {
|
|
|
372
380
|
*/
|
|
373
381
|
declare const rulesToSeed: <T extends PolicyRule>(seed: readonly T[], existing: readonly ExistingPolicyRule[]) => T[];
|
|
374
382
|
|
|
375
|
-
export { type ConformanceCheck, type ConformanceReport, DEFAULT_MIN_OBSERVATIONS, type DescribePolicyOptions, type DomainJournalRow, type ExistingPolicyRule, JournalObservationEntry, type JournalRowOptions, type Learning, LearningError, type LearningEvidence, type LearningKind, type LearningStatus, type Observation, type ObserveOptions, type Playbook, Policy, PolicyAdapter, type PolicyAdapterHarness, PolicyConfigReader, PolicyData, PolicyDecision, type PolicyInput, PolicyJournal, PolicyKindSpec, type PolicyMarkdownOptions, type PolicyOrDefaultInput, PolicyQuery, PolicyReading, PolicyRule, PolicyRuleReader, PolicyRuleRow, PolicyScope, PolicyTierSpec, type ReadPolicyOptions, UnusableRule, appliesTo, curate, definePolicy, demote, describePolicy, emptyPlaybook, generatePolicyMarkdown, journalRowForEvent, observeJournal, playbookGuidance, playbookRules, policyOrDefault, promote, readPolicy, reflect, resolveConstraint, rulesToSeed, runPolicyAdapterConformance, specificityOf, toPolicyRule, toPolicyRules, unsetKindsOf, unsupportedScopesOf, unusableRulesOf, usableRulesOf };
|
|
383
|
+
export { type ConformanceCheck, type ConformanceReport, DEFAULT_MIN_OBSERVATIONS, type DescribePolicyOptions, type DomainJournalRow, type ExistingPolicyRule, JournalObservationEntry, type JournalRowOptions, type Learning, LearningError, type LearningEvidence, type LearningKind, type LearningStatus, type Observation, type ObserveOptions, type Playbook, Policy, PolicyAdapter, type PolicyAdapterHarness, PolicyConfigReader, PolicyData, PolicyDecision, type PolicyInput, PolicyJournal, PolicyKindSpec, type PolicyMarkdownOptions, type PolicyOrDefaultInput, PolicyQuery, PolicyReading, PolicyRule, PolicyRuleReader, PolicyRuleRow, PolicyScope, PolicyTierSpec, type ReadPolicyOptions, UnusableRule, appliesTo, assertScopeOrder, curate, definePolicy, demote, describePolicy, emptyPlaybook, generatePolicyMarkdown, journalRowForEvent, observeJournal, playbookGuidance, playbookRules, policyOrDefault, promote, readPolicy, reflect, resolveConstraint, rulesToSeed, runPolicyAdapterConformance, specificityOf, toPolicyRule, toPolicyRules, unsetKindsOf, unsupportedScopesOf, unusableRulesOf, usableRulesOf };
|
package/dist/index.js
CHANGED
|
@@ -116,6 +116,11 @@ var refuseDuplicates = (values, what) => {
|
|
|
116
116
|
var definePolicy = (input) => {
|
|
117
117
|
const tiers = asTiers(input.tiers);
|
|
118
118
|
const kinds = asKinds(input.kinds);
|
|
119
|
+
if (input.scopeKeys !== void 0 && !Array.isArray(input.scopeKeys)) {
|
|
120
|
+
throw new TypeError(
|
|
121
|
+
"definePolicy: `scopeKeys` must be an ARRAY in precedence order (broadest first, narrowest last) \u2014 its order is the lattice, and a Set has none. Spell the order; `assertScopeOrder` can hold it against your scope type."
|
|
122
|
+
);
|
|
123
|
+
}
|
|
119
124
|
const scopeKeys = [...input.scopeKeys ?? []];
|
|
120
125
|
const rules = [...input.rules ?? []];
|
|
121
126
|
if (tiers.length === 0) {
|
|
@@ -173,6 +178,22 @@ var definePolicy = (input) => {
|
|
|
173
178
|
usableRules: (given = rules) => usableRulesOf(given, data)
|
|
174
179
|
};
|
|
175
180
|
};
|
|
181
|
+
var assertScopeOrder = (policy, expected) => {
|
|
182
|
+
const missing = expected.filter((key) => !policy.scopeKeys.includes(key));
|
|
183
|
+
const extra = policy.scopeKeys.filter((key) => !expected.includes(key));
|
|
184
|
+
if (missing.length > 0 || extra.length > 0) {
|
|
185
|
+
throw new Error(
|
|
186
|
+
`assertScopeOrder: the declared order and the scope type disagree \u2014 ${[...missing.map((k) => `"${k}" is in the type and not the order`), ...extra.map((k) => `"${k}" is in the order and not the type`)].join("; ")}.`
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
for (const [index, key] of expected.entries()) {
|
|
190
|
+
if (policy.scopeKeys[index] !== key) {
|
|
191
|
+
throw new Error(
|
|
192
|
+
`assertScopeOrder: position ${String(index)} holds "${policy.scopeKeys[index] ?? ""}" where the expected order holds "${key}" \u2014 the order is the lattice; if the type's order changed, change the declaration deliberately.`
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
};
|
|
176
197
|
|
|
177
198
|
// src/types.ts
|
|
178
199
|
var POLICY_FALLBACK = "policy.fallback";
|
|
@@ -752,6 +773,7 @@ export {
|
|
|
752
773
|
POLICY_FALLBACK,
|
|
753
774
|
POLICY_INVALID_VALUE,
|
|
754
775
|
appliesTo,
|
|
776
|
+
assertScopeOrder,
|
|
755
777
|
curate,
|
|
756
778
|
definePolicy,
|
|
757
779
|
demote,
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/medusa/index.ts
|
|
21
|
+
var medusa_exports = {};
|
|
22
|
+
__export(medusa_exports, {
|
|
23
|
+
configRow: () => configRow,
|
|
24
|
+
createMedusaPolicyAdapter: () => createMedusaPolicyAdapter,
|
|
25
|
+
medusaGrants: () => medusaGrants,
|
|
26
|
+
requirePermission: () => requirePermission
|
|
27
|
+
});
|
|
28
|
+
module.exports = __toCommonJS(medusa_exports);
|
|
29
|
+
|
|
30
|
+
// src/rows.ts
|
|
31
|
+
var toPolicyRule = (row) => ({
|
|
32
|
+
constraint: { kind: row.constraint_kind, value: row.constraint_value },
|
|
33
|
+
id: row.rule_key,
|
|
34
|
+
// Only `false` is worth carrying: `true` is the default a policy declares, and writing it back
|
|
35
|
+
// would make a rule that never said anything indistinguishable from one that agreed.
|
|
36
|
+
...row.overridable === false ? { overridable: false } : {},
|
|
37
|
+
reason: row.reason,
|
|
38
|
+
...row.scope ? { scope: row.scope } : {},
|
|
39
|
+
tier: row.tier
|
|
40
|
+
});
|
|
41
|
+
var toPolicyRules = (rows) => rows.filter((row) => (row.status ?? "active") === "active").map(toPolicyRule);
|
|
42
|
+
|
|
43
|
+
// src/medusa/index.ts
|
|
44
|
+
var configRow = (namespace, key) => (store) => store.get(namespace, key, void 0);
|
|
45
|
+
var defaultRow = (entry, eventPrefix) => ({
|
|
46
|
+
actor_kind: "system",
|
|
47
|
+
...entry.rejected ? { error: `rejected ${JSON.stringify(entry.rejected.value)}: ${entry.rejected.reason}` } : {},
|
|
48
|
+
event_name: `${eventPrefix}${entry.event}`,
|
|
49
|
+
fell_back_to: { constraintKind: entry.kind, value: entry.fellBackTo },
|
|
50
|
+
...entry.op ? { op: entry.op } : {},
|
|
51
|
+
...entry.subject ? { subject: entry.subject } : {}
|
|
52
|
+
});
|
|
53
|
+
var attempt = async (what) => {
|
|
54
|
+
try {
|
|
55
|
+
return await what();
|
|
56
|
+
} catch {
|
|
57
|
+
return void 0;
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
var createMedusaPolicyAdapter = (options) => {
|
|
61
|
+
const bindings = options.bindings ?? {};
|
|
62
|
+
const eventPrefix = options.eventPrefix ?? "";
|
|
63
|
+
const toRow = options.toRow ?? defaultRow;
|
|
64
|
+
const service = () => options.container.resolve(options.moduleKey);
|
|
65
|
+
const store = () => options.container.resolve(options.configStoreKey ?? "configStore");
|
|
66
|
+
return {
|
|
67
|
+
config: {
|
|
68
|
+
get: async (kind, query) => {
|
|
69
|
+
const binding = bindings[kind];
|
|
70
|
+
return binding ? attempt(() => binding(store(), query)) : void 0;
|
|
71
|
+
}
|
|
72
|
+
},
|
|
73
|
+
journal: {
|
|
74
|
+
write: async (entry) => {
|
|
75
|
+
await attempt(() => service().createPolicyJournalEntries?.(toRow(entry, eventPrefix)));
|
|
76
|
+
}
|
|
77
|
+
},
|
|
78
|
+
name: `medusa:${options.moduleKey}`,
|
|
79
|
+
rule: {
|
|
80
|
+
rules: async () => [
|
|
81
|
+
...toPolicyRules(await service().listPolicyRules?.({ status: "active" }) ?? []),
|
|
82
|
+
// Appended, never prepended: the lattice decides authority, and a list order that could
|
|
83
|
+
// stand in for it would be a second, silent one.
|
|
84
|
+
...await options.extraRules?.() ?? []
|
|
85
|
+
]
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
};
|
|
89
|
+
var medusaGrants = (roles) => Object.fromEntries(roles.map((role) => [role.id, role.policies ?? []]));
|
|
90
|
+
var passThrough = (_request, _response, next) => next();
|
|
91
|
+
var requirePermission = (wrap, ...policies) => wrap(passThrough, policies);
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { PermissionAction } from '../permissions/index.cjs';
|
|
2
|
+
import { A as Awaitable, P as PolicyQuery, d as PolicyRule, p as PolicyJournalEntry, a as PolicyRuleRow, b as PolicyAdapter } from '../types-DzC5zTZ8.cjs';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The Medusa store, behind the ports the kernel reads.
|
|
6
|
+
*
|
|
7
|
+
* Nothing here imports `@medusajs/*`. The container is a thing the runtime hands the caller, so it
|
|
8
|
+
* arrives as an argument — which is also what makes every check in the conformance suite runnable
|
|
9
|
+
* without a booted server, and what let the 219 lines of resolution logic this package extracted
|
|
10
|
+
* stop dragging a module, a service and three ORM models behind them.
|
|
11
|
+
*/
|
|
12
|
+
/** The bit of the container this needs — structural, so a plain object stands in for it. */
|
|
13
|
+
type MedusaContainerLike = {
|
|
14
|
+
resolve: (key: string) => unknown;
|
|
15
|
+
};
|
|
16
|
+
/** The bit of the module service this needs: the generated list, and the generated create. */
|
|
17
|
+
type MedusaPolicyServiceLike = {
|
|
18
|
+
createPolicyJournalEntries?: (data: Record<string, unknown>) => Awaitable<unknown>;
|
|
19
|
+
listPolicyRules?: (filter: Record<string, unknown>) => Awaitable<readonly PolicyRuleRow[]>;
|
|
20
|
+
};
|
|
21
|
+
/** The bit of a runtime-config service this needs. Its `get` answers with the fallback it is given. */
|
|
22
|
+
type ConfigStoreLike = {
|
|
23
|
+
get: <T>(namespace: string, key: string, fallback: T) => Awaitable<T>;
|
|
24
|
+
};
|
|
25
|
+
type ConfigStoreBinding = (store: ConfigStoreLike, query: PolicyQuery) => Awaitable<unknown>;
|
|
26
|
+
/**
|
|
27
|
+
* One row of the runtime config, as the value of one kind.
|
|
28
|
+
*
|
|
29
|
+
* The fallback handed to `get` is `undefined` on purpose: the service answers with whatever it is
|
|
30
|
+
* given when no row exists, so the only way to tell an unset row from a row holding that same value
|
|
31
|
+
* is to hand it something no row can legitimately hold. Junk in the row is not filtered here — the
|
|
32
|
+
* KIND's schema refuses it, once, for every layer that could produce one.
|
|
33
|
+
*/
|
|
34
|
+
declare const configRow: (namespace: string, key: string) => ConfigStoreBinding;
|
|
35
|
+
type MedusaPolicyAdapterOptions = {
|
|
36
|
+
/** Which config rows stand for which kind. A kind with no binding has no admin-set value. */
|
|
37
|
+
bindings?: Record<string, ConfigStoreBinding>;
|
|
38
|
+
configStoreKey?: string;
|
|
39
|
+
container: MedusaContainerLike;
|
|
40
|
+
/** What that store calls its own events, e.g. `rules_engine.`. */
|
|
41
|
+
eventPrefix?: string;
|
|
42
|
+
/** Rules from somewhere other than the table — a learned playbook's, appended LAST. */
|
|
43
|
+
extraRules?: () => Awaitable<readonly PolicyRule[]>;
|
|
44
|
+
moduleKey: string;
|
|
45
|
+
/** The row this store keeps. Overridden when its columns are not these. */
|
|
46
|
+
toRow?: (entry: PolicyJournalEntry, eventPrefix: string) => Record<string, unknown>;
|
|
47
|
+
};
|
|
48
|
+
declare const createMedusaPolicyAdapter: (options: MedusaPolicyAdapterOptions) => PolicyAdapter;
|
|
49
|
+
/** One role as that module holds it: an id, and the policies granted to it. */
|
|
50
|
+
type MedusaRbacRole = {
|
|
51
|
+
id: string;
|
|
52
|
+
policies?: readonly PermissionAction[];
|
|
53
|
+
};
|
|
54
|
+
/**
|
|
55
|
+
* The native RBAC module's roles, as grants the permission lattice can read.
|
|
56
|
+
*
|
|
57
|
+
* This is the whole bridge. Upstream's `hasPermission` fetches these itself through the container
|
|
58
|
+
* and a cache, which is why nothing that uses it can be answered without a booted server; the fetch
|
|
59
|
+
* is the caller's here, and the decision is a value.
|
|
60
|
+
*/
|
|
61
|
+
declare const medusaGrants: (roles: readonly MedusaRbacRole[]) => Record<string, readonly PermissionAction[]>;
|
|
62
|
+
/**
|
|
63
|
+
* The signature a middleware advertises, deliberately NOT the framework's `MiddlewareFunction`.
|
|
64
|
+
*
|
|
65
|
+
* That type carries `#private` class fields, so two copies of `@medusajs/framework` in one store
|
|
66
|
+
* make the same shape nominally incompatible and every `defineMiddlewares` call site goes red.
|
|
67
|
+
* `unknown` params are contravariant-safe: this assigns to every version's, and the runtime value
|
|
68
|
+
* is unchanged.
|
|
69
|
+
*/
|
|
70
|
+
type PortableMiddleware = (request: unknown, response: unknown, next: (error?: unknown) => void) => unknown;
|
|
71
|
+
type Wrapper = (handler: PortableMiddleware, policies: PermissionAction[]) => PortableMiddleware;
|
|
72
|
+
/**
|
|
73
|
+
* The framework's own permission check as a one-liner a route array can hold.
|
|
74
|
+
*
|
|
75
|
+
* The wrapper is passed in rather than imported, for the same reason the container is: a package
|
|
76
|
+
* that imported it would be unusable anywhere else, and would pin one of the two framework copies.
|
|
77
|
+
* The wrapped handler does nothing but continue — the wrapper itself is the gate.
|
|
78
|
+
*/
|
|
79
|
+
declare const requirePermission: (wrap: Wrapper, ...policies: PermissionAction[]) => PortableMiddleware;
|
|
80
|
+
|
|
81
|
+
export { type ConfigStoreBinding, type ConfigStoreLike, type MedusaContainerLike, type MedusaPolicyAdapterOptions, type MedusaPolicyServiceLike, type MedusaRbacRole, type PortableMiddleware, configRow, createMedusaPolicyAdapter, medusaGrants, requirePermission };
|