@geonosis/policy 2.13.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.
- package/CHANGELOG.md +4 -0
- package/dist/conformance.cjs +169 -0
- package/dist/conformance.d.cts +35 -0
- package/dist/conformance.d.ts +35 -0
- package/dist/conformance.js +129 -0
- package/dist/define.cjs +118 -0
- package/dist/define.d.cts +34 -0
- package/dist/define.d.ts +34 -0
- package/dist/define.js +85 -0
- package/dist/drizzle/index.cjs +37 -32
- package/dist/drizzle/index.d.cts +20 -23
- package/dist/drizzle/index.d.ts +20 -23
- package/dist/drizzle/index.js +2 -5
- package/dist/index.cjs +79 -856
- package/dist/index.d.cts +19 -428
- package/dist/index.d.ts +19 -428
- package/dist/index.js +35 -797
- package/dist/journal-events.cjs +68 -0
- package/dist/journal-events.d.cts +26 -0
- package/dist/journal-events.d.ts +26 -0
- package/dist/journal-events.js +28 -0
- package/dist/lattice.cjs +150 -0
- package/dist/lattice.d.cts +48 -0
- package/dist/lattice.d.ts +48 -0
- package/dist/lattice.js +110 -0
- package/dist/learning.cjs +246 -0
- package/dist/learning.d.cts +121 -0
- package/dist/learning.d.ts +121 -0
- package/dist/learning.js +206 -0
- package/dist/markdown.cjs +118 -0
- package/dist/markdown.d.cts +35 -0
- package/dist/markdown.d.ts +35 -0
- package/dist/markdown.js +78 -0
- package/dist/medusa/index.cjs +39 -36
- package/dist/medusa/index.d.cts +14 -16
- package/dist/medusa/index.d.ts +14 -16
- package/dist/medusa/index.js +4 -9
- package/dist/permissions/index.cjs +49 -40
- package/dist/permissions/index.d.cts +18 -20
- package/dist/permissions/index.d.ts +18 -20
- package/dist/permissions/index.js +15 -25
- package/dist/read.cjs +111 -0
- package/dist/read.d.cts +51 -0
- package/dist/read.d.ts +51 -0
- package/dist/read.js +71 -0
- package/dist/rows.cjs +54 -0
- package/dist/rows.d.cts +11 -0
- package/dist/rows.d.ts +11 -0
- package/dist/{chunk-JICJ4XEX.js → rows.js} +0 -3
- package/dist/seed.cjs +53 -0
- package/dist/seed.d.cts +18 -0
- package/dist/seed.d.ts +18 -0
- package/dist/seed.js +13 -0
- package/dist/threshold.cjs +73 -0
- package/dist/threshold.d.cts +45 -0
- package/dist/threshold.d.ts +45 -0
- package/dist/threshold.js +33 -0
- package/dist/types.cjs +47 -0
- package/dist/{types-C-Q3r-In.d.cts → types.d.cts} +21 -23
- package/dist/{types-C-Q3r-In.d.ts → types.d.ts} +21 -23
- package/dist/types.js +7 -0
- package/package.json +3 -3
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
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
|
+
}
|
|
29
|
+
var __export = (target, all) => {
|
|
30
|
+
for (var name in all)
|
|
31
|
+
__defProp(target, name, {
|
|
32
|
+
get: all[name],
|
|
33
|
+
enumerable: true,
|
|
34
|
+
configurable: true,
|
|
35
|
+
set: __exportSetter.bind(all, name)
|
|
36
|
+
});
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
// src/learning.ts
|
|
40
|
+
var exports_learning = {};
|
|
41
|
+
__export(exports_learning, {
|
|
42
|
+
DEFAULT_MIN_OBSERVATIONS: () => DEFAULT_MIN_OBSERVATIONS,
|
|
43
|
+
LearningError: () => LearningError,
|
|
44
|
+
curate: () => curate,
|
|
45
|
+
demote: () => demote,
|
|
46
|
+
emptyPlaybook: () => emptyPlaybook,
|
|
47
|
+
observeJournal: () => observeJournal,
|
|
48
|
+
playbookGuidance: () => playbookGuidance,
|
|
49
|
+
playbookRules: () => playbookRules,
|
|
50
|
+
promote: () => promote,
|
|
51
|
+
reflect: () => reflect
|
|
52
|
+
});
|
|
53
|
+
module.exports = __toCommonJS(exports_learning);
|
|
54
|
+
var emptyPlaybook = () => ({ entries: [], version: 0 });
|
|
55
|
+
var DEFAULT_MIN_OBSERVATIONS = 3;
|
|
56
|
+
|
|
57
|
+
class LearningError extends Error {
|
|
58
|
+
code;
|
|
59
|
+
constructor(code, message) {
|
|
60
|
+
super(`${code}: ${message}`);
|
|
61
|
+
this.code = code;
|
|
62
|
+
this.name = "LearningError";
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
var DEFAULT_REFUSAL_PREFIX = "POLICY_REFUSED";
|
|
66
|
+
var DEFAULT_REVERSAL_VERBS = /\b(override|revert|undo|cancel|reassign|reschedule)\b/i;
|
|
67
|
+
var observeReversals = (entries, verbs) => {
|
|
68
|
+
const out = [];
|
|
69
|
+
for (const [index, decided] of entries.entries()) {
|
|
70
|
+
const next = entries[index + 1];
|
|
71
|
+
if (!next)
|
|
72
|
+
continue;
|
|
73
|
+
if (decided.actor.kind === "user" || next.actor.kind !== "user")
|
|
74
|
+
continue;
|
|
75
|
+
if (!decided.subject || decided.subject !== next.subject)
|
|
76
|
+
continue;
|
|
77
|
+
if (!verbs.test(next.name))
|
|
78
|
+
continue;
|
|
79
|
+
const op = decided.op ?? decided.name;
|
|
80
|
+
out.push({
|
|
81
|
+
id: `reversed:${op}`,
|
|
82
|
+
journalRefs: [decided.id, next.id],
|
|
83
|
+
kind: "pitfall",
|
|
84
|
+
statement: `A person reversed the automated "${op}" on ${decided.subject} (via ${next.name}) — check the decision before repeating it`
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
return out;
|
|
88
|
+
};
|
|
89
|
+
var observeRuleFriction = (entry, prefix) => {
|
|
90
|
+
if (!entry.error)
|
|
91
|
+
return [];
|
|
92
|
+
const [, ruleId, detail] = new RegExp(`${prefix}: ([\\w:.-]+)(?: — (.*))?`).exec(entry.error) ?? [];
|
|
93
|
+
if (!ruleId)
|
|
94
|
+
return [];
|
|
95
|
+
return [
|
|
96
|
+
{
|
|
97
|
+
id: `friction:${ruleId}`,
|
|
98
|
+
journalRefs: [entry.id],
|
|
99
|
+
kind: "rule-friction",
|
|
100
|
+
statement: `Rule "${ruleId}" blocked an action again${detail ? ` — ${detail.slice(0, 140)}` : ""} — amend the rule or stop attempting it`
|
|
101
|
+
}
|
|
102
|
+
];
|
|
103
|
+
};
|
|
104
|
+
var observeUnsetPolicy = (entry) => {
|
|
105
|
+
const fell = entry.fellBackTo;
|
|
106
|
+
if (!fell)
|
|
107
|
+
return [];
|
|
108
|
+
return [
|
|
109
|
+
{
|
|
110
|
+
id: `unset:${fell.kind}`,
|
|
111
|
+
journalRefs: [entry.id],
|
|
112
|
+
kind: "unset-policy",
|
|
113
|
+
statement: `No rule sets "${fell.kind}", so the hardcoded default ${JSON.stringify(fell.value)} decided instead — write the rule or delete the knob`
|
|
114
|
+
}
|
|
115
|
+
];
|
|
116
|
+
};
|
|
117
|
+
var observeRecurringOps = (entries, minimum) => {
|
|
118
|
+
const byOp = new Map;
|
|
119
|
+
for (const entry of entries) {
|
|
120
|
+
if (entry.error || !entry.op)
|
|
121
|
+
continue;
|
|
122
|
+
const refs = byOp.get(entry.op);
|
|
123
|
+
if (refs)
|
|
124
|
+
refs.push(entry.id);
|
|
125
|
+
else
|
|
126
|
+
byOp.set(entry.op, [entry.id]);
|
|
127
|
+
}
|
|
128
|
+
return [...byOp].filter(([, refs]) => refs.length >= minimum).map(([op, refs]) => ({
|
|
129
|
+
id: `macro:${op}`,
|
|
130
|
+
journalRefs: refs,
|
|
131
|
+
kind: "macro",
|
|
132
|
+
statement: `"${op}" ran ${refs.length} times — save it as a named strategy`
|
|
133
|
+
}));
|
|
134
|
+
};
|
|
135
|
+
var observeJournal = (entries, options = {}) => [
|
|
136
|
+
...observeReversals(entries, options.reversalVerbs ?? DEFAULT_REVERSAL_VERBS),
|
|
137
|
+
...entries.flatMap((entry) => [
|
|
138
|
+
...observeRuleFriction(entry, options.refusalPrefix ?? DEFAULT_REFUSAL_PREFIX),
|
|
139
|
+
...observeUnsetPolicy(entry)
|
|
140
|
+
]),
|
|
141
|
+
...observeRecurringOps(entries, options.minRepeatsForMacro ?? 2)
|
|
142
|
+
];
|
|
143
|
+
var reflect = (observations, now = new Date) => {
|
|
144
|
+
const byId = new Map;
|
|
145
|
+
const at = now.toISOString();
|
|
146
|
+
for (const observation of observations) {
|
|
147
|
+
const existing = byId.get(observation.id);
|
|
148
|
+
if (existing) {
|
|
149
|
+
existing.evidence.observations += 1;
|
|
150
|
+
existing.evidence.journalRefs = [
|
|
151
|
+
...new Set([...existing.evidence.journalRefs, ...observation.journalRefs])
|
|
152
|
+
];
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
byId.set(observation.id, {
|
|
156
|
+
evidence: { journalRefs: [...observation.journalRefs], observations: 1, updatedAt: at },
|
|
157
|
+
id: observation.id,
|
|
158
|
+
kind: observation.kind,
|
|
159
|
+
...observation.scope ? { scope: observation.scope } : {},
|
|
160
|
+
statement: observation.statement,
|
|
161
|
+
status: "candidate",
|
|
162
|
+
...observation.suggests ? { suggests: observation.suggests } : {}
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
return [...byId.values()];
|
|
166
|
+
};
|
|
167
|
+
var curate = (playbook, candidates) => {
|
|
168
|
+
const entries = playbook.entries.map((entry) => ({ ...entry, evidence: { ...entry.evidence } }));
|
|
169
|
+
const byId = new Map(entries.map((entry) => [entry.id, entry]));
|
|
170
|
+
for (const candidate of candidates) {
|
|
171
|
+
const existing = byId.get(candidate.id);
|
|
172
|
+
if (!existing) {
|
|
173
|
+
entries.push(candidate);
|
|
174
|
+
byId.set(candidate.id, candidate);
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
if (existing.status === "demoted")
|
|
178
|
+
continue;
|
|
179
|
+
existing.evidence.observations += candidate.evidence.observations;
|
|
180
|
+
existing.evidence.journalRefs = [
|
|
181
|
+
...new Set([...existing.evidence.journalRefs, ...candidate.evidence.journalRefs])
|
|
182
|
+
];
|
|
183
|
+
existing.evidence.updatedAt = candidate.evidence.updatedAt;
|
|
184
|
+
if (existing.status === "candidate")
|
|
185
|
+
existing.statement = candidate.statement;
|
|
186
|
+
}
|
|
187
|
+
return { entries, version: playbook.version + 1 };
|
|
188
|
+
};
|
|
189
|
+
var promote = (playbook, id, options = {}) => {
|
|
190
|
+
const minimum = options.minObservations ?? DEFAULT_MIN_OBSERVATIONS;
|
|
191
|
+
const entry = playbook.entries.find((candidate) => candidate.id === id);
|
|
192
|
+
if (!entry)
|
|
193
|
+
throw new LearningError("UNKNOWN_LEARNING", `no learning "${id}"`);
|
|
194
|
+
if (entry.evidence.observations < minimum) {
|
|
195
|
+
throw new LearningError("INSUFFICIENT_EVIDENCE", `"${id}" has ${entry.evidence.observations} observation(s), needs ${minimum}`);
|
|
196
|
+
}
|
|
197
|
+
return {
|
|
198
|
+
entries: playbook.entries.map((candidate) => candidate.id === id ? {
|
|
199
|
+
...candidate,
|
|
200
|
+
evidence: {
|
|
201
|
+
...candidate.evidence,
|
|
202
|
+
...options.metric ? { metric: options.metric } : {}
|
|
203
|
+
},
|
|
204
|
+
status: "active"
|
|
205
|
+
} : candidate),
|
|
206
|
+
version: playbook.version + 1
|
|
207
|
+
};
|
|
208
|
+
};
|
|
209
|
+
var demote = (playbook, id, reason) => {
|
|
210
|
+
if (!playbook.entries.some((entry) => entry.id === id)) {
|
|
211
|
+
throw new LearningError("UNKNOWN_LEARNING", `no learning "${id}"`);
|
|
212
|
+
}
|
|
213
|
+
return {
|
|
214
|
+
entries: playbook.entries.map((entry) => entry.id === id ? { ...entry, demotedReason: reason, status: "demoted" } : entry),
|
|
215
|
+
version: playbook.version + 1
|
|
216
|
+
};
|
|
217
|
+
};
|
|
218
|
+
var playbookRules = (policy, playbook) => {
|
|
219
|
+
const advisory = policy.tiers.find((tier) => tier.advisory);
|
|
220
|
+
if (!advisory) {
|
|
221
|
+
throw new TypeError("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.");
|
|
222
|
+
}
|
|
223
|
+
return playbook.entries.flatMap((entry) => {
|
|
224
|
+
const suggests = entry.suggests;
|
|
225
|
+
if (entry.status !== "active" || !suggests)
|
|
226
|
+
return [];
|
|
227
|
+
return [
|
|
228
|
+
{
|
|
229
|
+
constraint: suggests,
|
|
230
|
+
id: `${advisory.name}:${entry.id}`,
|
|
231
|
+
reason: `${entry.statement} (${entry.evidence.observations} observations)`,
|
|
232
|
+
...entry.scope ? { scope: entry.scope } : {},
|
|
233
|
+
tier: advisory.name
|
|
234
|
+
}
|
|
235
|
+
];
|
|
236
|
+
});
|
|
237
|
+
};
|
|
238
|
+
var playbookGuidance = (playbook) => {
|
|
239
|
+
const active = playbook.entries.filter((entry) => entry.status === "active");
|
|
240
|
+
if (active.length === 0)
|
|
241
|
+
return "";
|
|
242
|
+
const lines = active.map((entry) => `- [${entry.kind}] ${entry.statement} (${entry.evidence.observations} observations)`);
|
|
243
|
+
return `Learned playbook (v${playbook.version}, advisory):
|
|
244
|
+
${lines.join(`
|
|
245
|
+
`)}`;
|
|
246
|
+
};
|
|
@@ -0,0 +1,121 @@
|
|
|
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';
|
|
32
|
+
export type LearningStatus = 'active' | 'candidate' | 'demoted';
|
|
33
|
+
export type LearningEvidence = {
|
|
34
|
+
/** Ids of the journal entries that support it. */
|
|
35
|
+
journalRefs: string[];
|
|
36
|
+
/** Measured effect, when there is one. */
|
|
37
|
+
metric?: {
|
|
38
|
+
delta: number;
|
|
39
|
+
name: string;
|
|
40
|
+
};
|
|
41
|
+
observations: number;
|
|
42
|
+
updatedAt: string;
|
|
43
|
+
};
|
|
44
|
+
export type Learning = {
|
|
45
|
+
demotedReason?: string;
|
|
46
|
+
evidence: LearningEvidence;
|
|
47
|
+
/** Stable key — curation merges on this, so evidence accumulates. */
|
|
48
|
+
id: string;
|
|
49
|
+
kind: LearningKind;
|
|
50
|
+
scope?: PolicyScope;
|
|
51
|
+
/** What was learned, in words a human can audit and edit. */
|
|
52
|
+
statement: string;
|
|
53
|
+
status: LearningStatus;
|
|
54
|
+
/** The advisory constraint this implies, if any. */
|
|
55
|
+
suggests?: {
|
|
56
|
+
kind: string;
|
|
57
|
+
value: unknown;
|
|
58
|
+
};
|
|
59
|
+
};
|
|
60
|
+
export type Playbook = {
|
|
61
|
+
entries: Learning[];
|
|
62
|
+
version: number;
|
|
63
|
+
};
|
|
64
|
+
export type Observation = {
|
|
65
|
+
id: string;
|
|
66
|
+
journalRefs: string[];
|
|
67
|
+
kind: LearningKind;
|
|
68
|
+
scope?: PolicyScope;
|
|
69
|
+
statement: string;
|
|
70
|
+
suggests?: {
|
|
71
|
+
kind: string;
|
|
72
|
+
value: unknown;
|
|
73
|
+
};
|
|
74
|
+
};
|
|
75
|
+
export declare const emptyPlaybook: () => Playbook;
|
|
76
|
+
/** Repeated evidence, not one lucky quarter. */
|
|
77
|
+
export declare const DEFAULT_MIN_OBSERVATIONS = 3;
|
|
78
|
+
export declare class LearningError extends Error {
|
|
79
|
+
readonly code: 'INSUFFICIENT_EVIDENCE' | 'UNKNOWN_LEARNING';
|
|
80
|
+
constructor(code: 'INSUFFICIENT_EVIDENCE' | 'UNKNOWN_LEARNING', message: string);
|
|
81
|
+
}
|
|
82
|
+
export type ObserveOptions = {
|
|
83
|
+
/** How few repeats of one operation are still a one-off. */
|
|
84
|
+
minRepeatsForMacro?: number;
|
|
85
|
+
/** The prefix a refusal carries, so friction is countable per rule. That word is a repo's own. */
|
|
86
|
+
refusalPrefix?: string;
|
|
87
|
+
/** What a human doing the undoing tends to call it. */
|
|
88
|
+
reversalVerbs?: RegExp;
|
|
89
|
+
};
|
|
90
|
+
/**
|
|
91
|
+
* The deterministic signals in a journal. Only behaviour that actually happened counts; nothing is
|
|
92
|
+
* inferred from intent alone.
|
|
93
|
+
*/
|
|
94
|
+
export declare const observeJournal: (entries: readonly JournalObservationEntry[], options?: ObserveOptions) => Observation[];
|
|
95
|
+
/** Fold repeats into one candidate each — the statistical reflector. */
|
|
96
|
+
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
|
+
*/
|
|
102
|
+
export declare const curate: (playbook: Playbook, candidates: readonly Learning[]) => Playbook;
|
|
103
|
+
export declare const promote: (playbook: Playbook, id: string, options?: {
|
|
104
|
+
metric?: {
|
|
105
|
+
delta: number;
|
|
106
|
+
name: string;
|
|
107
|
+
};
|
|
108
|
+
minObservations?: number;
|
|
109
|
+
}) => Playbook;
|
|
110
|
+
/** Demotion is always available and always recorded — auditable unlearning. */
|
|
111
|
+
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
|
+
*/
|
|
119
|
+
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
|
+
export declare const playbookGuidance: (playbook: Playbook) => string;
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import type { JournalObservationEntry, Policy, PolicyRule, PolicyScope } from './types.js';
|
|
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';
|
|
32
|
+
export type LearningStatus = 'active' | 'candidate' | 'demoted';
|
|
33
|
+
export type LearningEvidence = {
|
|
34
|
+
/** Ids of the journal entries that support it. */
|
|
35
|
+
journalRefs: string[];
|
|
36
|
+
/** Measured effect, when there is one. */
|
|
37
|
+
metric?: {
|
|
38
|
+
delta: number;
|
|
39
|
+
name: string;
|
|
40
|
+
};
|
|
41
|
+
observations: number;
|
|
42
|
+
updatedAt: string;
|
|
43
|
+
};
|
|
44
|
+
export type Learning = {
|
|
45
|
+
demotedReason?: string;
|
|
46
|
+
evidence: LearningEvidence;
|
|
47
|
+
/** Stable key — curation merges on this, so evidence accumulates. */
|
|
48
|
+
id: string;
|
|
49
|
+
kind: LearningKind;
|
|
50
|
+
scope?: PolicyScope;
|
|
51
|
+
/** What was learned, in words a human can audit and edit. */
|
|
52
|
+
statement: string;
|
|
53
|
+
status: LearningStatus;
|
|
54
|
+
/** The advisory constraint this implies, if any. */
|
|
55
|
+
suggests?: {
|
|
56
|
+
kind: string;
|
|
57
|
+
value: unknown;
|
|
58
|
+
};
|
|
59
|
+
};
|
|
60
|
+
export type Playbook = {
|
|
61
|
+
entries: Learning[];
|
|
62
|
+
version: number;
|
|
63
|
+
};
|
|
64
|
+
export type Observation = {
|
|
65
|
+
id: string;
|
|
66
|
+
journalRefs: string[];
|
|
67
|
+
kind: LearningKind;
|
|
68
|
+
scope?: PolicyScope;
|
|
69
|
+
statement: string;
|
|
70
|
+
suggests?: {
|
|
71
|
+
kind: string;
|
|
72
|
+
value: unknown;
|
|
73
|
+
};
|
|
74
|
+
};
|
|
75
|
+
export declare const emptyPlaybook: () => Playbook;
|
|
76
|
+
/** Repeated evidence, not one lucky quarter. */
|
|
77
|
+
export declare const DEFAULT_MIN_OBSERVATIONS = 3;
|
|
78
|
+
export declare class LearningError extends Error {
|
|
79
|
+
readonly code: 'INSUFFICIENT_EVIDENCE' | 'UNKNOWN_LEARNING';
|
|
80
|
+
constructor(code: 'INSUFFICIENT_EVIDENCE' | 'UNKNOWN_LEARNING', message: string);
|
|
81
|
+
}
|
|
82
|
+
export type ObserveOptions = {
|
|
83
|
+
/** How few repeats of one operation are still a one-off. */
|
|
84
|
+
minRepeatsForMacro?: number;
|
|
85
|
+
/** The prefix a refusal carries, so friction is countable per rule. That word is a repo's own. */
|
|
86
|
+
refusalPrefix?: string;
|
|
87
|
+
/** What a human doing the undoing tends to call it. */
|
|
88
|
+
reversalVerbs?: RegExp;
|
|
89
|
+
};
|
|
90
|
+
/**
|
|
91
|
+
* The deterministic signals in a journal. Only behaviour that actually happened counts; nothing is
|
|
92
|
+
* inferred from intent alone.
|
|
93
|
+
*/
|
|
94
|
+
export declare const observeJournal: (entries: readonly JournalObservationEntry[], options?: ObserveOptions) => Observation[];
|
|
95
|
+
/** Fold repeats into one candidate each — the statistical reflector. */
|
|
96
|
+
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
|
+
*/
|
|
102
|
+
export declare const curate: (playbook: Playbook, candidates: readonly Learning[]) => Playbook;
|
|
103
|
+
export declare const promote: (playbook: Playbook, id: string, options?: {
|
|
104
|
+
metric?: {
|
|
105
|
+
delta: number;
|
|
106
|
+
name: string;
|
|
107
|
+
};
|
|
108
|
+
minObservations?: number;
|
|
109
|
+
}) => Playbook;
|
|
110
|
+
/** Demotion is always available and always recorded — auditable unlearning. */
|
|
111
|
+
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
|
+
*/
|
|
119
|
+
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
|
+
export declare const playbookGuidance: (playbook: Playbook) => string;
|
package/dist/learning.js
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
// src/learning.ts
|
|
2
|
+
var emptyPlaybook = () => ({ entries: [], version: 0 });
|
|
3
|
+
var DEFAULT_MIN_OBSERVATIONS = 3;
|
|
4
|
+
|
|
5
|
+
class LearningError extends Error {
|
|
6
|
+
code;
|
|
7
|
+
constructor(code, message) {
|
|
8
|
+
super(`${code}: ${message}`);
|
|
9
|
+
this.code = code;
|
|
10
|
+
this.name = "LearningError";
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
var DEFAULT_REFUSAL_PREFIX = "POLICY_REFUSED";
|
|
14
|
+
var DEFAULT_REVERSAL_VERBS = /\b(override|revert|undo|cancel|reassign|reschedule)\b/i;
|
|
15
|
+
var observeReversals = (entries, verbs) => {
|
|
16
|
+
const out = [];
|
|
17
|
+
for (const [index, decided] of entries.entries()) {
|
|
18
|
+
const next = entries[index + 1];
|
|
19
|
+
if (!next)
|
|
20
|
+
continue;
|
|
21
|
+
if (decided.actor.kind === "user" || next.actor.kind !== "user")
|
|
22
|
+
continue;
|
|
23
|
+
if (!decided.subject || decided.subject !== next.subject)
|
|
24
|
+
continue;
|
|
25
|
+
if (!verbs.test(next.name))
|
|
26
|
+
continue;
|
|
27
|
+
const op = decided.op ?? decided.name;
|
|
28
|
+
out.push({
|
|
29
|
+
id: `reversed:${op}`,
|
|
30
|
+
journalRefs: [decided.id, next.id],
|
|
31
|
+
kind: "pitfall",
|
|
32
|
+
statement: `A person reversed the automated "${op}" on ${decided.subject} (via ${next.name}) — check the decision before repeating it`
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
return out;
|
|
36
|
+
};
|
|
37
|
+
var observeRuleFriction = (entry, prefix) => {
|
|
38
|
+
if (!entry.error)
|
|
39
|
+
return [];
|
|
40
|
+
const [, ruleId, detail] = new RegExp(`${prefix}: ([\\w:.-]+)(?: — (.*))?`).exec(entry.error) ?? [];
|
|
41
|
+
if (!ruleId)
|
|
42
|
+
return [];
|
|
43
|
+
return [
|
|
44
|
+
{
|
|
45
|
+
id: `friction:${ruleId}`,
|
|
46
|
+
journalRefs: [entry.id],
|
|
47
|
+
kind: "rule-friction",
|
|
48
|
+
statement: `Rule "${ruleId}" blocked an action again${detail ? ` — ${detail.slice(0, 140)}` : ""} — amend the rule or stop attempting it`
|
|
49
|
+
}
|
|
50
|
+
];
|
|
51
|
+
};
|
|
52
|
+
var observeUnsetPolicy = (entry) => {
|
|
53
|
+
const fell = entry.fellBackTo;
|
|
54
|
+
if (!fell)
|
|
55
|
+
return [];
|
|
56
|
+
return [
|
|
57
|
+
{
|
|
58
|
+
id: `unset:${fell.kind}`,
|
|
59
|
+
journalRefs: [entry.id],
|
|
60
|
+
kind: "unset-policy",
|
|
61
|
+
statement: `No rule sets "${fell.kind}", so the hardcoded default ${JSON.stringify(fell.value)} decided instead — write the rule or delete the knob`
|
|
62
|
+
}
|
|
63
|
+
];
|
|
64
|
+
};
|
|
65
|
+
var observeRecurringOps = (entries, minimum) => {
|
|
66
|
+
const byOp = new Map;
|
|
67
|
+
for (const entry of entries) {
|
|
68
|
+
if (entry.error || !entry.op)
|
|
69
|
+
continue;
|
|
70
|
+
const refs = byOp.get(entry.op);
|
|
71
|
+
if (refs)
|
|
72
|
+
refs.push(entry.id);
|
|
73
|
+
else
|
|
74
|
+
byOp.set(entry.op, [entry.id]);
|
|
75
|
+
}
|
|
76
|
+
return [...byOp].filter(([, refs]) => refs.length >= minimum).map(([op, refs]) => ({
|
|
77
|
+
id: `macro:${op}`,
|
|
78
|
+
journalRefs: refs,
|
|
79
|
+
kind: "macro",
|
|
80
|
+
statement: `"${op}" ran ${refs.length} times — save it as a named strategy`
|
|
81
|
+
}));
|
|
82
|
+
};
|
|
83
|
+
var observeJournal = (entries, options = {}) => [
|
|
84
|
+
...observeReversals(entries, options.reversalVerbs ?? DEFAULT_REVERSAL_VERBS),
|
|
85
|
+
...entries.flatMap((entry) => [
|
|
86
|
+
...observeRuleFriction(entry, options.refusalPrefix ?? DEFAULT_REFUSAL_PREFIX),
|
|
87
|
+
...observeUnsetPolicy(entry)
|
|
88
|
+
]),
|
|
89
|
+
...observeRecurringOps(entries, options.minRepeatsForMacro ?? 2)
|
|
90
|
+
];
|
|
91
|
+
var reflect = (observations, now = new Date) => {
|
|
92
|
+
const byId = new Map;
|
|
93
|
+
const at = now.toISOString();
|
|
94
|
+
for (const observation of observations) {
|
|
95
|
+
const existing = byId.get(observation.id);
|
|
96
|
+
if (existing) {
|
|
97
|
+
existing.evidence.observations += 1;
|
|
98
|
+
existing.evidence.journalRefs = [
|
|
99
|
+
...new Set([...existing.evidence.journalRefs, ...observation.journalRefs])
|
|
100
|
+
];
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
byId.set(observation.id, {
|
|
104
|
+
evidence: { journalRefs: [...observation.journalRefs], observations: 1, updatedAt: at },
|
|
105
|
+
id: observation.id,
|
|
106
|
+
kind: observation.kind,
|
|
107
|
+
...observation.scope ? { scope: observation.scope } : {},
|
|
108
|
+
statement: observation.statement,
|
|
109
|
+
status: "candidate",
|
|
110
|
+
...observation.suggests ? { suggests: observation.suggests } : {}
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
return [...byId.values()];
|
|
114
|
+
};
|
|
115
|
+
var curate = (playbook, candidates) => {
|
|
116
|
+
const entries = playbook.entries.map((entry) => ({ ...entry, evidence: { ...entry.evidence } }));
|
|
117
|
+
const byId = new Map(entries.map((entry) => [entry.id, entry]));
|
|
118
|
+
for (const candidate of candidates) {
|
|
119
|
+
const existing = byId.get(candidate.id);
|
|
120
|
+
if (!existing) {
|
|
121
|
+
entries.push(candidate);
|
|
122
|
+
byId.set(candidate.id, candidate);
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
if (existing.status === "demoted")
|
|
126
|
+
continue;
|
|
127
|
+
existing.evidence.observations += candidate.evidence.observations;
|
|
128
|
+
existing.evidence.journalRefs = [
|
|
129
|
+
...new Set([...existing.evidence.journalRefs, ...candidate.evidence.journalRefs])
|
|
130
|
+
];
|
|
131
|
+
existing.evidence.updatedAt = candidate.evidence.updatedAt;
|
|
132
|
+
if (existing.status === "candidate")
|
|
133
|
+
existing.statement = candidate.statement;
|
|
134
|
+
}
|
|
135
|
+
return { entries, version: playbook.version + 1 };
|
|
136
|
+
};
|
|
137
|
+
var promote = (playbook, id, options = {}) => {
|
|
138
|
+
const minimum = options.minObservations ?? DEFAULT_MIN_OBSERVATIONS;
|
|
139
|
+
const entry = playbook.entries.find((candidate) => candidate.id === id);
|
|
140
|
+
if (!entry)
|
|
141
|
+
throw new LearningError("UNKNOWN_LEARNING", `no learning "${id}"`);
|
|
142
|
+
if (entry.evidence.observations < minimum) {
|
|
143
|
+
throw new LearningError("INSUFFICIENT_EVIDENCE", `"${id}" has ${entry.evidence.observations} observation(s), needs ${minimum}`);
|
|
144
|
+
}
|
|
145
|
+
return {
|
|
146
|
+
entries: playbook.entries.map((candidate) => candidate.id === id ? {
|
|
147
|
+
...candidate,
|
|
148
|
+
evidence: {
|
|
149
|
+
...candidate.evidence,
|
|
150
|
+
...options.metric ? { metric: options.metric } : {}
|
|
151
|
+
},
|
|
152
|
+
status: "active"
|
|
153
|
+
} : candidate),
|
|
154
|
+
version: playbook.version + 1
|
|
155
|
+
};
|
|
156
|
+
};
|
|
157
|
+
var demote = (playbook, id, reason) => {
|
|
158
|
+
if (!playbook.entries.some((entry) => entry.id === id)) {
|
|
159
|
+
throw new LearningError("UNKNOWN_LEARNING", `no learning "${id}"`);
|
|
160
|
+
}
|
|
161
|
+
return {
|
|
162
|
+
entries: playbook.entries.map((entry) => entry.id === id ? { ...entry, demotedReason: reason, status: "demoted" } : entry),
|
|
163
|
+
version: playbook.version + 1
|
|
164
|
+
};
|
|
165
|
+
};
|
|
166
|
+
var playbookRules = (policy, playbook) => {
|
|
167
|
+
const advisory = policy.tiers.find((tier) => tier.advisory);
|
|
168
|
+
if (!advisory) {
|
|
169
|
+
throw new TypeError("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.");
|
|
170
|
+
}
|
|
171
|
+
return playbook.entries.flatMap((entry) => {
|
|
172
|
+
const suggests = entry.suggests;
|
|
173
|
+
if (entry.status !== "active" || !suggests)
|
|
174
|
+
return [];
|
|
175
|
+
return [
|
|
176
|
+
{
|
|
177
|
+
constraint: suggests,
|
|
178
|
+
id: `${advisory.name}:${entry.id}`,
|
|
179
|
+
reason: `${entry.statement} (${entry.evidence.observations} observations)`,
|
|
180
|
+
...entry.scope ? { scope: entry.scope } : {},
|
|
181
|
+
tier: advisory.name
|
|
182
|
+
}
|
|
183
|
+
];
|
|
184
|
+
});
|
|
185
|
+
};
|
|
186
|
+
var playbookGuidance = (playbook) => {
|
|
187
|
+
const active = playbook.entries.filter((entry) => entry.status === "active");
|
|
188
|
+
if (active.length === 0)
|
|
189
|
+
return "";
|
|
190
|
+
const lines = active.map((entry) => `- [${entry.kind}] ${entry.statement} (${entry.evidence.observations} observations)`);
|
|
191
|
+
return `Learned playbook (v${playbook.version}, advisory):
|
|
192
|
+
${lines.join(`
|
|
193
|
+
`)}`;
|
|
194
|
+
};
|
|
195
|
+
export {
|
|
196
|
+
DEFAULT_MIN_OBSERVATIONS,
|
|
197
|
+
LearningError,
|
|
198
|
+
curate,
|
|
199
|
+
demote,
|
|
200
|
+
emptyPlaybook,
|
|
201
|
+
observeJournal,
|
|
202
|
+
playbookGuidance,
|
|
203
|
+
playbookRules,
|
|
204
|
+
promote,
|
|
205
|
+
reflect
|
|
206
|
+
};
|