@geonosis/policy 2.12.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/conformance.cjs +169 -0
  3. package/dist/conformance.d.cts +35 -0
  4. package/dist/conformance.d.ts +35 -0
  5. package/dist/conformance.js +129 -0
  6. package/dist/define.cjs +118 -0
  7. package/dist/define.d.cts +34 -0
  8. package/dist/define.d.ts +34 -0
  9. package/dist/define.js +85 -0
  10. package/dist/drizzle/index.cjs +37 -32
  11. package/dist/drizzle/index.d.cts +20 -23
  12. package/dist/drizzle/index.d.ts +20 -23
  13. package/dist/drizzle/index.js +2 -5
  14. package/dist/index.cjs +79 -856
  15. package/dist/index.d.cts +19 -428
  16. package/dist/index.d.ts +19 -428
  17. package/dist/index.js +35 -797
  18. package/dist/journal-events.cjs +68 -0
  19. package/dist/journal-events.d.cts +26 -0
  20. package/dist/journal-events.d.ts +26 -0
  21. package/dist/journal-events.js +28 -0
  22. package/dist/lattice.cjs +150 -0
  23. package/dist/lattice.d.cts +48 -0
  24. package/dist/lattice.d.ts +48 -0
  25. package/dist/lattice.js +110 -0
  26. package/dist/learning.cjs +246 -0
  27. package/dist/learning.d.cts +121 -0
  28. package/dist/learning.d.ts +121 -0
  29. package/dist/learning.js +206 -0
  30. package/dist/markdown.cjs +118 -0
  31. package/dist/markdown.d.cts +35 -0
  32. package/dist/markdown.d.ts +35 -0
  33. package/dist/markdown.js +78 -0
  34. package/dist/medusa/index.cjs +39 -36
  35. package/dist/medusa/index.d.cts +14 -16
  36. package/dist/medusa/index.d.ts +14 -16
  37. package/dist/medusa/index.js +4 -9
  38. package/dist/permissions/index.cjs +49 -40
  39. package/dist/permissions/index.d.cts +18 -20
  40. package/dist/permissions/index.d.ts +18 -20
  41. package/dist/permissions/index.js +15 -25
  42. package/dist/read.cjs +111 -0
  43. package/dist/read.d.cts +51 -0
  44. package/dist/read.d.ts +51 -0
  45. package/dist/read.js +71 -0
  46. package/dist/rows.cjs +54 -0
  47. package/dist/rows.d.cts +11 -0
  48. package/dist/rows.d.ts +11 -0
  49. package/dist/{chunk-JICJ4XEX.js → rows.js} +0 -3
  50. package/dist/seed.cjs +53 -0
  51. package/dist/seed.d.cts +18 -0
  52. package/dist/seed.d.ts +18 -0
  53. package/dist/seed.js +13 -0
  54. package/dist/threshold.cjs +73 -0
  55. package/dist/threshold.d.cts +45 -0
  56. package/dist/threshold.d.ts +45 -0
  57. package/dist/threshold.js +33 -0
  58. package/dist/types.cjs +47 -0
  59. package/dist/{types-C-Q3r-In.d.cts → types.d.cts} +21 -23
  60. package/dist/{types-C-Q3r-In.d.ts → types.d.ts} +21 -23
  61. package/dist/types.js +7 -0
  62. package/package.json +3 -3
package/dist/index.cjs CHANGED
@@ -1,865 +1,88 @@
1
- "use strict";
2
1
  var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
2
  var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
