@geonosis/policy 3.1.0 → 3.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.
Files changed (46) hide show
  1. package/CHANGELOG.md +13 -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
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # @geonosis/policy
2
2
 
3
+ ## 3.3.0
4
+
5
+ This package had no change of its own in 3.3.0. What the group changed under that number is in `GROUP-CHANGELOG.md`, in the `@geonosis/cli` package.
6
+
7
+ ## 3.2.0
8
+
9
+ ### Patch Changes
10
+
11
+ - 58eaf3a: Two equal authorities holding the same object with its keys in another order are no longer reported as a conflict.
12
+ - 58eaf3a: `refusalPrefix` is read as the literal text it is, `reversalVerbs` with the `g` or `y` flag read every reversal rather than alternating, and `curate` no longer changes the candidates it was handed.
13
+ - 58eaf3a: A role named `constructor`, `toString` or `__proto__` has been granted nothing, rather than throwing a `TypeError` when grants are held as a record.
14
+ - 58eaf3a: `declareThreshold` refuses a `revisit` that has the shape of an ISO date and is not one (`2026-13-01`, `2026-02-30`). The first never expired, the second rolled into March.
15
+
3
16
  ## 3.1.0
4
17
 
5
18
  No changes in this release.
@@ -1,14 +1,5 @@
1
1
  import type { PolicyAdapter, PolicyRuleRow } from './types.cjs';
