@geonosis/policy 3.1.0 → 3.2.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 (46) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/dist/conformance.d.cts +1 -12
  3. package/dist/conformance.d.ts +1 -12
  4. package/dist/define.d.cts +2 -22
  5. package/dist/define.d.ts +2 -22
  6. package/dist/drizzle/index.cjs +2 -17
  7. package/dist/drizzle/index.d.cts +3 -11
  8. package/dist/drizzle/index.d.ts +3 -11
  9. package/dist/drizzle/index.js +2 -17
  10. package/dist/journal-events.d.cts +1 -14
  11. package/dist/journal-events.d.ts +1 -14
  12. package/dist/lattice.cjs +11 -3
  13. package/dist/lattice.d.cts +4 -37
  14. package/dist/lattice.d.ts +4 -37
  15. package/dist/lattice.js +11 -3
  16. package/dist/learning.cjs +10 -4
  17. package/dist/learning.d.cts +5 -58
  18. package/dist/learning.d.ts +5 -58
  19. package/dist/learning.js +10 -4
  20. package/dist/markdown.d.cts +2 -19
  21. package/dist/markdown.d.ts +2 -19
  22. package/dist/medusa/index.cjs +3 -18
  23. package/dist/medusa/index.d.cts +5 -46
  24. package/dist/medusa/index.d.ts +5 -46
  25. package/dist/medusa/index.js +2 -17
  26. package/dist/permissions/index.cjs +8 -4
  27. package/dist/permissions/index.d.cts +8 -67
  28. package/dist/permissions/index.d.ts +8 -67
  29. package/dist/permissions/index.js +8 -4
  30. package/dist/read.cjs +5 -11
  31. package/dist/read.d.cts +2 -31
  32. package/dist/read.d.ts +2 -31
  33. package/dist/read.js +1 -7
  34. package/dist/rows.cjs +17 -0
  35. package/dist/rows.d.cts +6 -9
  36. package/dist/rows.d.ts +6 -9
  37. package/dist/rows.js +17 -0
  38. package/dist/seed.d.cts +1 -13
  39. package/dist/seed.d.ts +1 -13
  40. package/dist/threshold.cjs +5 -1
  41. package/dist/threshold.d.cts +3 -29
  42. package/dist/threshold.d.ts +3 -29
  43. package/dist/threshold.js +5 -1
  44. package/dist/types.d.cts +2 -57
  45. package/dist/types.d.ts +2 -57
  46. package/package.json +1 -1
@@ -1,16 +1,4 @@
1
- /**
2
- * A permission lattice — Medusa 2.19.0's `definePolicies` / `hasPermission` / `resolvePermissions`
3
- * with the container lifted out.
4
- *
5
- * A Medusa storefront did not reinvent permissions and was right not to: it adopted the native
6
- * module and put a typed registry in front of it. What that registry could not be given was a way
7
- * to ANSWER the question without a booted container — so the same 22 named policies are
8
- * unit-testable in node and the check they feed is not. Everything here is pure: the grants are
9
- * data the caller fetched, and the answer is a value.
10
- *
11
- * Every semantic is pinned from the shipped implementation. No test file ships in either tarball.
12
- */
13
- /** The single character used as the wildcard in BOTH the resource and the operation slot. */
1
+ /** Medusa 2.19.0's `definePolicies` / `hasPermission` / `resolvePermissions` with the container lifted out, so the answer is a value that unit-tests without a booted server. */
14
2
  export declare const WILDCARD = "*";
