principles-disciple 1.146.0 → 1.148.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.
|
@@ -1,82 +1,30 @@
|
|
|
1
|
-
import type { Implementation, ImplementationLifecycleState, Principle, PrincipleTreeStore, PrincipleValueMetrics, Rule } from '../types/principle-tree-schema.js';
|
|
2
|
-
export declare const TREE_NAMESPACE = "_tree";
|
|
3
|
-
export interface LegacyPrincipleTrainingState {
|
|
4
|
-
principleId: string;
|
|
5
|
-
evaluability: 'deterministic' | 'weak_heuristic' | 'manual_only';
|
|
6
|
-
applicableOpportunityCount: number;
|
|
7
|
-
observedViolationCount: number;
|
|
8
|
-
complianceRate: number;
|
|
9
|
-
violationTrend: number;
|
|
10
|
-
generatedSampleCount: number;
|
|
11
|
-
approvedSampleCount: number;
|
|
12
|
-
includedTrainRunIds: string[];
|
|
13
|
-
deployedCheckpointIds: string[];
|
|
14
|
-
lastEvalScore?: number;
|
|
15
|
-
internalizationStatus: 'prompt_only' | 'needs_training' | 'in_training' | 'deployed_pending_eval' | 'internalized' | 'regressed';
|
|
16
|
-
}
|
|
17
|
-
export type LegacyPrincipleTrainingStore = Record<string, LegacyPrincipleTrainingState>;
|
|
18
|
-
export interface LedgerPrinciple extends Principle {
|
|
19
|
-
suggestedRules?: string[];
|
|
20
|
-
}
|
|
21
|
-
export interface LedgerRule extends Rule {
|
|
22
|
-
implementationIds: string[];
|
|
23
|
-
}
|
|
24
|
-
export interface LedgerTreeStore extends Omit<PrincipleTreeStore, 'principles' | 'rules'> {
|
|
25
|
-
principles: Record<string, LedgerPrinciple>;
|
|
26
|
-
rules: Record<string, LedgerRule>;
|
|
27
|
-
}
|
|
28
|
-
export interface HybridLedgerStore {
|
|
29
|
-
trainingStore: LegacyPrincipleTrainingStore;
|
|
30
|
-
tree: LedgerTreeStore;
|
|
31
|
-
}
|
|
32
|
-
export interface PrincipleSubtree {
|
|
33
|
-
principle: LedgerPrinciple;
|
|
34
|
-
rules: {
|
|
35
|
-
rule: LedgerRule;
|
|
36
|
-
implementations: Implementation[];
|
|
37
|
-
}[];
|
|
38
|
-
}
|
|
39
|
-
export declare function getLedgerFilePath(stateDir: string): string;
|
|
40
|
-
export declare function loadLedger(stateDir: string): HybridLedgerStore;
|
|
41
|
-
export declare function saveLedger(stateDir: string, store: HybridLedgerStore): void;
|
|
42
|
-
export declare function saveLedgerAsync(stateDir: string, store: HybridLedgerStore): Promise<void>;
|
|
43
|
-
export declare function updateTrainingStore(stateDir: string, mutate: (store: LegacyPrincipleTrainingStore) => void): void;
|
|
44
1
|
/**
|
|
45
|
-
*
|
|
46
|
-
* This is the companion to updatePrinciple() — use this when creating a NEW
|
|
47
|
-
* principle so the compiler can find it in tree.principles.
|
|
2
|
+
* Principle Tree Ledger — plugin adapter (re-export) over @principles/core.
|
|
48
3
|
*
|
|
49
|
-
*
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
*
|
|
64
|
-
*
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
*
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
* Transition an implementation's lifecycle state with validation.
|
|
73
|
-
* Throws on invalid transitions */
|
|
74
|
-
export declare function transitionImplementationState(stateDir: string, implementationId: string, newState: ImplementationLifecycleState): Implementation;
|
|
75
|
-
/**
|
|
76
|
-
* Get implementations in a specific lifecycle state for a given rule.
|
|
77
|
-
*/
|
|
78
|
-
export declare function listRuleImplementationsByState(stateDir: string, ruleId: string, state: ImplementationLifecycleState): Implementation[];
|
|
79
|
-
/**
|
|
80
|
-
* Find active implementation for a rule (helper for rule host lookup).
|
|
4
|
+
* PRI-459: This file WAS a full duplicate implementation of
|
|
5
|
+
* principle_training_state.json parsing / serialization / mutation (~600
|
|
6
|
+
* lines of inlined parsers, serializers, mutators, and a parallel codec).
|
|
7
|
+
* That dual ownership caused two real failure classes:
|
|
8
|
+
*
|
|
9
|
+
* 1. Lost updates — core wrote the file UNLOCKED, the plugin wrote it WITH
|
|
10
|
+
* a lock, and neither knew the other's lock. Concurrent writers (e.g.
|
|
11
|
+
* evolution-worker async + a pd-cli command) could silently drop edits.
|
|
12
|
+
* 2. Silent field loss — the two codecs parsed the same bytes at different
|
|
13
|
+
* strictness; a field one side persisted could be dropped on the next
|
|
14
|
+
* load by the other.
|
|
15
|
+
*
|
|
16
|
+
* Both are now fixed by converging on a SINGLE source of truth in core:
|
|
17
|
+
* - parse/serialize: @principles/core/runtime-v2/principle-tree/ledger-codec
|
|
18
|
+
* - mutation (with cross-process file lock): @principles/core/principle-tree-ledger
|
|
19
|
+
*
|
|
20
|
+
* This file is now a thin re-export so existing relative imports
|
|
21
|
+
* (`from './principle-tree-ledger.js'`) keep resolving. Consumers get the
|
|
22
|
+
* exact same API surface, now backed by the locked core implementation.
|
|
23
|
+
*
|
|
24
|
+
* Do NOT reintroduce parsing / serialization / mutation logic here. The
|
|
25
|
+
* architecture-regression guard "PRI-459: single principle_training_state
|
|
26
|
+
* ledger implementation" enforces this.
|
|
81
27
|
*/
|
|
82
|
-
export
|
|
28
|
+
export { type Principle, type Rule, type Implementation, type PrincipleValueMetrics, type LedgerPrinciple, type LedgerRule, type LedgerTreeStore, type LegacyPrincipleTrainingState, type LegacyPrincipleTrainingStore, type HybridLedgerStore, type ImplementationLifecycleState, type PrincipleSubtree, TREE_NAMESPACE, LockAcquisitionError, loadLedger, saveLedger, saveLedgerAsync, updateTrainingStore, addPrincipleToLedger, createRule, createImplementation, updatePrinciple, updateRule, deleteRule, updateImplementation, deleteImplementation, listImplementationsForRule, getPrincipleSubtree, updatePrincipleValueMetrics, isValidLifecycleTransition, getAllowedTransitions, transitionImplementationState, listRuleImplementationsByState, findActiveImplementation, } from '@principles/core/principle-tree-ledger';
|
|
29
|
+
import { getLedgerFilePathPublic } from '@principles/core/principle-tree-ledger';
|
|
30
|
+
export declare const getLedgerFilePath: typeof getLedgerFilePathPublic;
|
|
@@ -1,527 +1,42 @@
|
|
|
1
|
-
import * as fs from 'fs';
|
|
2
|
-
import * as path from 'path';
|
|
3
|
-
import { withLock, withLockAsync } from '../utils/file-lock.js';
|
|
4
|
-
import { atomicWriteFileSync } from '../utils/io.js';
|
|
5
|
-
const PRINCIPLE_TRAINING_FILE = 'principle_training_state.json';
|
|
6
|
-
export const TREE_NAMESPACE = '_tree';
|
|
7
|
-
const VALID_EVALUABILITIES = ['deterministic', 'weak_heuristic', 'manual_only'];
|
|
8
|
-
const VALID_INTERNALIZATION_STATUSES = [
|
|
9
|
-
'prompt_only',
|
|
10
|
-
'needs_training',
|
|
11
|
-
'in_training',
|
|
12
|
-
'deployed_pending_eval',
|
|
13
|
-
'internalized',
|
|
14
|
-
'regressed',
|
|
15
|
-
];
|
|
16
|
-
function isRecord(value) {
|
|
17
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
18
|
-
}
|
|
19
|
-
function clampFloat(value, min, max, fallback) {
|
|
20
|
-
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
|
21
|
-
return fallback;
|
|
22
|
-
}
|
|
23
|
-
return Math.max(min, Math.min(max, value));
|
|
24
|
-
}
|
|
25
|
-
function clampInt(value, min, max, fallback) {
|
|
26
|
-
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
|
27
|
-
return fallback;
|
|
28
|
-
}
|
|
29
|
-
return Math.max(min, Math.min(max, Math.round(value)));
|
|
30
|
-
}
|
|
31
|
-
function stringArray(value) {
|
|
32
|
-
return Array.isArray(value) ? value.filter((entry) => typeof entry === 'string') : [];
|
|
33
|
-
}
|
|
34
|
-
function uniqueStrings(values) {
|
|
35
|
-
return Array.from(new Set(values));
|
|
36
|
-
}
|
|
37
|
-
function createEmptyTree() {
|
|
38
|
-
return {
|
|
39
|
-
principles: {},
|
|
40
|
-
rules: {},
|
|
41
|
-
implementations: {},
|
|
42
|
-
metrics: {},
|
|
43
|
-
lastUpdated: new Date(0).toISOString(),
|
|
44
|
-
};
|
|
45
|
-
}
|
|
46
|
-
function parseLegacyTrainingStore(raw) {
|
|
47
|
-
if (!isRecord(raw)) {
|
|
48
|
-
return {};
|
|
49
|
-
}
|
|
50
|
-
const result = {};
|
|
51
|
-
for (const [principleId, candidate] of Object.entries(raw)) {
|
|
52
|
-
if (principleId === TREE_NAMESPACE || !isRecord(candidate)) {
|
|
53
|
-
continue;
|
|
54
|
-
}
|
|
55
|
-
if (candidate.principleId !== principleId) {
|
|
56
|
-
continue;
|
|
57
|
-
}
|
|
58
|
-
const evaluability = VALID_EVALUABILITIES.includes(candidate.evaluability)
|
|
59
|
-
? candidate.evaluability
|
|
60
|
-
: 'manual_only';
|
|
61
|
-
const internalizationStatus = VALID_INTERNALIZATION_STATUSES.includes(candidate.internalizationStatus)
|
|
62
|
-
? candidate.internalizationStatus
|
|
63
|
-
: 'prompt_only';
|
|
64
|
-
const rawLastEvalScore = candidate.lastEvalScore;
|
|
65
|
-
result[principleId] = {
|
|
66
|
-
principleId,
|
|
67
|
-
evaluability,
|
|
68
|
-
applicableOpportunityCount: clampInt(candidate.applicableOpportunityCount, 0, Number.POSITIVE_INFINITY, 0),
|
|
69
|
-
observedViolationCount: clampInt(candidate.observedViolationCount, 0, Number.POSITIVE_INFINITY, 0),
|
|
70
|
-
complianceRate: clampFloat(candidate.complianceRate, 0, 1, 0),
|
|
71
|
-
violationTrend: clampFloat(candidate.violationTrend, -1, 1, 0),
|
|
72
|
-
generatedSampleCount: clampInt(candidate.generatedSampleCount, 0, Number.POSITIVE_INFINITY, 0),
|
|
73
|
-
approvedSampleCount: clampInt(candidate.approvedSampleCount, 0, Number.POSITIVE_INFINITY, 0),
|
|
74
|
-
includedTrainRunIds: stringArray(candidate.includedTrainRunIds),
|
|
75
|
-
deployedCheckpointIds: stringArray(candidate.deployedCheckpointIds),
|
|
76
|
-
lastEvalScore: typeof rawLastEvalScore === 'number' && Number.isFinite(rawLastEvalScore)
|
|
77
|
-
? clampFloat(rawLastEvalScore, 0, 1, 0)
|
|
78
|
-
: undefined,
|
|
79
|
-
internalizationStatus,
|
|
80
|
-
};
|
|
81
|
-
}
|
|
82
|
-
return result;
|
|
83
|
-
}
|
|
84
|
-
function parsePrinciples(raw) {
|
|
85
|
-
if (!isRecord(raw)) {
|
|
86
|
-
return {};
|
|
87
|
-
}
|
|
88
|
-
const principles = {};
|
|
89
|
-
for (const [id, value] of Object.entries(raw)) {
|
|
90
|
-
if (!isRecord(value)) {
|
|
91
|
-
continue;
|
|
92
|
-
}
|
|
93
|
-
const suggestedRules = stringArray(value.suggestedRules);
|
|
94
|
-
principles[id] = {
|
|
95
|
-
...value,
|
|
96
|
-
id,
|
|
97
|
-
ruleIds: stringArray(value.ruleIds),
|
|
98
|
-
conflictsWithPrincipleIds: stringArray(value.conflictsWithPrincipleIds),
|
|
99
|
-
derivedFromPainIds: stringArray(value.derivedFromPainIds),
|
|
100
|
-
...(Object.prototype.hasOwnProperty.call(value, 'suggestedRules') ? { suggestedRules } : {}),
|
|
101
|
-
};
|
|
102
|
-
}
|
|
103
|
-
return principles;
|
|
104
|
-
}
|
|
105
|
-
function parseRules(raw) {
|
|
106
|
-
if (!isRecord(raw)) {
|
|
107
|
-
return {};
|
|
108
|
-
}
|
|
109
|
-
const rules = {};
|
|
110
|
-
for (const [id, value] of Object.entries(raw)) {
|
|
111
|
-
if (!isRecord(value)) {
|
|
112
|
-
continue;
|
|
113
|
-
}
|
|
114
|
-
rules[id] = {
|
|
115
|
-
...value,
|
|
116
|
-
id,
|
|
117
|
-
principleId: typeof value.principleId === 'string' ? value.principleId : '',
|
|
118
|
-
implementationIds: stringArray(value.implementationIds),
|
|
119
|
-
};
|
|
120
|
-
}
|
|
121
|
-
return rules;
|
|
122
|
-
}
|
|
123
|
-
function parseImplementations(raw) {
|
|
124
|
-
if (!isRecord(raw)) {
|
|
125
|
-
return {};
|
|
126
|
-
}
|
|
127
|
-
const implementations = {};
|
|
128
|
-
for (const [id, value] of Object.entries(raw)) {
|
|
129
|
-
if (!isRecord(value) || typeof value.ruleId !== 'string') {
|
|
130
|
-
continue;
|
|
131
|
-
}
|
|
132
|
-
implementations[id] = {
|
|
133
|
-
...value,
|
|
134
|
-
id,
|
|
135
|
-
ruleId: value.ruleId,
|
|
136
|
-
};
|
|
137
|
-
}
|
|
138
|
-
return implementations;
|
|
139
|
-
}
|
|
140
|
-
function parseMetrics(raw) {
|
|
141
|
-
if (!isRecord(raw)) {
|
|
142
|
-
return {};
|
|
143
|
-
}
|
|
144
|
-
const metrics = {};
|
|
145
|
-
for (const [id, value] of Object.entries(raw)) {
|
|
146
|
-
if (!isRecord(value)) {
|
|
147
|
-
continue;
|
|
148
|
-
}
|
|
149
|
-
metrics[id] = {
|
|
150
|
-
...value,
|
|
151
|
-
principleId: typeof value.principleId === 'string' ? value.principleId : id,
|
|
152
|
-
};
|
|
153
|
-
}
|
|
154
|
-
return metrics;
|
|
155
|
-
}
|
|
156
|
-
function parseTree(raw) {
|
|
157
|
-
if (!isRecord(raw)) {
|
|
158
|
-
return createEmptyTree();
|
|
159
|
-
}
|
|
160
|
-
return {
|
|
161
|
-
principles: parsePrinciples(raw.principles),
|
|
162
|
-
rules: parseRules(raw.rules),
|
|
163
|
-
implementations: parseImplementations(raw.implementations),
|
|
164
|
-
metrics: parseMetrics(raw.metrics),
|
|
165
|
-
lastUpdated: typeof raw.lastUpdated === 'string' ? raw.lastUpdated : new Date(0).toISOString(),
|
|
166
|
-
};
|
|
167
|
-
}
|
|
168
|
-
function serializeLedger(store) {
|
|
169
|
-
return JSON.stringify({
|
|
170
|
-
...store.trainingStore,
|
|
171
|
-
[TREE_NAMESPACE]: {
|
|
172
|
-
...store.tree,
|
|
173
|
-
lastUpdated: new Date().toISOString(),
|
|
174
|
-
},
|
|
175
|
-
}, null, 2);
|
|
176
|
-
}
|
|
177
|
-
function ensureParentDir(filePath) {
|
|
178
|
-
const dir = path.dirname(filePath);
|
|
179
|
-
if (!fs.existsSync(dir)) {
|
|
180
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
function readLedgerFromFile(filePath) {
|
|
184
|
-
if (!fs.existsSync(filePath)) {
|
|
185
|
-
return {
|
|
186
|
-
trainingStore: {},
|
|
187
|
-
tree: createEmptyTree(),
|
|
188
|
-
};
|
|
189
|
-
}
|
|
190
|
-
try {
|
|
191
|
-
const content = fs.readFileSync(filePath, 'utf-8');
|
|
192
|
-
if (!content || content.trim() === '') {
|
|
193
|
-
return { trainingStore: {}, tree: createEmptyTree() };
|
|
194
|
-
}
|
|
195
|
-
const parsed = JSON.parse(content);
|
|
196
|
-
const raw = isRecord(parsed) ? parsed : {};
|
|
197
|
-
// #219: Handle both formats:
|
|
198
|
-
// - New format: { trainingStore: {...}, tree: {...} }
|
|
199
|
-
// - Legacy format: { P_xxx: {...}, _tree: {...} }
|
|
200
|
-
const trainingStoreRaw = raw.trainingStore ?? raw;
|
|
201
|
-
const treeRaw = raw[TREE_NAMESPACE] ?? raw.tree;
|
|
202
|
-
return {
|
|
203
|
-
trainingStore: parseLegacyTrainingStore(trainingStoreRaw),
|
|
204
|
-
tree: parseTree(treeRaw),
|
|
205
|
-
};
|
|
206
|
-
}
|
|
207
|
-
catch (err) {
|
|
208
|
-
console.error(`[principle-tree-ledger] Failed to load ledger from ${filePath}: ${err instanceof Error ? err.message : String(err)}`);
|
|
209
|
-
return { trainingStore: {}, tree: createEmptyTree() };
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
function writeLedgerUnlocked(filePath, store) {
|
|
213
|
-
ensureParentDir(filePath);
|
|
214
|
-
atomicWriteFileSync(filePath, serializeLedger(store));
|
|
215
|
-
}
|
|
216
|
-
function mutateLedger(stateDir, mutate) {
|
|
217
|
-
const filePath = getLedgerFilePath(stateDir);
|
|
218
|
-
return withLock(filePath, () => {
|
|
219
|
-
const store = readLedgerFromFile(filePath);
|
|
220
|
-
const result = mutate(store);
|
|
221
|
-
writeLedgerUnlocked(filePath, store);
|
|
222
|
-
return result;
|
|
223
|
-
});
|
|
224
|
-
}
|
|
225
|
-
async function mutateLedgerAsync(stateDir, mutate) {
|
|
226
|
-
const filePath = getLedgerFilePath(stateDir);
|
|
227
|
-
return withLockAsync(filePath, async () => {
|
|
228
|
-
const store = readLedgerFromFile(filePath);
|
|
229
|
-
const result = await mutate(store);
|
|
230
|
-
writeLedgerUnlocked(filePath, store);
|
|
231
|
-
return result;
|
|
232
|
-
});
|
|
233
|
-
}
|
|
234
|
-
export function getLedgerFilePath(stateDir) {
|
|
235
|
-
return path.join(stateDir, PRINCIPLE_TRAINING_FILE);
|
|
236
|
-
}
|
|
237
|
-
export function loadLedger(stateDir) {
|
|
238
|
-
return readLedgerFromFile(getLedgerFilePath(stateDir));
|
|
239
|
-
}
|
|
240
|
-
export function saveLedger(stateDir, store) {
|
|
241
|
-
mutateLedger(stateDir, (current) => {
|
|
242
|
-
current.trainingStore = store.trainingStore;
|
|
243
|
-
current.tree = store.tree;
|
|
244
|
-
});
|
|
245
|
-
}
|
|
246
|
-
export async function saveLedgerAsync(stateDir, store) {
|
|
247
|
-
await mutateLedgerAsync(stateDir, async (current) => {
|
|
248
|
-
current.trainingStore = store.trainingStore;
|
|
249
|
-
current.tree = store.tree;
|
|
250
|
-
});
|
|
251
|
-
}
|
|
252
|
-
export function updateTrainingStore(stateDir, mutate) {
|
|
253
|
-
mutateLedger(stateDir, (store) => {
|
|
254
|
-
mutate(store.trainingStore);
|
|
255
|
-
});
|
|
256
|
-
}
|
|
257
1
|
/**
|
|
258
|
-
*
|
|
259
|
-
* This is the companion to updatePrinciple() — use this when creating a NEW
|
|
260
|
-
* principle so the compiler can find it in tree.principles.
|
|
2
|
+
* Principle Tree Ledger — plugin adapter (re-export) over @principles/core.
|
|
261
3
|
*
|
|
262
|
-
*
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
}
|
|
286
|
-
export function createImplementation(stateDir, implementation) {
|
|
287
|
-
return mutateLedger(stateDir, (store) => {
|
|
288
|
-
const rule = store.tree.rules[implementation.ruleId];
|
|
289
|
-
if (!rule) {
|
|
290
|
-
throw new Error(`Cannot create implementation "${implementation.id}" for missing rule "${implementation.ruleId}".`);
|
|
291
|
-
}
|
|
292
|
-
store.tree.implementations[implementation.id] = implementation;
|
|
293
|
-
rule.implementationIds = uniqueStrings([...rule.implementationIds, implementation.id]);
|
|
294
|
-
return implementation;
|
|
295
|
-
});
|
|
296
|
-
}
|
|
297
|
-
export function updatePrinciple(stateDir, principleId, updates) {
|
|
298
|
-
return mutateLedger(stateDir, (store) => {
|
|
299
|
-
const existingPrinciple = store.tree.principles[principleId];
|
|
300
|
-
if (!existingPrinciple) {
|
|
301
|
-
throw new Error(`Cannot update missing principle "${principleId}".`);
|
|
302
|
-
}
|
|
303
|
-
const nextPrinciple = {
|
|
304
|
-
...existingPrinciple,
|
|
305
|
-
...updates,
|
|
306
|
-
id: principleId,
|
|
307
|
-
ruleIds: updates.ruleIds ? uniqueStrings(updates.ruleIds) : existingPrinciple.ruleIds,
|
|
308
|
-
conflictsWithPrincipleIds: updates.conflictsWithPrincipleIds
|
|
309
|
-
? uniqueStrings(updates.conflictsWithPrincipleIds)
|
|
310
|
-
: existingPrinciple.conflictsWithPrincipleIds,
|
|
311
|
-
derivedFromPainIds: updates.derivedFromPainIds
|
|
312
|
-
? uniqueStrings(updates.derivedFromPainIds)
|
|
313
|
-
: existingPrinciple.derivedFromPainIds,
|
|
314
|
-
...(Object.prototype.hasOwnProperty.call(updates, 'suggestedRules')
|
|
315
|
-
? { suggestedRules: uniqueStrings(updates.suggestedRules ?? []) }
|
|
316
|
-
: Object.prototype.hasOwnProperty.call(existingPrinciple, 'suggestedRules')
|
|
317
|
-
? { suggestedRules: existingPrinciple.suggestedRules }
|
|
318
|
-
: {}),
|
|
319
|
-
};
|
|
320
|
-
store.tree.principles[principleId] = nextPrinciple;
|
|
321
|
-
return nextPrinciple;
|
|
322
|
-
});
|
|
323
|
-
}
|
|
324
|
-
export function updateRule(stateDir, ruleId, updates) {
|
|
325
|
-
return mutateLedger(stateDir, (store) => {
|
|
326
|
-
const existingRule = store.tree.rules[ruleId];
|
|
327
|
-
if (!existingRule) {
|
|
328
|
-
throw new Error(`Cannot update missing rule "${ruleId}".`);
|
|
329
|
-
}
|
|
330
|
-
const nextPrincipleId = updates.principleId ?? existingRule.principleId;
|
|
331
|
-
const nextPrinciple = store.tree.principles[nextPrincipleId];
|
|
332
|
-
if (!nextPrinciple) {
|
|
333
|
-
throw new Error(`Cannot move rule "${ruleId}" to missing principle "${nextPrincipleId}".`);
|
|
334
|
-
}
|
|
335
|
-
const nextRule = {
|
|
336
|
-
...existingRule,
|
|
337
|
-
...updates,
|
|
338
|
-
id: ruleId,
|
|
339
|
-
principleId: nextPrincipleId,
|
|
340
|
-
implementationIds: updates.implementationIds
|
|
341
|
-
? uniqueStrings(updates.implementationIds)
|
|
342
|
-
: existingRule.implementationIds,
|
|
343
|
-
};
|
|
344
|
-
if (existingRule.principleId !== nextPrincipleId) {
|
|
345
|
-
const previousPrinciple = store.tree.principles[existingRule.principleId];
|
|
346
|
-
if (previousPrinciple) {
|
|
347
|
-
previousPrinciple.ruleIds = previousPrinciple.ruleIds.filter((candidateId) => candidateId !== ruleId);
|
|
348
|
-
}
|
|
349
|
-
nextPrinciple.ruleIds = uniqueStrings([...nextPrinciple.ruleIds, ruleId]);
|
|
350
|
-
}
|
|
351
|
-
store.tree.rules[ruleId] = nextRule;
|
|
352
|
-
return nextRule;
|
|
353
|
-
});
|
|
354
|
-
}
|
|
355
|
-
export function deleteRule(stateDir, ruleId) {
|
|
356
|
-
return mutateLedger(stateDir, (store) => {
|
|
357
|
-
const existingRule = store.tree.rules[ruleId];
|
|
358
|
-
if (!existingRule) {
|
|
359
|
-
return undefined;
|
|
360
|
-
}
|
|
361
|
-
const parentPrinciple = store.tree.principles[existingRule.principleId];
|
|
362
|
-
if (parentPrinciple) {
|
|
363
|
-
parentPrinciple.ruleIds = parentPrinciple.ruleIds.filter((candidateId) => candidateId !== ruleId);
|
|
364
|
-
}
|
|
365
|
-
const implementationIds = uniqueStrings([
|
|
366
|
-
...existingRule.implementationIds,
|
|
367
|
-
...Object.values(store.tree.implementations)
|
|
368
|
-
.filter((implementation) => implementation.ruleId === ruleId)
|
|
369
|
-
.map((implementation) => implementation.id),
|
|
370
|
-
]);
|
|
371
|
-
for (const implementationId of implementationIds) {
|
|
372
|
-
delete store.tree.implementations[implementationId];
|
|
373
|
-
}
|
|
374
|
-
delete store.tree.rules[ruleId];
|
|
375
|
-
return existingRule;
|
|
376
|
-
});
|
|
377
|
-
}
|
|
378
|
-
export function updateImplementation(stateDir, implementationId, updates) {
|
|
379
|
-
return mutateLedger(stateDir, (store) => {
|
|
380
|
-
const existingImplementation = store.tree.implementations[implementationId];
|
|
381
|
-
if (!existingImplementation) {
|
|
382
|
-
throw new Error(`Cannot update missing implementation "${implementationId}".`);
|
|
383
|
-
}
|
|
384
|
-
const nextRuleId = updates.ruleId ?? existingImplementation.ruleId;
|
|
385
|
-
const nextRule = store.tree.rules[nextRuleId];
|
|
386
|
-
if (!nextRule) {
|
|
387
|
-
throw new Error(`Cannot move implementation "${implementationId}" to missing rule "${nextRuleId}".`);
|
|
388
|
-
}
|
|
389
|
-
const nextImplementation = {
|
|
390
|
-
...existingImplementation,
|
|
391
|
-
...updates,
|
|
392
|
-
id: implementationId,
|
|
393
|
-
ruleId: nextRuleId,
|
|
394
|
-
};
|
|
395
|
-
if (existingImplementation.ruleId !== nextRuleId) {
|
|
396
|
-
const previousRule = store.tree.rules[existingImplementation.ruleId];
|
|
397
|
-
if (previousRule) {
|
|
398
|
-
previousRule.implementationIds = previousRule.implementationIds.filter((candidateId) => candidateId !== implementationId);
|
|
399
|
-
}
|
|
400
|
-
nextRule.implementationIds = uniqueStrings([...nextRule.implementationIds, implementationId]);
|
|
401
|
-
}
|
|
402
|
-
store.tree.implementations[implementationId] = nextImplementation;
|
|
403
|
-
return nextImplementation;
|
|
404
|
-
});
|
|
405
|
-
}
|
|
406
|
-
export function deleteImplementation(stateDir, implementationId) {
|
|
407
|
-
return mutateLedger(stateDir, (store) => {
|
|
408
|
-
const existingImplementation = store.tree.implementations[implementationId];
|
|
409
|
-
if (!existingImplementation) {
|
|
410
|
-
return undefined;
|
|
411
|
-
}
|
|
412
|
-
const parentRule = store.tree.rules[existingImplementation.ruleId];
|
|
413
|
-
if (parentRule) {
|
|
414
|
-
parentRule.implementationIds = parentRule.implementationIds.filter((candidateId) => candidateId !== implementationId);
|
|
415
|
-
}
|
|
416
|
-
delete store.tree.implementations[implementationId];
|
|
417
|
-
return existingImplementation;
|
|
418
|
-
});
|
|
419
|
-
}
|
|
420
|
-
export function listImplementationsForRule(stateDir, ruleId) {
|
|
421
|
-
const ledger = loadLedger(stateDir);
|
|
422
|
-
const rule = ledger.tree.rules[ruleId];
|
|
423
|
-
if (!rule) {
|
|
424
|
-
return [];
|
|
425
|
-
}
|
|
426
|
-
return rule.implementationIds
|
|
427
|
-
.map((implementationId) => ledger.tree.implementations[implementationId])
|
|
428
|
-
.filter((implementation) => implementation !== undefined);
|
|
429
|
-
}
|
|
430
|
-
export function getPrincipleSubtree(stateDir, principleId) {
|
|
431
|
-
const ledger = loadLedger(stateDir);
|
|
432
|
-
const principle = ledger.tree.principles[principleId];
|
|
433
|
-
if (!principle) {
|
|
434
|
-
return undefined;
|
|
435
|
-
}
|
|
436
|
-
return {
|
|
437
|
-
principle,
|
|
438
|
-
rules: principle.ruleIds
|
|
439
|
-
.map((ruleId) => ledger.tree.rules[ruleId])
|
|
440
|
-
.filter((rule) => rule !== undefined)
|
|
441
|
-
.map((rule) => ({
|
|
442
|
-
rule,
|
|
443
|
-
implementations: rule.implementationIds
|
|
444
|
-
.map((implementationId) => ledger.tree.implementations[implementationId])
|
|
445
|
-
.filter((implementation) => implementation !== undefined),
|
|
446
|
-
})),
|
|
447
|
-
};
|
|
448
|
-
}
|
|
449
|
-
export function updatePrincipleValueMetrics(stateDir, principleId, metrics) {
|
|
450
|
-
return mutateLedger(stateDir, (store) => {
|
|
451
|
-
const nextMetrics = {
|
|
452
|
-
...metrics,
|
|
453
|
-
principleId,
|
|
454
|
-
};
|
|
455
|
-
store.tree.metrics[principleId] = nextMetrics;
|
|
456
|
-
return nextMetrics;
|
|
457
|
-
});
|
|
458
|
-
}
|
|
459
|
-
// ---------------------------------------------------------------------------
|
|
460
|
-
// Implementation Lifecycle State Transitions
|
|
461
|
-
// ---------------------------------------------------------------------------
|
|
462
|
-
/**
|
|
463
|
-
* Valid lifecycle state transitions (per Phase 13 context D-15):
|
|
464
|
-
* candidate -> active (promote)
|
|
465
|
-
* active -> disabled (disable)
|
|
466
|
-
* disabled -> active (re-enable via promote)
|
|
467
|
-
* disabled -> archived (permanent disable)
|
|
468
|
-
* active -> archived (direct archive)
|
|
469
|
-
* candidate -> archived (rejected candidate cleanup)
|
|
470
|
-
*/
|
|
471
|
-
const VALID_LIFECYCLE_TRANSITIONS = {
|
|
472
|
-
candidate: ['active', 'archived'],
|
|
473
|
-
active: ['disabled', 'archived'],
|
|
474
|
-
disabled: ['active', 'archived'],
|
|
475
|
-
archived: [],
|
|
476
|
-
};
|
|
477
|
-
/**
|
|
478
|
-
* Validate a lifecycle state transition.
|
|
479
|
-
* Returns true if the transition is valid, false otherwise.
|
|
480
|
-
*/
|
|
481
|
-
export function isValidLifecycleTransition(from, to) {
|
|
482
|
-
return VALID_LIFECYCLE_TRANSITIONS[from]?.includes(to) ?? false;
|
|
483
|
-
}
|
|
484
|
-
/**
|
|
485
|
-
* Get allowed transitions for a given lifecycle state.
|
|
486
|
-
*/
|
|
487
|
-
export function getAllowedTransitions(from) {
|
|
488
|
-
return VALID_LIFECYCLE_TRANSITIONS[from] ?? [];
|
|
489
|
-
}
|
|
490
|
-
/**
|
|
491
|
-
* Transition an implementation's lifecycle state with validation.
|
|
492
|
-
* Throws on invalid transitions */
|
|
493
|
-
export function transitionImplementationState(stateDir, implementationId, newState) {
|
|
494
|
-
return mutateLedger(stateDir, (store) => {
|
|
495
|
-
const impl = store.tree.implementations[implementationId];
|
|
496
|
-
if (!impl) {
|
|
497
|
-
throw new Error(`Implementation not found: ${implementationId}`);
|
|
498
|
-
}
|
|
499
|
-
const currentState = impl.lifecycleState ?? 'candidate';
|
|
500
|
-
if (!isValidLifecycleTransition(currentState, newState)) {
|
|
501
|
-
const allowed = getAllowedTransitions(currentState);
|
|
502
|
-
throw new Error(`Invalid lifecycle transition: ${currentState} -> ${newState}. ` +
|
|
503
|
-
`Allowed: ${allowed.length > 0 ? allowed.join(', ') : 'none (terminal state)'}`);
|
|
504
|
-
}
|
|
505
|
-
const updated = {
|
|
506
|
-
...impl,
|
|
507
|
-
lifecycleState: newState,
|
|
508
|
-
updatedAt: new Date().toISOString(),
|
|
509
|
-
};
|
|
510
|
-
store.tree.implementations[implementationId] = updated;
|
|
511
|
-
return updated;
|
|
512
|
-
});
|
|
513
|
-
}
|
|
514
|
-
/**
|
|
515
|
-
* Get implementations in a specific lifecycle state for a given rule.
|
|
516
|
-
*/
|
|
517
|
-
export function listRuleImplementationsByState(stateDir, ruleId, state) {
|
|
518
|
-
const implementations = listImplementationsForRule(stateDir, ruleId);
|
|
519
|
-
return implementations.filter((impl) => impl.lifecycleState === state);
|
|
520
|
-
}
|
|
521
|
-
/**
|
|
522
|
-
* Find active implementation for a rule (helper for rule host lookup).
|
|
4
|
+
* PRI-459: This file WAS a full duplicate implementation of
|
|
5
|
+
* principle_training_state.json parsing / serialization / mutation (~600
|
|
6
|
+
* lines of inlined parsers, serializers, mutators, and a parallel codec).
|
|
7
|
+
* That dual ownership caused two real failure classes:
|
|
8
|
+
*
|
|
9
|
+
* 1. Lost updates — core wrote the file UNLOCKED, the plugin wrote it WITH
|
|
10
|
+
* a lock, and neither knew the other's lock. Concurrent writers (e.g.
|
|
11
|
+
* evolution-worker async + a pd-cli command) could silently drop edits.
|
|
12
|
+
* 2. Silent field loss — the two codecs parsed the same bytes at different
|
|
13
|
+
* strictness; a field one side persisted could be dropped on the next
|
|
14
|
+
* load by the other.
|
|
15
|
+
*
|
|
16
|
+
* Both are now fixed by converging on a SINGLE source of truth in core:
|
|
17
|
+
* - parse/serialize: @principles/core/runtime-v2/principle-tree/ledger-codec
|
|
18
|
+
* - mutation (with cross-process file lock): @principles/core/principle-tree-ledger
|
|
19
|
+
*
|
|
20
|
+
* This file is now a thin re-export so existing relative imports
|
|
21
|
+
* (`from './principle-tree-ledger.js'`) keep resolving. Consumers get the
|
|
22
|
+
* exact same API surface, now backed by the locked core implementation.
|
|
23
|
+
*
|
|
24
|
+
* Do NOT reintroduce parsing / serialization / mutation logic here. The
|
|
25
|
+
* architecture-regression guard "PRI-459: single principle_training_state
|
|
26
|
+
* ledger implementation" enforces this.
|
|
523
27
|
*/
|
|
524
|
-
export
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
28
|
+
export {
|
|
29
|
+
// Constants
|
|
30
|
+
TREE_NAMESPACE,
|
|
31
|
+
// Lock
|
|
32
|
+
LockAcquisitionError,
|
|
33
|
+
// I/O + mutators
|
|
34
|
+
loadLedger, saveLedger, saveLedgerAsync, updateTrainingStore, addPrincipleToLedger, createRule, createImplementation, updatePrinciple, updateRule, deleteRule, updateImplementation, deleteImplementation, listImplementationsForRule, getPrincipleSubtree, updatePrincipleValueMetrics,
|
|
35
|
+
// Lifecycle
|
|
36
|
+
isValidLifecycleTransition, getAllowedTransitions, transitionImplementationState, listRuleImplementationsByState, findActiveImplementation, } from '@principles/core/principle-tree-ledger';
|
|
37
|
+
// Back-compat alias: the historical plugin module exported `getLedgerFilePath`
|
|
38
|
+
// (core names it `getLedgerFilePathPublic` for the same path). Keep the old
|
|
39
|
+
// name resolvable for any consumer still on it; both compute
|
|
40
|
+
// path.join(stateDir, 'principle_training_state.json').
|
|
41
|
+
import { getLedgerFilePathPublic } from '@principles/core/principle-tree-ledger';
|
|
42
|
+
export const getLedgerFilePath = getLedgerFilePathPublic;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
+
import { type LedgerPrinciple } from '../principle-tree-ledger.js';
|
|
1
2
|
import type { TrajectoryDatabase } from '../trajectory.js';
|
|
2
|
-
import type { Principle } from '../../types/principle-tree-schema.js';
|
|
3
3
|
export interface ReflectionContext {
|
|
4
|
-
principle:
|
|
4
|
+
principle: LedgerPrinciple;
|
|
5
5
|
painEvents: Array<{
|
|
6
6
|
source: string;
|
|
7
7
|
score: number;
|
|
@@ -6,12 +6,11 @@ import { HygieneTracker } from './hygiene/tracker.js';
|
|
|
6
6
|
import { EvolutionReducerImpl } from './evolution-reducer.js';
|
|
7
7
|
import type { TrajectoryDatabase } from './trajectory.js';
|
|
8
8
|
import { PrincipleLifecycleService } from './principle-internalization/principle-lifecycle-service.js';
|
|
9
|
-
import { type PrincipleSubtree } from './principle-tree-ledger.js';
|
|
10
|
-
import type { Principle, PrincipleValueMetrics } from '../types/principle-tree-schema.js';
|
|
9
|
+
import { type PrincipleSubtree, type LedgerPrinciple, type PrincipleValueMetrics } from './principle-tree-ledger.js';
|
|
11
10
|
import type { Principle as ActivePrinciple } from './evolution-types.js';
|
|
12
11
|
interface PrincipleTreeLedgerAccessor {
|
|
13
12
|
getPrincipleSubtree(_principleId: string): PrincipleSubtree | undefined;
|
|
14
|
-
updatePrinciple(_principleId: string, updates: Partial<
|
|
13
|
+
updatePrinciple(_principleId: string, updates: Partial<LedgerPrinciple>): LedgerPrinciple;
|
|
15
14
|
updatePrincipleValueMetrics(principleId: string, _metrics: PrincipleValueMetrics): PrincipleValueMetrics;
|
|
16
15
|
}
|
|
17
16
|
/**
|
package/openclaw.plugin.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"id": "principles-disciple",
|
|
3
3
|
"name": "Principles Disciple",
|
|
4
4
|
"description": "Evolutionary programming agent framework with strategic guardrails and reflection loops.",
|
|
5
|
-
"version": "1.
|
|
5
|
+
"version": "1.148.0",
|
|
6
6
|
"activation": {
|
|
7
7
|
"onCapabilities": [
|
|
8
8
|
"hook"
|