4
  var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ function __accessProp(key) {
6
+ return this[key];
7
+ }
8
+ var __toCommonJS = (from) => {
9
+ var entry = (__moduleCache ??= new WeakMap).get(from), desc;
10
+ if (entry)
11
+ return entry;
12
+ entry = __defProp({}, "__esModule", { value: true });
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (var key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(entry, key))
16
+ __defProp(entry, key, {
17
+ get: __accessProp.bind(from, key),
18
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
19
+ });
20
+ }
21
+ __moduleCache.set(from, entry);
22
+ return entry;
23
+ };
24
+ var __moduleCache;
25
+ var __returnValue = (v) => v;
26
+ function __exportSetter(name, newValue) {
27
+ this[name] = __returnValue.bind(null, newValue);
28
+ }
6
29
  var __export = (target, all) => {
7
30
  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/index.ts
21
- var index_exports = {};
22
- __export(index_exports, {
23
- DEFAULT_MIN_OBSERVATIONS: () => DEFAULT_MIN_OBSERVATIONS,
24
- LearningError: () => LearningError,
25
- POLICY_FALLBACK: () => POLICY_FALLBACK,
26
- POLICY_INVALID_VALUE: () => POLICY_INVALID_VALUE,
27
- appliesTo: () => appliesTo,
28
- assertScopeOrder: () => assertScopeOrder,
29
- curate: () => curate,
30
- declareThreshold: () => declareThreshold,
31
- definePolicy: () => definePolicy,
32
- demote: () => demote,
33
- describePolicy: () => describePolicy,
34
- describeThreshold: () => describeThreshold,
35
- emptyPlaybook: () => emptyPlaybook,
36
- expiredThresholds: () => expiredThresholds,
37
- generatePolicyMarkdown: () => generatePolicyMarkdown,
38
- isThreshold: () => isThreshold,
39
- journalRowForEvent: () => journalRowForEvent,
40
- observeJournal: () => observeJournal,
41
- playbookGuidance: () => playbookGuidance,
42
- playbookRules: () => playbookRules,
43
- policyOrDefault: () => policyOrDefault,
44
- promote: () => promote,
45
- readPolicy: () => readPolicy,
46
- reflect: () => reflect,
47
- resolveConstraint: () => resolveConstraint,
48
- rulesToSeed: () => rulesToSeed,
49
- runPolicyAdapterConformance: () => runPolicyAdapterConformance,
50
- specificityOf: () => specificityOf,
51
- toPolicyRule: () => toPolicyRule,
52
- toPolicyRules: () => toPolicyRules,
53
- unsetKindsOf: () => unsetKindsOf,
54
- unsupportedScopesOf: () => unsupportedScopesOf,
55
- unusableRulesOf: () => unusableRulesOf,
56
- usableRulesOf: () => usableRulesOf
57
- });
58
- module.exports = __toCommonJS(index_exports);
59
-
60
- // src/lattice.ts
61
- var specificityOf = (scopeKeys, scope) => {
62
- if (!scope) return 0;
63
- let score = 0;
64
- for (const [index, key] of scopeKeys.entries()) {
65
- if (scope[key] !== void 0) score += 2 ** index;
66
- }
67
- return score;
68
- };
69
- var appliesTo = (rule, query, scopeKeys) => {
70
- if (!rule.scope) return true;
71
- for (const [key, want] of Object.entries(rule.scope)) {
72
- if (want === void 0) continue;
73
- if (!scopeKeys.includes(key)) return false;
74
- if (query[key] !== want) return false;
75
- }
76
- return true;
77
- };
78
- var unsupportedScopesOf = (rules, scopeKeys) => {
79
- const out = [];
80
- for (const rule of rules) {
81
- const scope = rule.scope;
82
- if (!scope) continue;
83
- const keys = Object.keys(scope).filter(
84
- (key) => scope[key] !== void 0 && !scopeKeys.includes(key)
85
- );
86
- if (keys.length > 0) out.push({ id: rule.id, keys });
87
- }
88
- return out;
89
- };
90
- var unusableBecause = (rule, data) => {
91
- if (!data.tiers.some((tier) => tier.name === rule.tier)) return `unknown tier "${rule.tier}"`;
92
- const kind = data.kinds.find((spec) => spec.kind === rule.constraint.kind);
93
- if (!kind) return `unknown kind "${rule.constraint.kind}"`;
94
- if (kind.schema && !kind.schema.safeParse(rule.constraint.value).success) {
95
- return `value ${JSON.stringify(rule.constraint.value)} is not a ${kind.kind}`;
96
- }
97
- return void 0;
98
- };
99
- var unusableRulesOf = (rules, data) => rules.flatMap((rule) => {
100
- const reason2 = unusableBecause(rule, data);
101
- return reason2 ? [{ id: rule.id, reason: reason2 }] : [];
102
- });
103
- var usableRulesOf = (rules, data) => rules.filter((rule) => unusableBecause(rule, data) === void 0);
104
- var unsetKindsOf = (rules, kinds) => {
105
- const set = new Set(rules.map((rule) => rule.constraint.kind));
106
- return kinds.map((kind) => kind.kind).filter((kind) => !set.has(kind));
107
- };
108
- var sameValue = (kind, a, b) => kind?.sameValue ? kind.sameValue(a, b) : JSON.stringify(a) === JSON.stringify(b);
109
- var explainDecision = (winner, overrode, conflicts) => {
110
- const parts = [`${winner.id} (${winner.tier}) \u2014 ${winner.reason}`];
111
- if (overrode) parts.push(`overrides ${overrode.id} (${overrode.tier}, overridable)`);
112
- if (conflicts.length > 0) {
113
- parts.push(
114
- `CONFLICT with equal authority: ${conflicts.map((rule) => rule.id).join(", ")} \u2014 resolve in policy, not in code`
115
- );
116
- }
117
- return parts.join("; ");
118
- };
119
- var resolveConstraint = (data, kind, query = {}, rules = data.rules) => {
120
- const rank = (tier) => data.tiers.findIndex((spec) => spec.name === tier);
121
- const specificity = (scope) => specificityOf(data.scopeKeys, scope);
122
- const pool = usableRulesOf(rules, data).filter(
123
- (rule) => rule.constraint.kind === kind && appliesTo(rule, query, data.scopeKeys)
124
- );
125
- if (pool.length === 0) return void 0;
126
- const sorted = pool.map((rule, index) => ({ index, rule })).toSorted((a, b) => {
127
- const byTier = rank(a.rule.tier) - rank(b.rule.tier);
128
- if (byTier !== 0) return byTier;
129
- const bySpecificity = specificity(b.rule.scope) - specificity(a.rule.scope);
130
- return bySpecificity === 0 ? a.index - b.index : bySpecificity;
131
- }).map((entry) => entry.rule);
132
- const strongest = sorted[0];
133
- if (!strongest) return void 0;
134
- const tierOf = (rule) => data.tiers.find((spec) => spec.name === rule.tier);
135
- const mayBeOverridden = (rule) => tierOf(rule)?.overridable === true && (rule.overridable ?? data.overridableByDefault);
136
- const overrideTier = data.tiers.find((tier) => tier.overrides)?.name;
137
- const override = overrideTier ? sorted.find((rule) => rule.tier === overrideTier) : void 0;
138
- const overrode = override && override !== strongest && mayBeOverridden(strongest) ? strongest : void 0;
139
- const winner = overrode ? override : strongest;
140
- const suppressed = sorted.filter((rule) => rule !== winner);
141
- const kindSpec = data.kinds.find((spec) => spec.kind === kind);
142
- const conflicts = suppressed.filter(
143
- (rule) => rank(rule.tier) === rank(winner.tier) && specificity(rule.scope) === specificity(winner.scope) && !sameValue(kindSpec, rule.constraint.value, winner.constraint.value)
144
- );
145
- return {
146
- conflicts,
147
- explain: explainDecision(winner, overrode, conflicts),
148
- kind,
149
- ...overrode ? { overrode } : {},
150
- suppressed,
151
- value: winner.constraint.value,
152
- winner
153
- };
154
- };
155
-
156
- // src/define.ts
157
- var asTiers = (values) => values.map((value) => typeof value === "string" ? { name: value } : value);
158
- var asKinds = (values) => values.map((value) => typeof value === "string" ? { kind: value } : value);
159
- var refuseDuplicates = (values, what) => {
160
- const seen = /* @__PURE__ */ new Set();
161
- for (const value of values) {
162
- if (seen.has(value)) {
163
- throw new TypeError(
164
- `definePolicy: ${what} "${value}" is declared twice. Which one a rule means would then depend on which was found first.`
165
- );
166
- }
167
- seen.add(value);
168
- }
169
- };
170
- var definePolicy = (input) => {
171
- const tiers = asTiers(input.tiers);
172
- const kinds = asKinds(input.kinds);
173
- if (input.scopeKeys !== void 0 && !Array.isArray(input.scopeKeys)) {
174
- throw new TypeError(
175
- "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."
176
- );
177
- }
178
- const scopeKeys = [...input.scopeKeys ?? []];
179
- const rules = [...input.rules ?? []];
180
- if (tiers.length === 0) {
181
- throw new TypeError(
182
- "definePolicy: `tiers` is empty. A lattice with no authorities could never decide anything, and every rule written against it would name a tier it does not have."
183
- );
184
- }
185
- refuseDuplicates(
186
- tiers.map((tier) => tier.name),
187
- "tier"
188
- );
189
- refuseDuplicates(
190
- kinds.map((kind) => kind.kind),
191
- "kind"
192
- );
193
- refuseDuplicates(scopeKeys, "scope key");
194
- const overriding = tiers.filter((tier) => tier.overrides);
195
- if (overriding.length > 1) {
196
- throw new TypeError(
197
- `definePolicy: ${overriding.map((tier) => `"${tier.name}"`).join(
198
- " and "
199
- )} both declare \`overrides\`. The audited escape hatch is one tier or none \u2014 two of them race for the same rule.`
200
- );
201
- }
202
- const lastAuthority = tiers.findLastIndex((tier) => !tier.advisory);
203
- const firstAdvisory = tiers.findIndex((tier) => tier.advisory);
204
- if (firstAdvisory !== -1 && firstAdvisory < lastAuthority) {
205
- throw new TypeError(
206
- `definePolicy: advisory tier "${tiers[firstAdvisory]?.name}" is declared stronger than "${tiers[lastAuthority]?.name}". An advisory tier fills silence; one that outranks an authority is not advisory, it is an authority with a reassuring name.`
207
- );
208
- }
209
- const data = {
210
- kinds,
211
- overridableByDefault: input.overridableByDefault ?? true,
212
- rules,
213
- scopeKeys,
214
- tiers
215
- };
216
- const journalledOnce = /* @__PURE__ */ new Set();
217
- return {
218
- ...data,
219
- journalledOnce,
220
- kindOf: (kind) => kinds.find((spec) => spec.kind === kind),
221
- rank: (tier) => {
222
- const index = tiers.findIndex((spec) => spec.name === tier);
223
- return index === -1 ? void 0 : index;
224
- },
225
- resetJournal: () => journalledOnce.clear(),
226
- resolve: (kind, query, given) => resolveConstraint(data, kind, query, given),
227
- specificity: (scope) => specificityOf(scopeKeys, scope),
228
- tierOf: (tier) => tiers.find((spec) => spec.name === tier),
229
- unsetKinds: (given = rules) => unsetKindsOf(given, kinds),
230
- unsupportedScopes: (given = rules) => unsupportedScopesOf(given, scopeKeys),
231
- unusableRules: (given = rules) => unusableRulesOf(given, data),
232
- usableRules: (given = rules) => usableRulesOf(given, data)
233
- };
234
- };
235
- var assertScopeOrder = (policy, expected) => {
236
- const missing = expected.filter((key) => !policy.scopeKeys.includes(key));
237
- const extra = policy.scopeKeys.filter((key) => !expected.includes(key));
238
- if (missing.length > 0 || extra.length > 0) {
239
- throw new Error(
240
- `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("; ")}.`
241
- );
242
- }
243
- for (const [index, key] of expected.entries()) {
244
- if (policy.scopeKeys[index] !== key) {
245
- throw new Error(
246
- `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.`
247
- );
248
- }
249
- }
250
- };
251
-
252
- // src/types.ts
253
- var POLICY_FALLBACK = "policy.fallback";
254
- var POLICY_INVALID_VALUE = "policy.invalid_value";
255
-
256
- // src/read.ts
257
- var attempt = async (what) => {
258
- try {
259
- return await what();
260
- } catch {
261
- return void 0;
262
- }
263
- };
264
- var accepts = (policy, kind, value) => {
265
- const schema = policy.kindOf(kind)?.schema;
266
- return schema ? schema.safeParse(value).success : true;
267
- };
268
- var record = async (policy, journal, entry) => {
269
- const key = `${entry.event}::${entry.kind}::${entry.op ?? ""}`;
270
- if (policy.journalledOnce.has(key)) return;
271
- policy.journalledOnce.add(key);
272
- await attempt(() => journal?.write(entry));
273
- };
274
- var readPolicy = async (policy, kind, query = {}, options) => {
275
- const rules = options.rule ? await attempt(() => options.rule?.rules(kind, query)) ?? [] : policy.rules;
276
- const decision = policy.resolve(kind, query, rules);
277
- if (decision) {
278
- const spec = policy.kindOf(kind);
279
- if (spec?.isReference?.(decision.value)) {
280
- const referenced = await attempt(
281
- () => spec.dereference?.(decision.value, { config: options.config, query })
282
- );
283
- if (referenced !== void 0) {
284
- return { decision, source: "rule", usedFallback: false, value: referenced };
285
- }
286
- } else {
287
- return { decision, source: "rule", usedFallback: false, value: decision.value };
288
- }
289
- }
290
- const configured = await attempt(() => options.config?.get(kind, query));
291
- if (configured !== void 0 && accepts(policy, kind, configured)) {
292
- return { source: "config", usedFallback: false, value: configured };
293
- }
294
- if (!options.silent) {
295
- await record(policy, options.journal, {
296
- event: POLICY_FALLBACK,
297
- fellBackTo: options.fallback,
298
- kind,
299
- ...options.op ? { op: options.op } : {},
300
- ...options.subject ? { subject: options.subject } : {}
301
- });
302
- }
303
- return { source: "fallback", usedFallback: true, value: options.fallback };
304
- };
305
- var policyOrDefault = async (policy, input, apply) => {
306
- try {
307
- return apply(input.value);
308
- } catch (error) {
309
- await record(policy, input.journal, {
310
- event: POLICY_INVALID_VALUE,
311
- fellBackTo: input.fallback,
312
- kind: input.kind,
313
- op: input.op,
314
- rejected: {
315
- reason: error instanceof Error ? error.message : String(error),
316
- value: input.value
317
- },
318
- ...input.subject ? { subject: input.subject } : {}
31
+ __defProp(target, name, {
32
+ get: all[name],
33
+ enumerable: true,
34
+ configurable: true,
35
+ set: __exportSetter.bind(all, name)
319
36
  });
320
- return apply(input.fallback);
321
- }
322
37
  };
323
38
 
324
- // src/conformance.ts
325
- var probePolicy = () => definePolicy({
326
- kinds: ["quoteExpiryDays", "containerCutoff", "aiCostCapUsd", "unread"],
327
- scopeKeys: ["companyId"],
328
- tiers: ["contract", { name: "tenant", overridable: true }]
329
- });
330
- var reason = "the reason a person blocked by this rule would read";
331
- var ROWS = [
332
- {
333
- constraint_kind: "quoteExpiryDays",
334
- constraint_value: 30,
335
- reason,
336
- rule_key: "expiry-30",
337
- tier: "tenant"
338
- },
339
- {
340
- constraint_kind: "quoteExpiryDays",
341
- constraint_value: 60,
342
- reason,
343
- rule_key: "expiry-60-acme",
344
- scope: { companyId: "comp_acme" },
345
- tier: "tenant"
346
- },
347
- {
348
- constraint_kind: "containerCutoff",
349
- constraint_value: { dayOfWeek: 5, hourUtc: 18 },
350
- reason,
351
- rule_key: "cutoff-friday",
352
- tier: "tenant"
353
- },
354
- {
355
- constraint_kind: "aiCostCapUsd",
356
- constraint_value: 0.5,
357
- overridable: false,
358
- reason,
359
- rule_key: "cost-cap",
360
- tier: "tenant"
361
- },
362
- {
363
- constraint_kind: "quoteExpiryDays",
364
- constraint_value: 1,
365
- reason,
366
- rule_key: "expiry-retired",
367
- status: "retired",
368
- tier: "contract"
369
- }
370
- ];
371
- var check = async (name, assertion) => {
372
- try {
373
- await assertion();
374
- return { name, passed: true };
375
- } catch (error) {
376
- return { detail: error instanceof Error ? error.message : String(error), name, passed: false };
377
- }
378
- };
379
- var must = (condition, detail) => {
380
- if (!condition) throw new Error(detail);
381
- };
382
- var same = (actual, expected, what) => must(
383
- JSON.stringify(actual) === JSON.stringify(expected),
384
- `${what}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`
385
- );
386
- var runPolicyAdapterConformance = async (harness) => {
387
- const over = (config) => harness.create({ config, rows: ROWS });
388
- const checks = [
389
- await check("reads a stored rule back as one the lattice can use", async () => {
390
- const rules = await over().adapter.rule.rules("quoteExpiryDays", {});
391
- const found = rules.find((rule) => rule.id === "expiry-30");
392
- must(found !== void 0, "no rule came back under the key it was stored with");
393
- same(found?.constraint, { kind: "quoteExpiryDays", value: 30 }, "the constraint");
394
- same(found?.tier, "tenant", "the authority");
395
- same(found?.reason, reason, "the reason");
396
- }),
397
- await check("leaves a retired row out, because it is not a current opinion", async () => {
398
- const rules = await over().adapter.rule.rules("quoteExpiryDays", {});
399
- must(
400
- !rules.some((rule) => rule.id === "expiry-retired"),
401
- "a retired rule came back and would have decided"
402
- );
403
- }),
404
- await check("keeps the scope, so a rule reaches only the subject it was aimed at", async () => {
405
- const { adapter } = over();
406
- const policy = probePolicy();
407
- const rules = await adapter.rule.rules("quoteExpiryDays", {});
408
- same(
409
- policy.resolve("quoteExpiryDays", { companyId: "comp_acme" }, rules)?.value,
410
- 60,
411
- "the scoped rule"
412
- );
413
- same(
414
- policy.resolve("quoteExpiryDays", { companyId: "comp_other" }, rules)?.value,
415
- 30,
416
- "the general rule"
417
- );
418
- }),
419
- await check("carries a structured value through the store unchanged", async () => {
420
- const rules = await over().adapter.rule.rules("containerCutoff", {});
421
- same(
422
- rules.find((rule) => rule.id === "cutoff-friday")?.constraint.value,
423
- { dayOfWeek: 5, hourUtc: 18 },
424
- "the schedule"
425
- );
426
- }),
427
- await check("keeps a row that refuses to be overridden", async () => {
428
- const rules = await over().adapter.rule.rules("aiCostCapUsd", {});
429
- same(rules.find((rule) => rule.id === "cost-cap")?.overridable, false, "the override flag");
430
- }),
431
- await check("answers nothing for a kind the store holds no value for", async () => {
432
- const value = await over().adapter.config?.get("unread", {});
433
- must(value === void 0, `an unset kind answered with ${JSON.stringify(value)}`);
434
- }),
435
- await check("reads an admin-set value when no rule speaks", async () => {
436
- const { adapter } = over({ unread: 7 });
437
- const reading = await readPolicy(
438
- probePolicy(),
439
- "unread",
440
- {},
441
- {
442
- config: adapter.config,
443
- fallback: 1,
444
- rule: adapter.rule
445
- }
446
- );
447
- same(reading.value, 7, "the admin-set value");
448
- same(reading.source, "config", "which layer decided");
449
- }),
450
- await check("records a fallback, naming the kind that had nothing to say", async () => {
451
- const { adapter, written } = over();
452
- await readPolicy(
453
- probePolicy(),
454
- "unread",
455
- {},
456
- {
457
- config: adapter.config,
458
- fallback: 1,
459
- journal: adapter.journal,
460
- op: "a-named-operation",
461
- rule: adapter.rule
462
- }
463
- );
464
- const entries = written();
465
- same(entries.length, 1, "how many records one fallback produced");
466
- must(
467
- JSON.stringify(entries).includes("unread"),
468
- "the record does not name the kind, so nobody can count it"
469
- );
470
- must(
471
- JSON.stringify(entries).includes("a-named-operation"),
472
- "the record does not name the operation, so repeats cannot be told apart"
473
- );
474
- }),
475
- await check("does not let a store that is down throw out of a config read", async () => {
476
- await harness.createBroken().config?.get("unread", {});
477
- })
478
- ];
479
- return { adapter: harness.name, checks, passed: checks.every((entry) => entry.passed) };
480
- };
481
-
482
- // src/learning.ts
483
- var emptyPlaybook = () => ({ entries: [], version: 0 });
484
- var DEFAULT_MIN_OBSERVATIONS = 3;
485
- var LearningError = class extends Error {
486
- constructor(code, message) {
487
- super(`${code}: ${message}`);
488
- this.code = code;
489
- this.name = "LearningError";
490
- }
491
- code;
492
- };
493
- var DEFAULT_REFUSAL_PREFIX = "POLICY_REFUSED";
494
- var DEFAULT_REVERSAL_VERBS = /\b(override|revert|undo|cancel|reassign|reschedule)\b/i;
495
- var observeReversals = (entries, verbs) => {
496
- const out = [];
497
- for (const [index, decided] of entries.entries()) {
498
- const next = entries[index + 1];
499
- if (!next) continue;
500
- if (decided.actor.kind === "user" || next.actor.kind !== "user") continue;
501
- if (!decided.subject || decided.subject !== next.subject) continue;
502
- if (!verbs.test(next.name)) continue;
503
- const op = decided.op ?? decided.name;
504
- out.push({
505
- id: `reversed:${op}`,
506
- journalRefs: [decided.id, next.id],
507
- kind: "pitfall",
508
- statement: `A person reversed the automated "${op}" on ${decided.subject} (via ${next.name}) \u2014 check the decision before repeating it`
509
- });
510
- }
511
- return out;
512
- };
513
- var observeRuleFriction = (entry, prefix) => {
514
- if (!entry.error) return [];
515
- const [, ruleId, detail] = new RegExp(`${prefix}: ([\\w:.-]+)(?: \u2014 (.*))?`).exec(entry.error) ?? [];
516
- if (!ruleId) return [];
517
- return [
518
- {
519
- id: `friction:${ruleId}`,
520
- journalRefs: [entry.id],
521
- kind: "rule-friction",
522
- statement: `Rule "${ruleId}" blocked an action again${detail ? ` \u2014 ${detail.slice(0, 140)}` : ""} \u2014 amend the rule or stop attempting it`
523
- }
524
- ];
525
- };
526
- var observeUnsetPolicy = (entry) => {
527
- const fell = entry.fellBackTo;
528
- if (!fell) return [];
529
- return [
530
- {
531
- id: `unset:${fell.kind}`,
532
- journalRefs: [entry.id],
533
- kind: "unset-policy",
534
- statement: `No rule sets "${fell.kind}", so the hardcoded default ${JSON.stringify(
535
- fell.value
536
- )} decided instead \u2014 write the rule or delete the knob`
537
- }
538
- ];
539
- };
540
- var observeRecurringOps = (entries, minimum) => {
541
- const byOp = /* @__PURE__ */ new Map();
542
- for (const entry of entries) {
543
- if (entry.error || !entry.op) continue;
544
- const refs = byOp.get(entry.op);
545
- if (refs) refs.push(entry.id);
546
- else byOp.set(entry.op, [entry.id]);
547
- }
548
- return [...byOp].filter(([, refs]) => refs.length >= minimum).map(([op, refs]) => ({
549
- id: `macro:${op}`,
550
- journalRefs: refs,
551
- kind: "macro",
552
- statement: `"${op}" ran ${refs.length} times \u2014 save it as a named strategy`
553
- }));
554
- };
555
- var observeJournal = (entries, options = {}) => [
556
- ...observeReversals(entries, options.reversalVerbs ?? DEFAULT_REVERSAL_VERBS),
557
- ...entries.flatMap((entry) => [
558
- ...observeRuleFriction(entry, options.refusalPrefix ?? DEFAULT_REFUSAL_PREFIX),
559
- ...observeUnsetPolicy(entry)
560
- ]),
561
- ...observeRecurringOps(entries, options.minRepeatsForMacro ?? 2)
562
- ];
563
- var reflect = (observations, now = /* @__PURE__ */ new Date()) => {
564
- const byId = /* @__PURE__ */ new Map();
565
- const at = now.toISOString();
566
- for (const observation of observations) {
567
- const existing = byId.get(observation.id);
568
- if (existing) {
569
- existing.evidence.observations += 1;
570
- existing.evidence.journalRefs = [
571
- .../* @__PURE__ */ new Set([...existing.evidence.journalRefs, ...observation.journalRefs])
572
- ];
573
- continue;
574
- }
575
- byId.set(observation.id, {
576
- evidence: { journalRefs: [...observation.journalRefs], observations: 1, updatedAt: at },
577
- id: observation.id,
578
- kind: observation.kind,
579
- ...observation.scope ? { scope: observation.scope } : {},
580
- statement: observation.statement,
581
- status: "candidate",
582
- ...observation.suggests ? { suggests: observation.suggests } : {}
583
- });
584
- }
585
- return [...byId.values()];
586
- };
587
- var curate = (playbook, candidates) => {
588
- const entries = playbook.entries.map((entry) => ({ ...entry, evidence: { ...entry.evidence } }));
589
- const byId = new Map(entries.map((entry) => [entry.id, entry]));
590
- for (const candidate of candidates) {
591
- const existing = byId.get(candidate.id);
592
- if (!existing) {
593
- entries.push(candidate);
594
- byId.set(candidate.id, candidate);
595
- continue;
596
- }
597
- if (existing.status === "demoted") continue;
598
- existing.evidence.observations += candidate.evidence.observations;
599
- existing.evidence.journalRefs = [
600
- .../* @__PURE__ */ new Set([...existing.evidence.journalRefs, ...candidate.evidence.journalRefs])
601
- ];
602
- existing.evidence.updatedAt = candidate.evidence.updatedAt;
603
- if (existing.status === "candidate") existing.statement = candidate.statement;
604
- }
605
- return { entries, version: playbook.version + 1 };
606
- };
607
- var promote = (playbook, id, options = {}) => {
608
- const minimum = options.minObservations ?? DEFAULT_MIN_OBSERVATIONS;
609
- const entry = playbook.entries.find((candidate) => candidate.id === id);
610
- if (!entry) throw new LearningError("UNKNOWN_LEARNING", `no learning "${id}"`);
611
- if (entry.evidence.observations < minimum) {
612
- throw new LearningError(
613
- "INSUFFICIENT_EVIDENCE",
614
- `"${id}" has ${entry.evidence.observations} observation(s), needs ${minimum}`
615
- );
616
- }
617
- return {
618
- entries: playbook.entries.map(
619
- (candidate) => candidate.id === id ? {
620
- ...candidate,
621
- evidence: {
622
- ...candidate.evidence,
623
- ...options.metric ? { metric: options.metric } : {}
624
- },
625
- status: "active"
626
- } : candidate
627
- ),
628
- version: playbook.version + 1
629
- };
630
- };
631
- var demote = (playbook, id, reason2) => {
632
- if (!playbook.entries.some((entry) => entry.id === id)) {
633
- throw new LearningError("UNKNOWN_LEARNING", `no learning "${id}"`);
634
- }
635
- return {
636
- entries: playbook.entries.map(
637
- (entry) => entry.id === id ? { ...entry, demotedReason: reason2, status: "demoted" } : entry
638
- ),
639
- version: playbook.version + 1
640
- };
641
- };
642
- var playbookRules = (policy, playbook) => {
643
- const advisory = policy.tiers.find((tier) => tier.advisory);
644
- if (!advisory) {
645
- throw new TypeError(
646
- "playbookRules: this policy declares no advisory tier. A learning has to enter the lattice somewhere it can only fill silence; without one, promoting it would give a suggestion the authority of an authored rule."
647
- );
648
- }
649
- return playbook.entries.flatMap((entry) => {
650
- const suggests = entry.suggests;
651
- if (entry.status !== "active" || !suggests) return [];
652
- return [
653
- {
654
- constraint: suggests,
655
- id: `${advisory.name}:${entry.id}`,
656
- reason: `${entry.statement} (${entry.evidence.observations} observations)`,
657
- ...entry.scope ? { scope: entry.scope } : {},
658
- tier: advisory.name
659
- }
660
- ];
661
- });
662
- };
663
- var playbookGuidance = (playbook) => {
664
- const active = playbook.entries.filter((entry) => entry.status === "active");
665
- if (active.length === 0) return "";
666
- const lines = active.map(
667
- (entry) => `- [${entry.kind}] ${entry.statement} (${entry.evidence.observations} observations)`
668
- );
669
- return `Learned playbook (v${playbook.version}, advisory):
670
- ${lines.join("\n")}`;
671
- };
672
-
673
- // src/journal-events.ts
674
- var firstString = (data, keys) => {
675
- for (const key of keys) {
676
- const value = data[key];
677
- if (typeof value === "string" && value.length > 0) return value;
678
- }
679
- return null;
680
- };
681
- var journalRowForEvent = (eventName, data, options) => {
682
- const payload = Array.isArray(data) ? data[0] : data;
683
- if (!payload || typeof payload !== "object") return null;
684
- const subject = firstString(payload, options.subjectKeys);
685
- if (!subject) return null;
686
- const actorId = firstString(payload, options.actorKeys ?? []);
687
- return {
688
- actor_id: actorId,
689
- actor_kind: actorId ? "user" : "system",
690
- event_name: eventName,
691
- // The STEM, not the full name: two outcomes of one decision are the same operation being run
692
- // again, and the recurring-ops signal counts operations.
693
- op: eventName.split(".")[0] ?? eventName,
694
- subject
695
- };
696
- };
697
-
698
- // src/markdown.ts
699
- var scopeOf = (rule) => {
700
- const entries = Object.entries(rule.scope ?? {}).filter(([, value]) => value !== void 0);
701
- return entries.length === 0 ? "all" : entries.map(([key, value]) => `${key}=${String(value)}`).join(", ");
702
- };
703
- var generatePolicyMarkdown = (policy, options = {}) => {
704
- const rules = options.rules ?? policy.rules;
705
- const lines = [
706
- `# ${options.title ?? "Policy"}`,
707
- "",
708
- `> GENERATED by ${options.generator ?? "the policy kernel"} \u2014 do not hand-edit.`,
709
- `> ${options.source ?? "The policy data"} beside it is what the engine reads.`,
710
- "> Committed on purpose: this is the domain knowledge the business has accumulated, and it",
711
- "> should arrive with a checkout.",
712
- "",
713
- `## Rules (${rules.length}) \u2014 enforced`,
714
- "",
715
- // DERIVED, and printed whether or not any rule uses it: the ordering is a property of the
716
- // lattice, not of today's rules. Written as prose this sentence lies the moment a tier is added
717
- // or reordered — in a document whose whole purpose is that a fresh checkout starts knowing the
718
- // truth.
719
- `Precedence: ${policy.tiers.map((tier) => tier.name).join(" > ")}.`,
720
- "Within a tier the more specific scope wins; two equal authorities that disagree are reported,",
721
- "never resolved silently.",
722
- ""
723
- ];
724
- if (rules.length === 0) {
725
- lines.push("_None installed. Every reader falls back to its own constant, and says so._", "");
726
- } else {
727
- lines.push(
728
- "| Rule | Tier | Scope | Constraint | Why |",
729
- "| --- | --- | --- | --- | --- |",
730
- ...rules.map(
731
- (rule) => `| \`${rule.id}\` | ${rule.tier} | ${scopeOf(rule)} | \`${rule.constraint.kind}\` = \`${JSON.stringify(rule.constraint.value)}\` | ${rule.reason} |`
732
- ),
733
- ""
734
- );
735
- }
736
- const unset = policy.unsetKinds(rules);
737
- if (unset.length > 0) {
738
- lines.push(
739
- `## Constraints nothing sets (${unset.length})`,
740
- "",
741
- "A reader falling back to its own default forever looks identical to one that is working.",
742
- "",
743
- ...unset.map((kind) => `- \`${kind}\``),
744
- ""
745
- );
746
- }
747
- const unusable = [
748
- ...policy.unusableRules(rules).map((rule) => `- \`${rule.id}\` \u2014 ${rule.reason}`),
749
- ...policy.unsupportedScopes(rules).map(
750
- (rule) => `- \`${rule.id}\` \u2014 scoped on ${rule.keys.join(", ")}, which this build has no key for`
751
- )
752
- ];
753
- if (unusable.length > 0) {
754
- lines.push(
755
- `## Rules this build cannot honour (${unusable.length})`,
756
- "",
757
- "Named rather than dropped: a rule the code cannot read means the policy is newer than the",
758
- "build, or older \u2014 a deployment-order problem, and the one case always worth saying aloud.",
759
- "",
760
- ...unusable,
761
- ""
762
- );
763
- }
764
- const playbook = options.playbook;
765
- if (playbook) {
766
- const active = playbook.entries.filter((entry) => entry.status === "active");
767
- const candidates = playbook.entries.filter((entry) => entry.status === "candidate");
768
- lines.push(
769
- `## Learned playbook (v${playbook.version})`,
770
- "",
771
- `${active.length} active, ${candidates.length} candidate. An active entry that carries a`,
772
- "constraint enters the lattice at the advisory tier, where it can only fill silence.",
773
- "",
774
- ...active.map((entry) => `- **${entry.id}** \u2014 ${entry.statement}`),
775
- ""
776
- );
777
- }
778
- return `${lines.join("\n")}
779
- `;
780
- };
781
- var describePolicy = (policy, options = {}) => {
782
- const rules = options.rules ?? policy.rules;
783
- const maximum = options.maxRules ?? 8;
784
- const active = (options.playbook?.entries ?? []).filter((entry) => entry.status === "active");
785
- if (rules.length === 0) {
786
- return "No policy is installed yet \u2014 nothing is enforced, and every reader falls back to the constant compiled into it.";
787
- }
788
- const lines = [
789
- `ACTIVE POLICY (${rules.length} rule${rules.length === 1 ? "" : "s"}, enforced \u2014 a refusal names the rule that blocked it):`,
790
- ...rules.slice(0, maximum).map((rule) => {
791
- const scope = rule.scope && Object.keys(rule.scope).length > 0 ? ` [${scopeOf(rule)}]` : "";
792
- return ` ${rule.tier}:${rule.id}${scope} \u2014 ${rule.constraint.kind}=${JSON.stringify(
793
- rule.constraint.value
794
- )} (${rule.reason})`;
795
- })
796
- ];
797
- if (rules.length > maximum) {
798
- lines.push(` + ${rules.length - maximum} more \u2014 read the whole set before deciding.`);
799
- }
800
- lines.push(
801
- " A more specific scope beats a general one inside a tier; stronger tiers win outright."
802
- );
803
- if (active.length > 0) {
804
- lines.push("", "LEARNED (advisory \u2014 fills silence, never overrides a rule):");
805
- for (const entry of active.slice(0, 4)) lines.push(` ${entry.statement}`);
806
- }
807
- return lines.join("\n");
808
- };
809
-
810
- // src/rows.ts
811
- var toPolicyRule = (row) => ({
812
- constraint: { kind: row.constraint_kind, value: row.constraint_value },
813
- id: row.rule_key,
814
- // Only `false` is worth carrying: `true` is the default a policy declares, and writing it back
815
- // would make a rule that never said anything indistinguishable from one that agreed.
816
- ...row.overridable === false ? { overridable: false } : {},
817
- reason: row.reason,
818
- ...row.scope ? { scope: row.scope } : {},
819
- tier: row.tier
39
+ // src/index.ts
40
+ var exports_src = {};
41
+ __export(exports_src, {
42
+ DEFAULT_MIN_OBSERVATIONS: () => import_learning.DEFAULT_MIN_OBSERVATIONS,
43
+ LearningError: () => import_learning.LearningError,
44
+ POLICY_FALLBACK: () => import_types.POLICY_FALLBACK,
45
+ POLICY_INVALID_VALUE: () => import_types.POLICY_INVALID_VALUE,
46
+ appliesTo: () => import_lattice.appliesTo,
47
+ assertScopeOrder: () => import_define.assertScopeOrder,
48
+ curate: () => import_learning.curate,
49
+ declareThreshold: () => import_threshold.declareThreshold,
50
+ definePolicy: () => import_define.definePolicy,
51
+ demote: () => import_learning.demote,
52
+ describePolicy: () => import_markdown.describePolicy,
53
+ describeThreshold: () => import_threshold.describeThreshold,
54
+ emptyPlaybook: () => import_learning.emptyPlaybook,
55
+ expiredThresholds: () => import_threshold.expiredThresholds,
56
+ generatePolicyMarkdown: () => import_markdown.generatePolicyMarkdown,
57
+ isThreshold: () => import_threshold.isThreshold,
58
+ journalRowForEvent: () => import_journal_events.journalRowForEvent,
59
+ observeJournal: () => import_learning.observeJournal,
60
+ playbookGuidance: () => import_learning.playbookGuidance,
61
+ playbookRules: () => import_learning.playbookRules,
62
+ policyOrDefault: () => import_read.policyOrDefault,
63
+ promote: () => import_learning.promote,
64
+ readPolicy: () => import_read.readPolicy,
65
+ reflect: () => import_learning.reflect,
66
+ resolveConstraint: () => import_lattice.resolveConstraint,
67
+ rulesToSeed: () => import_seed.rulesToSeed,
68
+ runPolicyAdapterConformance: () => import_conformance.runPolicyAdapterConformance,
69
+ specificityOf: () => import_lattice.specificityOf,
70
+ toPolicyRule: () => import_rows.toPolicyRule,
71
+ toPolicyRules: () => import_rows.toPolicyRules,
72
+ unsetKindsOf: () => import_lattice.unsetKindsOf,
73
+ unsupportedScopesOf: () => import_lattice.unsupportedScopesOf,
74
+ unusableRulesOf: () => import_lattice.unusableRulesOf,
75
+ usableRulesOf: () => import_lattice.usableRulesOf
820
76
  });
821
- var toPolicyRules = (rows) => rows.filter((row) => (row.status ?? "active") === "active").map(toPolicyRule);
822
-
823
- // src/seed.ts
824
- var sameScope = (left, right) => {
825
- const a = left ?? {};
826
- const b = right ?? {};
827
- return [.../* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)])].every((key) => a[key] === b[key]);
828
- };
829
- var rulesToSeed = (seed, existing) => {
830
- const active = existing.filter((rule) => (rule.status ?? "active") === "active");
831
- return seed.filter(
832
- (rule) => !active.some(
833
- (row) => row.id === rule.id || row.constraint.kind === rule.constraint.kind && sameScope(row.scope, rule.scope)
834
- )
835
- );
836
- };
837
-
838
- // src/threshold.ts
839
- var DECLARED = /* @__PURE__ */ Symbol.for("com.microcompanies.geonosis.threshold");
840
- var ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
841
- var refuse = (what) => {
842
- throw new Error(
843
- `declareThreshold: ${what}. Next: give it one, or leave it as a plain constant and say why it needs no authority.`
844
- );
845
- };
846
- var filled = (value) => typeof value === "string" && value.trim() !== "";
847
- var declareThreshold = (input) => {
848
- if (!filled(input.authority)) refuse("a threshold whose authority is nobody is a magic number");
849
- if (!filled(input.reason)) refuse("a threshold with no reason cannot teach anyone what it is for");
850
- if (input.value === void 0) refuse("a threshold with no value decides nothing");
851
- if (input.revisit !== void 0 && !ISO_DATE.test(input.revisit)) {
852
- refuse(
853
- `revisit "${input.revisit}" is not an ISO date \u2014 a date nobody can compare never expires`
854
- );
855
- }
856
- return Object.freeze({ ...input, [DECLARED]: true });
857
- };
858
- var isThreshold = (value) => typeof value === "object" && value !== null && DECLARED in value;
859
- var expiredThresholds = (thresholds, now) => thresholds.filter((one) => one.revisit !== void 0 && new Date(one.revisit) <= now);
860
- var describeThreshold = (threshold) => [
861
- `${String(threshold.value)}`,
862
- threshold.subject === void 0 ? "" : ` for ${threshold.subject}`,
863
- ` \u2014 ${threshold.authority}: ${threshold.reason}`,
864
- threshold.revisit === void 0 ? "" : ` (revisit ${threshold.revisit})`
865
- ].join("");
77
+ module.exports = __toCommonJS(exports_src);
78
+ var import_conformance = require("./conformance.cjs");
79
+ var import_define = require("./define.cjs");
80
+ var import_lattice = require("./lattice.cjs");
81
+ var import_learning = require("./learning.cjs");
82
+ var import_journal_events = require("./journal-events.cjs");
83
+ var import_markdown = require("./markdown.cjs");
84
+ var import_read = require("./read.cjs");
85
+ var import_rows = require("./rows.cjs");
86
+ var import_seed = require("./seed.cjs");
87
+ var import_threshold = require("./threshold.cjs");
88
+ var import_types = require("./types.cjs");