15
3
  export type PolicyDefinition = {
16
4
  description?: string;
@@ -18,40 +6,23 @@ export type PolicyDefinition = {
18
6
  operation: string;
19
7
  resource: string;
20
8
  };
21
- /** A resource with one or more operations on it — what a route asks for. */
22
9
  export type PermissionAction = {
23
10
  operation: readonly string[] | string;
24
11
  resource: string;
25
12
  };
26
- /** A single (resource, operation) pair with the key a store would hold it under. */
27
13
  export type ExpandedPolicy = {
28
14
  key: string;
29
15
  operation: string;
30
16
  resource: string;
31
17
  };
32
- /** What each role has been granted. The caller fetched it; this decides with it. */
33
18
  export type PolicyGrants = ReadonlyMap<string, readonly PermissionAction[]> | Readonly<Record<string, readonly PermissionAction[]>>;
34
19
  export declare const permissionKey: (resource: string, operation: string) => string;
35
- /**
36
- * `ReadBrands` → `read_brands`, and the wildcard through untouched.
37
- *
38
- * Exported because a repo has to be able to check its own vocabulary against it: an operation
39
- * spelled `certificate:create` normalises to `certificate_create`, so a repo that authors its rows
40
- * directly (as a Medusa storefront does) and ALSO declares them through here would end up with two
41
- * spellings of one permission and no error anywhere.
42
- */
20
+ /** Exported so a repo can check its vocabulary: `certificate:create` normalises to `certificate_create`, so authoring rows directly and also declaring through here yields two spellings of one permission. */
43
21
  export declare const normalizePolicyKey: (key: string) => string;
44
22
  export type DefinePoliciesOptions = {
45
23
  normalize?: (key: string) => string;
46
24
  };
47
- /**
48
- * Declare policies. Answers with them; registers nothing globally.
49
- *
50
- * Upstream writes into three `globalThis` registries and REWRITES the caller's objects in place, so
51
- * the array you passed comes back normalised under you and a second file declaring the same name
52
- * silently replaces the first. Neither is load-bearing for the decision, and both are surprising, so
53
- * neither is reproduced — `createPolicyCatalog` is the registry, and it refuses a duplicate.
54
- */
25
+ /** Upstream writes into three `globalThis` registries and rewrites the caller's objects in place; neither is reproduced. `createPolicyCatalog` is the registry and refuses a duplicate. */
55
26
  export declare const definePolicies: (policies: PolicyDefinition | readonly PolicyDefinition[], options?: DefinePoliciesOptions) => {
56
27
  policies: PolicyDefinition[];
57
28
  };
@@ -62,63 +33,33 @@ export type PolicyCatalog = {
62
33
  operations: () => string[];
63
34
  resources: () => string[];
64
35
  };
65
- /** The registry upstream keeps globally, made local and made to refuse a name already taken. */
66
36
  export declare const createPolicyCatalog: (options?: DefinePoliciesOptions) => PolicyCatalog;
67
- /**
68
- * Expand actions into the unique one-operation rows a store keeps, deduped, key derived.
69
- *
70
- * The key is `<resource>:<operation>` on the RAW operation, which is how a wildcard grant becomes
71
- * the single `*:*` row that authorises every route — granting the union of a repo's own named
72
- * policies instead covers its custom resources only, and 403s every native one.
73
- */
37
+ /** Keyed `<resource>:<operation>` on the raw operation, so a wildcard grant is the single `*:*` row; granting the union of a repo's named policies would 403 every native route. */
74
38
  export declare const expandPolicies: (actions: readonly PermissionAction[]) => ExpandedPolicy[];
75
39
  export type HasPermissionInput = {
76
40
  actions: PermissionAction | readonly PermissionAction[];
77
- /**
78
- * Whether the mechanism is on at all. `false` allows everything, which is what the `rbac` feature
79
- * flag does upstream — and it is off by default there.
80
- */
41
+ /** `false` allows everything, as upstream's `rbac` feature flag does (off by default there). */
81
42
  enabled?: boolean;
82
43
  grants: PolicyGrants;
83
- /**
84
- * What an actor with NO roles gets. Upstream's `hasPermission` allows (`!roleIds?.length` returns
85
- * true) while its own route wrapper denies, so the same request gets opposite answers depending
86
- * on which door it came through. `allow` is upstream's answer here.
87
- */
44
+ /** Upstream's `hasPermission` allows a role-less actor while its route wrapper denies, so one request gets opposite answers by door. `allow` is upstream's answer here. */
88
45
  onEmptyRoles?: 'allow' | 'deny';
89
46
  roles: readonly string[] | string;
90
47
  };
91
- /** Do these roles grant every one of these actions? */
92
48
  export declare const hasPermission: (input: HasPermissionInput) => boolean;
93
49
  export type ResolvePermissionsInput = {
94
50
  enabled?: boolean;
95
51
  grants: PolicyGrants;
96
52
  roles: readonly string[] | string;
97
- /** The (resource, operation) pairs to evaluate against, with wildcards expanded into them. */
98
53
  universe: readonly {
99
54
  operation: string;
100
55
  resource: string;
101
56
  }[];
102
57
  };
103
- /**
104
- * The subset of the universe these roles are granted, keyed `resource:operation`.
105
- *
106
- * The inverse of `hasPermission`, for a client that would otherwise have to re-implement wildcard
107
- * semantics to render a menu. Note the asymmetry, which is upstream's: with the mechanism off this
108
- * answers with EVERYTHING, and for an actor with no roles it answers with NOTHING — where
109
- * `hasPermission` answers true for that same actor.
110
- */
58
+ /** Inverse of `hasPermission`. With the mechanism off it answers everything, and for a role-less actor nothing, where `hasPermission` answers true: upstream's asymmetry. */
111
59
  export declare const resolvePermissions: (input: ResolvePermissionsInput) => Set<string>;
112
60
  export type PermissionCheck = {
113
61
  allowed: boolean;
114
62
  required: string[];
115
63
  };
116
- /**
117
- * The decision a route guard needs: the answer, plus WHICH permissions were required.
118
- *
119
- * A refusal that names them teaches the person blocked by it something; one that says "Forbidden"
120
- * sends them to whoever owns the roles table. Denies a role-less actor, as the route wrapper does —
121
- * but unlike the wrapper it still honours the flag, which the wrapper reads only after it has
122
- * already thrown.
123
- */
64
+ /** Names the required permissions in the refusal. Denies a role-less actor like the route wrapper, but honours the flag, which the wrapper reads only after throwing. */
124
65
  export declare const checkPermissions: (input: Omit<HasPermissionInput, 'onEmptyRoles'>) => PermissionCheck;
@@ -3,7 +3,7 @@ var WILDCARD = "*";
3
3
  var permissionKey = (resource, operation) => `${resource}:${operation}`;
4
4
  var normalizePolicyKey = (key) => key === WILDCARD ? WILDCARD : key.replace(/([a-z])([A-Z])/g, "$1_$2").replace(/[^a-zA-Z0-9]+/g, "_").replace(/^_+|_+$/g, "").toLowerCase();
5
5
  var definePolicies = (policies, options = {}) => {
6
- const declared = Array.isArray(policies) ? policies : [policies];
6
+ const declared = asArray(policies);
7
7
  const normalize = options.normalize ?? normalizePolicyKey;
8
8
  return {
9
9
  policies: declared.map((policy) => {
@@ -42,15 +42,19 @@ var createPolicyCatalog = (options = {}) => {
42
42
  var expandPolicies = (actions) => {
43
43
  const byKey = new Map;
44
44
  for (const action of actions) {
45
- const operations = Array.isArray(action.operation) ? action.operation : [action.operation];
46
- for (const operation of operations) {
45
+ for (const operation of asArray(action.operation)) {
47
46
  const key = permissionKey(action.resource, operation);
48
47
  byKey.set(key, { key, operation, resource: action.resource });
49
48
  }
50
49
  }
51
50
  return [...byKey.values()];
52
51
  };
53
- var grantsFor = (grants, role) => grants instanceof Map ? grants.get(role) ?? [] : grants[role] ?? [];
52
+ var isMap = (grants) => grants instanceof Map;
53
+ var grantsFor = (grants, role) => {
54
+ if (isMap(grants))
55
+ return grants.get(role) ?? [];
56
+ return Object.hasOwn(grants, role) ? grants[role] ?? [] : [];
57
+ };
54
58
  var asArray = (value) => Array.isArray(value) ? value : [value];
55
59
  var policyAllows = (grants, roles, resource, operation) => roles.some((role) => {
56
60
  const allowed = new Set(expandPolicies(grantsFor(grants, role)).filter((policy) => policy.resource === resource || policy.resource === WILDCARD).map((policy) => policy.operation));
package/dist/read.cjs CHANGED
@@ -43,14 +43,8 @@ __export(exports_read, {
43
43
  readPolicy: () => readPolicy
44
44
  });
45
45
  module.exports = __toCommonJS(exports_read);
46
+ var import_rows = require("./rows.cjs");
46
47
  var import_types = require("./types.cjs");
47
- var attempt = async (what) => {
48
- try {
49
- return await what();
50
- } catch {
51
- return;
52
- }
53
- };
54
48
  var accepts = (policy, kind, value) => {
55
49
  const schema = policy.kindOf(kind)?.schema;
56
50
  return schema ? schema.safeParse(value).success : true;
@@ -60,15 +54,15 @@ var record = async (policy, journal, entry) => {
60
54
  if (policy.journalledOnce.has(key))
61
55
  return;
62
56
  policy.journalledOnce.add(key);
63
- await attempt(() => journal?.write(entry));
57
+ await import_rows.attempt(() => journal?.write(entry));
64
58
  };
65
59
  var readPolicy = async (policy, kind, query = {}, options) => {
66
- const rules = options.rule ? await attempt(() => options.rule?.rules(kind, query)) ?? [] : policy.rules;
60
+ const rules = options.rule ? await import_rows.attempt(() => options.rule?.rules(kind, query)) ?? [] : policy.rules;
67
61
  const decision = policy.resolve(kind, query, rules);
68
62
  if (decision) {
69
63
  const spec = policy.kindOf(kind);
70
64
  if (spec?.isReference?.(decision.value)) {
71
- const referenced = await attempt(() => spec.dereference?.(decision.value, { config: options.config, query }));
65
+ const referenced = await import_rows.attempt(() => spec.dereference?.(decision.value, { config: options.config, query }));
72
66
  if (referenced !== undefined) {
73
67
  return { decision, source: "rule", usedFallback: false, value: referenced };
74
68
  }
@@ -76,7 +70,7 @@ var readPolicy = async (policy, kind, query = {}, options) => {
76
70
  return { decision, source: "rule", usedFallback: false, value: decision.value };
77
71
  }
78
72
  }
79
- const configured = await attempt(() => options.config?.get(kind, query));
73
+ const configured = await import_rows.attempt(() => options.config?.get(kind, query));
80
74
  if (configured !== undefined && accepts(policy, kind, configured)) {
81
75
  return { source: "config", usedFallback: false, value: configured };
82
76
  }
package/dist/read.d.cts CHANGED
@@ -1,31 +1,14 @@
1
1
  import type { Policy, PolicyConfigReader, PolicyJournal, PolicyQuery, PolicyReading, PolicyRuleReader } from './types.cjs';
2
2
  export type ReadPolicyOptions<V> = {
3
3
  config?: PolicyConfigReader;
4
- /** The caller's own constant — the floor, and the type of the answer. */
5
4
  fallback: V;
6
5
  journal?: PolicyJournal;
7
- /** A named operation, so repeats become countable per operation rather than per request. */
8
6
  op?: string;
9
7
  rule?: PolicyRuleReader;
10
- /** Opt out of recording. Only for a caller that runs per request inside a loop. */
11
8
  silent?: boolean;
12
- /** What the decision is about — an order id, a company id. */
13
9
  subject?: string;
14
10
  };
15
- /**
16
- * Read one constraint, with the caller's own default as the floor.
17
- *
18
- * This is what a reader calls instead of reaching for a hardcoded constant. It answers with the
19
- * resolved value when policy speaks, the admin-set value when it does not, and the caller's own
20
- * constant when nobody has said anything — and, the part that matters, it RECORDS that last case,
21
- * so "nothing sets this" becomes a countable signal rather than a silence indistinguishable from
22
- * working.
23
- *
24
- * The resolution order is authored rule → config row → constant. A rule wins because it carries an
25
- * authority, a subject and a reason where a config row carries only a value; a config row beats the
26
- * constant because a value an admin actually typed must beat one a developer compiled in, or the
27
- * settings screen is a screen of knobs nothing reads.
28
- */
11
+ /** Order: authored rule, config row, constant. A rule carries an authority, a subject and a reason where a config row carries a value. The constant case is recorded, so "nothing sets this" is countable. */
29
12
  export declare const readPolicy: <V>(policy: Policy, kind: string, query: PolicyQuery | undefined, options: ReadPolicyOptions<V>) => Promise<PolicyReading<V>>;
30
13
  export type PolicyOrDefaultInput<V> = {
31
14
  fallback: V;
@@ -35,17 +18,5 @@ export type PolicyOrDefaultInput<V> = {
35
18
  subject?: string;
36
19
  value: V;
37
20
  };
38
- /**
39
- * Apply a resolved value, falling back to the caller's own default when it turns out to be
40
- * unusable.
41
- *
42
- * A validator that refuses a zero-day expiry or a zero-hour SLA is right to. But a number an admin
43
- * mistypes would then throw inside the work it was informing, and every one of those operations
44
- * would fail until somebody noticed — the customer paying for a misconfiguration. An unusable value
45
- * is a gap that arrived through a different door, so it is treated like every other gap: recorded
46
- * once per boot, and the default takes over while the mistake stays visible.
47
- *
48
- * A default that ALSO fails still throws. That is a bug in our own code rather than a
49
- * misconfiguration, and swallowing it would leave the caller with no value at all.
50
- */
21
+ /** An unusable value (a mistyped zero-day expiry) is a gap through another door: recorded once per boot while the default takes over. A default that also fails still throws: that is a bug in our code. */
51
22
  export declare const policyOrDefault: <T, V>(policy: Policy, input: PolicyOrDefaultInput<V>, apply: (value: V) => T) => Promise<T>;
package/dist/read.d.ts CHANGED
@@ -1,31 +1,14 @@
1
1
  import type { Policy, PolicyConfigReader, PolicyJournal, PolicyQuery, PolicyReading, PolicyRuleReader } from './types.js';
2
2
  export type ReadPolicyOptions<V> = {
3
3
  config?: PolicyConfigReader;
4
- /** The caller's own constant — the floor, and the type of the answer. */
5
4
  fallback: V;
6
5
  journal?: PolicyJournal;
7
- /** A named operation, so repeats become countable per operation rather than per request. */
8
6
  op?: string;
9
7
  rule?: PolicyRuleReader;
10
- /** Opt out of recording. Only for a caller that runs per request inside a loop. */
11
8
  silent?: boolean;
12
- /** What the decision is about — an order id, a company id. */
13
9
  subject?: string;
14
10
  };
15
- /**
16
- * Read one constraint, with the caller's own default as the floor.
17
- *
18
- * This is what a reader calls instead of reaching for a hardcoded constant. It answers with the
19
- * resolved value when policy speaks, the admin-set value when it does not, and the caller's own
20
- * constant when nobody has said anything — and, the part that matters, it RECORDS that last case,
21
- * so "nothing sets this" becomes a countable signal rather than a silence indistinguishable from
22
- * working.
23
- *
24
- * The resolution order is authored rule → config row → constant. A rule wins because it carries an
25
- * authority, a subject and a reason where a config row carries only a value; a config row beats the
26
- * constant because a value an admin actually typed must beat one a developer compiled in, or the
27
- * settings screen is a screen of knobs nothing reads.
28
- */
11
+ /** Order: authored rule, config row, constant. A rule carries an authority, a subject and a reason where a config row carries a value. The constant case is recorded, so "nothing sets this" is countable. */
29
12
  export declare const readPolicy: <V>(policy: Policy, kind: string, query: PolicyQuery | undefined, options: ReadPolicyOptions<V>) => Promise<PolicyReading<V>>;
30
13
  export type PolicyOrDefaultInput<V> = {
31
14
  fallback: V;
@@ -35,17 +18,5 @@ export type PolicyOrDefaultInput<V> = {
35
18
  subject?: string;
36
19
  value: V;
37
20
  };
38
- /**
39
- * Apply a resolved value, falling back to the caller's own default when it turns out to be
40
- * unusable.
41
- *
42
- * A validator that refuses a zero-day expiry or a zero-hour SLA is right to. But a number an admin
43
- * mistypes would then throw inside the work it was informing, and every one of those operations
44
- * would fail until somebody noticed — the customer paying for a misconfiguration. An unusable value
45
- * is a gap that arrived through a different door, so it is treated like every other gap: recorded
46
- * once per boot, and the default takes over while the mistake stays visible.
47
- *
48
- * A default that ALSO fails still throws. That is a bug in our own code rather than a
49
- * misconfiguration, and swallowing it would leave the caller with no value at all.
50
- */
21
+ /** An unusable value (a mistyped zero-day expiry) is a gap through another door: recorded once per boot while the default takes over. A default that also fails still throws: that is a bug in our code. */
51
22
  export declare const policyOrDefault: <T, V>(policy: Policy, input: PolicyOrDefaultInput<V>, apply: (value: V) => T) => Promise<T>;
package/dist/read.js CHANGED
@@ -1,12 +1,6 @@
1
1
  // src/read.ts
2
+ import { attempt } from "./rows.js";
2
3
  import { POLICY_FALLBACK, POLICY_INVALID_VALUE } from "./types.js";
3
- var attempt = async (what) => {
4
- try {
5
- return await what();
6
- } catch {
7
- return;
8
- }
9
- };
10
4
  var accepts = (policy, kind, value) => {
11
5
  const schema = policy.kindOf(kind)?.schema;
12
6
  return schema ? schema.safeParse(value).success : true;
package/dist/rows.cjs CHANGED
@@ -39,6 +39,8 @@ var __export = (target, all) => {
39
39
  // src/rows.ts
40
40
  var exports_rows = {};
41
41
  __export(exports_rows, {
42
+ attempt: () => attempt,
43
+ toJournalRow: () => toJournalRow,
42
44
  toPolicyRule: () => toPolicyRule,
43
45
  toPolicyRules: () => toPolicyRules
44
46
  });
@@ -52,3 +54,18 @@ var toPolicyRule = (row) => ({
52
54
  tier: row.tier
53
55
  });
54
56
  var toPolicyRules = (rows) => rows.filter((row) => (row.status ?? "active") === "active").map(toPolicyRule);
57
+ var toJournalRow = (entry, eventPrefix = "") => ({
58
+ actor_kind: "system",
59
+ ...entry.rejected ? { error: `rejected ${JSON.stringify(entry.rejected.value)}: ${entry.rejected.reason}` } : {},
60
+ event_name: `${eventPrefix}${entry.event}`,
61
+ fell_back_to: { constraintKind: entry.kind, value: entry.fellBackTo },
62
+ ...entry.op ? { op: entry.op } : {},
63
+ ...entry.subject ? { subject: entry.subject } : {}
64
+ });
65
+ var attempt = async (what) => {
66
+ try {
67
+ return await what();
68
+ } catch {
69
+ return;
70
+ }
71
+ };
package/dist/rows.d.cts CHANGED
@@ -1,11 +1,8 @@
1
- import type { PolicyRule, PolicyRuleRow } from './types.cjs';
2
- /**
3
- * A stored row, as a rule the lattice can use.
4
- *
5
- * This is the one part of a storage adapter that is not the store's own vocabulary, so it lives
6
- * once: two adapters that each did their own mapping would drift on what `overridable: true` means,
7
- * or on whether a null scope is a scope of nothing.
8
- */
1
+ import type { PolicyJournalEntry, PolicyRule, PolicyRuleRow } from './types.cjs';
2
+ /** The one part of a storage adapter that is not the store's vocabulary, so two adapters cannot drift on what `overridable: true` or a null scope means. */
9
3
  export declare const toPolicyRule: (row: PolicyRuleRow) => PolicyRule;
10
- /** The rules still in force. A retired row stays readable — it just stops deciding. */
11
4
  export declare const toPolicyRules: (rows: readonly PolicyRuleRow[]) => PolicyRule[];
5
+ /** The rejection goes into `error`, the one column that exists and the one the learning loop reads refusals from: a `rejected` key with no column fails inside a swallowing `catch`. */
6
+ export declare const toJournalRow: (entry: PolicyJournalEntry, eventPrefix?: string) => Record<string, unknown>;
7
+ /** Neither a config read nor a journal write may fail the decision it is informing. */
8
+ export declare const attempt: <T>(what: () => T) => Promise<Awaited<T> | undefined>;
package/dist/rows.d.ts CHANGED
@@ -1,11 +1,8 @@
1
- import type { PolicyRule, PolicyRuleRow } from './types.js';
2
- /**
3
- * A stored row, as a rule the lattice can use.
4
- *
5
- * This is the one part of a storage adapter that is not the store's own vocabulary, so it lives
6
- * once: two adapters that each did their own mapping would drift on what `overridable: true` means,
7
- * or on whether a null scope is a scope of nothing.
8
- */
1
+ import type { PolicyJournalEntry, PolicyRule, PolicyRuleRow } from './types.js';
2
+ /** The one part of a storage adapter that is not the store's vocabulary, so two adapters cannot drift on what `overridable: true` or a null scope means. */
9
3
  export declare const toPolicyRule: (row: PolicyRuleRow) => PolicyRule;
10
- /** The rules still in force. A retired row stays readable — it just stops deciding. */
11
4
  export declare const toPolicyRules: (rows: readonly PolicyRuleRow[]) => PolicyRule[];
5
+ /** The rejection goes into `error`, the one column that exists and the one the learning loop reads refusals from: a `rejected` key with no column fails inside a swallowing `catch`. */
6
+ export declare const toJournalRow: (entry: PolicyJournalEntry, eventPrefix?: string) => Record<string, unknown>;
7
+ /** Neither a config read nor a journal write may fail the decision it is informing. */
8
+ export declare const attempt: <T>(what: () => T) => Promise<Awaited<T> | undefined>;
package/dist/rows.js CHANGED
@@ -8,7 +8,24 @@ var toPolicyRule = (row) => ({
8
8
  tier: row.tier
9
9
  });
10
10
  var toPolicyRules = (rows) => rows.filter((row) => (row.status ?? "active") === "active").map(toPolicyRule);
11
+ var toJournalRow = (entry, eventPrefix = "") => ({
12
+ actor_kind: "system",
13
+ ...entry.rejected ? { error: `rejected ${JSON.stringify(entry.rejected.value)}: ${entry.rejected.reason}` } : {},
14
+ event_name: `${eventPrefix}${entry.event}`,
15
+ fell_back_to: { constraintKind: entry.kind, value: entry.fellBackTo },
16
+ ...entry.op ? { op: entry.op } : {},
17
+ ...entry.subject ? { subject: entry.subject } : {}
18
+ });
19
+ var attempt = async (what) => {
20
+ try {
21
+ return await what();
22
+ } catch {
23
+ return;
24
+ }
25
+ };
11
26
  export {
27
+ attempt,
28
+ toJournalRow,
12
29
  toPolicyRule,
13
30
  toPolicyRules
14
31
  };
package/dist/seed.d.cts CHANGED
@@ -1,18 +1,6 @@
1
1
  import type { PolicyRule } from './types.cjs';
2
- /** A rule as a store hands it back: the kernel's shape, plus whether it is still in force. */
3
2
  export type ExistingPolicyRule = PolicyRule & {
4
3
  status?: string;
5
4
  };
6
- /**
7
- * Which seed rules to author, given what is already there. Idempotent by ID and by COVERAGE.
8
- *
9
- * The coverage half is the one that was learned the hard way: a first seeding run produced two
10
- * active rules for one constraint with identical scope and value — the seed's, and one an admin had
11
- * authored by hand two days earlier. Same effect, two keys, and a conflict the lattice reports and
12
- * a human has to unpick.
13
- *
14
- * A seed provides DEFAULTS. If the business has already said something about a constraint at the
15
- * same scope, it has spoken, and the seed's opinion is not wanted. A RETIRED rule is not a current
16
- * opinion, so it does not block.
17
- */
5
+ /** Idempotent by id and by coverage. A seed provides defaults: if the business already has a rule at the same scope for the constraint, it has spoken (a first seeding run once duplicated an admin's hand-authored rule). A retired rule does not block. */
18
6
  export declare const rulesToSeed: <T extends PolicyRule>(seed: readonly T[], existing: readonly ExistingPolicyRule[]) => T[];
package/dist/seed.d.ts CHANGED
@@ -1,18 +1,6 @@
1
1
  import type { PolicyRule } from './types.js';
2
- /** A rule as a store hands it back: the kernel's shape, plus whether it is still in force. */
3
2
  export type ExistingPolicyRule = PolicyRule & {
4
3
  status?: string;
5
4
  };
6
- /**
7
- * Which seed rules to author, given what is already there. Idempotent by ID and by COVERAGE.
8
- *
9
- * The coverage half is the one that was learned the hard way: a first seeding run produced two
10
- * active rules for one constraint with identical scope and value — the seed's, and one an admin had
11
- * authored by hand two days earlier. Same effect, two keys, and a conflict the lattice reports and
12
- * a human has to unpick.
13
- *
14
- * A seed provides DEFAULTS. If the business has already said something about a constraint at the
15
- * same scope, it has spoken, and the seed's opinion is not wanted. A RETIRED rule is not a current
16
- * opinion, so it does not block.
17
- */
5
+ /** Idempotent by id and by coverage. A seed provides defaults: if the business already has a rule at the same scope for the constraint, it has spoken (a first seeding run once duplicated an admin's hand-authored rule). A retired rule does not block. */
18
6
  export declare const rulesToSeed: <T extends PolicyRule>(seed: readonly T[], existing: readonly ExistingPolicyRule[]) => T[];
@@ -50,6 +50,10 @@ var ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
50
50
  var refuse = (what) => {
51
51
  throw new Error(`declareThreshold: ${what}. Next: give it one, or leave it as a plain constant and say why it needs no authority.`);
52
52
  };
53
+ var isCalendarDate = (value) => {
54
+ const at = new Date(`${value}T00:00:00Z`);
55
+ return ISO_DATE.test(value) && !Number.isNaN(at.getTime()) && at.toISOString().startsWith(value);
56
+ };
53
57
  var filled = (value) => typeof value === "string" && value.trim() !== "";
54
58
  var declareThreshold = (input) => {
55
59
  if (!filled(input.authority))
@@ -58,7 +62,7 @@ var declareThreshold = (input) => {
58
62
  refuse("a threshold with no reason cannot teach anyone what it is for");
59
63
  if (input.value === undefined)
60
64
  refuse("a threshold with no value decides nothing");
61
- if (input.revisit !== undefined && !ISO_DATE.test(input.revisit)) {
65
+ if (input.revisit !== undefined && !isCalendarDate(input.revisit)) {
62
66
  refuse(`revisit "${input.revisit}" is not an ISO date — a date nobody can compare never expires`);
63
67
  }
64
68
  return Object.freeze({ ...input, [DECLARED]: true });
@@ -1,22 +1,8 @@
1
- /**
2
- * The compile-time tier: a threshold that no tenant sets and no config row overrides, declared where
3
- * it is used.
4
- *
5
- * The runtime lattice answers "what does this tenant, in this region, for this order, get?" — and it
6
- * needs a store, a boot and an await to answer it. Most thresholds are not that question.
7
- * `LIVENESS_TIMEOUT_MS = 3000` decides behaviour in code and will never be tenant-settable; what it
8
- * is missing is not a lattice, it is an authority. That is all this tier adds, and the reason it
9
- * adds nothing else: a threshold whose declaration cost an async call and a port would go back to
10
- * being a number.
11
- */
1
+ /** A threshold no tenant sets and no config row overrides, declared where it is used. It adds an authority and nothing else, so declaring one never costs an async call and a port. */
12
2
  export interface ThresholdInput<Value> {
13
- /** Who or what set it: a person and a date, a contract, a standard, an incident. */
14
3
  readonly authority: string;
15
- /** Why this number and not another. The sentence the person who was just blocked needs. */
16
4
  readonly reason: string;
17
- /** ISO date. When somebody should look at it again; absent means the authority is permanent. */
18
5
  readonly revisit?: string;
19
- /** What it reaches. Absent where the name says it. */
20
6
  readonly subject?: string;
21
7
  readonly value: Value;
22
8
  }
@@ -24,22 +10,10 @@ declare const DECLARED: unique symbol;
24
10
  export type Threshold<Value> = {
25
11
  readonly [DECLARED]: true;
26
12
  } & Readonly<ThresholdInput<Value>>;
27
- /**
28
- * Declared, frozen, and refused where it is incomplete.
29
- *
30
- * The refusal is at the declaration and not at the first read, because a declaration runs when the
31
- * module loads: a threshold missing its authority breaks the boot of whatever imports it, which is
32
- * the earliest anyone can be told and the last moment it is cheap.
33
- */
13
+ /** Refused at the declaration, not at the first read: a threshold missing its authority breaks the boot of whatever imports it. */
34
14
  export declare const declareThreshold: <Value>(input: ThresholdInput<Value>) => Threshold<Value>;
35
15
  export declare const isThreshold: (value: unknown) => value is Threshold<unknown>;
36
- /**
37
- * The thresholds whose revisit date has passed.
38
- *
39
- * Reported, never thrown. A declaration that started failing the build on a date would have its
40
- * date deleted by the first person it stopped, and the tier would be back to numbers with prose
41
- * beside them.
42
- */
16
+ /** Reported, never thrown: a build that failed on a date would have the date deleted by the first person it stopped. */
43
17
  export declare const expiredThresholds: (thresholds: readonly Threshold<unknown>[], now: Date) => Threshold<unknown>[];
44
18
  export declare const describeThreshold: (threshold: Threshold<unknown>) => string;
45
19
  export {};
@@ -1,22 +1,8 @@
1
- /**
2
- * The compile-time tier: a threshold that no tenant sets and no config row overrides, declared where
3
- * it is used.
4
- *
5
- * The runtime lattice answers "what does this tenant, in this region, for this order, get?" — and it
6
- * needs a store, a boot and an await to answer it. Most thresholds are not that question.
7
- * `LIVENESS_TIMEOUT_MS = 3000` decides behaviour in code and will never be tenant-settable; what it
8
- * is missing is not a lattice, it is an authority. That is all this tier adds, and the reason it
9
- * adds nothing else: a threshold whose declaration cost an async call and a port would go back to
10
- * being a number.
11
- */
1
+ /** A threshold no tenant sets and no config row overrides, declared where it is used. It adds an authority and nothing else, so declaring one never costs an async call and a port. */
12
2
  export interface ThresholdInput<Value> {
13
- /** Who or what set it: a person and a date, a contract, a standard, an incident. */
14
3
  readonly authority: string;
15
- /** Why this number and not another. The sentence the person who was just blocked needs. */
16
4
  readonly reason: string;
17
- /** ISO date. When somebody should look at it again; absent means the authority is permanent. */
18
5
  readonly revisit?: string;
19
- /** What it reaches. Absent where the name says it. */
20
6
  readonly subject?: string;
21
7
  readonly value: Value;
22
8
  }
@@ -24,22 +10,10 @@ declare const DECLARED: unique symbol;
24
10
  export type Threshold<Value> = {
25
11
  readonly [DECLARED]: true;
26
12
  } & Readonly<ThresholdInput<Value>>;
27
- /**
28
- * Declared, frozen, and refused where it is incomplete.
29
- *
30
- * The refusal is at the declaration and not at the first read, because a declaration runs when the
31
- * module loads: a threshold missing its authority breaks the boot of whatever imports it, which is
32
- * the earliest anyone can be told and the last moment it is cheap.
33
- */
13
+ /** Refused at the declaration, not at the first read: a threshold missing its authority breaks the boot of whatever imports it. */
34
14
  export declare const declareThreshold: <Value>(input: ThresholdInput<Value>) => Threshold<Value>;
35
15
  export declare const isThreshold: (value: unknown) => value is Threshold<unknown>;
36
- /**
37
- * The thresholds whose revisit date has passed.
38
- *
39
- * Reported, never thrown. A declaration that started failing the build on a date would have its
40
- * date deleted by the first person it stopped, and the tier would be back to numbers with prose
41
- * beside them.
42
- */
16
+ /** Reported, never thrown: a build that failed on a date would have the date deleted by the first person it stopped. */
43
17
  export declare const expiredThresholds: (thresholds: readonly Threshold<unknown>[], now: Date) => Threshold<unknown>[];
44
18
  export declare const describeThreshold: (threshold: Threshold<unknown>) => string;
45
19
  export {};
package/dist/threshold.js CHANGED
@@ -4,6 +4,10 @@ var ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
4
4
  var refuse = (what) => {
5
5
  throw new Error(`declareThreshold: ${what}. Next: give it one, or leave it as a plain constant and say why it needs no authority.`);
6
6
  };
7
+ var isCalendarDate = (value) => {
8
+ const at = new Date(`${value}T00:00:00Z`);
9
+ return ISO_DATE.test(value) && !Number.isNaN(at.getTime()) && at.toISOString().startsWith(value);
10
+ };
7
11
  var filled = (value) => typeof value === "string" && value.trim() !== "";
8
12
  var declareThreshold = (input) => {
9
13
  if (!filled(input.authority))
@@ -12,7 +16,7 @@ var declareThreshold = (input) => {
12
16
  refuse("a threshold with no reason cannot teach anyone what it is for");
13
17
  if (input.value === undefined)
14
18
  refuse("a threshold with no value decides nothing");
15
- if (input.revisit !== undefined && !ISO_DATE.test(input.revisit)) {
19
+ if (input.revisit !== undefined && !isCalendarDate(input.revisit)) {
16
20
  refuse(`revisit "${input.revisit}" is not an ISO date — a date nobody can compare never expires`);
17
21
  }
18
22
  return Object.freeze({ ...input, [DECLARED]: true });