2
- /**
3
- * One suite every storage adapter passes.
4
- *
5
- * A real Medusa module and a real drizzle table are the consumers' to run this against; what runs
6
- * here is a stub, which is the point — the checks are about what an adapter must MEAN, and neither
7
- * store's presence changes one of them.
8
- *
9
- * It answers with a report rather than an exit code: a gate that cannot say what it measured has
10
- * not been shown to measure anything.
11
- */
2
+ /** A report rather than an exit code: a gate that cannot say what it measured has not been shown to measure anything. */
12
3
  export type ConformanceCheck = {
13
4
  detail?: string;
14
5
  name: string;
@@ -20,7 +11,6 @@ export type ConformanceReport = {
20
11
  passed: boolean;
21
12
  };
22
13
  export type PolicyAdapterHarness = {
23
- /** An adapter whose store holds exactly this, and a way to read what its journal received. */
24
14
  create: (input: {
25
15
  config?: Record<string, unknown>;
26
16
  rows: readonly PolicyRuleRow[];
@@ -28,7 +18,6 @@ export type PolicyAdapterHarness = {
28
18
  adapter: PolicyAdapter;
29
19
  written: () => readonly unknown[];
30
20
  };
31
- /** An adapter over a store that is DOWN. Swallowing belongs inside the adapter, not around it. */
32
21
  createBroken: () => PolicyAdapter;
33
22
  name: string;
34
23
  };
@@ -1,14 +1,5 @@
1
1
  import type { PolicyAdapter, PolicyRuleRow } from './types.js';
2
- /**
3
- * One suite every storage adapter passes.
4
- *
5
- * A real Medusa module and a real drizzle table are the consumers' to run this against; what runs
6
- * here is a stub, which is the point — the checks are about what an adapter must MEAN, and neither
7
- * store's presence changes one of them.
8
- *
9
- * It answers with a report rather than an exit code: a gate that cannot say what it measured has
10
- * not been shown to measure anything.
11
- */
2
+ /** A report rather than an exit code: a gate that cannot say what it measured has not been shown to measure anything. */
12
3
  export type ConformanceCheck = {
13
4
  detail?: string;
14
5
  name: string;
@@ -20,7 +11,6 @@ export type ConformanceReport = {
20
11
  passed: boolean;
21
12
  };
22
13
  export type PolicyAdapterHarness = {
23
- /** An adapter whose store holds exactly this, and a way to read what its journal received. */
24
14
  create: (input: {
25
15
  config?: Record<string, unknown>;
26
16
  rows: readonly PolicyRuleRow[];
@@ -28,7 +18,6 @@ export type PolicyAdapterHarness = {
28
18
  adapter: PolicyAdapter;
29
19
  written: () => readonly unknown[];
30
20
  };
31
- /** An adapter over a store that is DOWN. Swallowing belongs inside the adapter, not around it. */
32
21
  createBroken: () => PolicyAdapter;
33
22
  name: string;
34
23
  };
package/dist/define.d.cts CHANGED
@@ -1,34 +1,14 @@
1
1
  import type { Policy, PolicyKindSpec, PolicyRule, PolicyTierSpec } from './types.cjs';
2
2
  export type PolicyInput = {
3
- /** What policy may constrain. A kind with no reader is an inert knob; a reader with no kind cannot be authored. */
4
3
  kinds: readonly (PolicyKindSpec | string)[];
5
- /**
6
- * May the overriding tier beat a rule that does not say either way?
7
- *
8
- * A Medusa storefront says yes (`rule.overridable !== false`), musa says no (`&& winner.overridable`).
9
- * Neither is wrong for the other's business, so it is declared rather than assumed.
10
- */
4
+ /** One consumer lets the overriding tier beat any rule that does not say no, another only a rule that says yes: declared, not assumed. */
11
5
  overridableByDefault?: boolean;
12
6
  rules?: readonly PolicyRule[];
13
- /** VAGUEST first — the weight of a key is derived from where it sits. */
14
7
  scopeKeys?: readonly string[];
15
- /** STRONGEST first. */
16
8
  tiers: readonly (PolicyTierSpec | string)[];
17
9
  };
18
- /**
19
- * Declare a policy: the authorities, the things they may constrain, the subjects they may be aimed
20
- * at, and — optionally — the rules themselves.
21
- *
22
- * A policy with no rules is INERT. Every read falls through to the caller's own constant and says
23
- * so, which is the posture the mechanism is built for: the loader is generic, the domain limits
24
- * live in data, and the kernel does nothing at all until someone writes a rule.
25
- */
26
10
  export declare const definePolicy: (input: PolicyInput) => Policy;
27
- /**
28
- * Holds a policy's declared scope order against the scope type's own key list, both directions and
29
- * in position — the checkable artefact that stops a key added alphabetically from silently
30
- * reordering the lattice. Call it once in a test beside the type.
31
- */
11
+ /** Holds the declared scope order against the scope type's key list, both directions and in position, so a key added alphabetically cannot reorder the lattice. */
32
12
  export declare const assertScopeOrder: (policy: {
33
13
  scopeKeys: readonly string[];
34
14
  }, expected: readonly string[]) => void;
package/dist/define.d.ts CHANGED
@@ -1,34 +1,14 @@
1
1
  import type { Policy, PolicyKindSpec, PolicyRule, PolicyTierSpec } from './types.js';
2
2
  export type PolicyInput = {
3
- /** What policy may constrain. A kind with no reader is an inert knob; a reader with no kind cannot be authored. */
4
3
  kinds: readonly (PolicyKindSpec | string)[];
5
- /**
6
- * May the overriding tier beat a rule that does not say either way?
7
- *
8
- * A Medusa storefront says yes (`rule.overridable !== false`), musa says no (`&& winner.overridable`).
9
- * Neither is wrong for the other's business, so it is declared rather than assumed.
10
- */
4
+ /** One consumer lets the overriding tier beat any rule that does not say no, another only a rule that says yes: declared, not assumed. */
11
5
  overridableByDefault?: boolean;
12
6
  rules?: readonly PolicyRule[];
13
- /** VAGUEST first — the weight of a key is derived from where it sits. */
14
7
  scopeKeys?: readonly string[];
15
- /** STRONGEST first. */
16
8
  tiers: readonly (PolicyTierSpec | string)[];
17
9
  };
18
- /**
19
- * Declare a policy: the authorities, the things they may constrain, the subjects they may be aimed
20
- * at, and — optionally — the rules themselves.
21
- *
22
- * A policy with no rules is INERT. Every read falls through to the caller's own constant and says
23
- * so, which is the posture the mechanism is built for: the loader is generic, the domain limits
24
- * live in data, and the kernel does nothing at all until someone writes a rule.
25
- */
26
10
  export declare const definePolicy: (input: PolicyInput) => Policy;
27
- /**
28
- * Holds a policy's declared scope order against the scope type's own key list, both directions and
29
- * in position — the checkable artefact that stops a key added alphabetically from silently
30
- * reordering the lattice. Call it once in a test beside the type.
31
- */
11
+ /** Holds the declared scope order against the scope type's key list, both directions and in position, so a key added alphabetically cannot reorder the lattice. */
32
12
  export declare const assertScopeOrder: (policy: {
33
13
  scopeKeys: readonly string[];
34
14
  }, expected: readonly string[]) => void;
@@ -64,26 +64,11 @@ var policyJournalColumns = {
64
64
  op: "text",
65
65
  subject: "text"
66
66
  };
67
- var attempt = async (what) => {
68
- try {
69
- return await what();
70
- } catch {
71
- return;
72
- }
73
- };
74
- var toRow = (entry) => ({
75
- actor_kind: "system",
76
- ...entry.rejected ? { error: `rejected ${JSON.stringify(entry.rejected.value)}: ${entry.rejected.reason}` } : {},
77
- event_name: entry.event,
78
- fell_back_to: { constraintKind: entry.kind, value: entry.fellBackTo },
79
- ...entry.op ? { op: entry.op } : {},
80
- ...entry.subject ? { subject: entry.subject } : {}
81
- });
82
67
  var createDrizzlePolicyAdapter = (options) => ({
83
- ...options.config ? { config: { get: async (kind, query) => attempt(() => options.config?.(kind, query)) } } : {},
68
+ ...options.config ? { config: { get: async (kind, query) => import_rows.attempt(() => options.config?.(kind, query)) } } : {},
84
69
  ...options.journal ? {
85
70
  journal: {
86
- write: async (entry) => void await attempt(() => options.journal?.(toRow(entry)))
71
+ write: async (entry) => void await import_rows.attempt(() => options.journal?.(import_rows.toJournalRow(entry)))
87
72
  }
88
73
  } : {},
89
74
  name: "drizzle",
@@ -1,14 +1,6 @@
1
1
  import type { Awaitable, PolicyAdapter, PolicyQuery, PolicyRuleRow } from '../types.cjs';
2
- /**
3
- * A drizzle table, behind the ports the kernel reads.
4
- *
5
- * Nothing here imports `drizzle-orm`. The query is the store's — a repo whose law says queries are
6
- * builders living in its own data layer would not accept one written in a dependency, and a package
7
- * that carried the ORM would be unusable in the other consumer's runtime. What this contributes is
8
- * the column contract, the mapping, and the posture: a store that is down answers with nothing and
9
- * changes no decision.
10
- */
11
- /** The columns the kernel reads. Declared once, so a table and a mapper cannot drift apart. */
2
+ /** Imports no `drizzle-orm`: the query belongs to the store's own data layer. This is the column contract, the mapping and the posture that a down store answers with nothing and changes no decision. */
3
+ /** Declared once, so a table and a mapper cannot drift apart. */
12
4
  export declare const policyRuleColumns: {
13
5
  readonly constraint_kind: 'text';
14
6
  readonly constraint_value: 'json';
@@ -19,7 +11,7 @@ export declare const policyRuleColumns: {
19
11
  readonly status: 'text';
20
12
  readonly tier: 'text';
21
13
  };
22
- /** The journal's columns. There is no `rejected` one: a rejection is written into `error`. */
14
+ /** No `rejected` column: a rejection is written into `error`. */
23
15
  export declare const policyJournalColumns: {
24
16
  readonly actor_id: 'text';
25
17
  readonly actor_kind: 'text';
@@ -1,14 +1,6 @@
1
1
  import type { Awaitable, PolicyAdapter, PolicyQuery, PolicyRuleRow } from '../types.js';
2
- /**
3
- * A drizzle table, behind the ports the kernel reads.
4
- *
5
- * Nothing here imports `drizzle-orm`. The query is the store's — a repo whose law says queries are
6
- * builders living in its own data layer would not accept one written in a dependency, and a package
7
- * that carried the ORM would be unusable in the other consumer's runtime. What this contributes is
8
- * the column contract, the mapping, and the posture: a store that is down answers with nothing and
9
- * changes no decision.
10
- */
11
- /** The columns the kernel reads. Declared once, so a table and a mapper cannot drift apart. */
2
+ /** Imports no `drizzle-orm`: the query belongs to the store's own data layer. This is the column contract, the mapping and the posture that a down store answers with nothing and changes no decision. */
3
+ /** Declared once, so a table and a mapper cannot drift apart. */
12
4
  export declare const policyRuleColumns: {
13
5
  readonly constraint_kind: 'text';
14
6
  readonly constraint_value: 'json';
@@ -19,7 +11,7 @@ export declare const policyRuleColumns: {
19
11
  readonly status: 'text';
20
12
  readonly tier: 'text';
21
13
  };
22
- /** The journal's columns. There is no `rejected` one: a rejection is written into `error`. */
14
+ /** No `rejected` column: a rejection is written into `error`. */
23
15
  export declare const policyJournalColumns: {
24
16
  readonly actor_id: 'text';
25
17
  readonly actor_kind: 'text';
@@ -1,5 +1,5 @@
1
1
  // src/drizzle/index.ts
2
- import { toPolicyRules } from "../rows.js";
2
+ import { attempt, toJournalRow, toPolicyRules } from "../rows.js";
3
3
  var policyRuleColumns = {
4
4
  constraint_kind: "text",
5
5
  constraint_value: "json",
@@ -19,26 +19,11 @@ var policyJournalColumns = {
19
19
  op: "text",
20
20
  subject: "text"
21
21
  };
22
- var attempt = async (what) => {
23
- try {
24
- return await what();
25
- } catch {
26
- return;
27
- }
28
- };
29
- var toRow = (entry) => ({
30
- actor_kind: "system",
31
- ...entry.rejected ? { error: `rejected ${JSON.stringify(entry.rejected.value)}: ${entry.rejected.reason}` } : {},
32
- event_name: entry.event,
33
- fell_back_to: { constraintKind: entry.kind, value: entry.fellBackTo },
34
- ...entry.op ? { op: entry.op } : {},
35
- ...entry.subject ? { subject: entry.subject } : {}
36
- });
37
22
  var createDrizzlePolicyAdapter = (options) => ({
38
23
  ...options.config ? { config: { get: async (kind, query) => attempt(() => options.config?.(kind, query)) } } : {},
39
24
  ...options.journal ? {
40
25
  journal: {
41
- write: async (entry) => void await attempt(() => options.journal?.(toRow(entry)))
26
+ write: async (entry) => void await attempt(() => options.journal?.(toJournalRow(entry)))
42
27
  }
43
28
  } : {},
44
29
  name: "drizzle",
@@ -1,4 +1,3 @@
1
- /** One journal row derived from something that happened. */
2
1
  export type DomainJournalRow = {
3
2
  actor_id: null | string;
4
3
  actor_kind: 'system' | 'user';
@@ -7,20 +6,8 @@ export type DomainJournalRow = {
7
6
  subject: string;
8
7
  };
9
8
  export type JournalRowOptions = {
10
- /** Where this build puts the human who caused it, when there is one. */
11
9
  actorKeys?: readonly string[];
12
- /** Where this build puts the id of the thing an event is about. */
13
10
  subjectKeys: readonly string[];
14
11
  };
15
- /**
16
- * The journal row for one domain event, or `null` when there is nothing countable to say.
17
- *
18
- * The learning loop reads four signals: a human reversing an automated decision, repeated refusals
19
- * of the same rule, readers falling back to their own defaults, and the same operation run over and
20
- * over. A reader journals its own fallbacks, so the third arrives on its own — the other three are
21
- * computed from things that HAPPENED, and without this they are computed over an empty table.
22
- *
23
- * The keys are the caller's, with no default: which field carries the id of the thing an event is
24
- * about is a fact about one system, and guessing would be quietly wrong rather than loudly absent.
25
- */
12
+ /** The keys are the caller's, with no default: which field carries the id of the thing an event is about is a fact about one system, and guessing would be quietly wrong. Without these rows the learning loop's reversal, refusal and recurring-operation signals are computed over an empty table. */
26
13
  export declare const journalRowForEvent: (eventName: string, data: unknown, options: JournalRowOptions) => DomainJournalRow | null;
@@ -1,4 +1,3 @@
1
- /** One journal row derived from something that happened. */
2
1
  export type DomainJournalRow = {
3
2
  actor_id: null | string;
4
3
  actor_kind: 'system' | 'user';
@@ -7,20 +6,8 @@ export type DomainJournalRow = {
7
6
  subject: string;
8
7
  };
9
8
  export type JournalRowOptions = {
10
- /** Where this build puts the human who caused it, when there is one. */
11
9
  actorKeys?: readonly string[];
12
- /** Where this build puts the id of the thing an event is about. */
13
10
  subjectKeys: readonly string[];
14
11
  };
15
- /**
16
- * The journal row for one domain event, or `null` when there is nothing countable to say.
17
- *
18
- * The learning loop reads four signals: a human reversing an automated decision, repeated refusals
19
- * of the same rule, readers falling back to their own defaults, and the same operation run over and
20
- * over. A reader journals its own fallbacks, so the third arrives on its own — the other three are
21
- * computed from things that HAPPENED, and without this they are computed over an empty table.
22
- *
23
- * The keys are the caller's, with no default: which field carries the id of the thing an event is
24
- * about is a fact about one system, and guessing would be quietly wrong rather than loudly absent.
25
- */
12
+ /** The keys are the caller's, with no default: which field carries the id of the thing an event is about is a fact about one system, and guessing would be quietly wrong. Without these rows the learning loop's reversal, refusal and recurring-operation signals are computed over an empty table. */
26
13
  export declare const journalRowForEvent: (eventName: string, data: unknown, options: JournalRowOptions) => DomainJournalRow | null;
package/dist/lattice.cjs CHANGED
@@ -103,7 +103,14 @@ var unsetKindsOf = (rules, kinds) => {
103
103
  const set = new Set(rules.map((rule) => rule.constraint.kind));
104
104
  return kinds.map((kind) => kind.kind).filter((kind) => !set.has(kind));
105
105
  };
106
- var sameValue = (kind, a, b) => kind?.sameValue ? kind.sameValue(a, b) : JSON.stringify(a) === JSON.stringify(b);
106
+ var withSortedKeys = (value) => {
107
+ if (Array.isArray(value))
108
+ return value.map(withSortedKeys);
109
+ if (typeof value !== "object" || value === null)
110
+ return value;
111
+ return Object.fromEntries(Object.entries(value).toSorted(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, one]) => [key, withSortedKeys(one)]));
112
+ };
113
+ var sameValue = (kind, a, b) => kind?.sameValue ? kind.sameValue(a, b) : JSON.stringify(withSortedKeys(a)) === JSON.stringify(withSortedKeys(b));
107
114
  var explainDecision = (winner, overrode, conflicts) => {
108
115
  const parts = [`${winner.id} (${winner.tier}) — ${winner.reason}`];
109
116
  if (overrode)
@@ -133,8 +140,9 @@ var resolveConstraint = (data, kind, query = {}, rules = data.rules) => {
133
140
  const mayBeOverridden = (rule) => tierOf(rule)?.overridable === true && (rule.overridable ?? data.overridableByDefault);
134
141
  const overrideTier = data.tiers.find((tier) => tier.overrides)?.name;
135
142
  const override = overrideTier ? sorted.find((rule) => rule.tier === overrideTier) : undefined;
136
- const overrode = override && override !== strongest && mayBeOverridden(strongest) ? strongest : undefined;
137
- const winner = overrode ? override : strongest;
143
+ const overrides = override !== undefined && override !== strongest && mayBeOverridden(strongest);
144
+ const overrode = overrides ? strongest : undefined;
145
+ const winner = overrides ? override : strongest;
138
146
  const suppressed = sorted.filter((rule) => rule !== winner);
139
147
  const kindSpec = data.kinds.find((spec) => spec.kind === kind);
140
148
  const conflicts = suppressed.filter((rule) => rank(rule.tier) === rank(winner.tier) && specificity(rule.scope) === specificity(winner.scope) && !sameValue(kindSpec, rule.constraint.value, winner.constraint.value));
@@ -1,35 +1,8 @@
1
1
  import type { PolicyData, PolicyDecision, PolicyKindSpec, PolicyQuery, PolicyRule, PolicyScope, UnusableRule } from './types.cjs';
2
- /**
3
- * The precedence lattice — deciding which authority wins when several speak at once.
4
- *
5
- * A business is governed by several at a time: law, a signed agreement, its own SOP, a buyer's
6
- * stated preference, the strategy currently running, an operator override typed at 6pm on a Friday.
7
- * They contradict each other constantly, so "which one wins" must not be an accident of evaluation
8
- * order — it is a declared ordering, and every decision carries a TRACE naming the winner and what
9
- * it suppressed.
10
- *
11
- * Nothing in this file names a tier, a kind or a scope key. Two consumers wrote this lattice
12
- * independently and disagreed on all three (a Medusa storefront's strongest tier is `regulatory`,
13
- * musa's is `physics`), which is why every one of them is data.
14
- */
15
- /**
16
- * The weight of a scope key, derived from where it was declared.
17
- *
18
- * Powers of two in declaration order, so a narrower key can never be outvoted by an accumulation of
19
- * vaguer ones: an order-scoped rule beats one scoped to region + category + group together, which
20
- * is the intent every time someone writes an order-scoped exception. Both consumers wrote exactly
21
- * that by hand and each needed a test to catch a key that had been given no weight at all — a rule
22
- * that matches but always loses. Deriving it designs the failure out.
23
- */
2
+ /** Nothing here names a tier, a kind or a scope key: two consumers wrote this lattice independently and disagreed on all three. */
3
+ /** Powers of two in declaration order, so a narrower key is never outvoted by an accumulation of vaguer ones. Deriving the weight designs out a key given none, which matches but always loses. */
24
4
  export declare const specificityOf: (scopeKeys: readonly string[], scope: PolicyScope | undefined) => number;
25
- /**
26
- * Does this rule reach this subject?
27
- *
28
- * A rule scoped on a key the query does not carry does NOT apply, and neither does one scoped on a
29
- * key this build has never heard of. That is the safe direction — a rule cannot reach a subject we
30
- * know nothing about — but refusing quietly is the same failure in a new coat, which is what
31
- * `unsupportedScopesOf` is for.
32
- */
5
+ /** A rule scoped on a key the query lacks, or one this build has never heard of, does not apply: the safe direction. `unsupportedScopesOf` makes the quiet refusal visible. */
33
6
  export declare const appliesTo: (rule: PolicyRule, query: PolicyQuery, scopeKeys: readonly string[]) => boolean;
34
7
  export declare const unsupportedScopesOf: (rules: readonly PolicyRule[], scopeKeys: readonly string[]) => {
35
8
  id: string;
@@ -38,11 +11,5 @@ export declare const unsupportedScopesOf: (rules: readonly PolicyRule[], scopeKe
38
11
  export declare const unusableRulesOf: (rules: readonly PolicyRule[], data: Pick<PolicyData, 'kinds' | 'tiers'>) => UnusableRule[];
39
12
  export declare const usableRulesOf: (rules: readonly PolicyRule[], data: Pick<PolicyData, 'kinds' | 'tiers'>) => PolicyRule[];
40
13
  export declare const unsetKindsOf: (rules: readonly PolicyRule[], kinds: readonly PolicyKindSpec[]) => string[];
41
- /**
42
- * Resolve one kind for one subject, with the whole trace.
43
- *
44
- * `undefined` when no rule speaks — silence is a legitimate answer and the caller's own default
45
- * takes over. Never a thrown error: a missing rule is the normal state of most subjects, and of
46
- * every subject in a build nobody has written a policy for yet.
47
- */
14
+ /** `undefined` when no rule speaks: silence is a legitimate answer, never a throw. */
48
15
  export declare const resolveConstraint: <V = unknown>(data: PolicyData, kind: string, query?: PolicyQuery, rules?: readonly PolicyRule[]) => PolicyDecision<V> | undefined;
package/dist/lattice.d.ts CHANGED
@@ -1,35 +1,8 @@
1
1
  import type { PolicyData, PolicyDecision, PolicyKindSpec, PolicyQuery, PolicyRule, PolicyScope, UnusableRule } from './types.js';
2
- /**
3
- * The precedence lattice — deciding which authority wins when several speak at once.
4
- *
5
- * A business is governed by several at a time: law, a signed agreement, its own SOP, a buyer's
6
- * stated preference, the strategy currently running, an operator override typed at 6pm on a Friday.
7
- * They contradict each other constantly, so "which one wins" must not be an accident of evaluation
8
- * order — it is a declared ordering, and every decision carries a TRACE naming the winner and what
9
- * it suppressed.
10
- *
11
- * Nothing in this file names a tier, a kind or a scope key. Two consumers wrote this lattice
12
- * independently and disagreed on all three (a Medusa storefront's strongest tier is `regulatory`,
13
- * musa's is `physics`), which is why every one of them is data.
14
- */
15
- /**
16
- * The weight of a scope key, derived from where it was declared.
17
- *
18
- * Powers of two in declaration order, so a narrower key can never be outvoted by an accumulation of
19
- * vaguer ones: an order-scoped rule beats one scoped to region + category + group together, which
20
- * is the intent every time someone writes an order-scoped exception. Both consumers wrote exactly
21
- * that by hand and each needed a test to catch a key that had been given no weight at all — a rule
22
- * that matches but always loses. Deriving it designs the failure out.
23
- */
2
+ /** Nothing here names a tier, a kind or a scope key: two consumers wrote this lattice independently and disagreed on all three. */
3
+ /** Powers of two in declaration order, so a narrower key is never outvoted by an accumulation of vaguer ones. Deriving the weight designs out a key given none, which matches but always loses. */
24
4
  export declare const specificityOf: (scopeKeys: readonly string[], scope: PolicyScope | undefined) => number;
25
- /**
26
- * Does this rule reach this subject?
27
- *
28
- * A rule scoped on a key the query does not carry does NOT apply, and neither does one scoped on a
29
- * key this build has never heard of. That is the safe direction — a rule cannot reach a subject we
30
- * know nothing about — but refusing quietly is the same failure in a new coat, which is what
31
- * `unsupportedScopesOf` is for.
32
- */
5
+ /** A rule scoped on a key the query lacks, or one this build has never heard of, does not apply: the safe direction. `unsupportedScopesOf` makes the quiet refusal visible. */
33
6
  export declare const appliesTo: (rule: PolicyRule, query: PolicyQuery, scopeKeys: readonly string[]) => boolean;
34
7
  export declare const unsupportedScopesOf: (rules: readonly PolicyRule[], scopeKeys: readonly string[]) => {
35
8
  id: string;
@@ -38,11 +11,5 @@ export declare const unsupportedScopesOf: (rules: readonly PolicyRule[], scopeKe
38
11
  export declare const unusableRulesOf: (rules: readonly PolicyRule[], data: Pick<PolicyData, 'kinds' | 'tiers'>) => UnusableRule[];
39
12
  export declare const usableRulesOf: (rules: readonly PolicyRule[], data: Pick<PolicyData, 'kinds' | 'tiers'>) => PolicyRule[];
40
13
  export declare const unsetKindsOf: (rules: readonly PolicyRule[], kinds: readonly PolicyKindSpec[]) => string[];
41
- /**
42
- * Resolve one kind for one subject, with the whole trace.
43
- *
44
- * `undefined` when no rule speaks — silence is a legitimate answer and the caller's own default
45
- * takes over. Never a thrown error: a missing rule is the normal state of most subjects, and of
46
- * every subject in a build nobody has written a policy for yet.
47
- */
14
+ /** `undefined` when no rule speaks: silence is a legitimate answer, never a throw. */
48
15
  export declare const resolveConstraint: <V = unknown>(data: PolicyData, kind: string, query?: PolicyQuery, rules?: readonly PolicyRule[]) => PolicyDecision<V> | undefined;
package/dist/lattice.js CHANGED
@@ -54,7 +54,14 @@ var unsetKindsOf = (rules, kinds) => {
54
54
  const set = new Set(rules.map((rule) => rule.constraint.kind));
55
55
  return kinds.map((kind) => kind.kind).filter((kind) => !set.has(kind));
56
56
  };
57
- var sameValue = (kind, a, b) => kind?.sameValue ? kind.sameValue(a, b) : JSON.stringify(a) === JSON.stringify(b);
57
+ var withSortedKeys = (value) => {
58
+ if (Array.isArray(value))
59
+ return value.map(withSortedKeys);
60
+ if (typeof value !== "object" || value === null)
61
+ return value;
62
+ return Object.fromEntries(Object.entries(value).toSorted(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, one]) => [key, withSortedKeys(one)]));
63
+ };
64
+ var sameValue = (kind, a, b) => kind?.sameValue ? kind.sameValue(a, b) : JSON.stringify(withSortedKeys(a)) === JSON.stringify(withSortedKeys(b));
58
65
  var explainDecision = (winner, overrode, conflicts) => {
59
66
  const parts = [`${winner.id} (${winner.tier}) — ${winner.reason}`];
60
67
  if (overrode)
@@ -84,8 +91,9 @@ var resolveConstraint = (data, kind, query = {}, rules = data.rules) => {
84
91
  const mayBeOverridden = (rule) => tierOf(rule)?.overridable === true && (rule.overridable ?? data.overridableByDefault);
85
92
  const overrideTier = data.tiers.find((tier) => tier.overrides)?.name;
86
93
  const override = overrideTier ? sorted.find((rule) => rule.tier === overrideTier) : undefined;
87
- const overrode = override && override !== strongest && mayBeOverridden(strongest) ? strongest : undefined;
88
- const winner = overrode ? override : strongest;
94
+ const overrides = override !== undefined && override !== strongest && mayBeOverridden(strongest);
95
+ const overrode = overrides ? strongest : undefined;
96
+ const winner = overrides ? override : strongest;
89
97
  const suppressed = sorted.filter((rule) => rule !== winner);
90
98
  const kindSpec = data.kinds.find((spec) => spec.kind === kind);
91
99
  const conflicts = suppressed.filter((rule) => rank(rule.tier) === rank(winner.tier) && specificity(rule.scope) === specificity(winner.scope) && !sameValue(kindSpec, rule.constraint.value, winner.constraint.value));
package/dist/learning.cjs CHANGED
@@ -86,10 +86,11 @@ var observeReversals = (entries, verbs) => {
86
86
  }
87
87
  return out;
88
88
  };
89
+ var escaped = (literal) => literal.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`);
89
90
  var observeRuleFriction = (entry, prefix) => {
90
91
  if (!entry.error)
91
92
  return [];
92
- const [, ruleId, detail] = new RegExp(`${prefix}: ([\\w:.-]+)(?: — (.*))?`).exec(entry.error) ?? [];
93
+ const [, ruleId, detail] = new RegExp(`${escaped(prefix)}: ([\\w:.-]+)(?: — (.*))?`).exec(entry.error) ?? [];
93
94
  if (!ruleId)
94
95
  return [];
95
96
  return [
@@ -132,8 +133,9 @@ var observeRecurringOps = (entries, minimum) => {
132
133
  statement: `"${op}" ran ${refs.length} times — save it as a named strategy`
133
134
  }));
134
135
  };
136
+ var unsticky = (verbs) => new RegExp(verbs.source, verbs.flags.replaceAll(/[gy]/g, ""));
135
137
  var observeJournal = (entries, options = {}) => [
136
- ...observeReversals(entries, options.reversalVerbs ?? DEFAULT_REVERSAL_VERBS),
138
+ ...observeReversals(entries, unsticky(options.reversalVerbs ?? DEFAULT_REVERSAL_VERBS)),
137
139
  ...entries.flatMap((entry) => [
138
140
  ...observeRuleFriction(entry, options.refusalPrefix ?? DEFAULT_REFUSAL_PREFIX),
139
141
  ...observeUnsetPolicy(entry)
@@ -170,8 +172,12 @@ var curate = (playbook, candidates) => {
170
172
  for (const candidate of candidates) {
171
173
  const existing = byId.get(candidate.id);
172
174
  if (!existing) {
173
- entries.push(candidate);
174
- byId.set(candidate.id, candidate);
175
+ const copy = {
176
+ ...candidate,
177
+ evidence: { ...candidate.evidence, journalRefs: [...candidate.evidence.journalRefs] }
178
+ };
179
+ entries.push(copy);
180
+ byId.set(copy.id, copy);
175
181
  continue;
176
182
  }
177
183
  if (existing.status === "demoted")
@@ -1,39 +1,9 @@
1
1
  import type { JournalObservationEntry, Policy, PolicyRule, PolicyScope } from './types.cjs';
2
- /**
3
- * The learning loop — a business improves from its own operations, visibly, versioned and
4
- * reversibly.
5
- *
6
- * Shaped after ACE (Generator / Reflector / Curator): the playbook EVOLVES by increments rather
7
- * than rewrites, which is what stops accumulated context from collapsing as it grows.
8
- *
9
- * observeJournal deterministic signal extraction — no model, fully testable. The strongest
10
- * signals are BEHAVIOURAL: a human reversing an automated decision is unambiguous
11
- * feedback in a way a survey never is.
12
- * reflect folds repeats into one candidate each. An agent may propose candidates too;
13
- * they enter through this same gate.
14
- * curate merges by stable id, ACCUMULATING evidence instead of overwriting statements.
15
- * promote evidence-gated. demote is always available and always recorded — auditable
16
- * unlearning is the point.
17
- *
18
- * The safety rail is the lattice: an active learning becomes a rule at the ADVISORY tier, which
19
- * can only ever fill silence. The loop can suggest; it can never quietly change what a business does.
20
- */
21
- export type LearningKind =
22
- /** A working practice worth repeating. */
23
- 'heuristic'
24
- /** A trap worth naming, so the next session starts knowing it. */
25
- | 'pitfall'
26
- /** Policy and the people running the business disagree, repeatedly. */
27
- | 'rule-friction'
28
- /** The same sequence keeps being run by hand — name it. */
29
- | 'macro'
30
- /** A knob that exists but nothing sets, so a hardcoded default rules instead. */
31
- | 'unset-policy';
2
+ /** ACE-shaped (Generator / Reflector / Curator): the playbook evolves by increments, not rewrites. `observeJournal` extracts deterministic signals, `reflect` folds repeats into candidates, curation merges them, and demotion is always available and recorded. */
3
+ export type LearningKind = 'heuristic' | 'pitfall' | 'rule-friction' | 'macro' | 'unset-policy';
32
4
  export type LearningStatus = 'active' | 'candidate' | 'demoted';
33
5
  export type LearningEvidence = {
34
- /** Ids of the journal entries that support it. */
35
6
  journalRefs: string[];
36
- /** Measured effect, when there is one. */
37
7
  metric?: {
38
8
  delta: number;
39
9
  name: string;
@@ -44,14 +14,12 @@ export type LearningEvidence = {
44
14
  export type Learning = {
45
15
  demotedReason?: string;
46
16
  evidence: LearningEvidence;
47
- /** Stable key — curation merges on this, so evidence accumulates. */
17
+ /** Curation merges on this key, so evidence accumulates. */
48
18
  id: string;
49
19
  kind: LearningKind;
50
20
  scope?: PolicyScope;
51
- /** What was learned, in words a human can audit and edit. */
52
21
  statement: string;
53
22
  status: LearningStatus;
54
- /** The advisory constraint this implies, if any. */
55
23
  suggests?: {
56
24
  kind: string;
57
25
  value: unknown;
@@ -73,32 +41,19 @@ export type Observation = {
73
41
  };
74
42
  };
75
43
  export declare const emptyPlaybook: () => Playbook;
76
- /** Repeated evidence, not one lucky quarter. */
77
44
  export declare const DEFAULT_MIN_OBSERVATIONS = 3;
78
45
  export declare class LearningError extends Error {
79
46
  readonly code: 'INSUFFICIENT_EVIDENCE' | 'UNKNOWN_LEARNING';
80
47
  constructor(code: 'INSUFFICIENT_EVIDENCE' | 'UNKNOWN_LEARNING', message: string);
81
48
  }
82
49
  export type ObserveOptions = {
83
- /** How few repeats of one operation are still a one-off. */
84
50
  minRepeatsForMacro?: number;
85
- /** The prefix a refusal carries, so friction is countable per rule. That word is a repo's own. */
86
51
  refusalPrefix?: string;
87
- /** What a human doing the undoing tends to call it. */
88
52
  reversalVerbs?: RegExp;
89
53
  };
90
- /**
91
- * The deterministic signals in a journal. Only behaviour that actually happened counts; nothing is
92
- * inferred from intent alone.
93
- */
94
54
  export declare const observeJournal: (entries: readonly JournalObservationEntry[], options?: ObserveOptions) => Observation[];
95
- /** Fold repeats into one candidate each — the statistical reflector. */
96
55
  export declare const reflect: (observations: readonly Observation[], now?: Date) => Learning[];
97
- /**
98
- * Merge candidates into the playbook. Evidence ACCUMULATES, and a statement is only refreshed while
99
- * the entry is still under review — an active learning's wording is stable, which is what makes the
100
- * playbook readable a year later.
101
- */
56
+ /** Evidence accumulates; wording is refreshed only while an entry is under review, so an active learning stays stable. */
102
57
  export declare const curate: (playbook: Playbook, candidates: readonly Learning[]) => Playbook;
103
58
  export declare const promote: (playbook: Playbook, id: string, options?: {
104
59
  metric?: {
@@ -107,15 +62,7 @@ export declare const promote: (playbook: Playbook, id: string, options?: {
107
62
  };
108
63
  minObservations?: number;
109
64
  }) => Playbook;
110
- /** Demotion is always available and always recorded — auditable unlearning. */
111
65
  export declare const demote: (playbook: Playbook, id: string, reason: string) => Playbook;
112
- /**
113
- * Active learnings that imply a constraint, as rules at the tier the policy calls advisory.
114
- *
115
- * A Medusa storefront writes `tier: 'learned'` into this function. Here the tier is read off the
116
- * lattice, because a policy that declares none has nowhere safe to put a suggestion — and quietly
117
- * choosing one would hand a suggestion the authority of an SOP.
118
- */
66
+ /** The tier is read off the lattice's advisory tier: guessing one would hand a suggestion the authority of an SOP. */
119
67
  export declare const playbookRules: (policy: Policy, playbook: Playbook) => PolicyRule[];
120
- /** The playbook as agent-readable guidance — a delta on top of a built prompt, never a replacement. */
121
68
  export declare const playbookGuidance: (playbook: Playbook) => string;