@principles/pd-cli 1.132.0 → 1.133.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/package.json
CHANGED
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 一次性数据迁移脚本:修正 pi_artifacts 中 expectedDecision = "requireApproval" 的历史坏数据。
|
|
3
|
+
*
|
|
4
|
+
* 背景:
|
|
5
|
+
* GoldenTraceDecision 的合法值只有 "allow" | "block" | "propose_correction"
|
|
6
|
+
* (定义在 @principles/core/runtime-v2 的 golden-trace.ts GoldenTraceDecisionSchema)。
|
|
7
|
+
* 但 PRI-427 加固前创建的 rule artifact 可能含有 "requireApproval"
|
|
8
|
+
* (这是 RuleHostDecision 的运行时枚举值,不是测试期望值)。
|
|
9
|
+
* 这类 artifact 在 owner 批准时会失败,错误信息为
|
|
10
|
+
* "gate_decision_not_accepted_shadow:rejected_validation_failed",对 owner 不可操作。
|
|
11
|
+
*
|
|
12
|
+
* 根因已在 rule-host-writer.ts 的 extractGoldenTrace() 中修复(调用 validateGoldenTrace
|
|
13
|
+
* 前置 schema 校验)。本脚本用于清理已存在的坏数据。
|
|
14
|
+
*
|
|
15
|
+
* 修复策略:
|
|
16
|
+
* - kind=negative + expectedDecision=requireApproval → 改为 "block"
|
|
17
|
+
* (validateCaseDecision 的 'block' case 接受 requireApproval 作为合法运行时输出)
|
|
18
|
+
* - kind=positive + expectedDecision=requireApproval → 改为 "allow"
|
|
19
|
+
* (理论上不应出现,但兜底处理)
|
|
20
|
+
* - 其他非法值 → 报告但不修改(需人工判断)
|
|
21
|
+
*
|
|
22
|
+
* 使用:
|
|
23
|
+
* npx tsx scripts/migrate-illegal-expected-decision.ts <workspace-dir> [--write]
|
|
24
|
+
*
|
|
25
|
+
* 示例:
|
|
26
|
+
* npx tsx scripts/migrate-illegal-expected-decision.ts D:/.openclaw/workspace
|
|
27
|
+
* npx tsx scripts/migrate-illegal-expected-decision.ts D:/.openclaw/workspace --write
|
|
28
|
+
*
|
|
29
|
+
* 安全保障:
|
|
30
|
+
* 1. 默认 dry-run(只读),必须显式 --write 才会写入
|
|
31
|
+
* 2. --write 模式下自动备份 state.db 到 state.db.backup-<timestamp>
|
|
32
|
+
* 3. 只修改 artifact_kind='rule' 的记录
|
|
33
|
+
* 4. 同时修正 goldenTrace 和 goldenTraceCases 两个字段(artificer raw 输出副本)
|
|
34
|
+
* 5. --write 模式下所有 UPDATE 在单个事务内执行,保证原子性
|
|
35
|
+
*/
|
|
36
|
+
import * as fs from 'node:fs';
|
|
37
|
+
import * as path from 'node:path';
|
|
38
|
+
import Database from 'better-sqlite3';
|
|
39
|
+
|
|
40
|
+
interface CliArgs {
|
|
41
|
+
workspaceDir: string;
|
|
42
|
+
dryRun: boolean;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function parseArgs(argv: string[]): CliArgs {
|
|
46
|
+
const positional = argv.slice(2).filter((a) => !a.startsWith('--'));
|
|
47
|
+
// Safety default: dry-run (read-only). Operator must pass --write to mutate.
|
|
48
|
+
const writeMode = argv.includes('--write');
|
|
49
|
+
if (positional.length === 0) {
|
|
50
|
+
console.error('Usage: npx tsx scripts/migrate-illegal-expected-decision.ts <workspace-dir> [--write]');
|
|
51
|
+
console.error('Example: npx tsx scripts/migrate-illegal-expected-decision.ts D:/.openclaw/workspace');
|
|
52
|
+
console.error(' npx tsx scripts/migrate-illegal-expected-decision.ts D:/.openclaw/workspace --write');
|
|
53
|
+
process.exit(1);
|
|
54
|
+
}
|
|
55
|
+
return { workspaceDir: positional[0] ?? '', dryRun: !writeMode };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
interface FixRecord {
|
|
59
|
+
artifactId: string;
|
|
60
|
+
caseId: string;
|
|
61
|
+
kind: string;
|
|
62
|
+
from: string;
|
|
63
|
+
to: string;
|
|
64
|
+
field: 'goldenTrace' | 'goldenTraceCases';
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function normalizeExpectedDecision(value: unknown, kind: unknown): string | null {
|
|
68
|
+
if (value !== 'requireApproval') return null;
|
|
69
|
+
// Only map explicit kinds — unknown kind must NOT be silently coerced.
|
|
70
|
+
// Unknown kinds are reported (not modified) so a human can review them.
|
|
71
|
+
if (kind === 'positive') return 'allow';
|
|
72
|
+
if (kind === 'negative') return 'block';
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function fixCasesArray(
|
|
77
|
+
cases: unknown,
|
|
78
|
+
artifactId: string,
|
|
79
|
+
field: 'goldenTrace' | 'goldenTraceCases',
|
|
80
|
+
fixes: FixRecord[],
|
|
81
|
+
issues: Array<{ artifactId: string; issue: string }>,
|
|
82
|
+
): boolean {
|
|
83
|
+
if (!Array.isArray(cases)) return false;
|
|
84
|
+
let modified = false;
|
|
85
|
+
for (const c of cases) {
|
|
86
|
+
if (typeof c !== 'object' || c === null) continue;
|
|
87
|
+
const rec = c as Record<string, unknown>;
|
|
88
|
+
const newVal = normalizeExpectedDecision(rec.expectedDecision, rec.kind);
|
|
89
|
+
if (newVal !== null) {
|
|
90
|
+
fixes.push({
|
|
91
|
+
artifactId,
|
|
92
|
+
caseId: typeof rec.caseId === 'string' ? rec.caseId : '<unknown>',
|
|
93
|
+
kind: typeof rec.kind === 'string' ? rec.kind : '<unknown>',
|
|
94
|
+
from: String(rec.expectedDecision),
|
|
95
|
+
to: newVal,
|
|
96
|
+
field,
|
|
97
|
+
});
|
|
98
|
+
rec.expectedDecision = newVal;
|
|
99
|
+
modified = true;
|
|
100
|
+
} else if (rec.expectedDecision === 'requireApproval') {
|
|
101
|
+
// Illegal value found but kind is not positive/negative — cannot
|
|
102
|
+
// auto-fix safely. Record for manual review instead of silently
|
|
103
|
+
// coercing to 'block' (rc-9: no silent fallback).
|
|
104
|
+
const kindStr = typeof rec.kind === 'string' ? rec.kind : '<unknown>';
|
|
105
|
+
const caseIdStr = typeof rec.caseId === 'string' ? rec.caseId : '<unknown>';
|
|
106
|
+
issues.push({
|
|
107
|
+
artifactId,
|
|
108
|
+
issue: `requireApproval with unknown kind="${kindStr}" (case=${caseIdStr}, field=${field}) — manual review required`,
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return modified;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function main(): void {
|
|
116
|
+
const { workspaceDir, dryRun } = parseArgs(process.argv);
|
|
117
|
+
const dbPath = path.join(workspaceDir, '.pd', 'state.db');
|
|
118
|
+
|
|
119
|
+
if (!fs.existsSync(dbPath)) {
|
|
120
|
+
console.error(`[error] state.db not found at ${dbPath}`);
|
|
121
|
+
process.exit(1);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// 1. 备份 DB(非 dry-run 时)
|
|
125
|
+
if (!dryRun) {
|
|
126
|
+
const backupPath = `${dbPath}.backup-${Date.now()}`;
|
|
127
|
+
fs.copyFileSync(dbPath, backupPath);
|
|
128
|
+
console.log(`[backup] created ${backupPath}`);
|
|
129
|
+
} else {
|
|
130
|
+
console.log('[dry-run] no backup created');
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const db = new Database(dbPath, { readonly: dryRun });
|
|
134
|
+
console.log(`\n[mode] ${dryRun ? 'DRY-RUN (read-only)' : 'WRITE'}`);
|
|
135
|
+
console.log(`[db] ${dbPath}`);
|
|
136
|
+
|
|
137
|
+
// 2. 扫描所有 rule artifact
|
|
138
|
+
const artifactsRaw = db
|
|
139
|
+
.prepare('SELECT artifact_id, content_json FROM pi_artifacts WHERE artifact_kind = ?')
|
|
140
|
+
.all('rule');
|
|
141
|
+
// Runtime guard: better-sqlite3 returns unknown[]. Validate shape before use (rc-1/rc-2).
|
|
142
|
+
const artifacts: Array<{ artifact_id: string; content_json: string }> = [];
|
|
143
|
+
if (Array.isArray(artifactsRaw)) {
|
|
144
|
+
for (const row of artifactsRaw) {
|
|
145
|
+
if (
|
|
146
|
+
typeof row === 'object' && row !== null
|
|
147
|
+
&& typeof (row as Record<string, unknown>).artifact_id === 'string'
|
|
148
|
+
&& typeof (row as Record<string, unknown>).content_json === 'string'
|
|
149
|
+
) {
|
|
150
|
+
artifacts.push({
|
|
151
|
+
artifact_id: (row as Record<string, string>).artifact_id,
|
|
152
|
+
content_json: (row as Record<string, string>).content_json,
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
console.log(`[scan] found ${artifacts.length} rule artifacts`);
|
|
158
|
+
|
|
159
|
+
const fixes: FixRecord[] = [];
|
|
160
|
+
const issues: Array<{ artifactId: string; issue: string }> = [];
|
|
161
|
+
|
|
162
|
+
for (const art of artifacts) {
|
|
163
|
+
let parsed: unknown;
|
|
164
|
+
try {
|
|
165
|
+
parsed = JSON.parse(art.content_json);
|
|
166
|
+
} catch {
|
|
167
|
+
issues.push({ artifactId: art.artifact_id, issue: 'content_json parse failed' });
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
if (typeof parsed !== 'object' || parsed === null) continue;
|
|
171
|
+
const obj = parsed as Record<string, unknown>;
|
|
172
|
+
|
|
173
|
+
// 修复 goldenTrace.cases
|
|
174
|
+
if (typeof obj.goldenTrace === 'object' && obj.goldenTrace !== null) {
|
|
175
|
+
const trace = obj.goldenTrace as Record<string, unknown>;
|
|
176
|
+
fixCasesArray(trace.cases, art.artifact_id, 'goldenTrace', fixes, issues);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// 修复 goldenTraceCases(artificer raw 输出副本)
|
|
180
|
+
fixCasesArray(obj.goldenTraceCases, art.artifact_id, 'goldenTraceCases', fixes, issues);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// 3. 报告
|
|
184
|
+
if (fixes.length === 0 && issues.length === 0) {
|
|
185
|
+
console.log('\n[summary] no illegal expectedDecision values found. Nothing to fix.');
|
|
186
|
+
db.close();
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
if (fixes.length > 0) {
|
|
191
|
+
console.log(`\n[fixes] ${fixes.length} case(s) ${dryRun ? 'would be ' : ''}fixed across ${new Set(fixes.map((f) => f.artifactId)).size} artifact(s):`);
|
|
192
|
+
for (const f of fixes) {
|
|
193
|
+
console.log(` ${f.artifactId} | ${f.field} | case=${f.caseId} kind=${f.kind}: ${f.from} → ${f.to}`);
|
|
194
|
+
}
|
|
195
|
+
} else {
|
|
196
|
+
console.log('\n[fixes] 0 cases can be auto-fixed.');
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
if (issues.length > 0) {
|
|
200
|
+
console.log(`\n[issues] ${issues.length} artifact(s) had parse issues or require manual review:`);
|
|
201
|
+
for (const i of issues) console.log(` ${i.artifactId}: ${i.issue}`);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
if (dryRun) {
|
|
205
|
+
console.log('\n[dry-run] no changes written. Re-run with --write to apply.');
|
|
206
|
+
db.close();
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
if (fixes.length === 0) {
|
|
211
|
+
// Nothing to write — only issues (manual review). Don't open a transaction.
|
|
212
|
+
db.close();
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// 4. 应用修复 — 所有 UPDATE 在单个事务内执行,保证原子性 (all-or-nothing)
|
|
217
|
+
let updatedCount = 0;
|
|
218
|
+
const artifactsToFix = new Set(fixes.map((f) => f.artifactId));
|
|
219
|
+
const applyTx = db.transaction(() => {
|
|
220
|
+
for (const art of artifacts) {
|
|
221
|
+
if (!artifactsToFix.has(art.artifact_id)) continue;
|
|
222
|
+
let parsed: unknown;
|
|
223
|
+
try {
|
|
224
|
+
parsed = JSON.parse(art.content_json);
|
|
225
|
+
} catch {
|
|
226
|
+
continue;
|
|
227
|
+
}
|
|
228
|
+
// Runtime guard (rc-1/rc-2): validate parsed shape before use.
|
|
229
|
+
if (typeof parsed !== 'object' || parsed === null) continue;
|
|
230
|
+
const parsedObj = parsed as Record<string, unknown>;
|
|
231
|
+
|
|
232
|
+
if (typeof parsedObj.goldenTrace === 'object' && parsedObj.goldenTrace !== null) {
|
|
233
|
+
const trace = parsedObj.goldenTrace as Record<string, unknown>;
|
|
234
|
+
fixCasesArray(trace.cases, art.artifact_id, 'goldenTrace', [], issues);
|
|
235
|
+
}
|
|
236
|
+
fixCasesArray(parsedObj.goldenTraceCases, art.artifact_id, 'goldenTraceCases', [], issues);
|
|
237
|
+
|
|
238
|
+
const newContentJson = JSON.stringify(parsedObj);
|
|
239
|
+
const result = db
|
|
240
|
+
.prepare('UPDATE pi_artifacts SET content_json = ?, updated_at = ? WHERE artifact_id = ?')
|
|
241
|
+
.run(newContentJson, new Date().toISOString(), art.artifact_id);
|
|
242
|
+
if (result.changes > 0) updatedCount++;
|
|
243
|
+
}
|
|
244
|
+
});
|
|
245
|
+
applyTx();
|
|
246
|
+
|
|
247
|
+
console.log(`\n[summary] ${updatedCount} artifact row(s) updated (transaction committed)`);
|
|
248
|
+
|
|
249
|
+
db.close();
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
main();
|